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/core.py ADDED
@@ -0,0 +1,857 @@
1
+ """Explode document containers to directories and implode them back."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import codecs
6
+ import hashlib
7
+ import io
8
+ import json
9
+ import os
10
+ import secrets
11
+ import shutil
12
+ import stat
13
+ import tempfile
14
+ import unicodedata
15
+ import zipfile
16
+ import zlib
17
+ from collections.abc import Iterator
18
+ from dataclasses import dataclass, field
19
+ from pathlib import Path
20
+ from typing import IO, Any
21
+
22
+ from lxml import etree
23
+
24
+ from . import __version__, xmlfmt
25
+ from .formats import (
26
+ CONTENT_TYPES_PART,
27
+ is_nested_document,
28
+ is_xml_content_type,
29
+ is_xml_name,
30
+ opc_content_types,
31
+ sniff,
32
+ )
33
+ from .protection import is_signature_part, scan
34
+
35
+ MANIFEST_NAME = ".exploderino.json"
36
+ MANIFEST_VERSION = 1
37
+ DEFAULT_MAX_SIZE = 2 * 1024**3 # refuse documents that inflate beyond 2 GiB in total
38
+ MAX_NESTING = 8 # embedded documents deeper than this are kept as files
39
+ OOXML_EPOCH = (1980, 1, 1, 0, 0, 0)
40
+ UTF8_FLAG = 0x800
41
+
42
+ # The only compression methods OPC, ODF and EPUB packages use. Others (bzip2, LZMA) are
43
+ # refused: zipfile decompresses them in one unbounded call, whatever size they declare.
44
+ COMPRESSION_METHODS = frozenset({zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED})
45
+ NAME_ENCODINGS = ("utf-8", "cp437")
46
+ _READ_CHUNK = 1024 * 1024
47
+
48
+ # OS and editor clutter that implode never packs as a new part. Parts listed in the
49
+ # manifest are always packed, whatever their name.
50
+ IGNORED_NAMES = frozenset({".DS_Store", "Thumbs.db", "desktop.ini", MANIFEST_NAME})
51
+ IGNORED_DIRS = frozenset({".git", ".hg", ".svn"})
52
+
53
+ # What zipfile raises for damaged or unsupported archive data.
54
+ _ZIP_ERRORS = (zipfile.BadZipFile, zlib.error, NotImplementedError, EOFError, ValueError)
55
+
56
+
57
+ class ExploderinoError(Exception):
58
+ """Raised for unsupported, unsafe or malformed input."""
59
+
60
+
61
+ class _SizeLimitError(ExploderinoError):
62
+ """The document inflates beyond the size budget (never downgraded to a warning)."""
63
+
64
+
65
+ @dataclass
66
+ class ExplodeResult:
67
+ """What :func:`explode` produced. See the README's Python API section for each field."""
68
+
69
+ source: Path
70
+ directory: Path
71
+ format: str
72
+ entries: int
73
+ pretty_printed: int = 0
74
+ nested: list[str] = field(default_factory=list)
75
+ encrypted: list[str] = field(default_factory=list)
76
+ signed: bool = False
77
+ warnings: list[str] = field(default_factory=list)
78
+
79
+
80
+ @dataclass
81
+ class ImplodeResult:
82
+ """What :func:`implode` produced. See the README's Python API section for each field."""
83
+
84
+ directory: Path
85
+ output: Path
86
+ entries: int
87
+ added: list[str] = field(default_factory=list)
88
+ missing: list[str] = field(default_factory=list)
89
+
90
+
91
+ @dataclass
92
+ class _Unpacked:
93
+ """What exploding one ZIP package produced (nested packages are folded in)."""
94
+
95
+ manifest: dict[str, Any]
96
+ pretty_printed: int = 0
97
+ nested: list[str] = field(default_factory=list)
98
+ encrypted: list[str] = field(default_factory=list)
99
+ signed: bool = False
100
+ warnings: list[str] = field(default_factory=list)
101
+
102
+ def absorb(self, name: str, child: _Unpacked) -> None:
103
+ self.pretty_printed += child.pretty_printed
104
+ self.nested += [name, *(f"{name}/{n}" for n in child.nested)]
105
+ self.encrypted += [f"{name}/{n}" for n in child.encrypted]
106
+ self.signed |= child.signed
107
+ self.warnings += [f"{name}: {w}" for w in child.warnings]
108
+
109
+
110
+ class _Budget:
111
+ """Bytes still allowed for the whole document, embedded documents included."""
112
+
113
+ def __init__(self, limit: int):
114
+ self.limit = self.remaining = limit
115
+
116
+ def take(self, size: int) -> None:
117
+ self.remaining -= size
118
+ if self.remaining < 0:
119
+ raise _SizeLimitError(f"document inflates beyond the {self.limit} byte limit (--max-size)")
120
+
121
+
122
+ class _RawNameInfo(zipfile.ZipInfo):
123
+ """A ZipInfo that writes its name bytes as given, without the UTF-8 flag.
124
+
125
+ Used to restore non-ASCII names of archives written without the UTF-8 flag (zipfile
126
+ would otherwise re-encode them as flagged UTF-8). Relies on ZipInfo._encodeFilenameFlags,
127
+ which zipfile uses for both the local and the central directory header.
128
+ """
129
+
130
+ __slots__ = ("raw_name",)
131
+ raw_name: bytes
132
+
133
+ def _encodeFilenameFlags(self) -> tuple[bytes, int]:
134
+ return self.raw_name, self.flag_bits & ~UTF8_FLAG
135
+
136
+
137
+ def _fold(name: str) -> str:
138
+ """Key under which two names collide on a case-insensitive file system (APFS, NTFS)."""
139
+ return unicodedata.normalize("NFD", name).casefold()
140
+
141
+
142
+ def _check_name(name: str) -> list[str]:
143
+ """Validate an archive entry name and return its path segments.
144
+
145
+ Besides traversal (``..``, absolute paths, backslashes), this refuses ``:`` in any
146
+ segment, because Windows reads ``x/D:y`` as a path on drive D:, and control characters,
147
+ which could rewrite the terminal when a name is printed.
148
+ """
149
+ parts = name.split("/")
150
+ if name.endswith("/"):
151
+ parts.pop() # explicit directory entry
152
+ unsafe = (
153
+ not parts
154
+ or any(p in ("", ".", "..") or ":" in p for p in parts)
155
+ or "\\" in name
156
+ or any(ord(c) < 0x20 or c == "\x7f" for c in name)
157
+ )
158
+ if unsafe:
159
+ raise ExploderinoError(f"unsafe entry name: {name!r}")
160
+ if _fold(parts[0]) == _fold(MANIFEST_NAME):
161
+ raise ExploderinoError(f"archive contains a part named {MANIFEST_NAME}, which exploderino reserves")
162
+ return parts
163
+
164
+
165
+ def _target(root: Path, parts: list[str]) -> Path:
166
+ """``root`` joined with checked segments, refusing anything that would land outside it."""
167
+ target = root.joinpath(*parts)
168
+ base = os.path.abspath(root)
169
+ if os.path.commonpath([base, os.path.abspath(target)]) != base:
170
+ raise ExploderinoError(f"unsafe entry name: {'/'.join(parts)!r}")
171
+ return target
172
+
173
+
174
+ def _write_new(target: Path, data: bytes) -> None:
175
+ """Create ``target``, failing if a file the file system considers the same already exists."""
176
+ try:
177
+ with open(target, "xb") as fh:
178
+ fh.write(data)
179
+ except (FileExistsError, IsADirectoryError) as exc:
180
+ raise ExploderinoError(f"entry {target.name!r} collides with another entry on disk") from exc
181
+
182
+
183
+ def _decoded_name(info: zipfile.ZipInfo) -> tuple[str, str | None]:
184
+ """The entry's real name, plus the legacy encoding of its bytes if the UTF-8 flag is unset."""
185
+ if info.flag_bits & UTF8_FLAG:
186
+ return info.filename, None
187
+ raw = info.orig_filename.encode("cp437") # zipfile decoded unflagged names as cp437
188
+ if raw.isascii():
189
+ return info.filename, None
190
+ try:
191
+ return raw.decode("utf-8"), "utf-8" # what most tools actually wrote
192
+ except UnicodeDecodeError:
193
+ return info.filename, "cp437"
194
+
195
+
196
+ def _make_sibling_dir(path: Path, suffix: str) -> Path:
197
+ """Create a new, uniquely named hidden directory next to ``path``, honoring the umask."""
198
+ while True:
199
+ candidate = path.with_name(f".{path.name}.{secrets.token_hex(4)}{suffix}")
200
+ try:
201
+ os.mkdir(candidate, 0o777)
202
+ return candidate
203
+ except FileExistsError:
204
+ continue
205
+
206
+
207
+ # --------------------------------------------------------------------------- explode
208
+
209
+
210
+ def explode(
211
+ source: Path | str,
212
+ out_dir: Path | str | None = None,
213
+ *,
214
+ pretty: bool = True,
215
+ recursive: bool = False,
216
+ force: bool = False,
217
+ max_size: int = DEFAULT_MAX_SIZE,
218
+ ) -> ExplodeResult:
219
+ """Unpack ``source`` into ``out_dir`` (default: ``<source>.exploded``).
220
+
221
+ The document is exploded into a temporary directory next to ``out_dir`` and moved into
222
+ place only when everything succeeded, so a failure never touches an existing directory.
223
+
224
+ Raises:
225
+ ExploderinoError: the input is unsupported, unsafe, malformed or too large, or the
226
+ output directory can't be used.
227
+ OSError: a file-system operation failed, e.g. for lack of permission.
228
+ """
229
+ source = Path(source)
230
+ if not source.is_file():
231
+ raise ExploderinoError(f"{source}: not a file")
232
+ out = Path(out_dir) if out_dir else default_exploded_dir(source)
233
+ # Work with the absolute path, so that "-o ." has a parent to build the result in
234
+ final = Path(os.path.abspath(out))
235
+ kind = sniff(source)
236
+ if kind not in ("zip", "ole"):
237
+ raise ExploderinoError(f"{source}: not a ZIP-based or OLE document")
238
+ _check_out_dir(final, force)
239
+
240
+ data = source.read_bytes()
241
+ final.parent.mkdir(parents=True, exist_ok=True)
242
+ staging = _make_sibling_dir(final, ".tmp")
243
+ try:
244
+ budget = _Budget(max_size)
245
+ if kind == "zip":
246
+ unpacked = _explode_zip(data, staging, pretty=pretty, recursive=recursive, budget=budget, depth=0)
247
+ else:
248
+ from .ole import explode_ole
249
+
250
+ manifest, encrypted, warnings = explode_ole(source, staging, budget.take)
251
+ unpacked = _Unpacked(manifest, encrypted=encrypted, warnings=warnings)
252
+ _write_manifest(staging, unpacked.manifest, source.name, data)
253
+ leftover = _move_into_place(staging, final)
254
+ except BaseException:
255
+ shutil.rmtree(staging, ignore_errors=True)
256
+ raise
257
+ if leftover:
258
+ unpacked.warnings.append(leftover)
259
+ return ExplodeResult(
260
+ source=source,
261
+ directory=out,
262
+ format=kind,
263
+ entries=len(unpacked.manifest["entries"]),
264
+ pretty_printed=unpacked.pretty_printed,
265
+ nested=unpacked.nested,
266
+ encrypted=unpacked.encrypted,
267
+ signed=unpacked.signed,
268
+ warnings=unpacked.warnings,
269
+ )
270
+
271
+
272
+ def default_exploded_dir(source: Path) -> Path:
273
+ """Where :func:`explode` writes by default: ``<source>.exploded`` next to the source."""
274
+ return source.with_name(source.name + ".exploded")
275
+
276
+
277
+ def _check_out_dir(out: Path, force: bool) -> None:
278
+ if out.is_symlink():
279
+ raise ExploderinoError(f"{out}: is a symbolic link; choose another output directory")
280
+ if not out.exists():
281
+ return
282
+ if not out.is_dir():
283
+ raise ExploderinoError(f"{out}: exists and is not a directory")
284
+ if any(out.iterdir()):
285
+ if not force:
286
+ raise ExploderinoError(f"{out}: directory is not empty (use --force to replace it)")
287
+ try:
288
+ read_manifest(out)
289
+ except ExploderinoError:
290
+ raise ExploderinoError(
291
+ f"{out}: refusing to replace a directory that was not created by exploderino"
292
+ ) from None
293
+
294
+
295
+ def _move_into_place(staging: Path, out: Path) -> str | None:
296
+ """Replace ``out`` with ``staging``. If that fails, ``out`` is left as it was.
297
+
298
+ An existing ``out`` keeps its identity: its contents are swapped, not the directory itself,
299
+ so it keeps its permissions and can be the current directory. Returns a warning if the
300
+ replaced contents could not be deleted completely.
301
+ """
302
+ if not out.exists():
303
+ os.replace(staging, out)
304
+ return None
305
+ backup = _make_sibling_dir(out, ".old")
306
+ moved_out: list[str] = []
307
+ moved_in: list[str] = []
308
+ try:
309
+ for child in list(out.iterdir()):
310
+ os.replace(child, backup / child.name)
311
+ moved_out.append(child.name)
312
+ for child in list(staging.iterdir()):
313
+ os.replace(child, out / child.name)
314
+ moved_in.append(child.name)
315
+ except BaseException:
316
+ try:
317
+ for name in moved_in:
318
+ os.replace(out / name, staging / name)
319
+ for name in moved_out:
320
+ os.replace(backup / name, out / name)
321
+ os.rmdir(backup)
322
+ except OSError as exc:
323
+ raise ExploderinoError(
324
+ f"{out}: replacing the directory failed, and so did restoring it; "
325
+ f"the previous contents are in {backup}"
326
+ ) from exc
327
+ raise
328
+ os.rmdir(staging)
329
+ shutil.rmtree(backup, ignore_errors=True)
330
+ if backup.exists():
331
+ return f"the replaced directory could not be deleted completely; it was left at {backup}"
332
+ return None
333
+
334
+
335
+ def _open_zip(
336
+ data: bytes, budget: _Budget
337
+ ) -> tuple[zipfile.ZipFile, dict[str, zipfile.ZipInfo], dict[str, str]]:
338
+ """Open an archive and reject anything unsafe before a single file is written.
339
+
340
+ Returns the archive, its members by real name, and the legacy name encoding of members
341
+ whose non-ASCII names were stored without the UTF-8 flag.
342
+ """
343
+ try:
344
+ zf = zipfile.ZipFile(io.BytesIO(data))
345
+ infos = zf.infolist()
346
+ except (*_ZIP_ERRORS, UnicodeDecodeError) as exc:
347
+ raise ExploderinoError(f"corrupt ZIP container: {exc}") from exc
348
+ budget.take(sum(i.file_size for i in infos))
349
+
350
+ members: dict[str, zipfile.ZipInfo] = {}
351
+ legacy: dict[str, str] = {}
352
+ files: set[str] = set()
353
+ dirs: set[str] = set()
354
+ for info in infos:
355
+ name, encoding = _decoded_name(info)
356
+ parts = _check_name(name)
357
+ key = _fold("/".join(parts))
358
+ if key in files or (key in dirs and not info.is_dir()):
359
+ raise ExploderinoError(f"duplicate entry in archive (names collide on disk): {name!r}")
360
+ if info.flag_bits & 0x1:
361
+ raise ExploderinoError(f"entry is encrypted: {name!r}")
362
+ if info.compress_type not in COMPRESSION_METHODS:
363
+ raise ExploderinoError(f"unsupported compression method {info.compress_type}: {name!r}")
364
+ (dirs if info.is_dir() else files).add(key)
365
+ dirs.update(_fold("/".join(parts[:i])) for i in range(1, len(parts)))
366
+ members[name] = info
367
+ if encoding:
368
+ legacy[name] = encoding
369
+ clash = files & dirs
370
+ if clash:
371
+ raise ExploderinoError(f"entry is both a file and a directory: {sorted(clash)[0]!r}")
372
+ return zf, members, legacy
373
+
374
+
375
+ def _read(zf: zipfile.ZipFile, info: zipfile.ZipInfo, name: str) -> bytes:
376
+ """Read an entry in chunks, so it never inflates beyond its declared (budgeted) size."""
377
+ chunks = []
378
+ try:
379
+ with zf.open(info) as fh:
380
+ while True:
381
+ chunk = fh.read(_READ_CHUNK)
382
+ if not chunk:
383
+ break
384
+ chunks.append(chunk)
385
+ except _ZIP_ERRORS as exc:
386
+ raise ExploderinoError(f"cannot read {name!r}: {exc}") from exc
387
+ return b"".join(chunks)
388
+
389
+
390
+ def _explode_zip(
391
+ data: bytes, out: Path, *, pretty: bool, recursive: bool, budget: _Budget, depth: int
392
+ ) -> _Unpacked:
393
+ zf, members, legacy = _open_zip(data, budget)
394
+
395
+ def read(name: str) -> bytes:
396
+ return _read(zf, members[name], name)
397
+
398
+ types = opc_content_types(read(CONTENT_TYPES_PART), members) if CONTENT_TYPES_PART in members else {}
399
+ protection = scan(read, members, types)
400
+ exact = bool(protection.signatures) # signatures cover raw bytes
401
+ unpacked = _Unpacked(
402
+ {"format": "zip", "comment": zf.comment.decode("latin-1"), "entries": []},
403
+ encrypted=sorted(protection.encrypted),
404
+ signed=exact,
405
+ warnings=list(protection.warnings),
406
+ )
407
+ kept_nested = []
408
+
409
+ for name, info in members.items():
410
+ entry: dict[str, Any] = {
411
+ "name": name,
412
+ "compress_type": info.compress_type,
413
+ "date_time": list(info.date_time),
414
+ }
415
+ if name in legacy:
416
+ entry["name_encoding"] = legacy[name]
417
+ unpacked.manifest["entries"].append(entry)
418
+ target = _target(out, _check_name(name))
419
+ if info.is_dir():
420
+ entry["is_dir"] = True
421
+ target.mkdir(parents=True, exist_ok=True)
422
+ continue
423
+
424
+ payload = read(name)
425
+ target.parent.mkdir(parents=True, exist_ok=True)
426
+ nested = recursive and is_nested_document(name, payload)
427
+ if name in protection.encrypted:
428
+ entry["encrypted"] = True # opaque bytes: never parse
429
+ _write_new(target, payload)
430
+ elif nested and (exact or depth >= MAX_NESTING):
431
+ kept_nested.append(name)
432
+ _write_new(target, payload)
433
+ elif nested:
434
+ if _explode_nested(name, payload, target, unpacked, pretty=pretty, budget=budget, depth=depth):
435
+ entry["nested"] = True
436
+ elif (
437
+ pretty
438
+ and (is_xml_name(name) or is_xml_content_type(types.get(name)))
439
+ and (formatted := _pretty(name, payload, exact, unpacked.warnings))
440
+ ):
441
+ budget.take(max(0, len(formatted[0]) - len(payload))) # indentation counts too
442
+ entry["xml"] = formatted[1].to_json()
443
+ _write_new(target, formatted[0])
444
+ unpacked.pretty_printed += 1
445
+ else:
446
+ _write_new(target, payload)
447
+ if name in protection.obfuscated:
448
+ entry["obfuscated"] = True
449
+
450
+ if kept_nested:
451
+ why = "the document is signed" if exact else f"they are nested more than {MAX_NESTING} levels deep"
452
+ unpacked.warnings.append(f"{len(kept_nested)} embedded documents were kept as files because {why}")
453
+ return unpacked
454
+
455
+
456
+ def _explode_nested(
457
+ name: str, payload: bytes, target: Path, unpacked: _Unpacked, *, pretty: bool, budget: _Budget, depth: int
458
+ ) -> bool:
459
+ """Explode an embedded document in place; keep it as a file (with a warning) if it is damaged."""
460
+ try:
461
+ target.mkdir()
462
+ except FileExistsError as exc:
463
+ raise ExploderinoError(f"entry {name!r} collides with another entry on disk") from exc
464
+ try:
465
+ child = _explode_zip(payload, target, pretty=pretty, recursive=True, budget=budget, depth=depth + 1)
466
+ except _SizeLimitError:
467
+ raise
468
+ except ExploderinoError as exc:
469
+ shutil.rmtree(target)
470
+ _write_new(target, payload)
471
+ unpacked.warnings.append(
472
+ f"{name}: embedded document could not be exploded and was kept as a file ({exc})"
473
+ )
474
+ return False
475
+ _write_manifest(target, child.manifest, target.name, payload)
476
+ unpacked.absorb(name, child)
477
+ return True
478
+
479
+
480
+ def _pretty(
481
+ name: str, payload: bytes, exact: bool, warnings: list[str]
482
+ ) -> tuple[bytes, xmlfmt.XmlInfo] | None:
483
+ try:
484
+ return xmlfmt.pretty(payload, exact=exact)
485
+ except etree.XMLSyntaxError:
486
+ warnings.append(f"{name}: not well-formed XML, left as-is")
487
+ return None
488
+
489
+
490
+ def _write_manifest(out: Path, manifest: dict[str, Any], source_name: str, data: bytes) -> None:
491
+ full = {
492
+ "tool": "exploderino",
493
+ "tool_version": __version__,
494
+ "manifest_version": MANIFEST_VERSION,
495
+ "source": {
496
+ "name": source_name,
497
+ "size": len(data),
498
+ "sha256": hashlib.sha256(data).hexdigest(),
499
+ },
500
+ **manifest,
501
+ }
502
+ text = json.dumps(full, indent=2) + "\n"
503
+ try:
504
+ # newline="\n": the same bytes on every platform, so manifests diff cleanly in git
505
+ with open(out / MANIFEST_NAME, "x", encoding="utf-8", newline="\n") as fh:
506
+ fh.write(text)
507
+ except FileExistsError as exc:
508
+ raise ExploderinoError(f"an entry collides on disk with {MANIFEST_NAME}") from exc
509
+
510
+
511
+ def read_manifest(directory: Path | str) -> dict[str, Any]:
512
+ """Read and validate the manifest of an exploded directory.
513
+
514
+ Raises:
515
+ ExploderinoError: there is no manifest, or it is damaged or from an unsupported version.
516
+ """
517
+ path = Path(directory) / MANIFEST_NAME
518
+ if not path.is_file():
519
+ raise ExploderinoError(f"{directory}: no {MANIFEST_NAME} found; not an exploded document")
520
+ try:
521
+ manifest = json.loads(path.read_text(encoding="utf-8"))
522
+ except (ValueError, UnicodeDecodeError) as exc:
523
+ raise ExploderinoError(f"{path}: damaged manifest: {exc}") from exc
524
+ if not isinstance(manifest, dict) or manifest.get("manifest_version") != MANIFEST_VERSION:
525
+ raise ExploderinoError(f"{path}: unsupported or damaged manifest")
526
+ if not _valid_manifest(manifest):
527
+ raise ExploderinoError(f"{path}: damaged manifest (missing or invalid fields)")
528
+ return manifest
529
+
530
+
531
+ # Largest value of each MS-DOS date and time field (year, month, day, hour, minute, second)
532
+ _DOS_DATE_TIME_MAX = (2107, 15, 31, 31, 63, 62)
533
+
534
+
535
+ def _valid_manifest(m: dict[str, Any]) -> bool:
536
+ if m.get("format") == "ole":
537
+ return isinstance(m.get("entries"), list)
538
+ if not (
539
+ m.get("format") == "zip"
540
+ and isinstance(m.get("source"), dict)
541
+ and isinstance(m["source"].get("name"), str)
542
+ and isinstance(m.get("comment", ""), str)
543
+ and _encodable(m.get("comment", ""), "latin-1")
544
+ and isinstance(m.get("entries"), list)
545
+ ):
546
+ return False
547
+ names = set()
548
+ for e in m["entries"]:
549
+ if not _valid_entry(e):
550
+ return False
551
+ key = _fold(e["name"].rstrip("/"))
552
+ if key in names:
553
+ return False # a duplicate would pack the same file twice
554
+ names.add(key)
555
+ return True
556
+
557
+
558
+ def _valid_entry(e: Any) -> bool:
559
+ if not (
560
+ isinstance(e, dict)
561
+ and isinstance(e.get("name"), str)
562
+ and type(e.get("compress_type")) is int
563
+ and e["compress_type"] in COMPRESSION_METHODS
564
+ and isinstance(e.get("date_time"), list)
565
+ and len(e["date_time"]) == 6
566
+ and all(type(x) is int for x in e["date_time"])
567
+ and e["date_time"][0] >= 1980
568
+ and all(0 <= x <= hi for x, hi in zip(e["date_time"], _DOS_DATE_TIME_MAX))
569
+ ):
570
+ return False
571
+ encoding = e.get("name_encoding")
572
+ if encoding is not None and not (encoding in NAME_ENCODINGS and _encodable(e["name"], encoding)):
573
+ return False
574
+ return "xml" not in e or _valid_xml_info(e["xml"])
575
+
576
+
577
+ def _valid_xml_info(x: Any) -> bool:
578
+ if not (
579
+ isinstance(x, dict)
580
+ and (x.get("declaration") is None or isinstance(x.get("declaration"), str))
581
+ and isinstance(x.get("encoding"), str)
582
+ and isinstance(x.get("bom"), bool)
583
+ and isinstance(x.get("trailer"), str)
584
+ ):
585
+ return False
586
+ try:
587
+ codecs.lookup(x["encoding"])
588
+ except LookupError:
589
+ return False
590
+ return (x["declaration"] or "").isascii() and not x["trailer"].strip(" \t\r\n")
591
+
592
+
593
+ def _encodable(text: str, encoding: str) -> bool:
594
+ try:
595
+ text.encode(encoding)
596
+ except UnicodeEncodeError:
597
+ return False
598
+ return True
599
+
600
+
601
+ # --------------------------------------------------------------------------- implode
602
+
603
+
604
+ def implode(directory: Path | str, output: Path | str | None = None, *, force: bool = False) -> ImplodeResult:
605
+ """Rebuild a document from a directory produced by :func:`explode`.
606
+
607
+ The default ``output`` is the directory name without ``.exploded``, or else the original
608
+ file name next to the directory.
609
+
610
+ Raises:
611
+ ExploderinoError: the directory or its manifest is unusable, an edited part is no
612
+ longer well-formed XML, or ``output`` exists and ``force`` is not set.
613
+ OSError: a file-system operation failed, e.g. for lack of permission.
614
+ """
615
+ directory = Path(directory).absolute()
616
+ manifest = read_manifest(directory)
617
+ if manifest["format"] != "zip":
618
+ kind = manifest["format"].upper()
619
+ raise ExploderinoError(
620
+ f"{directory}: {kind} containers are exploded read-only and cannot be imploded"
621
+ )
622
+ out = Path(output) if output else default_imploded_path(directory, manifest)
623
+ if out.is_dir():
624
+ raise ExploderinoError(f"{out}: is a directory; choose an output file with -o")
625
+ if out.exists() and not force:
626
+ raise ExploderinoError(f"{out}: already exists (use --force to overwrite)")
627
+
628
+ out.parent.mkdir(parents=True, exist_ok=True)
629
+ mode = (out.stat().st_mode & 0o7777) if out.exists() else None
630
+ tmp = _create_temp_file(out)
631
+ try:
632
+ with open(tmp, "wb") as fh:
633
+ count, added, missing = _implode_zip(fh, directory, manifest, directory.resolve(), depth=0)
634
+ if mode is not None:
635
+ os.chmod(tmp, mode) # a replaced file keeps its permissions
636
+ os.replace(tmp, out)
637
+ except BaseException:
638
+ tmp.unlink(missing_ok=True)
639
+ raise
640
+ return ImplodeResult(directory=directory, output=out, entries=count, added=added, missing=missing)
641
+
642
+
643
+ def _create_temp_file(out: Path) -> Path:
644
+ """Create an empty, uniquely named file next to ``out``, with permissions from the umask."""
645
+ flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_BINARY", 0)
646
+ while True:
647
+ tmp = out.with_name(f".{out.name}.{secrets.token_hex(4)}.tmp")
648
+ try:
649
+ os.close(os.open(tmp, flags, 0o666))
650
+ return tmp
651
+ except FileExistsError:
652
+ continue
653
+
654
+
655
+ def default_imploded_path(directory: Path, manifest: dict[str, Any]) -> Path:
656
+ """Where :func:`implode` writes by default (see :func:`implode`)."""
657
+ if directory.name.endswith(".exploded"):
658
+ return directory.with_name(directory.name[: -len(".exploded")])
659
+ name = manifest["source"]["name"]
660
+ # The manifest may come from someone else: never let it pick a path or a dotfile
661
+ if not name or name.startswith(".") or any(c in name for c in "/\\:") or name != name.strip():
662
+ raise ExploderinoError(
663
+ f"{directory}: the manifest's source name {name!r} isn't a plain document name; "
664
+ "choose an output file with -o"
665
+ )
666
+ return directory.with_name(name)
667
+
668
+
669
+ def _inside(root: Path, path: Path) -> Path:
670
+ """Refuse symlinks and anything resolving outside the exploded directory."""
671
+ if path.is_symlink():
672
+ raise ExploderinoError(f"{path}: refusing to pack a symbolic link")
673
+ resolved = path.resolve()
674
+ if resolved != root and root not in resolved.parents:
675
+ raise ExploderinoError(f"{path}: resolves outside the exploded directory")
676
+ return path
677
+
678
+
679
+ def _read_regular(path: Path) -> bytes:
680
+ """Read a part's file, refusing FIFOs, devices and sockets (reading could block forever)."""
681
+ if not stat.S_ISREG(path.lstat().st_mode):
682
+ raise ExploderinoError(f"{path}: not a regular file")
683
+ return path.read_bytes()
684
+
685
+
686
+ def _implode_zip(
687
+ fh: IO[bytes], directory: Path, manifest: dict[str, Any], root: Path, depth: int
688
+ ) -> tuple[int, list[str], list[str]]:
689
+ known: set[str] = set()
690
+ nested_dirs: set[Path] = set()
691
+ added: list[str] = []
692
+ missing: list[str] = []
693
+ count = 0
694
+
695
+ with zipfile.ZipFile(fh, "w") as zf:
696
+ for entry in manifest["entries"]:
697
+ name = entry["name"]
698
+ known.add(_fold(name.rstrip("/")))
699
+ path = _inside(root, _target(directory, _check_name(name)))
700
+ info = _zip_info(name, tuple(entry["date_time"]), entry.get("name_encoding"))
701
+ info.compress_type = entry["compress_type"]
702
+
703
+ if entry.get("is_dir"):
704
+ zf.writestr(info, b"")
705
+ count += 1
706
+ continue
707
+ if entry.get("nested") and path.is_dir():
708
+ payload = _implode_nested(path, name, root, depth, added, missing)
709
+ nested_dirs.add(path.resolve())
710
+ elif not path.exists():
711
+ missing.append(name)
712
+ continue
713
+ elif "xml" in entry:
714
+ payload = _compact_xml(path, xmlfmt.XmlInfo.from_json(entry["xml"]))
715
+ else:
716
+ payload = _read_regular(path)
717
+ zf.writestr(info, payload)
718
+ count += 1
719
+
720
+ for path in sorted(_iter_new_files(directory, nested_dirs, root)):
721
+ name = path.relative_to(directory).as_posix()
722
+ if _fold(name) in known: # the same part, spelled differently by the file system
723
+ continue
724
+ _check_name(name)
725
+ info = _zip_info(name, OOXML_EPOCH, None)
726
+ info.compress_type = zipfile.ZIP_DEFLATED
727
+ payload = _read_regular(path)
728
+ if is_xml_name(name):
729
+ try:
730
+ payload = xmlfmt.compact_new(payload)
731
+ except (etree.XMLSyntaxError, xmlfmt.XmlEncodingError) as exc:
732
+ raise ExploderinoError(f"{path}: new part is not well-formed XML: {exc}") from exc
733
+ zf.writestr(info, payload)
734
+ added.append(name)
735
+ count += 1
736
+
737
+ zf.comment = manifest.get("comment", "").encode("latin-1")
738
+ return count, added, missing
739
+
740
+
741
+ def _implode_nested(
742
+ path: Path, name: str, root: Path, depth: int, added: list[str], missing: list[str]
743
+ ) -> bytes:
744
+ """Rebuild an embedded document that explode exploded in place."""
745
+ if depth >= MAX_NESTING:
746
+ raise ExploderinoError(f"{path}: embedded documents are nested more than {MAX_NESTING} levels deep")
747
+ manifest = read_manifest(path)
748
+ if manifest["format"] != "zip":
749
+ raise ExploderinoError(f"{path}: embedded document has an unsupported manifest")
750
+ buf = io.BytesIO()
751
+ _, child_added, child_missing = _implode_zip(buf, path, manifest, root, depth + 1)
752
+ added.extend(f"{name}/{n}" for n in child_added)
753
+ missing.extend(f"{name}/{n}" for n in child_missing)
754
+ return buf.getvalue()
755
+
756
+
757
+ def _zip_info(name: str, date_time: tuple[int, ...], name_encoding: str | None) -> zipfile.ZipInfo:
758
+ if not name_encoding:
759
+ return zipfile.ZipInfo(name, date_time=date_time) # type: ignore[arg-type]
760
+ info = _RawNameInfo(name, date_time=date_time) # type: ignore[arg-type]
761
+ info.raw_name = name.encode(name_encoding)
762
+ return info
763
+
764
+
765
+ def _compact_xml(path: Path, info: xmlfmt.XmlInfo) -> bytes:
766
+ data = _read_regular(path)
767
+ try:
768
+ return xmlfmt.compact(data, info)
769
+ except etree.XMLSyntaxError as exc:
770
+ raise ExploderinoError(f"{path}: XML is no longer well-formed: {exc}") from exc
771
+ except xmlfmt.XmlEncodingError as exc:
772
+ raise ExploderinoError(f"{path}: {exc}") from exc
773
+
774
+
775
+ def _ignored_file(name: str) -> bool:
776
+ """OS clutter, and editor swap and backup files."""
777
+ return name in IGNORED_NAMES or name.startswith(("._", ".#")) or name.endswith(("~", ".swp", ".swo"))
778
+
779
+
780
+ def _iter_new_files(directory: Path, skip_dirs: set[Path], root: Path) -> Iterator[Path]:
781
+ for parent, dirs, files in os.walk(directory):
782
+ parent_path = Path(parent)
783
+ dirs[:] = [d for d in dirs if d not in IGNORED_DIRS]
784
+ for d in dirs:
785
+ _inside(root, parent_path / d)
786
+ dirs[:] = [d for d in dirs if (parent_path / d).resolve() not in skip_dirs]
787
+ for fname in files:
788
+ if _ignored_file(fname):
789
+ continue
790
+ yield _inside(root, parent_path / fname)
791
+
792
+
793
+ # --------------------------------------------------------------------------- verify
794
+
795
+
796
+ def verify(source: Path | str, *, recursive: bool = True, max_size: int = DEFAULT_MAX_SIZE) -> list[str]:
797
+ """Explode and implode ``source`` in a temporary directory; return a list of differences.
798
+
799
+ An empty list means a clean round trip. Only ZIP-based documents can be verified.
800
+
801
+ Raises:
802
+ ExploderinoError: the input can't be exploded or imploded.
803
+ """
804
+ source = Path(source)
805
+ if not source.is_file():
806
+ raise ExploderinoError(f"{source}: not a file")
807
+ if sniff(source) != "zip":
808
+ raise ExploderinoError(f"{source}: only ZIP-based documents can be round-tripped")
809
+ with tempfile.TemporaryDirectory(prefix="exploderino-") as tmp:
810
+ exploded = Path(tmp) / "exploded"
811
+ rebuilt = Path(tmp) / "rebuilt" / source.name
812
+ explode(source, exploded, recursive=recursive, max_size=max_size)
813
+ implode(exploded, rebuilt)
814
+ try:
815
+ return compare_zips(source.read_bytes(), rebuilt.read_bytes())
816
+ except (*_ZIP_ERRORS, UnicodeDecodeError) as exc:
817
+ raise ExploderinoError(f"{source}: cannot compare: {exc}") from exc
818
+
819
+
820
+ def compare_zips(original: bytes, rebuilt: bytes, prefix: str = "") -> list[str]:
821
+ """Differences between two archives: entry names, order, compression, timestamps and content.
822
+
823
+ XML parts count as unchanged when they have the same XML content (canonical form, which
824
+ includes all whitespace text, plus the DOCTYPE), except in digitally signed packages,
825
+ where every part must keep its exact bytes.
826
+ """
827
+ a = zipfile.ZipFile(io.BytesIO(original))
828
+ b = zipfile.ZipFile(io.BytesIO(rebuilt))
829
+ a_names = [i.filename for i in a.infolist()]
830
+ b_names = [i.filename for i in b.infolist()]
831
+ if a_names != b_names:
832
+ return [f"{prefix}entry list differs: {a_names} != {b_names}"]
833
+
834
+ types = opc_content_types(a.read(CONTENT_TYPES_PART), a_names) if CONTENT_TYPES_PART in a_names else {}
835
+ exact = any(is_signature_part(n, types.get(n)) for n in a_names)
836
+ diffs = []
837
+ if a.comment != b.comment:
838
+ diffs.append(f"{prefix}archive comment differs")
839
+ for name in a_names:
840
+ ia, ib = a.getinfo(name), b.getinfo(name)
841
+ if (ia.flag_bits ^ ib.flag_bits) & UTF8_FLAG:
842
+ diffs.append(f"{prefix}{name}: name encoding differs")
843
+ if ia.compress_type != ib.compress_type:
844
+ diffs.append(f"{prefix}{name}: compression {ia.compress_type} != {ib.compress_type}")
845
+ if ia.date_time != ib.date_time:
846
+ diffs.append(f"{prefix}{name}: timestamp {ia.date_time} != {ib.date_time}")
847
+ da, db = a.read(name), b.read(name)
848
+ if da == db:
849
+ continue
850
+ if exact:
851
+ diffs.append(f"{prefix}{name}: bytes differ in a signed package (the signature would break)")
852
+ elif is_nested_document(name, da) and db.startswith(b"PK"):
853
+ # Embedded documents are re-compressed, so compare their parts instead.
854
+ diffs.extend(compare_zips(da, db, prefix=f"{prefix}{name}/"))
855
+ elif not xmlfmt.same_content(da, db):
856
+ diffs.append(f"{prefix}{name}: content differs")
857
+ return diffs