-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpfc_validator.py
More file actions
821 lines (684 loc) · 29.6 KB
/
Copy pathpfc_validator.py
File metadata and controls
821 lines (684 loc) · 29.6 KB
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
#!/usr/bin/env python3
"""
pfc-validator — Standalone integrity checker for .pfc archives.
Verifies header magic, per-block decompression, and SHA-256 checksums.
CLI:
pfc-validator scan <path> [--output-dir <dir>]
pfc-validator report <results.json> [--format html]
pfc-validator --help
Exit codes:
0 = All files valid
1 = One or more files/blocks have errors
2 = Usage error (invalid args, file not found, etc.)
No external dependencies — uses only Python stdlib + pfc_jsonl binary.
"""
from __future__ import annotations
import argparse
import datetime
import hashlib
import json
import os
import re
import struct
import subprocess
import sys
from pathlib import Path
from typing import Any
# ── Constants ────────────────────────────────────────────────────────────
PFC_MAGIC = b"PFC3"
BIDX_MAGIC = b"PFCI"
BIDX_ENTRY_SIZE = 32
BIDX_HEADER_SIZE = 16
PFC_JSONL_BINARY = os.environ.get("PFC_JSONL_BINARY", "pfc_jsonl")
# ── Logging ──────────────────────────────────────────────────────────────
import logging
logger = logging.getLogger("pfc-validator")
def info(msg: str) -> None:
logger.info(msg)
def warn(msg: str) -> None:
logger.warning(msg)
def error(msg: str) -> None:
logger.error(msg)
# ── BIDX parsing ──────────────────────────────────────────────────────────
def parse_bidx(bidx_path: str | Path) -> list[dict[str, int]] | None:
"""Parse a .pfc.bidx file and return per-block offset/size information."""
bidx = Path(bidx_path)
if not bidx.exists():
return None
data = bidx.read_bytes()
if len(data) < BIDX_HEADER_SIZE or data[:4] != BIDX_MAGIC:
return None
entries_data = data[BIDX_HEADER_SIZE:]
if len(entries_data) % BIDX_ENTRY_SIZE != 0:
warn(f"BIDX file {bidx_path} has unexpected size — entries not aligned")
return None
num_entries = len(entries_data) // BIDX_ENTRY_SIZE
blocks: list[dict[str, int]] = []
for i in range(num_entries):
off = i * BIDX_ENTRY_SIZE
entry = entries_data[off : off + BIDX_ENTRY_SIZE]
if len(entry) < BIDX_ENTRY_SIZE:
break
block_id = struct.unpack_from("<I", entry, 0)[0]
byte_offset = struct.unpack_from("<Q", entry, 4)[0]
block_size = struct.unpack_from("<I", entry, 12)[0]
ts_start = struct.unpack_from("<q", entry, 16)[0]
ts_end = struct.unpack_from("<q", entry, 24)[0]
blocks.append({
"block_id": block_id,
"byte_offset": byte_offset,
"block_size": block_size,
"ts_start": ts_start,
"ts_end": ts_end,
})
return blocks
# ── pfc_jsonl info parsing ───────────────────────────────────────────────
def get_pfc_info(pfc_path: str | Path) -> dict[str, Any]:
"""Run pfc_jsonl info --blocks and parse output."""
result: dict[str, Any] = {"num_blocks": 0, "version": 0, "orig_size": 0,
"comp_size": 0, "block_size": 0, "ratio": 0.0}
try:
proc = subprocess.run(
[PFC_JSONL_BINARY, "info", "--blocks", str(pfc_path)],
capture_output=True, timeout=60,
)
except (FileNotFoundError, subprocess.TimeoutExpired) as e:
result["error"] = str(e)
return result
if proc.returncode != 0:
result["error"] = proc.stderr.decode("utf-8", errors="replace").strip()
return result
out = proc.stdout.decode("utf-8", errors="replace")
result["raw_output"] = out
# Parse header fields
for line in out.splitlines():
m = re.match(r"^Magic:\s+(\S+)", line)
if m:
result["magic"] = m.group(1)
continue
m = re.match(r"^Version:\s+(\d+)", line)
if m:
result["version"] = int(m.group(1))
continue
m = re.match(r"^Blocks:\s+(\d+)", line)
if m:
result["num_blocks"] = int(m.group(1))
continue
m = re.match(r"^Block size:\s+(\d+)\s+(KiB|MiB|GiB)", line)
if m:
result["block_size"] = int(m.group(1))
continue
m = re.match(r"^Orig size:\s+(\d+)", line)
if m:
result["orig_size"] = int(m.group(1))
continue
m = re.match(r"^Comp size:\s+(\d+)", line)
if m:
result["comp_size"] = int(m.group(1))
continue
m = re.match(r"^Ratio:\s+([\d.]+)%", line)
if m:
result["ratio"] = float(m.group(1))
continue
# Parse block table from --blocks output
# Format: IDX OFFSET COMP_SIZE TS_START TS_END
in_block_table = False
for line in out.splitlines():
if line.startswith("Block table"):
in_block_table = True
continue
if not in_block_table:
continue
# Skip header line (IDX OFFSET ...)
if line.startswith(" IDX"):
continue
if not line.strip():
continue
m = re.match(
r"\s+(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(\S+)",
line
)
if m:
result.setdefault("blocks", []).append({
"idx": int(m.group(1)),
"offset": int(m.group(2)),
"comp_size": int(m.group(3)),
"ts_start": m.group(4),
"ts_end": m.group(5),
})
return result
# ── File utilities ───────────────────────────────────────────────────────
def get_file_size(path: str | Path) -> int:
return os.path.getsize(path)
def get_file_mtime(path: str | Path) -> str:
ts = os.path.getmtime(path)
return datetime.datetime.fromtimestamp(ts, tz=datetime.timezone.utc).isoformat()
def sha256_file(path: str | Path) -> str:
"""Compute SHA-256 of entire file (streaming, OOM-safe)."""
h = hashlib.sha256()
with open(path, "rb") as f:
while True:
chunk = f.read(64 * 1024)
if not chunk:
break
h.update(chunk)
return h.hexdigest()
def sha256_block(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def format_bytes(n: int) -> str:
for unit in ("B", "KB", "MB", "GB", "TB"):
if abs(n) < 1024:
return f"{n:.1f} {unit}"
n /= 1024
return f"{n:.1f} PB"
# ── Block verification ───────────────────────────────────────────────────
def verify_block_decompression(
pfc_path: str | Path, block_id: int
) -> dict[str, Any]:
"""Try to decompress a single block using pfc_jsonl seek-block."""
result: dict[str, Any] = {
"block_id": block_id,
"decompression_ok": False,
"exit_code": -1,
"stderr": "",
}
try:
proc = subprocess.run(
[PFC_JSONL_BINARY, "seek-block", "-q", str(block_id), str(pfc_path), "/dev/null"],
capture_output=True,
timeout=120,
)
result["exit_code"] = proc.returncode
result["stderr"] = proc.stderr.decode("utf-8", errors="replace").strip()
if proc.returncode == 0:
result["decompression_ok"] = True
stderr_text = result["stderr"]
m = re.search(r"Block \d+: (\d+) bytes decompressed", stderr_text)
if m:
result["decompressed_bytes"] = int(m.group(1))
else:
result["decompression_ok"] = False
stderr_text = result["stderr"]
if "not a valid block" in stderr_text.lower():
result["error_type"] = "invalid_block"
elif "out of range" in stderr_text.lower():
result["error_type"] = "block_out_of_range"
else:
result["error_type"] = "decompression_failed"
except FileNotFoundError:
result["decompression_ok"] = False
result["error_type"] = "binary_not_found"
result["stderr"] = (
f"pfc_jsonl binary not found. Install from "
f"https://github.com/ImpossibleForge/pfc-jsonl"
)
except subprocess.TimeoutExpired:
result["decompression_ok"] = False
result["error_type"] = "timeout"
result["stderr"] = "Block decompression timed out after 120s"
except Exception as e:
result["decompression_ok"] = False
result["error_type"] = "exception"
result["stderr"] = str(e)
return result
# ── File scanning ─────────────────────────────────────────────────────────
def scan_pfc_file(
pfc_path: str | Path,
output_dir: str | Path | None = None,
) -> dict[str, Any]:
"""Scan a single .pfc file and produce a validation result."""
pfc = Path(pfc_path)
pfc_abs = str(pfc.resolve())
result: dict[str, Any] = {
"file": pfc_abs,
"file_name": pfc.name,
"file_size": get_file_size(pfc),
"file_mtime": get_file_mtime(pfc),
"scan_timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat(),
"valid": False,
"errors": [],
"warnings": [],
"info": None,
"blocks": [],
"file_sha256": "",
"has_bidx": False,
"summary": {},
}
# ── 1. Check file exists and is readable ──
if not pfc.exists():
result["errors"].append("File does not exist")
return result
if not pfc.is_file():
result["errors"].append("Path is not a file")
return result
# ── 2. Quick PFC3 magic check (before SHA-256 — security: don't hash non-PFC files) ──
magic_ok = False
try:
with open(pfc, "rb") as f:
magic_bytes = f.read(4)
magic_ok = magic_bytes == PFC_MAGIC
except OSError as e:
result["errors"].append(f"Cannot read file: {e}")
return result
if not magic_ok:
result["errors"].append(
f"Not a PFC3 file (magic detected: {magic_bytes.hex() if magic_bytes else 'file too short'})"
)
return result
# ── 3. Compute file SHA-256 ──
try:
result["file_sha256"] = sha256_file(pfc)
except Exception as e:
result["errors"].append(f"Cannot compute SHA-256: {e}")
return result
# ── 3. Get file info via pfc_jsonl info --blocks ──
info_result = get_pfc_info(pfc)
if info_result.get("error"):
result["errors"].append(info_result["error"])
return result
result["info"] = {
"magic": info_result.get("magic", ""),
"version": info_result.get("version", 0),
"num_blocks": info_result.get("num_blocks", 0),
"block_size": info_result.get("block_size", 0),
"block_size_human": format_bytes(info_result.get("block_size", 0)),
"orig_size": info_result.get("orig_size", 0),
"orig_size_human": format_bytes(info_result.get("orig_size", 0)),
"comp_size": info_result.get("comp_size", 0),
"comp_size_human": format_bytes(info_result.get("comp_size", 0)),
"ratio": info_result.get("ratio", 0.0),
}
if info_result.get("magic") != "PFC3":
result["errors"].append(
f"Invalid magic: expected 'PFC3', got '{info_result.get('magic', '?')}'"
)
return result
num_blocks = info_result.get("num_blocks", 0)
if num_blocks == 0:
result["errors"].append("File reports 0 blocks — possibly empty or invalid")
return result
# ── 4. Parse BIDX for block offsets ──
bidx_path = pfc.with_suffix(pfc.suffix + ".bidx")
bidx_blocks = parse_bidx(bidx_path) if bidx_path.exists() else None
result["has_bidx"] = bidx_path.exists()
# ── 5. Verify each block ──
blocks_ok = 0
blocks_fail = 0
for block_id in range(num_blocks):
block_result: dict[str, Any] = {"block_id": block_id}
# a) Look up BIDX info if available
if bidx_blocks and block_id < len(bidx_blocks):
b = bidx_blocks[block_id]
block_result["byte_offset"] = b["byte_offset"]
block_result["compressed_size"] = b["block_size"]
block_result["ts_start"] = b["ts_start"]
block_result["ts_end"] = b["ts_end"]
# Read raw compressed block data for SHA-256
try:
with open(pfc, "rb") as f:
f.seek(b["byte_offset"])
raw_data = f.read(b["block_size"])
block_result["compressed_sha256"] = sha256_block(raw_data)
block_result["raw_read_ok"] = True
except Exception as e:
block_result["raw_read_ok"] = False
block_result["raw_read_error"] = str(e)
warn(f"Block {block_id}: cannot read raw data: {e}")
else:
block_result["byte_offset"] = None
block_result["compressed_size"] = None
block_result["compressed_sha256"] = None
block_result["raw_read_ok"] = False
if not result["has_bidx"]:
block_result["note"] = "No BIDX file — cannot compute per-block SHA-256"
else:
block_result["note"] = "BIDX entry not found for this block"
# b) Verify decompression via seek-block
dec_result = verify_block_decompression(pfc, block_id)
block_result["decompression_ok"] = dec_result["decompression_ok"]
block_result["decompressed_bytes"] = dec_result.get("decompressed_bytes")
block_result["exit_code"] = dec_result["exit_code"]
block_result["stderr"] = dec_result["stderr"]
block_result["error_type"] = dec_result.get("error_type")
# c) Overall block status
if dec_result["decompression_ok"]:
block_result["status"] = "PASS"
blocks_ok += 1
else:
block_result["status"] = "FAIL"
blocks_fail += 1
result["blocks"].append(block_result)
# ── 6. Summary ──
result["summary"] = {
"total_blocks": num_blocks,
"blocks_ok": blocks_ok,
"blocks_fail": blocks_fail,
"has_bidx": result["has_bidx"],
"file_size_bytes": result["file_size"],
"file_size_human": format_bytes(result["file_size"]),
"file_sha256": result["file_sha256"],
}
result["valid"] = blocks_fail == 0 and len(result["errors"]) == 0
return result
# ── HTML Report ───────────────────────────────────────────────────────────
def generate_html_report(results: list[dict[str, Any]]) -> str:
"""Generate an HTML integrity report from scan results."""
num_files = len(results)
total_valid = sum(1 for r in results if r.get("valid", False))
total_blocks = sum(r.get("summary", {}).get("total_blocks", 0) for r in results)
total_fail = sum(r.get("summary", {}).get("blocks_fail", 0) for r in results)
total_errors = sum(len(r.get("errors", [])) for r in results)
now = datetime.datetime.now(datetime.timezone.utc).isoformat()
if total_errors > 0:
overall_status = "ERROR"
overall_color = "#dc3545"
elif total_fail > 0:
overall_status = "CORRUPTED"
overall_color = "#ff8c00"
else:
overall_status = "INTEGRITY OK"
overall_color = "#28a745"
rows_buf: list[str] = []
for r in results:
fname = r.get("file_name", "?")
fsize = r.get("summary", {}).get("file_size_human", "?")
total = r.get("summary", {}).get("total_blocks", 0)
ok = r.get("summary", {}).get("blocks_ok", 0)
fail = r.get("summary", {}).get("blocks_fail", 0)
sha = r.get("summary", {}).get("file_sha256", "")[:16] + "…"
valid = r.get("valid", False)
info_data = r.get("info") or {}
file_status = "✅" if valid else "❌"
file_color = "#28a745" if valid else "#dc3545"
bidx_mark = "✅" if r.get("has_bidx", False) else "❌"
err_output = r.get("errors") or []
version = info_data.get("version", "?")
ratio = info_data.get("ratio", 0)
orig = info_data.get("orig_size_human", "?")
comp = info_data.get("comp_size_human", "?")
block_sz = info_data.get("block_size_human", "?")
# Block details
block_rows: list[str] = []
for b in r.get("blocks", []):
bid = b.get("block_id", 0)
bstatus = b.get("status", "?")
bicon = "✅" if bstatus == "PASS" else "❌"
bcolor = "#28a745" if bstatus == "PASS" else "#dc3545"
dec_bytes = b.get("decompressed_bytes", "")
dec_bytes_str = format_bytes(dec_bytes) if dec_bytes else "—"
csha = b.get("compressed_sha256", "—")
if csha and csha != "—":
csha = csha[:12] + "…"
err_info = ""
if bstatus == "FAIL":
et = b.get("error_type", "")
err_info = f'<span style="color:#dc3545;font-size:0.85rem">({et})</span>'
block_rows.append(
f'<tr style="background:{bcolor}10">'
f"<td>{bid}</td>"
f"<td>{bicon} {bstatus} {err_info}</td>"
f"<td>{dec_bytes_str}</td>"
f"<td><code>{csha}</code></td>"
f"</tr>"
)
errors_lines = ""
if err_output:
for e in r["errors"]:
errors_lines += f'<p class="error-msg">{e}</p>'
blocks_table = ""
if block_rows:
blocks_table = f"""
<details>
<summary>Block details ({total} blocks, {ok} ok, {fail} fail)</summary>
<table class="block-table">
<tr><th>Block</th><th>Status</th><th>Decompressed</th><th>SHA-256</th></tr>
{''.join(block_rows)}
</table>
</details>
"""
errors_section = ""
if errors_lines:
errors_section = f'<div class="errors">{errors_lines}</div>'
rows_buf.append(f"""
<div class="file-card" style="border-left: 4px solid {file_color};">
<h3>{file_status} {fname}</h3>
<table class="meta-table">
<tr><td>Version</td><td>PFC3 v{version}</td></tr>
<tr><td>Size</td><td>{fsize} (orig: {orig} → comp: {comp}, {ratio:.2f}%)</td></tr>
<tr><td>Blocks</td><td>{total} ({ok} ok, {fail} fail) @ {block_sz if block_sz != '?' else '—'}</td></tr>
<tr><td>BIDX present</td><td>{bidx_mark}</td></tr>
<tr><td>SHA-256</td><td><code>{sha if r.get('file_sha256') else '— no data —'}</code></td></tr>
</table>
{errors_section}
{blocks_table}
</div>
""")
html = f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PFC Integrity Report</title>
<style>
* {{ box-sizing: border-box; margin: 0; padding: 0; }}
body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: #0d1117; color: #c9d1d9; padding: 2rem; }}
h1 {{ font-size: 1.8rem; margin-bottom: 0.5rem; }}
.subtitle {{ color: #8b949e; margin-bottom: 2rem; }}
.header {{ display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem; }}
.summary-cards {{ display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 1rem; margin-bottom: 2rem; }}
.stat-card {{ background: #161b22; border: 1px solid #30363d; border-radius: 6px; padding: 1rem; text-align: center; }}
.stat-card .value {{ font-size: 2rem; font-weight: 600; }}
.stat-card .label {{ font-size: 0.8rem; color: #8b949e; margin-top: 0.3rem; }}
.file-card {{ background: #161b22; border: 1px solid #30363d; border-radius: 6px;
padding: 1.5rem; margin-bottom: 1.5rem; }}
.file-card h3 {{ margin-bottom: 1rem; font-size: 1.1rem; }}
.meta-table {{ width: 100%; border-collapse: collapse; margin-bottom: 1rem; }}
.meta-table td {{ padding: 0.3rem 0.5rem; border-bottom: 1px solid #21262d; }}
.meta-table td:first-child {{ color: #8b949e; width: 120px; }}
.block-table {{ width: 100%; border-collapse: collapse; margin-top: 0.5rem; font-size: 0.9rem; }}
.block-table th {{ background: #21262d; padding: 0.5rem; text-align: left; }}
.block-table td {{ padding: 0.4rem; border-bottom: 1px solid #21262d; }}
.errors {{ margin: 0.5rem 0; }}
.error-msg {{ color: #dc3545; font-size: 0.9rem; margin: 0.2rem 0; }}
code {{ background: #21262d; padding: 0.1rem 0.3rem; border-radius: 3px; font-size: 0.85rem; }}
summary {{ cursor: pointer; color: #58a6ff; padding: 0.5rem 0; font-weight: 500; }}
.footer {{ text-align: center; color: #8b949e; margin-top: 3rem; font-size: 0.85rem; }}
.overall-status {{ display: inline-block; background: {overall_color}; color: #0d1117;
padding: 0.3rem 1rem; border-radius: 4px; font-weight: 600; }}
</style>
</head>
<body>
<div class="header">
<div>
<h1>🔍 PFC Integrity Report</h1>
<div class="subtitle">pfc-validator • Generated {now}</div>
</div>
<div class="overall-status">{overall_status}</div>
</div>
<div class="summary-cards">
<div class="stat-card"><div class="value">{num_files}</div><div class="label">Files scanned</div></div>
<div class="stat-card"><div class="value">{total_valid}/{num_files}</div><div class="label">Valid files</div></div>
<div class="stat-card"><div class="value">{total_blocks}</div><div class="label">Total blocks</div></div>
<div class="stat-card"><div class="value" style="color:{'#dc3545' if total_fail>0 else '#28a745'}">{total_fail}</div><div class="label">Failed blocks</div></div>
<div class="stat-card"><div class="value" style="color:{'#dc3545' if total_errors>0 else '#28a745'}">{total_errors}</div><div class="label">Errors</div></div>
</div>
{''.join(rows_buf)}
<div class="footer">
<p>ImpossibleForge pfc-validator • {os.uname().nodename} • Python {sys.version.split()[0]}</p>
</div>
</body>
</html>"""
return html
# ── CLI ───────────────────────────────────────────────────────────────────
def build_arg_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
prog="pfc-validator",
description="Standalone integrity checker for .pfc archives.",
epilog=(
"Examples:\n"
" pfc-validator scan data.pfc\n"
" pfc-validator scan /var/pfc/ --output-dir ./reports/\n"
" pfc-validator report results.json --format html\n"
"\nExit codes: 0 = all valid, 1 = errors found, 2 = usage error"
),
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
"--version", action="version", version="pfc-validator 1.0.0"
)
sub = parser.add_subparsers(dest="command", required=True)
scan = sub.add_parser("scan", help="Scan .pfc file(s) and validate integrity")
scan.add_argument("path", help="Path to a .pfc file or directory containing .pfc files")
scan.add_argument(
"--output-dir", default=".",
help="Directory to write results JSON and HTML (default: current dir)",
)
report = sub.add_parser("report", help="Generate a report from scan results")
report.add_argument("results_file", help="Path to scan results JSON file")
report.add_argument(
"--format", choices=["html", "json"], default="html",
help="Report format (default: html)",
)
report.add_argument(
"--output", default=None,
help="Output file path (default: derived from input filename)",
)
return parser
def cmd_scan(args: argparse.Namespace) -> int:
path = Path(args.path)
# ── C-3: Graceful error on unreadable paths (too long, broken symlink, etc.) ──
try:
path_exists = path.exists()
path_is_file = path.is_file()
path_is_dir = path.is_dir()
except OSError as e:
error(f"Cannot access path: {e}")
return 2
if not path_exists:
error(f"Path not found: {path}")
return 2
# ── C-1: Validate output directory ──
output_dir_raw = args.output_dir
try:
output_dir = Path(output_dir_raw).resolve()
cwd = Path.cwd().resolve()
# Safe if: (a) relative path (stays under CWD), or (b) absolute under /tmp/
if output_dir.is_absolute():
safe_prefixes = [Path("/tmp/")]
if not any(str(output_dir).startswith(str(p)) for p in safe_prefixes):
error(
f"Security: output-dir '{output_dir_raw}' resolves to '{output_dir}' — "
f"absolute paths outside /tmp/ are not allowed. "
f"Use a relative path (under current dir) or an absolute path under /tmp/."
)
return 2
except OSError as e:
error(f"Cannot resolve output directory: {e}")
return 2
if path.is_dir():
pfc_files = sorted(path.glob("*.pfc"))
if not pfc_files:
error(f"No .pfc files found in {path}")
return 2
info(f"Found {len(pfc_files)} .pfc file(s) in {path}")
elif path.is_file():
pfc_files = [path]
else:
error(f"Invalid path: {path}")
return 2
all_results: list[dict[str, Any]] = []
has_error = False
for pfc_file in pfc_files:
info(f"Scanning {pfc_file.name}…")
try:
result = scan_pfc_file(pfc_file)
all_results.append(result)
if result.get("valid", False):
info(f" ✅ {pfc_file.name} — {result['summary']['total_blocks']} blocks OK")
else:
fail_count = result.get("summary", {}).get("blocks_fail", 0)
err_count = len(result.get("errors", []))
if err_count > 0:
for e in result["errors"]:
warn(f" ERROR: {e}")
has_error = True
if fail_count > 0:
warn(f" FAIL: {fail_count} corrupted block(s) in {pfc_file.name}")
has_error = True
except Exception as e:
error(f" EXCEPTION scanning {pfc_file.name}: {e}")
has_error = True
output_dir = Path(args.output_dir)
if output_dir.exists() and not output_dir.is_dir():
error(f"Output path '{output_dir}' exists and is not a directory")
return 2
output_dir.mkdir(parents=True, exist_ok=True)
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
results_payload = {
"tool": "pfc-validator",
"version": "1.0.0",
"scan_timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat(),
"hostname": os.uname().nodename,
"pfc_jsonl_binary": PFC_JSONL_BINARY,
"total_files": len(pfc_files),
"files": all_results,
}
json_path = output_dir / f"pfc_scan_{timestamp}.json"
json_path.write_text(json.dumps(results_payload, indent=2, default=str))
info(f"Scan results written to {json_path}")
latest_path = output_dir / "pfc_scan_latest.json"
latest_path.write_text(json.dumps(results_payload, indent=2, default=str))
html_path = json_path.with_suffix(".html")
html = generate_html_report(all_results)
html_path.write_text(html)
info(f"HTML report written to {html_path}")
total_valid = sum(1 for r in all_results if r.get("valid", False))
total_fail = sum(r.get("summary", {}).get("blocks_fail", 0) for r in all_results)
info(
f"Scan complete: {len(pfc_files)} files, "
f"{total_valid} valid, "
f"{total_fail} block failures"
)
return 1 if (has_error or total_fail > 0) else 0
def cmd_report(args: argparse.Namespace) -> int:
results_path = Path(args.results_file)
if not results_path.exists():
error(f"Results file not found: {results_path}")
return 2
try:
data = json.loads(results_path.read_text())
except json.JSONDecodeError as e:
error(f"Invalid JSON in {results_path}: {e}")
return 2
files_data = data.get("files", [])
out_path = args.output
if args.format == "html":
html = generate_html_report(files_data)
if out_path is None:
out_path = results_path.with_suffix(".html")
Path(out_path).write_text(html)
info(f"HTML report written to {out_path}")
elif args.format == "json":
if out_path is None:
out_path = results_path
Path(out_path).write_text(json.dumps(data, indent=2, default=str))
info(f"JSON report written to {out_path}")
return 0
def main() -> int:
logging.basicConfig(
level=logging.INFO,
format="[pfc-validator] %(levelname)s %(message)s",
stream=sys.stdout,
)
parser = build_arg_parser()
args = parser.parse_args()
if args.command == "scan":
return cmd_scan(args)
elif args.command == "report":
return cmd_report(args)
else:
parser.print_help()
return 2
if __name__ == "__main__":
sys.exit(main())