File size: 14,666 Bytes
f89c6d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
#!/usr/bin/env python3
"""Verify a complete MindView dataset snapshot; optionally extract its listed assets.

Standard library only. Does not access credentials, networks, or model runtimes.
Use a trusted, pinned snapshot and a destination not modified by other processes.
"""
from __future__ import annotations

import argparse
import hashlib
import json
import os
from pathlib import Path, PurePosixPath
import re
import stat
import sys
import tarfile
import tempfile

CHUNK = 8 * 1024 * 1024
SOURCES = {"scannet", "scannetpp", "arkitscenes"}
SHA = re.compile(r"[0-9a-f]{64}\Z")


class VerificationError(Exception):
    """Invalid package or unsafe extraction request."""


def relative(value: object, label: str) -> str:
    if not isinstance(value, str) or not value or "\\" in value or any(ord(char) < 32 or ord(char) == 127 for char in value):
        raise VerificationError(f"Invalid {label}: {value!r}")
    parts = value.split("/")
    if value.startswith("/") or any(p in {"", ".", ".."} for p in parts):
        raise VerificationError(f"Unsafe {label}: {value!r}")
    if ":" in parts[0] or str(PurePosixPath(value)) != value:
        raise VerificationError(f"Noncanonical {label}: {value!r}")
    return value


def digest_value(value: object, label: str) -> str:
    if not isinstance(value, str) or SHA.fullmatch(value) is None:
        raise VerificationError(f"Invalid SHA256 for {label}")
    return value


def size_value(value: object, label: str) -> int:
    if type(value) is not int or value < 0:
        raise VerificationError(f"Invalid byte size for {label}")
    return value


def check_ancestors(path: Path, *, missing_ok: bool = False) -> None:
    """Reject symlinks and non-directories in every existing parent component."""
    absolute = path.absolute()
    current = Path(absolute.anchor)
    for part in absolute.parts[1:]:
        current = current / part
        try:
            status = current.lstat()
        except FileNotFoundError:
            if missing_ok:
                return
            raise VerificationError(f"Missing directory: {current}") from None
        if stat.S_ISLNK(status.st_mode) or not stat.S_ISDIR(status.st_mode):
            raise VerificationError(f"Expected a real directory, found unsafe component: {current}")


def input_file(repo: Path, name: str) -> Path:
    path = repo / relative(name, "repository path")
    check_ancestors(path.parent)
    try:
        mode = path.lstat().st_mode
    except FileNotFoundError:
        raise VerificationError(f"Missing package file: {name}") from None
    if not stat.S_ISREG(mode):
        raise VerificationError(f"Package file is not a regular file: {name}")
    return path


def open_regular(path: Path):
    flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)
    fd = os.open(path, flags)
    if not stat.S_ISREG(os.fstat(fd).st_mode):
        os.close(fd)
        raise VerificationError(f"Not a regular file: {path}")
    return os.fdopen(fd, "rb")


def hash_stream(stream) -> tuple[str, int]:
    digest = hashlib.sha256()
    total = 0
    while True:
        block = stream.read(CHUNK)
        if not block:
            return digest.hexdigest(), total
        digest.update(block)
        total += len(block)


def file_hash(path: Path) -> tuple[str, int]:
    with open_regular(path) as stream:
        return hash_stream(stream)


def checksum_inventory(repo: Path) -> dict[str, str]:
    checks = {}
    inventory = input_file(repo, "SHA256SUMS")
    with inventory.open("r", encoding="utf-8") as stream:
        for number, line in enumerate(stream, 1):
            line = line.rstrip("\n")
            match = re.fullmatch(r"([0-9a-f]{64}) [ *](.+)", line)
            if match is None:
                raise VerificationError(f"Malformed SHA256SUMS line {number}")
            expected, name = match.groups()
            relative(name, "checksum path")
            if name == "SHA256SUMS" or name in checks:
                raise VerificationError(f"Duplicate/self-referential checksum path: {name}")
            checks[name] = expected
    if not checks:
        raise VerificationError("Empty SHA256SUMS inventory")
    for name, expected in checks.items():
        actual, _ = file_hash(input_file(repo, name))
        if actual != expected:
            raise VerificationError(f"Checksum mismatch: {name}")
    return checks


