1"""Early detection of escape-sequence-based encodings (ISO-2022, HZ-GB-2312, UTF-7).
2
3These encodings use ESC (0x1B), tilde (~), or plus (+) sequences to switch
4character sets. They must be detected before binary detection (ESC is a control
5byte) and before ASCII detection (HZ-GB-2312 and UTF-7 use only printable ASCII
6bytes plus their respective shift markers).
7
8Note: ``from __future__ import annotations`` is intentionally omitted because
9this module is compiled with mypyc, which does not support PEP 563 string
10annotations.
11"""
12
13import codecs
14
15from chardet._utils import (
16 _DECODE_CHUNK_SIZE,
17 EVIDENCE_CAP_BYTES,
18 count_deleted,
19 decodes_without_error,
20)
21from chardet.pipeline import DETERMINISTIC_CONFIDENCE, DetectionResult
22
23# HTML/XML syntax characters that UTF-7 can smuggle inside a shifted run.
24_MARKUP_CHARS: str = "<>&\"'"
25
26# Byte values legal inside an HZ-GB-2312 ``~{...~}`` region.
27_HZ_GB_BYTES: bytes = bytes(range(0x21, 0x7F))
28
29
30def _has_valid_hz_regions(data: bytes, max_start: int, max_end: int) -> bool:
31 """Check that at least one ~{...~} region contains valid GB2312 byte pairs.
32
33 In HZ-GB-2312 GB mode, characters are encoded as pairs of bytes in the
34 0x21-0x7E range. We require at least one region with a non-empty, even-
35 length run of such bytes.
36
37 *max_start* bounds where a region may open and *max_end* where it may
38 close. Keeping them separate is what lets a region that opens inside
39 the evidence window close beyond it: bounding both at the same offset
40 would cut a straddling region and hide the only escape evidence a
41 document has (ADR-0006).
42 """
43 start = 0
44 while True:
45 begin = data.find(b"~{", start)
46 if begin == -1 or begin >= max_start:
47 return False
48 end = data.find(b"~}", begin + 2, max_end)
49 if end == -1:
50 return False
51 region = data[begin + 2 : end]
52 # Must be non-empty, even length, and all bytes in GB2312 range.
53 # The range test is a C-level scan rather than a Python loop: a
54 # region may now run past the evidence window, and per-byte Python
55 # work proportional to it is exactly what the window exists to
56 # prevent.
57 if (
58 len(region) >= 2
59 and len(region) % 2 == 0
60 and count_deleted(region, _HZ_GB_BYTES) == len(region)
61 ):
62 return True
63 start = end + 2
64
65
66# Base64 alphabet used inside UTF-7 shifted sequences (+<Base64>-)
67_B64_CHARS: bytes = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
68_UTF7_BASE64: frozenset[int] = frozenset(_B64_CHARS)
69
70# Uppercase ASCII letters (A-Z), used by Guard C in _has_valid_utf7_sequences.
71_B64_UPPERCASE: frozenset[int] = frozenset(b"ABCDEFGHIJKLMNOPQRSTUVWXYZ")
72
73# Lookup table mapping each Base64 byte to its 6-bit value (0-63).
74_B64_DECODE: dict[int, int] = {c: i for i, c in enumerate(_B64_CHARS)}
75
76# Consecutive base64 characters before a '+' that mark it as part of a
77# base64 stream rather than a UTF-7 shift.
78_EMBEDDED_B64_RUN: int = 4
79
80
81def _is_valid_utf7_b64(b64_bytes: bytes) -> bool:
82 """Check if base64 bytes decode to valid UTF-16BE with correct padding.
83
84 A valid UTF-7 shifted sequence must:
85 1. Contain at least 3 Base64 characters (18 bits, enough for one 16-bit
86 UTF-16 code unit).
87 2. Have zero-valued trailing padding bits (the unused low bits of the last
88 Base64 sextet after the last complete 16-bit code unit).
89 3. Decode to valid UTF-16BE — no lone surrogates.
90
91 This rejects accidental ``+<alphanum>-`` patterns found in URLs, MIME
92 boundaries, hex-encoded hashes (e.g. SHA-1 git refs), and other ASCII data.
93
94 The caller (``_has_valid_utf7_sequences``) already checks ``b64_len >= 3``
95 before calling this function, so *b64_bytes* is always at least 3 bytes.
96 """
97 n = len(b64_bytes)
98 total_bits = n * 6
99 # Check that padding bits (trailing bits after last complete code unit)
100 # are zero.
101 padding_bits = total_bits % 16
102 if padding_bits > 0:
103 last_val = _B64_DECODE[b64_bytes[-1]]
104 # The low `padding_bits` of the last sextet must be zero
105 mask = (1 << padding_bits) - 1
106 if last_val & mask:
107 return False
108 # Decode the base64 to raw bytes and validate as UTF-16BE.
109 # Lone surrogates (unpaired 0xD800-0xDFFF code units) are illegal in
110 # well-formed UTF-16 and cannot appear in real UTF-7 text. This catches
111 # hex-encoded hashes and other accidental base64-like sequences.
112 # The bit buffer keeps only the bits not yet emitted: left to grow, it
113 # becomes an integer as wide as the run, and shifting it per sextet
114 # makes the decode quadratic in the run length.
115 num_bytes = total_bits // 8
116 raw = bytearray(num_bytes)
117 bit_buf = 0
118 bit_count = 0
119 out_idx = 0
120 for c in b64_bytes:
121 bit_buf = (bit_buf << 6) | _B64_DECODE[c]
122 bit_count += 6
123 if bit_count >= 8:
124 bit_count -= 8
125 raw[out_idx] = (bit_buf >> bit_count) & 0xFF
126 bit_buf &= (1 << bit_count) - 1
127 out_idx += 1
128 prev_high = False
129 for i in range(0, num_bytes - 1, 2):
130 code_unit = (raw[i] << 8) | raw[i + 1]
131 if 0xD800 <= code_unit <= 0xDBFF: # high surrogate
132 if prev_high:
133 return False # consecutive high surrogates
134 prev_high = True
135 elif 0xDC00 <= code_unit <= 0xDFFF: # low surrogate
136 if not prev_high:
137 return False # lone low surrogate
138 prev_high = False
139 else:
140 if prev_high:
141 return False # high surrogate not followed by low surrogate
142 prev_high = False
143 return not prev_high
144
145
146def _is_embedded_in_base64(data: bytes, pos: int) -> bool:
147 """Return True if the ``+`` at *pos* is embedded in a base64 stream.
148
149 Walks backward from *pos*, skipping CR/LF, and counts consecutive base64
150 characters (including ``=`` for padding). If 4 or more are found, the
151 ``+`` is likely part of a PEM certificate, email attachment, or similar
152 base64 blob rather than a real UTF-7 shift character.
153
154 The walk stops at the fourth character rather than running to the start
155 of the run. Only the ``>= 4`` verdict is used, and newlines are
156 skipped rather than ending the walk, so without the early exit a
157 line-wrapped base64 blob — a PEM file, a MIME attachment, exactly what
158 this guard exists to recognize — makes each ``+`` rescan everything
159 before it, and the caller quadratic in the size of the blob.
160 """
161 b64_with_pad: frozenset[int] = _UTF7_BASE64 | frozenset(b"=")
162 count = 0
163 i = pos - 1
164 while i >= 0:
165 b = data[i]
166 if b in {0x0A, 0x0D}: # skip newlines
167 i -= 1
168 continue
169 if b in b64_with_pad:
170 count += 1
171 if count >= _EMBEDDED_B64_RUN:
172 return True
173 i -= 1
174 else:
175 break
176 return False
177
178
179def _single_unit(b64_data: bytes) -> int:
180 """Decode the first (only) UTF-16 code unit of a single-unit block."""
181 return (
182 (_B64_DECODE[b64_data[0]] << 12)
183 | (_B64_DECODE[b64_data[1]] << 6)
184 | _B64_DECODE[b64_data[2]]
185 ) >> 2
186
187
188def _plausible_lone_unit(unit: int) -> bool:
189 """Script ranges where a lone shifted character plausibly occurs."""
190 return (
191 0x0080 <= unit <= 0x07FF # Latin supp. .. Arabic
192 or 0x0E00 <= unit <= 0x0FFF # Thai, Lao, Tibetan
193 or 0x2000 <= unit <= 0x2BFF # punctuation .. arrows (em dash, euro)
194 or 0x3000 <= unit <= 0x30FF # CJK punctuation, kana
195 or 0x4E00 <= unit <= 0x9FFF # CJK unified
196 or 0xAC00 <= unit <= 0xD7A3 # Hangul
197 or 0xFF00 <= unit <= 0xFFEF # fullwidth forms
198 )
199
200
201def _has_valid_utf7_sequences(data: bytes, max_start: int, max_end: int) -> bool:
202 """Check that *data* contains at least one valid UTF-7 shifted sequence.
203
204 A valid shifted sequence is ``+<base64 chars>`` terminated by either an
205 explicit ``-`` or any non-Base64 character (per RFC 2152). The base64
206 portion must decode to valid UTF-16BE with correct zero-padding bits.
207 The sequence ``+-`` is a literal plus sign and is **not** counted.
208
209 *max_start* bounds where a shift may occur and *max_end* how far its
210 base64 run may reach, so a run that begins inside the evidence window
211 can finish beyond it (ADR-0006). A run that outruns *max_end* is
212 skipped rather than judged on the part that fits: the padding and
213 surrogate checks read a cut run as a different run, and accepting on
214 evidence we did not see is the one direction this must never fail in.
215 """
216 start = 0
217 limit = min(len(data), max_end)
218 while True:
219 shift_pos = data.find(ord("+"), start)
220 if shift_pos == -1 or shift_pos >= max_start:
221 return False
222 pos = shift_pos + 1 # skip the '+'
223 # +- is a literal plus, not a shifted sequence
224 if pos < len(data) and data[pos] == ord("-"):
225 start = pos + 1
226 continue
227 # Guard A: '+' as the first base64 character encodes PUA code points
228 # (U+F800-U+FBFC) which never appear in real text. This catches
229 # patterns like "C++20" and "++row". Skip past ALL consecutive '+'
230 # characters so the next '+' in a run like ``++`` or ``+++`` is not
231 # re-examined as a new shift character.
232 if pos < len(data) and data[pos] == ord("+"):
233 while pos < len(data) and data[pos] == ord("+"):
234 pos += 1
235 start = pos
236 continue
237 # Guard B: if the '+' is embedded in a base64 stream (PEM, email
238 # attachment, etc.), it's not a real UTF-7 shift character.
239 if _is_embedded_in_base64(data, shift_pos):
240 start = pos
241 continue
242 # Collect consecutive Base64 characters
243 i = pos
244 while i < limit and data[i] in _UTF7_BASE64:
245 i += 1
246 if i == limit and limit < len(data) and data[i] in _UTF7_BASE64:
247 # The run outruns the bound — skip it (see the docstring).
248 start = i
249 continue
250 b64_len = i - pos
251 b64_data = data[pos:i]
252 # Guard C: reject base64 blocks with no uppercase letters.
253 # UTF-7 encodes UTF-16BE code points, and the high byte for virtually
254 # every script (Latin Extended, Cyrillic, Arabic, CJK, …) produces
255 # uppercase base64 characters. Sequences without any uppercase like
256 # "row", "foo", "pos" (variable names / English words) or "100", "99"
257 # (digit runs) are almost always ASCII text that accidentally follows a
258 # '+'. Out of 71,510 real UTF-7 base64 blocks in the test corpus, only
259 # 4 lack uppercase letters (0.006%).
260 #
261 # NOTE: this must test for the *absence of uppercase letters*, not
262 # ``bytes.islower()``. ``b"100".islower()`` is ``False`` (there are no
263 # cased characters at all), so an all-digit run like ``+100`` would slip
264 # through an ``islower()`` guard and be misdetected as UTF-7 (issue #371).
265 if b64_len >= 3 and not any(b in _B64_UPPERCASE for b in b64_data):
266 start = i
267 continue
268 # Accept if base64 content is valid UTF-16BE (padding bits check
269 # prevents false positives). Terminator can be '-', any non-Base64
270 # byte, or end of data — all per RFC 2152.
271 if b64_len >= 3 and _is_valid_utf7_b64(b64_data):
272 # Guard D: a block encoding a *single* code unit — with or
273 # without a dash terminator — must decode into a script range
274 # where a lone shifted character plausibly occurs. The corpus's
275 # single-unit blocks live in Latin/Greek/Cyrillic/Hebrew/Arabic
276 # supplements, Thai, general punctuation through arrows (em
277 # dashes and ellipses dominate), CJK, kana, Hangul, and
278 # fullwidth forms. An accidental uppercase run like "+LAY"
279 # (issue #371) decodes to U+2C06, Glagolitic — no genuine lone
280 # block in 149 corpus files lands in such a range. Multi-unit
281 # blocks are untouched: accidental ASCII does not survive the
282 # padding and surrogate checks for long runs.
283 if (b64_len * 6) // 16 == 1:
284 unit = _single_unit(b64_data)
285 if not _plausible_lone_unit(unit):
286 start = i
287 continue
288 return True
289 start = max(pos, i)
290
291
292def utf7_shifts_markup(data: bytes) -> bool:
293 """Return True if a UTF-7 shifted run in *data* decodes to markup syntax.
294
295 ``+ADw-`` is ``<`` in UTF-7, so a shifted run can turn ASCII bytes that
296 carry no tag into one (the UTF-7 XSS that made browsers drop the
297 encoding). Encoders write these characters directly as a rule. Read
298 as UTF-7, a direct character decodes to itself and the shift markers
299 ``+`` and ``-`` are not among them, so the decode holds more of one
300 than the bytes do exactly when a run shifted it.
301
302 *data* must already decode as UTF-7 the way
303 :func:`~chardet._utils.decodes_without_error` checks it, with the last
304 chunk left open. The decode here is chunked the same way, so the
305 transient text stays bounded on a large window, but the last chunk is
306 closed. An open decode buffers a run the window cuts off, so a tag
307 smuggled right at the edge would otherwise go uncounted; closing it
308 yields every character the run completed. A run cut inside a
309 character is replaced rather than raised, since the caller has already
310 accepted the window.
311 """
312 decoder = codecs.getincrementaldecoder("utf-7")("replace")
313 decoded = dict.fromkeys(_MARKUP_CHARS, 0)
314 size = len(data)
315 for pos in range(0, size, _DECODE_CHUNK_SIZE):
316 end = pos + _DECODE_CHUNK_SIZE
317 text = decoder.decode(data[pos:end], final=end >= size)
318 for ch in _MARKUP_CHARS:
319 decoded[ch] += text.count(ch)
320 return any(decoded[ch] > data.count(ord(ch)) for ch in _MARKUP_CHARS)
321
322
323def _iso2022_variant(data: bytes) -> tuple[str, str] | None:
324 """Name the ISO-2022 variant whose designations appear in *data*.
325
326 :returns: ``(encoding, language)`` or ``None`` when no designation is
327 present.
328 """
329 # ISO-2022-JP-2004: JIS X 0213 designations are unique to this variant.
330 # Python's codec reads the 2004 plane-1 (Q) and plane-2 (P) designations
331 # but not the 2000 plane-1 one (O), so an O stream fails the decode gate
332 # below and the other stages answer; naming it here would hand the
333 # caller an encoding that raises.
334 if b"\x1b$(O" in data or b"\x1b$(P" in data or b"\x1b$(Q" in data:
335 return "iso2022_jp_2004", "ja"
336
337 # ISO-2022-JP-EXT: JIS X 0201 Kana designation is unique to this variant.
338 if b"\x1b(I" in data:
339 return "iso2022_jp_ext", "ja"
340
341 # ISO-2022-JP base: JIS X 0208/0201/0212 designations.
342 if (
343 b"\x1b$B" in data
344 or b"\x1b$@" in data
345 or b"\x1b(J" in data
346 or b"\x1b$(D" in data # JIS X 0212-1990 (JP-1/JP-2/JP-EXT)
347 ):
348 # SI/SO (0x0E / 0x0F) shift controls -> JP-EXT
349 if b"\x0e" in data and b"\x0f" in data:
350 return "iso2022_jp_ext", "ja"
351 # Default to JP-2: a strict superset of JP and JP-1 that
352 # decodes all base sequences correctly.
353 return "iso2022_jp_2", "ja"
354
355 # ISO-2022-KR: ESC sequence for KS C 5601
356 if b"\x1b$)C" in data:
357 return "iso2022_kr", "ko"
358
359 return None
360
361
362def detect_escape_encoding(data: bytes) -> DetectionResult | None:
363 """Detect ISO-2022, HZ-GB-2312, and UTF-7 from escape/tilde/plus sequences.
364
365 Every answer this stage returns decodes the whole window: a designation
366 is three bytes that ordinary text can contain (``log: ESC $ B is the
367 escape``), and a genuine ISO-2022 or HZ stream can still carry a bad
368 byte past the header. The gate costs one decode per hit only.
369
370 :param data: The raw byte data to examine.
371 :returns: A :class:`DetectionResult` if an escape encoding is found, or ``None``.
372 """
373 has_esc = b"\x1b" in data
374 has_tilde = b"~" in data
375 has_plus = b"+" in data
376
377 if not has_esc and not has_tilde and not has_plus:
378 return None
379
380 if has_esc:
381 variant = _iso2022_variant(data)
382 if variant is not None and decodes_without_error(data, variant[0]):
383 return DetectionResult(
384 encoding=variant[0],
385 confidence=DETERMINISTIC_CONFIDENCE,
386 language=variant[1],
387 )
388
389 # Bounds for the deep validators below. They walk candidate sites in
390 # Python loops whose pathological case is *rejection* — a large tilde-
391 # or plus-heavy file that is neither HZ nor UTF-7 — so where a sequence
392 # may *begin* converges on the evidence cap (ADR-0006). Where it may
393 # *end* is a separate bound, one further window on, so a sequence that
394 # opens just inside the evidence window is judged whole rather than cut
395 # by the boundary and read as malformed. Nothing plausible sits
396 # between the two: a single escape run a quarter of a megabyte long is
397 # not text. Gates that decide whether an answer is *true* stay
398 # exhaustive over the window.
399 max_start = min(len(data), EVIDENCE_CAP_BYTES)
400 max_end = min(len(data), 2 * EVIDENCE_CAP_BYTES)
401
402 # HZ-GB-2312: tilde escapes for GB2312
403 # Require valid GB2312 byte pairs (0x21-0x7E range) between ~{ and ~}
404 # markers.
405 if (
406 has_tilde
407 and b"~{" in data
408 and b"~}" in data
409 and _has_valid_hz_regions(data, max_start, max_end)
410 and decodes_without_error(data, "hz")
411 ):
412 return DetectionResult(
413 encoding="hz",
414 confidence=DETERMINISTIC_CONFIDENCE,
415 language="zh",
416 )
417
418 # UTF-7: plus-sign shifts into Base64-encoded Unicode.
419 # UTF-7 is a 7-bit encoding (RFC 2152): every byte must be in 0x00-0x7F,
420 # checked over the whole window (isascii is exactly that predicate, at C
421 # scan speed). The buffer must also *decode* as UTF-7: tabular ASCII
422 # like "|16847+|" contains "+|", which is illegal (a shift must be
423 # followed by base64 or "-"), so the decode gate kills the
424 # delimited-data false-positive class outright while genuine UTF-7 —
425 # which real encoders emit as valid streams — always passes. The
426 # decoder fails fast on the first bad sequence.
427 #
428 # The decode gate keeps the *whole* window: it is what makes a utf-7
429 # answer true, and this stage returns it at deterministic confidence.
430 # Capping it would let an illegal shift past the cap pass as utf-7 that
431 # the caller's own ``decode`` then rejects.
432 #
433 # It runs *after* the bounded sequence validator, which is the reverse
434 # of the obvious order. A decode gate normally fails fast, but plain
435 # ASCII is valid UTF-7, so on the common case — a large ASCII file
436 # containing a '+' anywhere — it succeeds over every byte instead, at
437 # about a second per 272 MiB. The validator settles the same files
438 # from bounded evidence, leaving the full decode for data that already
439 # looks like UTF-7. Both are pure predicates, so the order changes
440 # only cost.
441 if (
442 has_plus
443 and data.isascii()
444 and _has_valid_utf7_sequences(data, max_start, max_end)
445 and decodes_without_error(data, "utf-7")
446 ):
447 return DetectionResult(
448 encoding="utf-7",
449 confidence=DETERMINISTIC_CONFIDENCE,
450 language=None,
451 )
452
453 return None