1"""Stage 1b: charset declarations (HTML/XML/PEP 263) and the answer they give.
2
3The module has two seams. :func:`iter_declarations` is the parser: it
4reads the head of the data and yields every charset declaration it finds,
5resolved to a registry name, without decoding the window.
6:func:`detect_markup_charset` is the stage: it walks those declarations
7and decides which one, if any, is the answer, including any promotion to
8a Windows superset.
9
10Note: ``from __future__ import annotations`` is intentionally omitted because
11this module is compiled with mypyc, which does not support PEP 563 string
12annotations.
13"""
14
15import re
16from collections.abc import Iterator
17from typing import NamedTuple
18
19from chardet._utils import decodes_without_error
20from chardet.enums import EncodingEra
21from chardet.output_names import display_codec
22from chardet.pipeline import DETERMINISTIC_CONFIDENCE, DetectionResult, PipelineContext
23from chardet.pipeline.structural import compute_structural_score
24from chardet.registry import CJK_SUPERSETS, REGISTRY, lookup_encoding
25
26# Markup charset declarations that commonly refer to a Windows superset
27# encoding rather than the strict standard encoding. Japanese web content
28# almost universally declares "Shift_JIS" but actually uses CP932 extensions;
29# similarly, Korean web content declares "EUC-KR" but uses CP949/UHC.
30# When the declared encoding resolves to the base (key), we check whether
31# ``superset`` is a better answer. ``reported_codec`` is the codec that the
32# *reported* encoding name resolves to for callers: shift_jis_2004 is
33# displayed as "SHIFT_JIS", which standard codec lookup resolves to plain
34# shift_jis, so that is the codec whose decode must not break for the
35# un-promoted name to be safe to report. The pairs come from the
36# registry's superset fact, limited to the multi-byte CJK encodings
37# (ADR-0007).
38
39
40class _Promotion(NamedTuple):
41 """The two names a declared CJK encoding can be reported under."""
42
43 reported_codec: str
44 superset: str
45
46
47_MARKUP_SUPERSET_PROMOTIONS: dict[str, _Promotion] = {
48 name: _Promotion(display_codec(name), superset)
49 for name, superset in CJK_SUPERSETS.items()
50}
51_SCAN_LIMIT = 4096
52
53# Labels that cannot describe a document whose declaration was read as
54# ASCII bytes: UTF-16 and UTF-32 text would have put null bytes between the
55# letters of the tag. The WHATWG prescan reads such a label as UTF-8, and
56# ``x-user-defined`` as windows-1252, so the declared page still has a
57# chance of decoding under the name it is given.
58_SELF_CONTRADICTING_LABELS = frozenset(
59 {"utf-16", "utf-16-be", "utf-16-le", "utf-32", "utf-32-be", "utf-32-le"}
60)
61
62# Labels a browser never decodes the page under: ``utf-7`` is not a WHATWG
63# label at all, and ``hz-gb-2312`` maps to the replacement encoding. Both
64# decoders turn ASCII that is not markup (``+ADw-script+AD4-``,
65# ``<~{~}script>``) into tags, which is why browsers dropped them, so the
66# prescan's answer is to ignore the declaration. The PEP 263 cookie
67# follows the same rule, so a label alone never names either encoding. A
68# genuine UTF-7 or HZ stream is still found from its own bytes by the
69# escape stage.
70_IGNORED_LABELS = frozenset({"utf-7", "hz"})
71
72# A tag scan stops at the next ``<`` as well as at ``>``. A tag that never
73# closes is not a declaration either way, but with ``[^>]`` every unclosed
74# ``<meta`` ran to the end of the head before failing, and a head made of
75# nothing else cost a thousand times a normal one. The price is a literal
76# ``<`` inside an attribute value, which hides that one tag.
77_XML_ENCODING_RE = re.compile(
78 rb"""<\?xml\s[^<>]*encoding\s*=\s*['"]([^'"]+)['"]""", re.IGNORECASE
79)
80_META_TAG_RE = re.compile(rb"<meta\b([^<>]*)>", re.IGNORECASE)
81# DOTALL so a quoted value may span lines.
82_ATTR_RE = re.compile(
83 rb"""([^\s=/>]+)(?:\s*=\s*(?:(["'])(.*?)\2|([^\s>"']+)))?""",
84 re.IGNORECASE | re.DOTALL,
85)
86_CONTENT_CHARSET_RE = re.compile(
87 rb"""charset[\t\n\f\r ]*=[\t\n\f\r ]*(?:(["'])([^"']+)\1|([^\s;"']+))""",
88 re.IGNORECASE,
89)
90
91# PEP 263: encoding declaration in the first two lines of a Python file.
92# https://peps.python.org/pep-0263/
93_PEP263_RE = re.compile(rb"^[ \t\f]*#.*?coding[:=][ \t]*([-\w.]+)")
94_PEP263_BLANK_RE = re.compile(rb"^[ \t\f]*(?:[#\r]|$)")
95
96# Charset declarations in EBCDIC-encoded markup, matched against a cp037
97# decode of the head. Letters, digits, and the anchor characters ``<``,
98# ``>``, ``?``, ``=``, and ``/`` sit at the same code points in every
99# supported EBCDIC code page, so the ``<meta``/``<?xml`` tag anchor, the
100# ``charset=``/``encoding=`` label, and the encoding name itself decode
101# correctly through cp037 regardless of which EBCDIC variant the data
102# actually uses. The tag anchor is required so plain EBCDIC prose that
103# merely mentions ``encoding=NAME`` is not treated as a declaration; the
104# tag span and the declaration tokens are matched by separate regexes so
105# a bogus earlier ``encoding=`` token inside the same tag cannot consume
106# the anchor away from the genuine ``charset=`` that follows it. Quote
107# characters are NOT invariant (e.g. cp1026 moves ``"``), so an optional
108# single junk character stands in for the opening quote. That junk
109# character is grouped with its own trailing whitespace rather than left
110# between two ``\s*`` runs: ``\s*X?\s*`` lets a whitespace byte land in
111# either run, so a value that never arrives (``charset=`` followed by a
112# long space run) backtracks over every split and makes the match
113# quadratic in the whitespace length. ``\s*(?:X\s*)?`` matches the same
114# strings with one way to place each space.
115_EBCDIC_TAG_RE = re.compile(r"<(?:meta|\?xml)[^<>]*", re.IGNORECASE)
116_EBCDIC_DECL_RE = re.compile(
117 r"(?:charset|encoding)\s*=\s*(?:[^\sA-Za-z0-9._-]\s*)?([A-Za-z][A-Za-z0-9._-]+)",
118 re.IGNORECASE,
119)
120
121# High bytes: EBCDIC text is dominated by bytes >= 0x80 (Latin lowercase
122# letters all sit at 0x81+; other scripts likewise), while ASCII-compatible
123# markup is dominated by bytes < 0x80.
124_MARKUP_HIGH_BYTES = bytes(range(0x80, 0x100))
125
126# Minimum fraction of high bytes in the head for an EBCDIC scan to be
127# worth attempting.
128_EBCDIC_SCAN_MIN_HIGH_FRACTION = 0.25
129
130
131class Declaration(NamedTuple):
132 """One charset declaration found in the head of the data.
133
134 :ivar encoding: The registry name the label resolves to under its
135 scanner's rule, or ``None`` when no codec answers to the label.
136 :ivar mime_type: ``text/xml`` for an XML prolog, ``text/html`` for a
137 meta tag, ``text/x-python`` for a PEP 263 coding cookie.
138 """
139
140 encoding: str | None
141 mime_type: str
142
143
144def _ascii_label(raw: bytes) -> str | None:
145 """Return *raw* as a stripped ASCII string, or ``None`` if it is not ASCII."""
146 try:
147 return raw.decode("ascii").strip()
148 except UnicodeDecodeError:
149 return None
150
151
152def _iter_ebcdic_declarations(data: bytes) -> Iterator[Declaration]:
153 """Yield the charset declarations in EBCDIC-encoded markup.
154
155 The ASCII regexes cannot see declarations in EBCDIC bytes, so when the
156 head looks like EBCDIC text (dominated by high bytes), decode it through
157 cp037, the EBCDIC page whose letter and digit positions are shared by
158 all variants, and scan the decoded text. Only declarations naming a
159 MAINFRAME-era encoding are yielded. The MIME type follows the tag the
160 declaration sits in.
161 """
162 head = data[:_SCAN_LIMIT]
163 high_count = len(head) - len(head.translate(None, _MARKUP_HIGH_BYTES))
164 if high_count < len(head) * _EBCDIC_SCAN_MIN_HIGH_FRACTION:
165 return
166 decoded = head.decode("cp037", errors="replace")
167 # Scan every declaration token inside every anchor tag: an unrelated
168 # earlier ``charset=``/``encoding=`` token (a query string in an href,
169 # a bogus attribute in the same tag) must not mask a genuine EBCDIC
170 # declaration after it.
171 for tag in _EBCDIC_TAG_RE.finditer(decoded):
172 for match in _EBCDIC_DECL_RE.finditer(tag.group(0)):
173 encoding = lookup_encoding(match.group(1).strip())
174 if encoding is not None and REGISTRY[encoding].era & EncodingEra.MAINFRAME:
175 is_xml = tag.group(0)[1] == "?"
176 yield Declaration(encoding, "text/xml" if is_xml else "text/html")
177
178
179def _pep263_encoding(raw_name: str) -> str | None:
180 """Resolve a coding cookie the way :func:`tokenize.detect_encoding` does.
181
182 Python folds the ``utf-8-*`` spellings to UTF-8 and ``latin-1``,
183 ``iso-8859-1``, and ``iso-latin-1`` (with or without a suffix) to
184 Latin-1 before it consults the codec registry, so ``iso-latin-1`` is a
185 valid cookie even though no codec answers to it, and ``utf-8-sig``
186 names plain UTF-8 rather than a file that starts with a mark.
187 """
188 name = raw_name[:12].lower().replace("_", "-")
189 if name == "utf-8" or name.startswith("utf-8-"):
190 return "utf-8"
191 if name in ("latin-1", "iso-8859-1", "iso-latin-1") or name.startswith(
192 ("latin-1-", "iso-8859-1-", "iso-latin-1-")
193 ):
194 return "iso8859-1"
195 encoding = lookup_encoding(raw_name)
196 if encoding in _IGNORED_LABELS:
197 return None
198 return encoding
199
200
201def _pep263_declaration(data: bytes) -> Declaration | None:
202 """Return the PEP 263 coding cookie in the first two lines of *data*.
203
204 PEP 263 declarations (e.g. ``# -*- coding: utf-8 -*-``) are only valid
205 on line 1 or line 2 of a Python source file. Both lines have to start
206 inside the first :data:`_SCAN_LIMIT` bytes, the same bound the markup
207 scan uses.
208 """
209 head = data[:_SCAN_LIMIT]
210 # PEP 263 requires a '#' comment marker on line 1 or 2.
211 if b"#" not in head:
212 return None
213 # Python only examines line 2 when line 1 is a comment or blank.
214 lines = head.split(b"\n", 2)
215 match = _PEP263_RE.match(lines[0])
216 if match is None and len(lines) > 1 and _PEP263_BLANK_RE.match(lines[0]):
217 match = _PEP263_RE.match(lines[1])
218 if match is None:
219 return None
220 raw_name = _ascii_label(match.group(1))
221 if raw_name is None:
222 return None
223 return Declaration(_pep263_encoding(raw_name), "text/x-python")
224
225
226def _strip_comments(head: bytes) -> bytes:
227 """Return *head* without its ``<!-- -->`` comments.
228
229 A declaration inside a comment is not a declaration, and the WHATWG
230 prescan skips comments for that reason. As in the prescan, the dashes
231 that open a comment may also close it (``<!-->`` is a whole comment),
232 and a comment that never closes runs to the end of the head.
233 """
234 start = head.find(b"<!--")
235 if start < 0:
236 return head
237 parts: list[bytes] = []
238 pos = 0
239 while start >= 0:
240 parts.append(head[pos:start])
241 end = head.find(b"-->", start + 2)
242 if end < 0:
243 return b"".join(parts)
244 pos = end + 3
245 start = head.find(b"<!--", pos)
246 parts.append(head[pos:])
247 return b"".join(parts)
248
249
250def _markup_encoding(raw_name: str) -> str | None:
251 """Resolve a charset label found in ASCII-compatible markup."""
252 if raw_name.lower() == "x-user-defined":
253 return "cp1252"
254 encoding = lookup_encoding(raw_name)
255 if encoding in _SELF_CONTRADICTING_LABELS:
256 return "utf-8"
257 if encoding in _IGNORED_LABELS:
258 return None
259 return encoding
260
261
262def _meta_attributes(body: bytes) -> dict[bytes, bytes]:
263 """Return the attributes of one meta tag, lowercased by name."""
264 attrs: dict[bytes, bytes] = {}
265 for match in _ATTR_RE.finditer(body):
266 name = match.group(1).lower()
267 if name in attrs:
268 continue
269 value = match.group(3)
270 if value is None:
271 value = match.group(4)
272 if value is not None:
273 attrs[name] = value
274 return attrs
275
276
277def _iter_html_charsets(head: bytes) -> Iterator[bytes]:
278 """Yield charset labels from real meta declarations, in document order.
279
280 ``charset=`` inside some other attribute (a refresh URL, a description)
281 is not a declaration. A declaration is a ``charset`` attribute, or the
282 ``charset`` parameter of an ``http-equiv="content-type"`` tag.
283 ``name="content-type"`` is wrong by the spec but common enough in the
284 wild that it counts too.
285 """
286 for tag in _META_TAG_RE.finditer(head):
287 attrs = _meta_attributes(tag.group(1))
288 charset = attrs.get(b"charset")
289 if charset is not None and charset.strip():
290 yield charset
291 continue
292 equiv = attrs.get(b"http-equiv")
293 if equiv is None:
294 equiv = attrs.get(b"name")
295 content = attrs.get(b"content")
296 if (
297 equiv is not None
298 and content is not None
299 and equiv.strip().lower() == b"content-type"
300 ):
301 found = _CONTENT_CHARSET_RE.search(content)
302 if found:
303 yield found.group(2) if found.group(1) else found.group(3)
304
305
306def iter_declarations(data: bytes) -> Iterator[Declaration]:
307 """Yield every charset declaration in the head of *data*, in scan order.
308
309 The scan order is the order a reader honors them in:
310
311 1. ``<?xml ... encoding="..."?>``
312 2. ``<meta charset="...">`` and ``<meta http-equiv="Content-Type"
313 content="...; charset=...">`` (also with ``name`` in place of
314 ``http-equiv``), in document order
315 3. declarations inside EBCDIC-encoded markup, when the head is
316 dominated by high bytes
317 4. PEP 263 ``# -*- coding: ... -*-`` (first two lines only)
318
319 Markup inside ``<!-- -->`` comments is not scanned. A UTF-16 or UTF-32
320 label is read as UTF-8 and ``x-user-defined`` as windows-1252, as in the
321 WHATWG prescan, since a declaration found in ASCII bytes cannot be
322 describing UTF-16 text. A ``utf-7`` or ``hz-gb-2312`` label resolves
323 to ``None`` in every scanner, the PEP 263 cookie included, since the
324 prescan never decodes a page under either. A label that is not ASCII
325 is skipped.
326
327 This is parsing only: nothing here decodes the window, so whether a
328 declaration is believable is left to :func:`detect_markup_charset`.
329 The scans run lazily, so a consumer that stops at the first answer
330 never pays for the EBCDIC or PEP 263 scan.
331
332 :param data: The raw byte data to scan.
333 :returns: An iterator of :class:`Declaration`.
334 """
335 if not data:
336 return
337
338 head = _strip_comments(data[:_SCAN_LIMIT])
339
340 match = _XML_ENCODING_RE.search(head)
341 if match:
342 raw_name = _ascii_label(match.group(1))
343 if raw_name is not None:
344 yield Declaration(
345 _markup_encoding(raw_name) if raw_name else None, "text/xml"
346 )
347
348 for raw in _iter_html_charsets(head):
349 raw_name = _ascii_label(raw)
350 if raw_name is not None:
351 yield Declaration(_markup_encoding(raw_name), "text/html")
352
353 yield from _iter_ebcdic_declarations(data)
354
355 pep263 = _pep263_declaration(data)
356 if pep263 is not None:
357 yield pep263
358
359
360class _Verdict(NamedTuple):
361 """What one declaration says about the window.
362
363 :ivar answer: The name to report, or ``None``.
364 :ivar settled: Whether the declared encoding or its Windows superset
365 decodes the window, allowed or not. A settled declaration ends
366 the scan even when it has no answer to give: the page named an
367 encoding that fits its bytes, and when the caller's filters rule
368 that out, a later declaration is not more trustworthy for it.
369 Often the later one is a Latin-1 default that decodes any bytes.
370 """
371
372 answer: str | None
373 settled: bool
374
375
376_UNSETTLED = _Verdict(None, settled=False)
377
378
379def _declared_answer(data: bytes, encoding: str, allowed: frozenset[str]) -> _Verdict:
380 """Return what a declaration of *encoding* says about *data*.
381
382 A declaration is an answer only if the declared encoding, or its Windows
383 superset, decodes the whole of *data*, and only if that name is in
384 *allowed*. (When the declared encoding decodes but the narrower codec
385 its display name resolves to does not, the superset is preferred; if
386 that fails too, the declared name stands and rendering keeps the
387 internal name, which decodes.) The decoder stops at the first bad
388 sequence, so a declaration that lies about the header fails as fast as
389 a head-only check would, and a cut multi-byte sequence at the very end
390 is tolerated as everywhere else. A declaration that decodes but names
391 nothing in *allowed* is settled without an answer (see :class:`_Verdict`).
392
393 For a declared CJK encoding with a Windows superset in *allowed*
394 (Shift_JIS and CP932, EUC-KR and CP949), the superset is reported when
395 its structural score on the head is strictly higher and it decodes, or
396 when it decodes and the name the caller would see for the declared
397 encoding does not (a declared Shift_JIS page using NEC extensions, a
398 declared EUC-KR page whose first CP949-only hangul sits past the
399 header). The decode checks read the whole window: what a caller can
400 ``.decode()`` is a fact about their entire input. The structural
401 comparison reads only the first :data:`_SCAN_LIMIT` bytes, since
402 multi-byte structure is uniform enough that the ranking has converged
403 by then. It runs first because it is cheap and settles which decode
404 the answer needs: a 200 kB window decodes in a few hundred
405 microseconds, and every declared page of a promotable encoding comes
406 through here.
407 """
408 promotion = _MARKUP_SUPERSET_PROMOTIONS.get(encoding)
409 if promotion is None or promotion.superset not in allowed:
410 if decodes_without_error(data, encoding):
411 return _Verdict(encoding if encoding in allowed else None, settled=True)
412 # A failed subset is still settled when the superset the caller
413 # ruled out decodes, as a declared EUC-KR page with CP949 hangul is.
414 settled = promotion is not None and decodes_without_error(
415 data, promotion.superset
416 )
417 return _Verdict(None, settled)
418 reported_codec, superset = promotion
419 if encoding not in allowed:
420 # The declared name cannot be reported. The superset stands in for
421 # it only when the declared encoding itself fails the window; a
422 # declaration that decodes is an answer, just not an allowed one.
423 if decodes_without_error(data, encoding):
424 return _Verdict(None, settled=True)
425 if decodes_without_error(data, superset):
426 return _Verdict(superset, settled=True)
427 return _UNSETTLED
428 head = data[:_SCAN_LIMIT]
429 # The orchestrator's context cannot be shared: its structural cache is
430 # keyed by encoding name only, and this scores a different slice.
431 ctx = PipelineContext()
432 base_score = compute_structural_score(head, REGISTRY[encoding], ctx)
433 superset_score = compute_structural_score(head, REGISTRY[superset], ctx)
434 if superset_score > base_score:
435 # The superset fits the structure better; take it if it decodes.
436 if decodes_without_error(data, superset):
437 return _Verdict(superset, settled=True)
438 if decodes_without_error(data, encoding):
439 return _Verdict(encoding, settled=True)
440 return _UNSETTLED
441 # The reported codec is a subset of the declared one: plain shift_jis
442 # decodes nothing that shift_jis_2004 cannot, and euc_kr reports as
443 # itself. So when the reported codec decodes the window, the declared
444 # encoding does too, and a clean declared page costs this one decode.
445 if decodes_without_error(data, reported_codec):
446 return _Verdict(encoding, settled=True)
447 # Decode-safety: if the reported name cannot decode the data, the
448 # superset is the only answer a caller can actually use with
449 # ``.decode()``, regardless of the structural tie.
450 if decodes_without_error(data, superset):
451 return _Verdict(superset, settled=True)
452 # Neither the reported codec nor the superset decodes. The declared
453 # encoding is still the answer if it decodes (a JIS X 0213 character
454 # that only shift_jis_2004 maps); when the reported codec is the same
455 # codec, its failure above already settled that it does not.
456 if reported_codec != encoding and decodes_without_error(data, encoding):
457 return _Verdict(encoding, settled=True)
458 return _UNSETTLED
459
460
461def detect_markup_charset(
462 data: bytes,
463 allowed: frozenset[str],
464 utf8_precheck: DetectionResult | None = None,
465) -> DetectionResult | None:
466 """Return the answer the charset declarations in *data* give, if any.
467
468 Runs before the ASCII and UTF-8 stages so explicit declarations like
469 ``<?xml encoding="iso-8859-1"?>`` are honored even when the bytes
470 happen to be pure ASCII. Declarations from :func:`iter_declarations`
471 are tried in order. One counts only if the name it resolves to, or its
472 Windows superset (see :func:`_declared_answer`), decodes the whole of
473 *data* and is in *allowed*. A declaration that fails to decode is
474 skipped and the next one is tried, so a stale prolog does not hide a
475 correct meta. A declaration that decodes but is filtered out ends the
476 scan with no answer, leaving the page to the later stages, the same as
477 a page without one. Each failed encoding is decoded once: the head can
478 repeat one label hundreds of times, and every try reads the window.
479
480 A declaration is honored over pure ASCII, since the declared encoding
481 decodes those bytes identically, but not over genuine UTF-8 structure:
482 data containing valid multi-byte UTF-8 sequences is UTF-8 regardless of
483 what the (frequently stale) declaration claims, and decoding it as the
484 declared encoding would produce mojibake. So when *utf8_precheck* is
485 a UTF-8 result in *allowed* and the first accepted declaration names
486 something else, that UTF-8 result is returned instead, keeping the
487 declaration's MIME type; only the encoding wins.
488
489 :param data: The raw byte data to scan.
490 :param allowed: The encoding names the caller's filters permit.
491 :param utf8_precheck: The UTF-8 stage's result for *data*, if any.
492 :returns: A :class:`DetectionResult` with confidence 0.95 (or the UTF-8
493 precheck's), or ``None`` when no declaration is accepted.
494 """
495 rejected: set[str] = set()
496 for declaration in iter_declarations(data):
497 encoding = declaration.encoding
498 if encoding is None or encoding in rejected:
499 continue
500 answer, settled = _declared_answer(data, encoding, allowed)
501 if answer is None:
502 if settled:
503 return None
504 rejected.add(encoding)
505 continue
506 if (
507 utf8_precheck is not None
508 and utf8_precheck.encoding != answer
509 and utf8_precheck.encoding in allowed
510 ):
511 return DetectionResult(
512 utf8_precheck.encoding,
513 utf8_precheck.confidence,
514 utf8_precheck.language,
515 declaration.mime_type,
516 )
517 return DetectionResult(
518 encoding=answer,
519 confidence=DETERMINISTIC_CONFIDENCE,
520 language=None,
521 mime_type=declaration.mime_type,
522 )
523 return None