def read_manifest(repo: Path, checks: dict[str, str]):
    index_name = "manifests/asset_archives.json"
    assets_name = "manifests/assets.jsonl"
    for name in (index_name, assets_name):
        if name not in checks:
            raise VerificationError(f"Missing checksum entry: {name}")
    with input_file(repo, index_name).open("r", encoding="utf-8") as stream:
        index = json.load(stream)
    if not isinstance(index, dict) or not isinstance(index.get("archives"), list):
        raise VerificationError("Archive index must contain an archives list")
    archives = {}
    members = {}
    destinations = set()
    for entry in index["archives"]:
        if not isinstance(entry, dict):
            raise VerificationError("Archive entry must be an object")
        name = relative(entry.get("path"), "archive path")
        if not name.startswith("assets/") or not name.endswith(".tar"):
            raise VerificationError(f"Expected an assets/*.tar archive: {name}")
        if name in archives:
            raise VerificationError(f"Duplicate archive: {name}")
        source = entry.get("dataset")
        if not isinstance(source, str) or source not in SOURCES:
            raise VerificationError(f"Unknown source dataset: {source!r}")
        size_value(entry.get("bytes"), name)
        digest_value(entry.get("sha256"), name)
        if checks.get(name) != entry["sha256"]:
            raise VerificationError(f"Archive hash absent/inconsistent in SHA256SUMS: {name}")
        if input_file(repo, name).stat().st_size != entry["bytes"]:
            raise VerificationError(f"Archive size mismatch: {name}")
        archives[name] = entry
        members[name] = {}
    with input_file(repo, assets_name).open("r", encoding="utf-8") as stream:
        for number, line in enumerate(stream, 1):
            try:
                row = json.loads(line)
            except json.JSONDecodeError as exc:
                raise VerificationError(f"Malformed assets.jsonl line {number}: {exc}") from None
            if not isinstance(row, dict):
                raise VerificationError(f"Asset row {number} is not an object")
            shard = relative(row.get("shard"), "asset shard")
            member = relative(row.get("member"), "TAR member")
            source_path = relative(row.get("relative_path"), "asset source path")
            if shard not in archives:
                raise VerificationError(f"Asset points to an unlisted archive: {shard}")
            if row.get("dataset") != archives[shard]["dataset"]:
                raise VerificationError(f"Dataset mismatch for {shard}:{member}")
            if member != source_path:
                raise VerificationError(f"Member/source path mismatch: {shard}:{member}")
            size_value(row.get("bytes"), member)
            digest_value(row.get("sha256"), member)
            destination = f"{row['dataset']}/{source_path}"
            if member in members[shard] or destination in destinations:
                raise VerificationError(f"Duplicate asset destination: {destination}")
            destinations.add(destination)
            members[shard][member] = row
    ordered_destinations = sorted(destinations)
    for first, second in zip(ordered_destinations, ordered_destinations[1:]):
        if second.startswith(first + "/"):
            raise VerificationError(f"Overlapping asset destinations: {first} and {second}")
    if not destinations or not archives:
        raise VerificationError("Empty asset/archive inventory")
    for name, entries in members.items():
        if not entries:
            raise VerificationError(f"Archive has no listed assets: {name}")
        declared = archives[name].get("num_assets")
        if declared is not None and declared != len(entries):
            raise VerificationError(f"Archive member count mismatch: {name}")
        declared_bytes = archives[name].get("uncompressed_bytes")
        if declared_bytes is not None and declared_bytes != sum(r["bytes"] for r in entries.values()):
            raise VerificationError(f"Archive uncompressed byte count mismatch: {name}")
    return archives, members


def checked_members(repo: Path, name: str, expected: dict):
    """Yield regular, listed members only; the caller must consume all members."""
    seen = set()
    with open_regular(input_file(repo, name)) as stream:
        with tarfile.open(fileobj=stream, mode="r:") as archive:
            for member in archive:
                relative(member.name, "TAR member")
                if not member.isfile() or member.issparse():
                    raise VerificationError(f"Non-regular/sparse TAR member: {name}:{member.name}")
                if member.name in seen or member.name not in expected:
                    raise VerificationError(f"Duplicate/unlisted TAR member: {name}:{member.name}")
                seen.add(member.name)
                row = expected[member.name]
                if member.size != row["bytes"]:
                    raise VerificationError(f"Member size mismatch: {name}:{member.name}")
                payload = archive.extractfile(member)
                if payload is None:
                    raise VerificationError(f"Cannot read TAR member: {name}:{member.name}")
                with payload:
                    yield row, payload
    if seen != set(expected):
        missing = sorted(set(expected) - seen)
        raise VerificationError(f"Missing TAR members in {name}: {missing[:3]}")


