-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhelix
More file actions
executable file
·3521 lines (3143 loc) · 179 KB
/
Copy pathhelix
File metadata and controls
executable file
·3521 lines (3143 loc) · 179 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
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""helix — build and refresh the Helix Boot USB.
Resolves the newest upstream release of every tool in tools.toml, downloads and
verifies it into a local cache, then syncs the cache onto a Ventoy stick with a
generated boot menu. Standard library only (Python 3.11+).
"""
from __future__ import annotations
import argparse
import datetime as dt
import hashlib
import html
import importlib.util
import json
import os
import re
import shutil
import subprocess
import struct
import sys
import tarfile
import time
import urllib.error
import urllib.parse
import urllib.request
import xml.etree.ElementTree as ET
import zipfile
import zlib
from email.utils import parsedate_to_datetime
from pathlib import Path, PureWindowsPath
if sys.version_info < (3, 11):
sys.exit("✗ helix needs Python 3.11 or newer (for tomllib).")
import tomllib # noqa: E402
__version__ = "0.6.7"
REPO = Path(__file__).resolve().parent
def _env(name: str, default: str | None = None) -> str | None:
"""HELIX_<name>, or the CRESCUE_<name> it was called before the rename to Helix Boot."""
return os.environ.get(f"HELIX_{name}") or os.environ.get(f"CRESCUE_{name}") or default
GITHUB_API = _env("GITHUB_API", "https://api.github.com")
SF_RSS = _env("SF_RSS", "https://sourceforge.net/projects/{project}/rss?path={path}") # SourceForge rejects limit > 100
SF_DL = _env("SF_DL", "https://downloads.sourceforge.net/project/{project}{path}")
USER_AGENT = f"helix-boot/{__version__} (+https://github.com/Commanderx-code/helix-boot)"
# For the few sites that turn away anything but a browser (`user_agent = "browser"` on a tool)
BROWSER_UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:140.0) Gecko/20100101 Firefox/140.0"
KINDS = {"iso", "app", "ventoy", "file", "tree"}
SOURCES = {"github": ["repo"], "sourceforge": ["project", "path"], "url": ["url"], "page": ["page", "asset", "version"],
"local": ["path"]}
HASH_BY_LEN = {32: "md5", 40: "sha1", 64: "sha256", 128: "sha512"}
STRENGTH = {"md5": 1, "sha1": 2, "sha256": 3, "sha512": 4}
STATE_DIR = ".helix-boot"
TAG_FILE = "helix-boot.tag"
STICK_LABEL = "HelixBoot" # the volume name a new stick gets (Ventoy's own is "Ventoy")
# The stick's look (`helix theme`): ventoy/theme and ventoy/ventoy.json are built from these
THEME_SRC = f"{STATE_DIR}/theme" # the theme as synced: presets, icon packs, your own icons
BASE_JSON = f"{STATE_DIR}/ventoy.base.json" # the boot menu before the look is applied
LOOK_FILE = f"{STATE_DIR}/look.json" # the choice
LOOK_DIR = f"{STATE_DIR}/look" # your own background.png / splash.png, set on the stick
LOOK_DEFAULT = {"theme": "default", "icons": "auto", "background": "theme", "splash": "auto"}
HASHES = f"{STATE_DIR}/hashes.json" # every app file's sha256 as it was put on (`helix verify`)
# Before the rename to Helix Boot: still written or read, so older sticks, launchers and
# Lazarus PE builds keep working
OLD_STATE_DIR = ".commander-rescue"
OLD_TAG_FILE = "commander-rescue.tag"
OLD_CACHE = "~/.cache/commander-rescue"
# Category ids from before the MediCat-style menu; local.toml entries using them keep working.
OLD_CATEGORIES = {"windows-pe": "live", "rescue": "live"}
# ── Output ────────────────────────────────────────────────────────────────
def _isatty(stream) -> bool:
"""Is this a terminal? A windowed program started from Explorer (HelixBoot.exe) has no
console at all: its sys.stdout and sys.stderr are None."""
return bool(stream) and getattr(stream, "isatty", lambda: False)()
class C:
on = _isatty(sys.stdout) and not os.environ.get("NO_COLOR")
G, Y, R, B, D, X = (
("\033[32m", "\033[33m", "\033[31m", "\033[1m", "\033[2m", "\033[0m") if on else ("",) * 6
)
def ok(msg: str) -> None:
print(f"{C.G}✓{C.X} {msg}")
def warn(msg: str) -> None:
print(f"{C.Y}!{C.X} {msg}", file=sys.stderr) # stderr: keeps `check --json` output clean
def bad(msg: str) -> None:
print(f"{C.R}✗{C.X} {msg}", file=sys.stderr)
def info(msg: str) -> None:
print(f"{C.D}•{C.X} {msg}")
def head(msg: str) -> None:
print(f"\n{C.B}{msg}{C.X}")
class RescueError(Exception):
"""An error with a message meant for humans. No tracebacks."""
# ── Config ────────────────────────────────────────────────────────────────
class Config:
def __init__(self, repo: Path = REPO, manifest: Path | None = None, assets: Path | None = None,
windows: bool | None = None):
"""repo: your folder (local.toml, byo/). assets: the shipped files (tools.toml, theme/,
pe/launcher/), the same folder except in the Windows app, which carries them inside."""
self.repo = repo
self.assets = assets or repo
self.windows = os.name == "nt" if windows is None else windows
path = manifest or self.assets / "tools.toml"
if not path.exists():
raise RescueError(f"can't find {path}")
try:
data = tomllib.loads(path.read_text(encoding="utf-8"))
except tomllib.TOMLDecodeError as e:
raise RescueError(f"{path.name} has a syntax error: {e}") from None
local = repo / "local.toml"
overrides: dict = {}
if local.exists() and manifest is None:
try:
ldata = tomllib.loads(local.read_text(encoding="utf-8"))
except tomllib.TOMLDecodeError as e:
raise RescueError(f"local.toml has a syntax error: {e}") from None
overrides = ldata.get("overrides", {})
data.setdefault("tool", []).extend(ldata.get("tool", []))
data.setdefault("settings", {}).update(ldata.get("settings", {}))
ldata_tools = ldata.get("tool", [])
else:
ldata_tools = []
# Tools you switched off yourself, in local.toml. Not the ones that are off as shipped
# (Kaspersky): another PC may have them on, and an update here mustn't remove theirs.
self.switched_off = ({n for n, o in overrides.items() if o.get("enabled") is False}
| {t.get("name") for t in ldata_tools if t.get("enabled") is False})
self.settings = data.get("settings", {})
self.categories = {c["id"]: c for c in data.get("category", [])}
self.tools: list[dict] = []
seen = set()
for t in data.get("tool", []):
t = {**t, **overrides.get(t.get("name", ""), {})}
if self.windows: # `windows = { asset = [...] }` swaps in the Windows download
t.update(t.get("windows", {}))
self._validate(t, seen)
seen.add(t["name"])
self.tools.append(t)
unknown = set(overrides) - seen
if unknown:
raise RescueError(f"local.toml overrides unknown tool(s): {', '.join(sorted(unknown))}")
cache = _env("CACHE") or self.settings.get("cache_dir", "~/.cache/helix-boot")
self.cache = Path(cache).expanduser()
old = Path(OLD_CACHE).expanduser()
# Only for a real run: code that loads a manifest itself (tests) must not move your cache
if manifest is None and not self.cache.exists() and old.is_dir() and self.cache.name == "helix-boot":
self.cache.parent.mkdir(parents=True, exist_ok=True)
os.rename(old, self.cache) # renamed with the project: move it over, don't re-download
self.iso_root = self.settings.get("iso_root", "ISO")
self.apps_root = self.settings.get("apps_root", "Apps")
self.mac_root = self.settings.get("mac_root", "Mac") # apps with platform = "mac"
self.stick_label = str(self.settings.get("stick_label", STICK_LABEL)) # the name install gives a stick
if not re.fullmatch(r"[A-Za-z0-9_-]{1,11}", self.stick_label):
raise RescueError("stick_label must be 1 to 11 letters, digits, - or _ (it is the stick's volume name)")
def _validate(self, t: dict, seen: set) -> None:
name = t.get("name")
where = f"tool '{name}'" if name else "a [[tool]] entry"
if not name or not re.fullmatch(r"[a-z0-9][a-z0-9_-]*", name):
raise RescueError(f"{where}: name must be lowercase letters, digits, - or _")
if name in seen:
raise RescueError(f"{where} is defined twice")
if t.get("kind") not in KINDS:
raise RescueError(f"{where}: kind must be one of {sorted(KINDS)}")
for img, colour in (t.get("recolor") or {}).items():
if not re.fullmatch(r"[0-9A-Fa-f]{6}", str(colour)):
raise RescueError(f"{where}: recolor.{img} must be a hex colour like 2AA9BE")
if t.get("ventoy_mode") and t.get("ventoy_mode") not in VENTOY_MODES:
raise RescueError(f"{where}: ventoy_mode must be one of {sorted(VENTOY_MODES)}")
if t.get("platform") not in (None, "mac") or (t.get("platform") and t["kind"] != "app"):
raise RescueError(f"{where}: platform can only be \"mac\", on an app")
if t["kind"] == "file":
dest = t.get("dest") or ""
if not dest or dest.startswith("/") or ".." in dest.split("/"):
raise RescueError(f"{where}: a file needs 'dest', a path on the stick such as ventoy/x.img")
if t["kind"] == "tree":
for key in ("dest", "once"):
v = t.get(key)
if v is None or v.startswith("/") or ".." in v.split("/") or (key == "once" and not v):
raise RescueError(f"{where}: a tree needs 'dest' (\"\" for the stick's root) and 'once', "
"the file whose presence means it's installed")
src = t.get("source")
if src not in SOURCES:
raise RescueError(f"{where}: source must be one of {sorted(SOURCES)}")
for key in SOURCES[src]:
if key not in t:
raise RescueError(f"{where}: source '{src}' needs '{key}'")
if src in ("github", "sourceforge") and not (t.get("asset") or t.get("download_template")):
raise RescueError(f"{where}: needs an 'asset' regex list (or a download_template)")
if t["kind"] == "iso" and t.get("category") not in self.categories \
and OLD_CATEGORIES.get(t.get("category")) in self.categories:
t["category"] = OLD_CATEGORIES[t["category"]]
if t["kind"] == "iso" and t.get("category") not in self.categories:
raise RescueError(f"{where}: category '{t.get('category')}' isn't a [[category]] id")
if src != "local" and not t.get("checksum"):
raise RescueError(
f"{where}: no checksum strategy. Add one, or checksum = [\"tofu\"] to accept "
"unverified downloads explicitly."
)
for pat in t.get("asset", []) + [t.get("version") or "", t.get("extract") or ""]:
try:
re.compile(pat.replace("{name}", "x"))
except re.error as e:
raise RescueError(f"{where}: bad regex {pat!r}: {e}") from None
def pc_id(self) -> str:
"""A random name for this PC, kept in its cache: a stick records which PC put each tool
on it, so a PC tidies up after itself and leaves another PC's tools alone."""
if not getattr(self, "_pc_id", None):
f = self.cache / "pc-id"
try:
self._pc_id = f.read_text(encoding="utf-8").strip()
except OSError:
self._pc_id = ""
if not re.fullmatch(r"[0-9a-f]{16}", self._pc_id):
self._pc_id = os.urandom(8).hex()
try:
self.cache.mkdir(parents=True, exist_ok=True)
f.write_text(self._pc_id + "\n", encoding="utf-8")
except OSError:
pass # a cache it can't write: a new name each run, so it only ever keeps
return self._pc_id
def enabled(self, names: list[str] | None = None, kinds: set[str] | None = None) -> list[dict]:
if names:
known = {t["name"] for t in self.tools}
missing = [n for n in names if n not in known]
if missing:
raise RescueError(f"unknown tool(s): {', '.join(missing)} (see `helix list`)")
picked = [t for t in self.tools if t["name"] in names]
else:
picked = [t for t in self.tools if t.get("enabled", True)]
return [t for t in picked if not kinds or t["kind"] in kinds]
# ── HTTP ──────────────────────────────────────────────────────────────────
def _is_github_api(url: str) -> bool:
"""Is url on the GitHub API itself? Compared by parsed scheme, host and port, never by
string prefix: https://api.github.com.example.net/ must not get the token."""
u, api = urllib.parse.urlsplit(url), urllib.parse.urlsplit(GITHUB_API)
try:
same_port = u.port == api.port
except ValueError:
return False
return (u.scheme == api.scheme and u.hostname is not None and u.hostname == api.hostname and same_port
and (u.path == api.path or u.path.startswith(api.path.rstrip("/") + "/")))
def _request(url: str, headers: dict | None = None) -> urllib.request.Request:
req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT, **(headers or {})})
if os.environ.get("GITHUB_TOKEN") and _is_github_api(url):
# unredirected: urllib doesn't pass it on if GitHub redirects elsewhere
req.add_unredirected_header("Authorization", f"Bearer {os.environ['GITHUB_TOKEN']}")
return req
def _ua(tool: dict) -> dict | None:
return {"User-Agent": BROWSER_UA} if tool.get("user_agent") == "browser" else None
def http_get(url: str, headers: dict | None = None, timeout: int = 60) -> bytes:
"""GET a page or API response. Server errors and timeouts are retried like downloads."""
for delay in RETRY_DELAYS:
try:
return _http_get_once(url, headers, timeout)
except _Transient as e:
warn(f"{e} — retrying in {delay}s")
time.sleep(delay)
try:
return _http_get_once(url, headers, timeout)
except _Transient as e:
raise RescueError(str(e)) from None
class _Transient(Exception):
"""A failure worth retrying: 5xx, timeout, dropped connection."""
def _http_get_once(url: str, headers: dict | None, timeout: int) -> bytes:
host = urllib.parse.urlparse(url).netloc
try:
with urllib.request.urlopen(_request(url, headers), timeout=timeout) as r:
return r.read()
except urllib.error.HTTPError as e:
if e.code >= 500:
raise _Transient(f"HTTP {e.code} from {url}") from None
if e.code in (403, 429) and _is_github_api(url):
body = e.read().decode("utf-8", "replace")
if "rate limit" in body.lower():
raise RescueError(
"GitHub API rate limit hit. Set GITHUB_TOKEN (any read-only token) and retry."
) from None
try:
msg = json.loads(body).get("message", body)
except ValueError:
msg = body
raise RescueError(f"GitHub refused the request ({e.code}): {msg.strip()[:200]}") from None
if e.code == 404:
raise FileNotFoundError(url) from None
raise RescueError(f"HTTP {e.code} from {url}") from None
except urllib.error.URLError as e:
raise _Transient(f"couldn't reach {host}: {e.reason}") from None
except (TimeoutError, ConnectionError) as e:
raise _Transient(f"lost the connection to {host}: {e or 'timed out'}") from None
def _fmt_bytes(n: float) -> str:
for unit in ("B", "KiB", "MiB", "GiB"):
if n < 1024 or unit == "GiB":
return f"{n:.1f} {unit}" if unit != "B" else f"{int(n)} B"
n /= 1024
return f"{n:.1f} GiB"
def _fmt_eta(seconds: float) -> str:
s = int(seconds)
return f"{s // 3600}h{s % 3600 // 60:02d}m" if s >= 3600 else f"{s // 60}m{s % 60:02d}s"
class Progress:
"""One status line on stderr for long copies. With a known total it shows the whole
job (bar, bytes, speed, ETA); otherwise just the current file. Silent unless stderr
is a terminal, so logs and the Windows app stay clean."""
def __init__(self, total: int = 0, hook=None):
self.total, self.done = total, 0
self.hook = hook # hook(percent): the Windows app's progress bar
self.tty = _isatty(sys.stderr)
self.start = self.last = time.monotonic()
self.label, self.fsize, self.fdone, self.fstart = "", 0, 0, self.start
def file(self, label: str, size: int) -> None:
self.label, self.fsize, self.fdone, self.fstart = label, size, 0, time.monotonic()
def add(self, n: int) -> None:
self.done += n
self.fdone += n
now = time.monotonic()
if (self.tty or self.hook) and now - self.last > 0.25:
self.last = now
if self.tty:
print("\r" + self.line(now), end="", file=sys.stderr)
if self.hook and self.total:
self.hook(min(self.done * 100 // self.total, 100))
def line(self, now: float) -> str:
width = shutil.get_terminal_size((100, 20)).columns - 1
if self.total:
frac = min(self.done / self.total, 1.0)
rate = self.done / max(now - self.start, 1e-6)
fill = int(frac * 20)
bar = "=" * fill + (">" if fill < 20 else "") + " " * max(19 - fill, 0)
text = (f" [{bar}] {frac * 100:3.0f}% {_fmt_bytes(self.done)}/{_fmt_bytes(self.total)}"
f" {_fmt_bytes(rate)}/s ETA {_fmt_eta((self.total - self.done) / rate if rate else 0)}"
f" {self.label}")
else:
rate = self.fdone / max(now - self.fstart, 1e-6)
pct = self.fdone * 100 // self.fsize if self.fsize else 0
text = (f" -> {self.label} {pct:3d}% {_fmt_bytes(self.fdone)}/{_fmt_bytes(self.fsize)}"
f" {_fmt_bytes(rate)}/s")
return text[:width].ljust(width)
def clear(self) -> None:
if self.tty:
print("\r" + " " * (shutil.get_terminal_size((100, 20)).columns - 1) + "\r", end="", file=sys.stderr)
RETRY_DELAYS = (2, 5, 10) # seconds to wait before each retry of a failed request
def download(url: str, dest: Path) -> None:
"""Download to dest, resuming a previous .part file when the server allows it.
Server errors (5xx), timeouts and dropped connections are retried a few
times: release hosts like GitHub's return the odd transient 500.
"""
part = dest.with_name(dest.name + ".part")
have = part.stat().st_size if part.exists() else 0
headers = {"Range": f"bytes={have}-"} if have else {}
for attempt, delay in enumerate((*RETRY_DELAYS, None)):
try:
resp = urllib.request.urlopen(_request(url, headers), timeout=60)
break
except urllib.error.HTTPError as e:
if e.code == 416 and have: # .part already complete
os.replace(part, dest)
return
err = f"HTTP {e.code} from {url}"
if e.code < 500:
raise RescueError(f"download failed: {err}") from None
except (urllib.error.URLError, TimeoutError, ConnectionError) as e:
err = str(getattr(e, "reason", e))
if delay is None:
raise RescueError(f"download failed after {attempt + 1} tries: {err}")
warn(f"{err} — retrying in {delay}s")
time.sleep(delay)
with resp:
resumed = have and resp.status == 206
if not resumed:
have = 0
total = resp.headers.get("Content-Length")
total = int(total) + have if total else None
done, last, start = have, 0.0, time.monotonic()
tty = _isatty(sys.stderr)
with open(part, "ab" if resumed else "wb") as f:
while chunk := resp.read(1 << 20):
f.write(chunk)
done += len(chunk)
now = time.monotonic()
if tty and now - last > 0.25:
last = now
rate = (done - have) / max(now - start, 1e-6)
pct = f"{done * 100 // total:3d}%" if total else " "
tot = f"/{_fmt_bytes(total)}" if total else ""
print(
f"\r ↓ {_fmt_bytes(done)}{tot} {pct} {_fmt_bytes(rate)}/s ",
end="",
file=sys.stderr,
)
f.flush()
os.fsync(f.fileno())
if tty:
print("\r" + " " * 60 + "\r", end="", file=sys.stderr)
if total and done != total:
raise RescueError(f"download was cut short ({_fmt_bytes(done)} of {_fmt_bytes(total)}); run fetch again to resume")
os.replace(part, dest)
def file_hash(path: Path, algo: str = "sha256", progress: "Progress | None" = None) -> str:
h = hashlib.new(algo)
with open(path, "rb") as f:
while chunk := f.read(1 << 20):
h.update(chunk)
if progress:
progress.add(len(chunk))
return h.hexdigest()
def folder_hash(path: Path) -> str:
"""One sha256 for a folder: every file's path and content, so any change shows."""
h = hashlib.sha256()
for f in sorted(p for p in path.rglob("*") if p.is_file()):
h.update(f"{f.relative_to(path).as_posix()}\0{file_hash(f)}\n".encode("utf-8"))
return h.hexdigest()
def _uncached(path: Path) -> None:
"""Have the OS drop its cached copy of path, so hashing it next really reads the disk.
Without this, verifying a file just written to a stick would read it back from RAM."""
if hasattr(os, "posix_fadvise"):
fd = os.open(path, os.O_RDONLY)
try:
os.posix_fadvise(fd, 0, 0, os.POSIX_FADV_DONTNEED)
finally:
os.close(fd)
def remote_id(url: str) -> str | None:
"""Identify an unversioned download by ETag / Last-Modified / size (HEAD request)."""
req = _request(url)
req.method = "HEAD"
try:
with urllib.request.urlopen(req, timeout=30) as r:
parts = [r.headers.get("ETag"), r.headers.get("Last-Modified"), r.headers.get("Content-Length")]
except (urllib.error.URLError, TimeoutError):
return None
return "|".join(p or "" for p in parts) if any(parts) else None
def is_current(prev: dict | None, res: dict) -> bool:
if not prev or prev.get("source_file", prev.get("file")) != res["file"]:
return False
if res["version"] is not None:
return prev.get("version") == res["version"]
return res.get("remote_id") is not None and prev.get("remote_id") == res["remote_id"]
# ── Resolving the latest upstream release ─────────────────────────────────
def _pick(names: list[str], patterns: list[str]) -> list[str]:
"""Return matches for the first pattern that matches anything."""
for pat in patterns:
rx = re.compile(pat)
hits = [n for n in names if rx.search(n)]
if hits:
return hits
return []
def _version(tool: dict, filename: str, fallback: str | None) -> str:
if tool.get("version_pin"):
return str(tool["version_pin"])
if tool.get("version"):
m = re.search(tool["version"], filename)
if m:
return "-".join(g for g in m.groups() if g) if m.groups() else m.group(0)
if fallback:
return clean_tag(fallback)
return dt.date.today().isoformat()
def clean_tag(tag: str) -> str:
"""'v8.10' → '8.10', 'version-1.4.0' → '1.4.0', 'rel_2024' → '2024'."""
m = re.search(r"\d[\w.+-]*", tag)
return m.group(0) if m else tag
def resolve(tool: dict, cfg: Config) -> dict:
"""Work out what the newest upstream file is, without downloading it."""
src = tool["source"]
res: dict = {"digest": None, "md5": None, "gh_assets": {}, "dir_url": None}
if src == "github":
try:
raw = http_get(f"{GITHUB_API}/repos/{tool['repo']}/releases/latest",
{"Accept": "application/vnd.github+json"})
except FileNotFoundError:
raise RescueError(f"{tool['repo']} has no published releases on GitHub") from None
rel = json.loads(raw)
assets = {a["name"]: a for a in rel.get("assets", [])}
if tool.get("download_template"):
# GitHub only tells us the version; the file lives on the project's own site.
ver = clean_tag(rel.get("tag_name") or "")
url = tool["download_template"].format(version=ver, tag=rel.get("tag_name"))
res.update(file=urllib.parse.unquote(url.rsplit("/", 1)[-1]), url=url,
dir_url=url.rsplit("/", 1)[0], tag=rel.get("tag_name"), gh_assets=assets)
res["version"] = _version(tool, res["file"], ver)
return res
hits = _pick(list(assets), tool["asset"])
if not hits:
raise RescueError(
f"no file in {tool['repo']} {rel.get('tag_name')} matches {tool['asset']} "
f"(files: {', '.join(assets) or 'none'})"
)
a = assets[hits[0]]
res.update(file=a["name"], url=a["browser_download_url"], size=a.get("size"),
gh_assets=assets, tag=rel.get("tag_name"))
if (a.get("digest") or "").startswith("sha256:"):
res["digest"] = a["digest"].split(":", 1)[1]
res["version"] = _version(tool, a["name"], rel.get("tag_name"))
elif src == "sourceforge":
url = SF_RSS.format(project=tool["project"], path=urllib.parse.quote(tool["path"]))
try:
root = ET.fromstring(http_get(url))
except FileNotFoundError:
raise RescueError(f"SourceForge project '{tool['project']}' not found") from None
except ET.ParseError:
raise RescueError(f"SourceForge returned something that isn't RSS for {tool['project']}") from None
entries = []
for i, item in enumerate(root.iter("item")):
title = (item.findtext("title") or "").strip()
if not title:
continue
md5 = None
for el in item.iter():
if el.tag.endswith("hash") and el.get("algo") == "md5":
md5 = (el.text or "").strip().lower()
try:
when = parsedate_to_datetime(item.findtext("pubDate") or "").timestamp()
except (TypeError, ValueError):
when = -i # RSS is newest-first; keep that order
entries.append({"path": title, "name": title.rsplit("/", 1)[-1], "md5": md5, "when": when})
hits = set(_pick([e["name"] for e in entries], tool["asset"]))
cands = [e for e in entries if e["name"] in hits]
if not cands:
raise RescueError(f"no file in SourceForge {tool['project']}{tool['path']} matches {tool['asset']}")
e = max(cands, key=lambda e: e["when"])
quoted = urllib.parse.quote(e["path"])
res.update(file=e["name"], url=SF_DL.format(project=tool["project"], path=quoted), md5=e["md5"],
dir_url=SF_DL.format(project=tool["project"], path=quoted.rsplit("/", 1)[0]))
# Version: from the file name, else its release folder, else SourceForge's upload date
folder = e["path"].rstrip("/").split("/")[-2] if e["path"].count("/") > 1 else None
uploaded = dt.date.fromtimestamp(e["when"]).isoformat() if e["when"] > 0 else None
res["version"] = _version(tool, e["name"], folder or uploaded)
elif src == "url":
# `file` names downloads whose URL doesn't end in one (redirect links like .../fwlink/?LinkId=…)
name = tool.get("file") or urllib.parse.unquote(urllib.parse.urlparse(tool["url"]).path.rsplit("/", 1)[-1])
if not name:
raise RescueError(f"{tool['title']}: {tool['url']} doesn't end in a file name — add file = \"name.ext\"")
res.update(file=name, url=tool["url"], dir_url=tool["url"].rsplit("/", 1)[0])
res["version"] = _version(tool, name, None) if (tool.get("version") or tool.get("version_pin")) else None
if res["version"] is None:
res["remote_id"] = remote_id(tool["url"])
elif src == "page":
# A download page whose links carry the version (hdat2cd_76.iso, DGEng6201829_x64.zip)
text = http_get(tool["page"], _ua(tool)).decode("utf-8", "replace")
hrefs = [urllib.parse.urljoin(tool["page"], html.unescape(h))
for h in re.findall(r"""href\s*=\s*["']([^"']+)""", text, re.I)]
hits: list[tuple[str, str]] = []
for pat in tool["asset"]: # first pattern that matches anything wins, as for releases
hits = [(m.group(0), h) for h in hrefs if (m := re.search(pat, h))]
if hits:
break
if not hits:
raise RescueError(f"no link on {tool['page']} matches {tool['asset']}")
name, url = max(hits, key=lambda nh: [int(n) for n in re.findall(r"\d+", _version(tool, nh[0], None))])
res.update(file=name, url=url, dir_url=tool["page"], version=_version(tool, name, None))
elif src == "local":
p = (cfg.repo / Path(tool["path"]).expanduser()).resolve()
res.update(file=p.name, url=None, path=p)
res["version"] = (
dt.date.fromtimestamp(p.stat().st_mtime).isoformat() if p.exists() else None
)
return res
# ── Checksums ─────────────────────────────────────────────────────────────
def parse_checksum_text(text: str, filename: str) -> tuple[str, str] | None:
"""Find the strongest hash for `filename` in a sha*sum / CHECKSUMS.TXT / BSD-style file."""
hexrx = re.compile(r"\b([0-9a-fA-F]{128}|[0-9a-fA-F]{64}|[0-9a-fA-F]{40}|[0-9a-fA-F]{32})\b")
best: tuple[str, str] | None = None
lines = text.splitlines()
for line in lines:
if filename not in line:
continue
for h in hexrx.findall(line):
algo = HASH_BY_LEN[len(h)]
if not best or STRENGTH[algo] > STRENGTH[best[0]]:
best = (algo, h.lower())
if best:
return best
# single-file checksum (e.g. foo.iso.sha256 containing just the hash)
allhex = hexrx.findall(text)
if len(allhex) == 1:
return HASH_BY_LEN[len(allhex[0])], allhex[0].lower()
return None
def expected_hash(tool: dict, res: dict) -> tuple[str, str | None, str]:
"""Return (algo, hex, how) — algo 'tofu' means no upstream hash."""
tried = []
for strat in tool.get("checksum", []):
if strat == "github-digest":
tried.append("GitHub digest")
if res.get("digest"):
return "sha256", res["digest"], "GitHub sha256 digest"
elif strat == "sf-md5":
tried.append("SourceForge md5")
if res.get("md5"):
return "md5", res["md5"], "SourceForge md5 (integrity only)"
elif strat == "tofu":
return "tofu", None, "unverified (trust on first use)"
elif isinstance(strat, dict) and "sha256" in strat:
return "sha256", strat["sha256"].lower(), "pinned sha256"
elif isinstance(strat, dict):
if "asset" in strat:
pat = strat["asset"].replace("{name}", re.escape(res["file"]))
tried.append(f"release asset /{pat}/")
hit = next((n for n in res.get("gh_assets", {}) if re.search(pat, n)), None)
url = res["gh_assets"][hit]["browser_download_url"] if hit else None
elif "sibling" in strat:
tried.append(strat["sibling"])
url = f"{res['dir_url']}/{urllib.parse.quote(strat['sibling'].format(name=res['file']))}" if res.get("dir_url") else None
elif "url" in strat and "regex" in strat: # a hash shown on a web page, next to the file name
tried.append(strat["url"])
try:
raw = html.unescape(http_get(strat["url"], _ua(tool)).decode("utf-8", "replace"))
except (FileNotFoundError, RescueError):
continue
text = re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", raw)) # the page as it reads
m = re.search(strat["regex"], text)
if m and res["file"] in raw and len(m.group(1)) in HASH_BY_LEN:
algo = HASH_BY_LEN[len(m.group(1))]
return algo, m.group(1).lower(), f"{algo} from {urllib.parse.urlsplit(strat['url']).netloc}"
continue
elif "url" in strat:
tried.append(strat["url"])
url = strat["url"]
else:
raise RescueError(f"{tool['name']}: unknown checksum strategy {strat}")
if not url:
continue
try:
text = http_get(url).decode("utf-8", "replace")
except (FileNotFoundError, RescueError):
continue
found = parse_checksum_text(text, res["file"])
if found:
return found[0], found[1], f"{found[0]} from {url.rsplit('/', 1)[-1]}"
else:
raise RescueError(f"{tool['name']}: unknown checksum strategy {strat!r}")
raise RescueError(
f"{tool['name']}: couldn't find an upstream checksum for {res['file']} "
f"(tried: {', '.join(tried)}). Refusing to use an unverified download — add \"tofu\" "
"to its checksum list if you accept that."
)
# ── Lock file ─────────────────────────────────────────────────────────────
def load_lock(cfg: Config) -> dict:
p = cfg.cache / "lock.json"
return json.loads(p.read_text(encoding="utf-8")) if p.exists() else {}
def save_lock(cfg: Config, lock: dict) -> None:
cfg.cache.mkdir(parents=True, exist_ok=True)
tmp = cfg.cache / "lock.json.tmp"
tmp.write_text(json.dumps(lock, indent=2, sort_keys=True) + "\n", encoding="utf-8")
os.replace(tmp, cfg.cache / "lock.json")
def _safe_extract_tar(tar: tarfile.TarFile, dest: Path) -> None:
if hasattr(tarfile, "data_filter"):
tar.extractall(dest, filter="data")
return
root = dest.resolve()
for m in tar.getmembers():
target = (dest / m.name).resolve()
if not str(target).startswith(str(root)) or m.issym() and os.path.isabs(m.linkname):
raise RescueError(f"refusing unsafe path in archive: {m.name}")
tar.extractall(dest)
def _top_dir(name: str) -> str | None:
"""First real folder of an archive member: 'ventoy-1.1.17' for both 'ventoy-1.1.17/x' and './ventoy-1.1.17/x'."""
parts = [p for p in name.replace("\\", "/").split("/") if p not in ("", ".")]
return parts[0] if parts else None
SAFE_NAME = re.compile(r"[a-z0-9][a-z0-9_-]*") # tool names, so also the apps on a stick
def _safe_rel(rel: str, what: str = "path") -> str:
"""A path read from a pack, a zip or a stick, accepted only as a plain relative path:
no root, no drive (C:, also on Linux), no '..', no ':' (NTFS streams)."""
parts = re.split(r"[\\/]", rel) if isinstance(rel, str) else None
if (not parts or not rel or rel[0] in "/\\" or ":" in rel or ".." in parts
or PureWindowsPath(rel).anchor or Path(rel).is_absolute()):
raise RescueError(f"refusing unsafe {what}: {rel!r}")
return rel
def _inside(root: Path, rel: str, what: str = "path") -> Path:
"""root / rel for a rel read from a pack or a stick, refused unless it stays inside root."""
dst = root / _safe_rel(rel, what)
if not dst.resolve().is_relative_to(root.resolve()):
raise RescueError(f"refusing {what} outside {root}: {rel!r}")
return dst
def _safe_zip_members(zf: zipfile.ZipFile) -> list[zipfile.ZipInfo]:
for m in zf.infolist():
_safe_rel(m.filename, "path in zip")
return zf.infolist()
def fetch_tool(cfg: Config, tool: dict, lock: dict, force: bool = False) -> str:
"""Fetch one tool. Returns 'new', 'current' or 'skipped'."""
name = tool["name"]
res = resolve(tool, cfg)
prev = lock.get(name)
if tool["source"] == "local":
p: Path = res["path"]
if not p.exists():
lock.pop(name, None) # file gone: drop it from the stick on the next sync
if not tool.get("byo"): # bring-your-own slots are simply empty until filled
warn(f"{tool['title']}: {tool['path']} isn't built yet — skipping (see pe/README.md)")
return "skipped"
kind = "your own file" if tool.get("byo") else "local build"
sha = folder_hash(p) if p.is_dir() else file_hash(p)
if prev and prev.get("sha256") == sha:
ok(f"{tool['title']} {res['version']} — {kind}, unchanged")
return "current"
lock[name] = {"version": res["version"], "file": p.name, "path": str(p), "sha256": sha,
"verified_by": kind, "fetched": dt.datetime.now().isoformat(timespec="seconds")}
ok(f"{tool['title']} {res['version']} — {kind} registered")
return "new"
tdir = cfg.cache / name
# final "." is what older versions recorded for Ventoy's ./-prefixed tarball: not really cached
cached = bool(prev and prev.get("final") not in (None, "", ".") and (tdir / prev["final"]).exists())
if not force and cached and is_current(prev, res):
ok(f"{tool['title']} {prev['version']} — up to date")
return "current"
algo, want, how = expected_hash(tool, res)
tdir.mkdir(parents=True, exist_ok=True)
dest = tdir / res["file"]
info(f"{tool['title']}: downloading {res['file']}")
download(res["url"], dest)
sha256 = file_hash(dest)
if algo == "tofu":
if (prev and prev.get("source_file") == res["file"] and prev.get("sha256_download")
and prev["sha256_download"] != sha256 and res["version"] is not None
and prev.get("version") == res["version"]):
dest.unlink()
raise RescueError(
f"{tool['title']}: {res['file']} changed upstream without a version bump. That can be "
"a silent re-release — or tampering. Check the vendor's site, then rerun with --force."
)
else:
got = sha256 if algo == "sha256" else file_hash(dest, algo)
if got != want:
dest.unlink()
raise RescueError(
f"{tool['title']}: checksum MISMATCH for {res['file']} ({algo})\n"
f" expected {want}\n got {got}\n The file was deleted. Try again; if it "
"keeps happening, don't use it."
)
# SourceForge serves files, and checksum files next to them, from third-party mirrors; the
# md5 in sourceforge.net's own feed is the independent check, so it must agree as well.
if res.get("md5") and algo != "md5":
got = file_hash(dest, "md5")
if got != res["md5"].lower():
dest.unlink()
raise RescueError(
f"{tool['title']}: {res['file']} doesn't match the md5 SourceForge publishes for it\n"
f" expected {res['md5'].lower()}\n got {got}\n The file was deleted: a download "
"mirror may have served a changed file. Try again later."
)
how += " + SourceForge md5"
version = res["version"]
if version is None: # unversioned url source: version by content
version = (prev["version"] if prev and prev.get("sha256_download") == sha256
else f"{dt.date.today().isoformat()}-{sha256[:8]}")
final = res["file"]
if tool.get("extract"):
with zipfile.ZipFile(dest) as zf:
members = [m for m in _safe_zip_members(zf) if re.search(tool["extract"], m.filename)]
if not members:
raise RescueError(f"{tool['title']}: nothing in {res['file']} matches {tool['extract']}")
m = members[0]
final = Path(m.filename).name
with zf.open(m) as s, open(tdir / final, "wb") as d:
shutil.copyfileobj(s, d)
elif tool["kind"] == "ventoy" and zipfile.is_zipfile(dest): # the Windows package
with zipfile.ZipFile(dest) as zf:
members = _safe_zip_members(zf)
top = {t for t in map(_top_dir, (m.filename for m in members)) if t}
zf.extractall(tdir, members=members)
if len(top) != 1:
raise RescueError(f"unexpected Ventoy archive layout: {sorted(top)}")
final = top.pop()
elif tool["kind"] == "tree": # e.g. a PortableApps.com .paf.exe (NSIS): only 7-Zip opens those
seven = shutil.which("7z") or shutil.which("7za") or shutil.which("7zz")
if not seven:
dest.unlink(missing_ok=True)
raise RescueError(f"{tool['title']}: unpacking needs 7-Zip. Install it (e.g. sudo pacman -S 7zip) and fetch again.")
final = f"tree-{re.sub(r'[^A-Za-z0-9._-]', '_', res['version'] or 'x')}"
out = tdir / final
shutil.rmtree(out, ignore_errors=True)
r = subprocess.run([seven, "x", "-y", f"-o{out}", str(dest)], capture_output=True, text=True)
if r.returncode:
raise RescueError(f"{tool['title']}: 7-Zip couldn't unpack {res['file']}: {r.stderr.strip() or r.stdout[-300:]}")
for f in sorted(out.rglob("*"), key=lambda f: -len(f.parts)):
rel = f.relative_to(out).as_posix()
if any(re.search(pat, rel) for pat in tool.get("drop", [])):
shutil.rmtree(f) if f.is_dir() else f.unlink(missing_ok=True)
if not (out / tool["once"]).exists():
raise RescueError(f"{tool['title']}: {tool['once']} isn't in {res['file']}; the layout has changed")
elif tool["kind"] == "ventoy":
with tarfile.open(dest) as tar:
top = {t for t in map(_top_dir, tar.getnames()) if t} # Ventoy's tarball says ./ventoy-x/…
_safe_extract_tar(tar, tdir)
if len(top) != 1:
raise RescueError(f"unexpected Ventoy archive layout: {sorted(top)}")
final = top.pop()
keep = {res["file"], final}
for old in tdir.iterdir():
if old.name not in keep and not old.name.endswith(".part"):
shutil.rmtree(old) if old.is_dir() else old.unlink()
lock[name] = {
"version": version,
"source_file": res["file"],
"final": final,
"sha256_download": sha256,
"sha256": file_hash(tdir / final) if (tdir / final).is_file() else None,
"verified_by": how,
"url": res["url"],
"remote_id": res.get("remote_id"),
"fetched": dt.datetime.now().isoformat(timespec="seconds"),
}
marker = f"{C.Y}unverified{C.X}" if algo == "tofu" else f"{C.D}{how}{C.X}"
ok(f"{tool['title']} {version} — {marker}")
return "new"
# ── Commands ──────────────────────────────────────────────────────────────
def cmd_list(cfg: Config, args) -> int:
rows = [("NAME", "KIND", "CATEGORY", "SOURCE", "ON")]
for t in cfg.tools:
cat = cfg.categories.get(t.get("category"), {}).get("title", "—")
src = t.get("repo") or t.get("project") or t.get("url") or t.get("page") or t.get("path")
rows.append((t["name"], t["kind"], cat, f"{t['source']}:{src}"[:52],
"yes" if t.get("enabled", True) else "no"))
w = [max(len(r[i]) for r in rows) for i in range(5)]
for i, r in enumerate(rows):
line = " ".join(c.ljust(w[j]) for j, c in enumerate(r))
print(f"{C.B}{line}{C.X}" if i == 0 else line)
return 0
def cmd_check(cfg: Config, args) -> int:
lock = load_lock(cfg)
out, updates, errors = {}, 0, 0
for t in cfg.enabled(args.tools):
try:
res = resolve(t, cfg)
except RescueError as e:
errors += 1
out[t["name"]] = {"error": str(e)}
if not args.json:
bad(f"{t['title']}: {e}")
continue
prev = lock.get(t["name"])
have = prev.get("version") if prev else None
latest = res["version"] or "unversioned download"
if t["source"] == "local":
hint = f"put your {'ISO' if t['kind'] == 'iso' else 'file'} at {t['path']}" if t.get("byo") else f"{t['path']} missing — see pe/README.md"
latest = res["version"] or hint
status = ("not provided" if t.get("byo") else "not built") if not res["version"] \
else "up to date" if prev and prev.get("path") else "not fetched"
else:
status = "not fetched" if not have else "up to date" if is_current(prev, res) else "update"
updates += status in ("update", "not fetched")
out[t["name"]] = {"latest": res["version"], "file": res["file"], "have": have, "status": status}
if not args.json:
mark = {"up to date": ok, "update": warn, "not fetched": warn}.get(status, info)
mark(f"{t['title']}: {status} ({have or '—'} → {latest})" if status == "update"
else f"{t['title']}: {status} ({latest})")
if args.json:
print(json.dumps(out, indent=2, sort_keys=True))
elif not errors:
print(f"\n{updates} to fetch." if updates else "\nEverything is current.")
return 1 if errors else 0
UPDATES_FILE = "updates.json" # in the cache: the last look upstream, for the Windows app
def tool_updates(cfg: Config, max_age: float = 6 * 3600, refresh: bool = False) -> dict:
"""Which tools have a newer release than this PC has fetched, for the app to mention.
Looks upstream at most every max_age seconds (each look costs GitHub API calls, of which an
unsigned-in PC gets 60 an hour); in between, compares the last look with what's been fetched."""
path = cfg.cache / UPDATES_FILE
try:
saved = json.loads(path.read_text(encoding="utf-8"))
age = time.time() - saved["at"]
except (OSError, ValueError, KeyError, TypeError):
saved, age = None, max_age
if refresh or not saved or not 0 <= age < max_age:
latest, failed = {}, 0
for t in cfg.enabled([]):
if t["source"] == "local":
continue
try:
res = resolve(t, cfg)
except RescueError:
failed += 1
continue
latest[t["name"]] = {"version": res["version"], "file": res["file"], "remote_id": res.get("remote_id")}
saved = {"at": time.time(), "latest": latest, "failed": failed}
cfg.cache.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(saved, indent=1) + "\n", encoding="utf-8")
lock, titles = load_lock(cfg), {t["name"]: t["title"] for t in cfg.enabled([])}
newer = [{"name": n, "title": titles[n], "have": lock[n].get("version"), "latest": res["version"]}
for n, res in sorted(saved["latest"].items(), key=lambda kv: titles.get(kv[0], "").lower())
if n in titles and lock.get(n) and not is_current(lock[n], res)]
return {"checked": dt.datetime.fromtimestamp(saved["at"]).isoformat(timespec="minutes"), "newer": newer,
"failed": saved["failed"], "fetched": sum(n in lock for n in titles)}
def updates_text(found: dict) -> str:
"""One line about tool_updates, for the app's window."""
if not found["fetched"]:
return "Nothing is downloaded on this PC yet: Install or Update gets the latest of every tool."
n = len(found["newer"])
when = found["checked"].replace("T", " ")
if not n: