exploderino 1.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- exploderino/__init__.py +27 -0
- exploderino/__main__.py +3 -0
- exploderino/cli.py +188 -0
- exploderino/core.py +857 -0
- exploderino/formats.py +128 -0
- exploderino/ole.py +74 -0
- exploderino/protection.py +135 -0
- exploderino/py.typed +0 -0
- exploderino/xmlfmt.py +270 -0
- exploderino-1.0.1.dist-info/METADATA +232 -0
- exploderino-1.0.1.dist-info/RECORD +15 -0
- exploderino-1.0.1.dist-info/WHEEL +4 -0
- exploderino-1.0.1.dist-info/entry_points.txt +2 -0
- exploderino-1.0.1.dist-info/licenses/LICENSE +202 -0
- exploderino-1.0.1.dist-info/licenses/NOTICE +2 -0
exploderino/formats.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""Format registry and detection for document containers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterable
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from pathlib import Path, PurePosixPath
|
|
8
|
+
|
|
9
|
+
from lxml import etree
|
|
10
|
+
|
|
11
|
+
from . import xmlfmt
|
|
12
|
+
|
|
13
|
+
ZIP_MAGIC = b"PK\x03\x04"
|
|
14
|
+
CONTENT_TYPES_PART = "[Content_Types].xml"
|
|
15
|
+
CONTENT_TYPES_NS = "http://schemas.openxmlformats.org/package/2006/content-types"
|
|
16
|
+
SIGNATURE_CONTENT_TYPE = "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml"
|
|
17
|
+
OLE_MAGIC = b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class Family:
|
|
22
|
+
name: str
|
|
23
|
+
container: str # "zip" or "ole"
|
|
24
|
+
extensions: tuple[str, ...]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
# Containers are detected from magic bytes, so these lists do not limit what can be
|
|
28
|
+
# exploded. They decide which embedded files --recursive treats as documents, and they
|
|
29
|
+
# are the documented set of supported formats (tests check the README lists them all).
|
|
30
|
+
# fmt: off
|
|
31
|
+
FAMILIES: tuple[Family, ...] = (
|
|
32
|
+
Family("Word", "zip", (".docx", ".docm", ".dotx", ".dotm")),
|
|
33
|
+
Family("Excel", "zip", (".xlsx", ".xlsm", ".xltx", ".xltm", ".xlam", ".xlsb")),
|
|
34
|
+
Family(
|
|
35
|
+
"PowerPoint",
|
|
36
|
+
"zip",
|
|
37
|
+
(".pptx", ".pptm", ".potx", ".potm", ".ppsx", ".ppsm", ".ppam", ".sldx", ".sldm", ".thmx"),
|
|
38
|
+
),
|
|
39
|
+
Family("Visio", "zip", (".vsdx", ".vsdm", ".vstx", ".vstm", ".vssx", ".vssm")),
|
|
40
|
+
Family(
|
|
41
|
+
"OpenDocument",
|
|
42
|
+
"zip",
|
|
43
|
+
(
|
|
44
|
+
".odt", ".ott", ".ods", ".ots", ".odp", ".otp", ".odg", ".otg", ".odc", ".otc",
|
|
45
|
+
".odi", ".oti", ".odf", ".otf", ".odm", ".otm", ".oth", ".odb",
|
|
46
|
+
),
|
|
47
|
+
),
|
|
48
|
+
Family("XPS", "zip", (".xps", ".oxps")),
|
|
49
|
+
Family("EPUB", "zip", (".epub",)),
|
|
50
|
+
Family(
|
|
51
|
+
"Legacy Office (OLE)",
|
|
52
|
+
"ole",
|
|
53
|
+
(
|
|
54
|
+
".doc", ".dot", ".wbk", ".xls", ".xlt", ".xla", ".xlw", ".ppt", ".pot", ".pps",
|
|
55
|
+
".ppa", ".vsd", ".vss", ".vst", ".pub", ".mpp", ".mpt", ".msg",
|
|
56
|
+
),
|
|
57
|
+
),
|
|
58
|
+
)
|
|
59
|
+
# fmt: on
|
|
60
|
+
|
|
61
|
+
ZIP_DOCUMENT_EXTENSIONS = frozenset(e for f in FAMILIES if f.container == "zip" for e in f.extensions)
|
|
62
|
+
OLE_DOCUMENT_EXTENSIONS = frozenset(e for f in FAMILIES if f.container == "ole" for e in f.extensions)
|
|
63
|
+
|
|
64
|
+
# Parts that are XML and get pretty-printed on explode (when that is reversible).
|
|
65
|
+
# fmt: off
|
|
66
|
+
XML_EXTENSIONS = (
|
|
67
|
+
".xml", ".rels", ".vml", # OOXML / ODF
|
|
68
|
+
".xhtml", ".html", ".htm", ".opf", ".ncx", # EPUB
|
|
69
|
+
".fdseq", ".fdoc", ".fpage", ".dict", ".struct", ".frag", # XPS
|
|
70
|
+
".psmdcp", ".psdsxs", # OPC core properties and signatures
|
|
71
|
+
)
|
|
72
|
+
# fmt: on
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def sniff(path: Path) -> str | None:
|
|
76
|
+
"""Return "zip", "ole" or None based on the file's magic bytes."""
|
|
77
|
+
with open(path, "rb") as fh:
|
|
78
|
+
head = fh.read(8)
|
|
79
|
+
if head.startswith(ZIP_MAGIC):
|
|
80
|
+
return "zip"
|
|
81
|
+
if head == OLE_MAGIC:
|
|
82
|
+
return "ole"
|
|
83
|
+
return None
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def is_nested_document(name: str, data: bytes) -> bool:
|
|
87
|
+
"""True if a zip entry is itself a ZIP-based document (e.g. an embedded workbook)."""
|
|
88
|
+
return Path(name).suffix.lower() in ZIP_DOCUMENT_EXTENSIONS and data.startswith(ZIP_MAGIC)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def is_xml_name(name: str) -> bool:
|
|
92
|
+
# endswith rather than Path.suffix: the package root "_rels/.rels" has no suffix.
|
|
93
|
+
return name.lower().endswith(XML_EXTENSIONS)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def is_xml_content_type(content_type: str | None) -> bool:
|
|
97
|
+
"""XML by declared media type (images such as image/svg+xml are left alone)."""
|
|
98
|
+
if not content_type or content_type.startswith("image/"):
|
|
99
|
+
return False
|
|
100
|
+
base = content_type.split(";")[0].strip().lower()
|
|
101
|
+
return base.endswith("+xml") or base in ("application/xml", "text/xml")
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def opc_content_types(types_xml: bytes, names: Iterable[str]) -> dict[str, str]:
|
|
105
|
+
"""Content type of each part, from an OPC ``[Content_Types].xml`` (Override, else Default).
|
|
106
|
+
|
|
107
|
+
OPC part names are case-insensitive. Returns {} if the part cannot be parsed.
|
|
108
|
+
"""
|
|
109
|
+
try:
|
|
110
|
+
root = xmlfmt.parse(types_xml)[0].getroot()
|
|
111
|
+
except etree.XMLSyntaxError:
|
|
112
|
+
return {}
|
|
113
|
+
overrides = {
|
|
114
|
+
(el.get("PartName") or "").lstrip("/").lower(): el.get("ContentType") or ""
|
|
115
|
+
for el in root.iter(f"{{{CONTENT_TYPES_NS}}}Override")
|
|
116
|
+
}
|
|
117
|
+
defaults = {
|
|
118
|
+
(el.get("Extension") or "").lower(): el.get("ContentType") or ""
|
|
119
|
+
for el in root.iter(f"{{{CONTENT_TYPES_NS}}}Default")
|
|
120
|
+
}
|
|
121
|
+
types = {}
|
|
122
|
+
for name in names:
|
|
123
|
+
key = name.lower()
|
|
124
|
+
ext = PurePosixPath(key).suffix.lstrip(".")
|
|
125
|
+
content_type = overrides.get(key) or defaults.get(ext)
|
|
126
|
+
if content_type:
|
|
127
|
+
types[name] = content_type
|
|
128
|
+
return types
|
exploderino/ole.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Read-only explode of legacy OLE compound files (.doc, .xls, .ppt, ...)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any, TypeVar
|
|
8
|
+
|
|
9
|
+
_UNSAFE = set('/\\:*?"<>|%')
|
|
10
|
+
_T = TypeVar("_T")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _safe_component(name: str) -> str:
|
|
14
|
+
"""Make an OLE stream name filesystem-safe; control chars become %XX."""
|
|
15
|
+
safe = "".join(f"%{ord(c):02X}" if ord(c) < 0x20 or c in _UNSAFE else c for c in name)
|
|
16
|
+
return "%2E" + safe[1:] if safe in (".", "..") else safe
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _read_stream(ole: Any, parts: list[str]) -> bytes:
|
|
20
|
+
with ole.openstream(parts) as stream:
|
|
21
|
+
return stream.read() # type: ignore[no-any-return]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def explode_ole(
|
|
25
|
+
source: Path, out: Path, take: Callable[[int], None]
|
|
26
|
+
) -> tuple[dict[str, Any], list[str], list[str]]:
|
|
27
|
+
"""Write every stream to a file; return (manifest, encrypted streams, warnings).
|
|
28
|
+
|
|
29
|
+
``take(size)`` is called with each stream's size before it is read, and raises when the
|
|
30
|
+
document exceeds its size budget. Streams can share sectors, so the output can be much
|
|
31
|
+
larger than the file.
|
|
32
|
+
"""
|
|
33
|
+
from .core import MANIFEST_NAME, ExploderinoError, _fold, _write_new
|
|
34
|
+
|
|
35
|
+
try:
|
|
36
|
+
import olefile
|
|
37
|
+
except ImportError as exc:
|
|
38
|
+
raise ExploderinoError(
|
|
39
|
+
"legacy OLE files need the optional 'olefile' package: pip install 'exploderino[ole]'"
|
|
40
|
+
) from exc
|
|
41
|
+
|
|
42
|
+
def parse(call: Callable[..., _T], *args: Any) -> _T:
|
|
43
|
+
# olefile raises many exception types for damaged input
|
|
44
|
+
try:
|
|
45
|
+
return call(*args)
|
|
46
|
+
except Exception as exc:
|
|
47
|
+
raise ExploderinoError(f"damaged OLE file: {exc}") from exc
|
|
48
|
+
|
|
49
|
+
warnings: list[str] = []
|
|
50
|
+
encrypted: list[str] = []
|
|
51
|
+
entries: list[dict[str, Any]] = []
|
|
52
|
+
ole = parse(olefile.OleFileIO, str(source))
|
|
53
|
+
with ole:
|
|
54
|
+
for parts in parse(ole.listdir, True, False):
|
|
55
|
+
rel = [_safe_component(p) for p in parts]
|
|
56
|
+
if _fold(rel[0]) == _fold(MANIFEST_NAME):
|
|
57
|
+
raise ExploderinoError(
|
|
58
|
+
f"OLE file contains a stream named {MANIFEST_NAME}, which exploderino reserves"
|
|
59
|
+
)
|
|
60
|
+
take(parse(ole.get_size, parts))
|
|
61
|
+
data = parse(_read_stream, ole, parts)
|
|
62
|
+
target = out.joinpath(*rel)
|
|
63
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
64
|
+
_write_new(target, data)
|
|
65
|
+
entry: dict[str, Any] = {"stream": parts, "path": "/".join(rel)}
|
|
66
|
+
if parts == ["EncryptedPackage"]:
|
|
67
|
+
entry["encrypted"] = True
|
|
68
|
+
encrypted.append("EncryptedPackage")
|
|
69
|
+
warnings.append(
|
|
70
|
+
"password-protected Office file: the document is inside the encrypted "
|
|
71
|
+
"EncryptedPackage stream; remove the password to work with it"
|
|
72
|
+
)
|
|
73
|
+
entries.append(entry)
|
|
74
|
+
return {"format": "ole", "entries": entries}, encrypted, warnings
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
"""Detect encrypted, obfuscated and digitally signed parts inside ZIP-based documents.
|
|
2
|
+
|
|
3
|
+
Password-protected ODF and DRM-protected EPUB files are ordinary ZIP archives whose
|
|
4
|
+
parts are encrypted by the document format itself; their manifests say which ones.
|
|
5
|
+
Such parts can be extracted and re-packed byte for byte but must never be parsed.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import posixpath
|
|
11
|
+
from collections.abc import Callable, Collection, Container
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from urllib.parse import unquote
|
|
14
|
+
|
|
15
|
+
from lxml import etree
|
|
16
|
+
|
|
17
|
+
from . import xmlfmt
|
|
18
|
+
from .formats import SIGNATURE_CONTENT_TYPE
|
|
19
|
+
|
|
20
|
+
ODF_MANIFEST = "META-INF/manifest.xml"
|
|
21
|
+
EPUB_ENCRYPTION = "META-INF/encryption.xml"
|
|
22
|
+
# ODF manifest namespaces: OASIS ODF, and OpenOffice.org 1.x (still read by LibreOffice).
|
|
23
|
+
MANIFEST_NAMESPACES = (
|
|
24
|
+
"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0",
|
|
25
|
+
"http://openoffice.org/2001/manifest",
|
|
26
|
+
)
|
|
27
|
+
XMLENC_NS = "http://www.w3.org/2001/04/xmlenc#"
|
|
28
|
+
|
|
29
|
+
# EPUB font obfuscation (IDPF and Adobe): a reversible scrambling, not protection.
|
|
30
|
+
FONT_OBFUSCATION = frozenset({"http://www.idpf.org/2008/embedding", "http://ns.adobe.com/pdf/enc#RC"})
|
|
31
|
+
|
|
32
|
+
# Files that DRM schemes add: Adobe ADEPT / Kobo (rights.xml), Readium LCP, Apple FairPlay.
|
|
33
|
+
# Kobo encrypts content without listing it in encryption.xml.
|
|
34
|
+
DRM_MARKERS = ("META-INF/rights.xml", "rights.xml", "META-INF/license.lcpl", "META-INF/sinf.xml")
|
|
35
|
+
|
|
36
|
+
# Signature parts of OPC (OOXML, XPS), ODF and EPUB packages.
|
|
37
|
+
SIGNATURE_DIRS = ("_xmlsignatures/",)
|
|
38
|
+
SIGNATURE_SUFFIXES = (".psdsxs",)
|
|
39
|
+
SIGNATURE_FILES = frozenset(
|
|
40
|
+
{
|
|
41
|
+
"meta-inf/documentsignatures.xml",
|
|
42
|
+
"meta-inf/macrosignatures.xml",
|
|
43
|
+
"meta-inf/packagesignatures.xml",
|
|
44
|
+
"meta-inf/signatures.xml",
|
|
45
|
+
}
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass
|
|
50
|
+
class Protection:
|
|
51
|
+
encrypted: set[str] = field(default_factory=set) # entries stored encrypted
|
|
52
|
+
obfuscated: set[str] = field(default_factory=set) # EPUB fonts with reversible obfuscation
|
|
53
|
+
signatures: list[str] = field(default_factory=list) # digital signature parts
|
|
54
|
+
warnings: list[str] = field(default_factory=list)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def is_signature_part(name: str, content_type: str | None = None) -> bool:
|
|
58
|
+
lower = name.lower()
|
|
59
|
+
return (
|
|
60
|
+
content_type == SIGNATURE_CONTENT_TYPE
|
|
61
|
+
or lower in SIGNATURE_FILES
|
|
62
|
+
or lower.endswith(SIGNATURE_SUFFIXES)
|
|
63
|
+
or (lower.startswith(SIGNATURE_DIRS) and lower.endswith(".xml"))
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def scan(read: Callable[[str], bytes], names: Collection[str], types: dict[str, str]) -> Protection:
|
|
68
|
+
"""Inspect a package. ``read`` returns a member's bytes, ``types`` its OPC content types."""
|
|
69
|
+
found = Protection(signatures=sorted(n for n in names if is_signature_part(n, types.get(n))))
|
|
70
|
+
_scan_odf(read, names, found)
|
|
71
|
+
_scan_epub(read, names, found)
|
|
72
|
+
if found.signatures:
|
|
73
|
+
found.warnings.append(
|
|
74
|
+
"digitally signed: XML is only pretty-printed where that keeps the exact bytes, so an "
|
|
75
|
+
"unedited round trip keeps the signature valid; editing a signed part invalidates it"
|
|
76
|
+
)
|
|
77
|
+
return found
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _scan_odf(read: Callable[[str], bytes], names: Container[str], found: Protection) -> None:
|
|
81
|
+
root = _read_xml(read, ODF_MANIFEST, names, found)
|
|
82
|
+
if root is None:
|
|
83
|
+
return
|
|
84
|
+
for ns in MANIFEST_NAMESPACES:
|
|
85
|
+
for entry in root.iter(f"{{{ns}}}file-entry"):
|
|
86
|
+
path = entry.get(f"{{{ns}}}full-path")
|
|
87
|
+
if path is not None and path in names and entry.find(f"{{{ns}}}encryption-data") is not None:
|
|
88
|
+
found.encrypted.add(path)
|
|
89
|
+
if found.encrypted:
|
|
90
|
+
found.warnings.append(
|
|
91
|
+
f"password-protected document: {len(found.encrypted)} parts are encrypted and were "
|
|
92
|
+
"extracted as opaque bytes; remove the password (e.g. in LibreOffice) to work with them"
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _scan_epub(read: Callable[[str], bytes], names: Container[str], found: Protection) -> None:
|
|
97
|
+
drm: set[str] = set()
|
|
98
|
+
root = _read_xml(read, EPUB_ENCRYPTION, names, found)
|
|
99
|
+
if root is not None:
|
|
100
|
+
for data in root.iter(f"{{{XMLENC_NS}}}EncryptedData"):
|
|
101
|
+
method = data.find(f"{{{XMLENC_NS}}}EncryptionMethod")
|
|
102
|
+
ref = data.find(f"{{{XMLENC_NS}}}CipherData/{{{XMLENC_NS}}}CipherReference")
|
|
103
|
+
uri = ref.get("URI") if ref is not None else None
|
|
104
|
+
if not uri:
|
|
105
|
+
continue
|
|
106
|
+
# URL relative to the container root: percent-decode; "/" and ".." stay at the root.
|
|
107
|
+
path = posixpath.normpath("/" + unquote(uri.split("#")[0])).lstrip("/")
|
|
108
|
+
if path not in names:
|
|
109
|
+
continue
|
|
110
|
+
algorithm = method.get("Algorithm") if method is not None else None
|
|
111
|
+
(found.obfuscated if algorithm in FONT_OBFUSCATION else drm).add(path)
|
|
112
|
+
if drm:
|
|
113
|
+
found.encrypted |= drm
|
|
114
|
+
found.warnings.append(
|
|
115
|
+
f"DRM-protected EPUB: {len(drm)} resources are encrypted and were extracted as opaque bytes"
|
|
116
|
+
)
|
|
117
|
+
else:
|
|
118
|
+
markers = [m for m in DRM_MARKERS if m in names]
|
|
119
|
+
if markers:
|
|
120
|
+
found.warnings.append(
|
|
121
|
+
f"possibly DRM-protected: {', '.join(markers)} is present, so content may be encrypted "
|
|
122
|
+
"even though no encrypted parts are listed"
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _read_xml(
|
|
127
|
+
read: Callable[[str], bytes], name: str, names: Container[str], found: Protection
|
|
128
|
+
) -> etree._Element | None:
|
|
129
|
+
if name not in names:
|
|
130
|
+
return None
|
|
131
|
+
try:
|
|
132
|
+
return xmlfmt.parse(read(name))[0].getroot()
|
|
133
|
+
except etree.XMLSyntaxError:
|
|
134
|
+
found.warnings.append(f"could not read {name}, so encrypted parts cannot be detected")
|
|
135
|
+
return None
|
exploderino/py.typed
ADDED
|
File without changes
|
exploderino/xmlfmt.py
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
"""Reversible XML pretty-printing.
|
|
2
|
+
|
|
3
|
+
Indentation is only added to element-only content (no meaningful text between
|
|
4
|
+
children) outside of ``xml:space="preserve"`` and outside elements whose whitespace
|
|
5
|
+
is content (see ``WHITESPACE_SENSITIVE``). ``condense`` removes exactly that kind of
|
|
6
|
+
whitespace. ``pretty`` additionally checks that compacting its output gives back the
|
|
7
|
+
original: the same XML content (canonical form, which includes all whitespace text) or,
|
|
8
|
+
when ``exact`` is requested, the same bytes. Parts that fail the check are left as stored.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import re
|
|
14
|
+
from collections.abc import Callable
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from lxml import etree
|
|
19
|
+
|
|
20
|
+
XML_SPACE = "{http://www.w3.org/XML/1998/namespace}space"
|
|
21
|
+
UTF8_BOM = b"\xef\xbb\xbf"
|
|
22
|
+
|
|
23
|
+
_ODF_TEXT = "urn:oasis:names:tc:opendocument:xmlns:text:1.0"
|
|
24
|
+
_LOEXT = "urn:org:documentfoundation:names:experimental:office:xmlns:loext:1.0"
|
|
25
|
+
_VISIO = (
|
|
26
|
+
"http://schemas.microsoft.com/office/visio/2012/main",
|
|
27
|
+
"http://schemas.microsoft.com/office/visio/2011/1/core",
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
# Elements whose subtrees are never re-indented, because whitespace between their
|
|
31
|
+
# children is content (ODF paragraphs and scripts, XHTML body, MathML, Visio mixed-content
|
|
32
|
+
# elements, legacy VML text boxes) or is covered by a digital signature (XML-DSig).
|
|
33
|
+
WHITESPACE_SENSITIVE = frozenset(
|
|
34
|
+
{
|
|
35
|
+
f"{{{_ODF_TEXT}}}p",
|
|
36
|
+
f"{{{_ODF_TEXT}}}h",
|
|
37
|
+
f"{{{_LOEXT}}}p",
|
|
38
|
+
f"{{{_LOEXT}}}h",
|
|
39
|
+
"{urn:oasis:names:tc:opendocument:xmlns:office:1.0}script",
|
|
40
|
+
"{http://www.w3.org/1999/xhtml}body",
|
|
41
|
+
"{http://www.w3.org/1998/Math/MathML}math",
|
|
42
|
+
"{urn:schemas-microsoft-com:vml}textbox",
|
|
43
|
+
"{http://www.w3.org/2000/09/xmldsig#}Signature",
|
|
44
|
+
*(f"{{{ns}}}{name}" for ns in _VISIO for name in ("Text", "Cell", "Trigger", "ForeignData")),
|
|
45
|
+
}
|
|
46
|
+
)
|
|
47
|
+
_XML_WHITESPACE = " \t\r\n"
|
|
48
|
+
|
|
49
|
+
# Indentation stops growing below this depth, so a deeply nested part can't make the
|
|
50
|
+
# exploded file many times larger (a few hundred levels of nesting cost no more per line).
|
|
51
|
+
MAX_INDENT_DEPTH = 64
|
|
52
|
+
|
|
53
|
+
# libxml2 2.11 and later keep their protection against entity amplification and excessive
|
|
54
|
+
# depth when huge_tree is on; older versions (bundled with lxml 4) turn it off.
|
|
55
|
+
_HUGE_TREE = etree.LIBXML_VERSION >= (2, 11)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class XmlEncodingError(ValueError):
|
|
59
|
+
"""An edited part contains characters its original encoding cannot represent."""
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass
|
|
63
|
+
class XmlInfo:
|
|
64
|
+
"""What the original serialization looked like, so implode can restore it."""
|
|
65
|
+
|
|
66
|
+
declaration: str | None # exact prolog text incl. trailing whitespace, or None
|
|
67
|
+
encoding: str
|
|
68
|
+
bom: bool
|
|
69
|
+
trailer: str = "" # whitespace after the last top-level node
|
|
70
|
+
|
|
71
|
+
def to_json(self) -> dict[str, Any]:
|
|
72
|
+
return {
|
|
73
|
+
"declaration": self.declaration,
|
|
74
|
+
"encoding": self.encoding,
|
|
75
|
+
"bom": self.bom,
|
|
76
|
+
"trailer": self.trailer,
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
@classmethod
|
|
80
|
+
def from_json(cls, data: dict[str, Any]) -> XmlInfo:
|
|
81
|
+
return cls(data["declaration"], data["encoding"], data["bom"], data["trailer"])
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _parser() -> etree.XMLParser:
|
|
85
|
+
# No entity expansion or network access: exploded files are untrusted input.
|
|
86
|
+
return etree.XMLParser(
|
|
87
|
+
resolve_entities=False,
|
|
88
|
+
no_network=True,
|
|
89
|
+
huge_tree=_HUGE_TREE,
|
|
90
|
+
strip_cdata=False,
|
|
91
|
+
remove_blank_text=False,
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def parse(data: bytes) -> tuple[etree._ElementTree, XmlInfo]:
|
|
96
|
+
"""Parse XML bytes. Raises ``etree.XMLSyntaxError`` if not well-formed.
|
|
97
|
+
|
|
98
|
+
The returned ``XmlInfo`` is only meaningful for ASCII-compatible encodings; see
|
|
99
|
+
``ascii_compatible``. Other parts are never re-serialized.
|
|
100
|
+
"""
|
|
101
|
+
tree = etree.ElementTree(etree.fromstring(data, _parser()))
|
|
102
|
+
bom = data.startswith(UTF8_BOM)
|
|
103
|
+
body = data[len(UTF8_BOM) :] if bom else data
|
|
104
|
+
match = _DECLARATION.match(body)
|
|
105
|
+
info = XmlInfo(
|
|
106
|
+
declaration=match.group(0).decode("ascii") if match else None,
|
|
107
|
+
encoding=tree.docinfo.encoding or "UTF-8",
|
|
108
|
+
bom=bom,
|
|
109
|
+
trailer=body[len(body.rstrip(_XML_WHITESPACE.encode())) :].decode("ascii"),
|
|
110
|
+
)
|
|
111
|
+
return tree, info
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
_DECLARATION = re.compile(rb"<\?xml\s[^>]*\?>\s*")
|
|
115
|
+
_WIDE_BOMS = (b"\xff\xfe", b"\xfe\xff", b"\x00\x00\xfe\xff")
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def ascii_compatible(data: bytes) -> bool:
|
|
119
|
+
"""False for UTF-16/UTF-32 documents, whose prolog this module cannot reproduce."""
|
|
120
|
+
return not data.startswith(_WIDE_BOMS) and b"\x00" not in data[:4]
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def serialize(tree: etree._ElementTree, info: XmlInfo) -> bytes:
|
|
124
|
+
out = etree.tostring(tree, xml_declaration=False, encoding=info.encoding)
|
|
125
|
+
if info.declaration:
|
|
126
|
+
out = info.declaration.encode("ascii") + out
|
|
127
|
+
out += info.trailer.encode("ascii")
|
|
128
|
+
return UTF8_BOM + out if info.bom else out
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _is_ws(text: str | None) -> bool:
|
|
132
|
+
# XML whitespace only: U+00A0, U+3000 and friends are characters, not formatting.
|
|
133
|
+
return text is None or not text.strip(_XML_WHITESPACE)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _element_only(elem: etree._Element, preserve: bool) -> bool:
|
|
137
|
+
if preserve or len(elem) == 0 or not _is_ws(elem.text):
|
|
138
|
+
return False
|
|
139
|
+
# An entity reference (e.g. in EPUB 2 XHTML) is text, so its parent is mixed content.
|
|
140
|
+
return all(_is_ws(child.tail) and not isinstance(child, etree._Entity) for child in elem)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _walk(root: etree._Element, visit: Callable[[etree._Element, bool, int], None]) -> None:
|
|
144
|
+
"""Call ``visit(elem, preserve, depth)`` for every element outside sensitive subtrees."""
|
|
145
|
+
stack = [(root, False, 0)] # iterative: documents can nest deeper than Python's recursion limit
|
|
146
|
+
while stack:
|
|
147
|
+
elem, preserve, depth = stack.pop()
|
|
148
|
+
if elem.tag in WHITESPACE_SENSITIVE:
|
|
149
|
+
continue
|
|
150
|
+
space = elem.get(XML_SPACE)
|
|
151
|
+
if space == "preserve":
|
|
152
|
+
preserve = True
|
|
153
|
+
elif space == "default":
|
|
154
|
+
preserve = False
|
|
155
|
+
visit(elem, preserve, depth)
|
|
156
|
+
stack.extend((child, preserve, depth + 1) for child in elem if isinstance(child.tag, str))
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def indent(tree: etree._ElementTree, unit: str = " ") -> None:
|
|
160
|
+
def visit(elem: etree._Element, preserve: bool, depth: int) -> None:
|
|
161
|
+
if not _element_only(elem, preserve):
|
|
162
|
+
return
|
|
163
|
+
inner = "\n" + unit * min(depth + 1, MAX_INDENT_DEPTH)
|
|
164
|
+
elem.text = inner
|
|
165
|
+
for child in elem:
|
|
166
|
+
child.tail = inner
|
|
167
|
+
elem[-1].tail = "\n" + unit * min(depth, MAX_INDENT_DEPTH)
|
|
168
|
+
|
|
169
|
+
_walk(tree.getroot(), visit)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def condense(tree: etree._ElementTree) -> None:
|
|
173
|
+
def visit(elem: etree._Element, preserve: bool, depth: int) -> None:
|
|
174
|
+
if not _element_only(elem, preserve):
|
|
175
|
+
return
|
|
176
|
+
elem.text = None
|
|
177
|
+
for child in elem:
|
|
178
|
+
child.tail = None
|
|
179
|
+
|
|
180
|
+
_walk(tree.getroot(), visit)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def pretty(data: bytes, *, exact: bool = False) -> tuple[bytes, XmlInfo] | None:
|
|
184
|
+
"""Return indented UTF-8 XML plus the original serialization info.
|
|
185
|
+
|
|
186
|
+
Returns None when the part cannot be pretty-printed reversibly, i.e. when what implode
|
|
187
|
+
would write back differs in XML content from ``data`` (e.g. whitespace that is not just
|
|
188
|
+
formatting, or a UTF-16 prolog) or, with ``exact``, differs at all (lxml normalizes
|
|
189
|
+
attribute order, quotes, empty elements and character references).
|
|
190
|
+
"""
|
|
191
|
+
if not ascii_compatible(data):
|
|
192
|
+
return None
|
|
193
|
+
tree, info = parse(data)
|
|
194
|
+
original = _fingerprint(tree)
|
|
195
|
+
indent(tree)
|
|
196
|
+
standalone = tree.docinfo.standalone
|
|
197
|
+
decl = '<?xml version="1.0" encoding="UTF-8"%s?>\n' % (
|
|
198
|
+
"" if standalone is None else f' standalone="{"yes" if standalone else "no"}"'
|
|
199
|
+
)
|
|
200
|
+
formatted = serialize(tree, XmlInfo(decl, "UTF-8", False, "\n"))
|
|
201
|
+
written = serialize(_condensed(formatted), info) # exactly what implode will produce
|
|
202
|
+
if written == data:
|
|
203
|
+
return formatted, info
|
|
204
|
+
if exact or original is None:
|
|
205
|
+
return None
|
|
206
|
+
try:
|
|
207
|
+
same = _fingerprint(parse(written)[0]) == original
|
|
208
|
+
except etree.XMLSyntaxError:
|
|
209
|
+
same = False
|
|
210
|
+
return (formatted, info) if same else None
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _condensed(data: bytes) -> etree._ElementTree:
|
|
214
|
+
tree, _ = parse(data)
|
|
215
|
+
condense(tree)
|
|
216
|
+
return tree
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _c14n(tree: etree._ElementTree) -> bytes | None:
|
|
220
|
+
try:
|
|
221
|
+
return etree.tostring(tree, method="c14n")
|
|
222
|
+
except (etree.C14NError, ValueError): # e.g. unexpanded entity references
|
|
223
|
+
return None
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _fingerprint(tree: etree._ElementTree) -> tuple[bytes, bytes] | None:
|
|
227
|
+
"""XML content as canonical form plus the DOCTYPE (C14N omits it, including any internal subset)."""
|
|
228
|
+
c14n = _c14n(tree)
|
|
229
|
+
if c14n is None:
|
|
230
|
+
return None
|
|
231
|
+
doctype = b""
|
|
232
|
+
if tree.docinfo.doctype:
|
|
233
|
+
out = etree.tostring(tree)
|
|
234
|
+
end = out.find(b">")
|
|
235
|
+
if b"[" in out[:end]:
|
|
236
|
+
end = out.find(b"]>") + 1
|
|
237
|
+
doctype = out[: end + 1]
|
|
238
|
+
return c14n, doctype
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def compact(data: bytes, info: XmlInfo) -> bytes:
|
|
242
|
+
"""Remove formatting whitespace and re-serialize in the original style.
|
|
243
|
+
|
|
244
|
+
Raises ``XmlEncodingError`` if the part's original encoding cannot represent the edited
|
|
245
|
+
content (libxml2 would write character references where they are not allowed).
|
|
246
|
+
"""
|
|
247
|
+
tree = _condensed(data)
|
|
248
|
+
out = serialize(tree, info)
|
|
249
|
+
if info.encoding.upper().replace("-", "") != "UTF8":
|
|
250
|
+
try:
|
|
251
|
+
ok = _c14n(parse(out)[0]) == _c14n(tree)
|
|
252
|
+
except etree.XMLSyntaxError:
|
|
253
|
+
ok = False
|
|
254
|
+
if not ok:
|
|
255
|
+
raise XmlEncodingError(f"content cannot be represented in the part's encoding ({info.encoding})")
|
|
256
|
+
return out
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def compact_new(data: bytes) -> bytes:
|
|
260
|
+
"""Condense a part added after explode, keeping its own prolog; UTF-16/32 parts are left as is."""
|
|
261
|
+
return compact(data, parse(data)[1]) if ascii_compatible(data) else data
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def same_content(a: bytes, b: bytes) -> bool:
|
|
265
|
+
"""True if two XML documents have the same content (canonical form and DOCTYPE)."""
|
|
266
|
+
try:
|
|
267
|
+
fa = _fingerprint(parse(a)[0])
|
|
268
|
+
return fa is not None and fa == _fingerprint(parse(b)[0])
|
|
269
|
+
except etree.XMLSyntaxError:
|
|
270
|
+
return False
|