Datasets:
File size: 4,156 Bytes
7527f42 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | #!/usr/bin/env python3
"""Safely extract V-Zero image TAR shards and verify content hashes."""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import shutil
import tarfile
from pathlib import Path, PurePosixPath
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--root", type=Path, required=True, help="Downloaded dataset repository root")
return parser.parse_args()
def sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(8 * 1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def safe_target(root: Path, member: tarfile.TarInfo) -> Path:
archive_path = PurePosixPath(member.name)
if archive_path.is_absolute() or ".." in archive_path.parts:
raise ValueError(f"Unsafe archive member: {member.name}")
if not archive_path.parts or archive_path.parts[0] != "images":
raise ValueError(f"Archive member is outside images/: {member.name}")
target = (root / Path(*archive_path.parts)).resolve()
try:
target.relative_to(root)
except ValueError as error:
raise ValueError(f"Archive member escapes dataset root: {member.name}") from error
return target
def main() -> None:
args = parse_args()
root = args.root.resolve()
manifest_path = root / "release_manifest.json"
shard_root = root / "image_shards"
if not root.is_dir() or not manifest_path.is_file() or not shard_root.is_dir():
raise FileNotFoundError("Dataset root must contain release_manifest.json and image_shards/")
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
expected_count = int(manifest["unique_published_images"])
extracted = 0
reused = 0
shard_paths = sorted(shard_root.glob("*.tar"))
if len(shard_paths) != int(manifest["shard_count"]):
raise ValueError(f"Expected {manifest['shard_count']} shards, found {len(shard_paths)}")
for shard_path in shard_paths:
with tarfile.open(shard_path, mode="r:") as archive:
for member in archive:
target = safe_target(root, member)
if member.isdir():
target.mkdir(parents=True, exist_ok=True)
continue
if not member.isfile():
raise ValueError(f"Unsupported archive member type: {member.name}")
expected_digest = Path(member.name).stem
if len(expected_digest) != 64:
raise ValueError(f"Image filename is not a SHA-256 digest: {member.name}")
if target.is_file():
if target.stat().st_size != member.size or sha256_file(target) != expected_digest:
raise ValueError(f"Existing image has unexpected content: {target}")
reused += 1
continue
target.parent.mkdir(parents=True, exist_ok=True)
temporary = target.with_name(f".{target.name}.tmp")
source = archive.extractfile(member)
if source is None:
raise RuntimeError(f"Unable to read archive member: {member.name}")
with source, temporary.open("wb") as destination:
shutil.copyfileobj(source, destination, length=8 * 1024 * 1024)
if temporary.stat().st_size != member.size or sha256_file(temporary) != expected_digest:
temporary.unlink(missing_ok=True)
raise ValueError(f"Extracted image failed verification: {member.name}")
os.replace(temporary, target)
extracted += 1
actual_count = sum(1 for path in (root / "images").glob("*/*") if path.is_file())
if actual_count != expected_count:
raise ValueError(f"Expected {expected_count} extracted images, found {actual_count}")
print(f"Verified {actual_count:,} images ({extracted:,} extracted, {reused:,} already present)")
if __name__ == "__main__":
main()
|