def verify_members(repo: Path, members: dict) -> None:
    for name, entries in members.items():
        for row, payload in checked_members(repo, name, entries):
            digest, length = hash_stream(payload)
            if digest != row["sha256"] or length != row["bytes"]:
                raise VerificationError(f"Member checksum mismatch: {name}:{row['member']}")


def output_file(output: Path, row: dict) -> Path:
    path = output / row["dataset"] / row["relative_path"]
    check_ancestors(path.parent, missing_ok=True)
    try:
        mode = path.lstat().st_mode
    except FileNotFoundError:
        return path
    if not stat.S_ISREG(mode):
        raise VerificationError(f"Existing output is not a regular file: {path}")
    actual, length = file_hash(path)
    if actual != row["sha256"] or length != row["bytes"]:
        raise VerificationError(f"Refusing to overwrite a conflicting output: {path}")
    return path


def extract(repo: Path, output: Path, members: dict) -> tuple[int, int]:
    # Preflight every destination before any writes; identical files are reusable.
    for entries in members.values():
        for row in entries.values():
            output_file(output, row)
    extracted = reused = 0
    for name, entries in members.items():
        for row, payload in checked_members(repo, name, entries):
            path = output_file(output, row)
            if path.exists():
                reused += 1
                # Ensure the second archive traversal still consumes payload safely.
                digest, length = hash_stream(payload)
                if digest != row["sha256"] or length != row["bytes"]:
                    raise VerificationError(f"Archive changed after verification: {name}:{row['member']}")
                continue
            path.parent.mkdir(parents=True, exist_ok=True)
            check_ancestors(path.parent)
            descriptor, temporary = tempfile.mkstemp(prefix=".mindview-", dir=path.parent)
            try:
                digest = hashlib.sha256()
                length = 0
                with os.fdopen(descriptor, "wb") as target:
                    while True:
                        block = payload.read(CHUNK)
                        if not block:
                            break
                        target.write(block)
                        digest.update(block)
                        length += len(block)
                    target.flush()
                    os.fsync(target.fileno())
                if digest.hexdigest() != row["sha256"] or length != row["bytes"]:
                    raise VerificationError(f"Archive changed after verification: {name}:{row['member']}")
                os.chmod(temporary, 0o644)
                # A hard-link install is atomic and refuses to replace an existing path.
                try:
                    os.link(temporary, path, follow_symlinks=False)
                except FileExistsError:
                    output_file(output, row)
                    reused += 1
                else:
                    extracted += 1
            finally:
                Path(temporary).unlink(missing_ok=True)
    return extracted, reused


def main(argv=None) -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--repo", type=Path, default=Path(__file__).resolve().parents[1], help="Complete downloaded dataset repository")
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument("--verify-only", action="store_true", help="Verify all package files and TAR members; write no assets")
    group.add_argument("--output", type=Path, help="Extract under OUTPUT/<source-dataset>/")
    args = parser.parse_args(argv)
    repo = Path(os.path.abspath(args.repo))
    check_ancestors(repo)
    checks = checksum_inventory(repo)
    archives, members = read_manifest(repo, checks)
    verify_members(repo, members)
    result = {"status": "pass", "checksum_files": len(checks), "archives": len(archives), "assets": sum(map(len, members.values())), "mode": "verify-only"}
    if args.output is not None:
        output = Path(os.path.abspath(args.output))
        check_ancestors(output, missing_ok=True)
        if output == repo or repo in output.parents or output in repo.parents:
            raise VerificationError("Extraction directory and package directory must not contain one another")
        created, reused = extract(repo, output, members)
        result.update(mode="verified-extraction", extracted=created, reused=reused)
    print(json.dumps(result, indent=2))
    return 0


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except (VerificationError, OSError, ValueError, tarfile.TarError) as exc:
        print(f"ERROR: {exc}", file=sys.stderr)
        raise SystemExit(1)