Repository navigation
Expand file tree
/
Copy patharcadia_cli.py
More file actions
1885 lines (1685 loc) · 74.9 KB
/
Copy patharcadia_cli.py
File metadata and controls
1885 lines (1685 loc) · 74.9 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
"""
Arcadia CLI — Phase 1 POC (merged)
- pack: build .arcpack (zip), .torrent (libtorrent), .arcmanifest
- seed: seed a .torrent (DHT+LSD enabled) until Ctrl+C
- get: fetch manifest (file/URL), download via torrent, verify, install, update library
- list: show installed titles
- launch: run installed title (reads launch_rel from library, decrypt-on-launch if encrypted)
- inspect: list files inside an installed title (decrypts temporarily if encrypted)
- sign/verify: detached signatures for provenance (RSA-PSS/SHA-256)
- verify-license: verify dev-signed license (RSA-PSS/SHA-256)
New in this merge:
- Always-on local SQLite metrics:
• Client: ~/.arcadia/library.db (transfer_session, transfer_progress, launch_session)
• Dev/seeder: ~/.arcadia/dev.db (same schema for seeding sessions)
- Progress callback writes rows during download/seed loops
- Plain logging remains unchanged (you’ll still see console progress)
Notes:
- Pure libtorrent (no external mktorrent). LSD + DHT enabled.
- Optional AES-256-GCM encryption with per-client RSA-wrapped content keys.
"""
from __future__ import annotations
import argparse
import base64
import hashlib
import json
import logging
import os
import re
import shutil
import socket
import sqlite3
import subprocess
import sys
import tempfile
import time
import urllib.request
import zipfile
from pathlib import Path
from typing import Optional, List, Tuple
from security.iam import (
ArcadiaSecurityError,
LicenseManager,
ManifestSigner,
SecurityContext,
license_doc_from_dict,
license_doc_to_dict,
manifest_core_from_dict,
manifest_signature_from_dict,
manifest_signature_to_dict,
)
from db.library import (
export_library_json,
init_library_db,
load_game as load_library_game,
load_library as load_library_state,
migrate_json_to_db,
upsert_installed_title,
)
try:
import libtorrent as lt
except Exception:
lt = None # type: ignore
# ------------------------------
# Logging
# ------------------------------
LOGGER = logging.getLogger("arcadia")
def setup_logging(verbosity: int) -> None:
level = logging.INFO
if verbosity <= -1:
level = logging.ERROR
elif verbosity >= 2:
level = logging.DEBUG
elif verbosity == 1:
level = logging.INFO
logging.basicConfig(
level=level,
format="%(asctime)s │ %(levelname)-8s │ %(name)s │ %(message)s",
datefmt="%H:%M:%S",
)
# ------------------------------
# Crypto helpers (AES-GCM + RSA)
# ------------------------------
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding, rsa
from cryptography.hazmat.primitives.asymmetric import utils as asym_utils
import secrets
def _rsa_load_private(path: Path):
return serialization.load_pem_private_key(path.read_bytes(), password=None)
def _rsa_load_public(path: Path):
return serialization.load_pem_public_key(path.read_bytes())
def _encrypt_file_aesgcm(src: Path, dst: Path, key: bytes) -> dict:
"""Encrypt src → dst (AES-256-GCM). Returns {'nonce_b64', 'ciphertext_sha256'}."""
nonce = secrets.token_bytes(12)
aes = AESGCM(key)
pt = src.read_bytes() # P1: OK; P2: stream/chunk
ct = aes.encrypt(nonce, pt, b"") # includes auth tag
dst.write_bytes(ct)
sha = hashlib.sha256(ct).hexdigest()
return {"nonce_b64": base64.b64encode(nonce).decode(), "ciphertext_sha256": sha}
def _decrypt_arcpack(enc_path: Path, out_zip: Path, nonce_b64: str, key: bytes) -> None:
aes = AESGCM(key)
nonce = base64.b64decode(nonce_b64)
ct = enc_path.read_bytes()
pt = aes.decrypt(nonce, ct, b"")
out_zip.write_bytes(pt)
def _make_license(game_id: str, version: str, content_key: bytes,
dev_priv_pem: Path, client_pub_pem: Path) -> dict:
"""License format:
enc_key_b64 : content_key encrypted to client (RSA-OAEP-256)
sig_b64 : RSA-PSS over SHA256(game_id|version|enc_key)
"""
dev_priv = _rsa_load_private(dev_priv_pem)
cli_pub = _rsa_load_public(client_pub_pem)
enc_key = cli_pub.encrypt(
content_key,
padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(), label=None)
)
sep = b"|"
h = hashlib.sha256()
h.update(game_id.encode()); h.update(sep); h.update(version.encode()); h.update(sep); h.update(enc_key)
digest = h.digest()
sig = dev_priv.sign(
digest,
padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH),
asym_utils.Prehashed(hashes.SHA256())
)
return {
"schema_version": "1",
"alg": "RSA-OAEP-256+AES-256-GCM",
"game_id": game_id,
"version": version,
"enc_key_b64": base64.b64encode(enc_key).decode(),
"sig_b64": base64.b64encode(sig).decode(),
}
def _decrypt_content_key(license_path: Path, dev_pubkey: Optional[Path], player_privkey: Path) -> bytes:
"""Verify (optional) dev signature, then unwrap content key with player's private key."""
lic = json.loads(license_path.read_text())
enc_key = base64.b64decode(lic["enc_key_b64"])
sig = base64.b64decode(lic["sig_b64"])
game_id, version = lic["game_id"], lic["version"]
if dev_pubkey:
pub = _rsa_load_public(dev_pubkey)
sep = b"|"
h = hashlib.sha256()
h.update(game_id.encode()); h.update(sep); h.update(version.encode()); h.update(sep); h.update(enc_key)
pub.verify(
sig, h.digest(),
padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH),
asym_utils.Prehashed(hashes.SHA256())
)
priv = _rsa_load_private(player_privkey)
key = priv.decrypt(
enc_key,
padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None)
)
return key
def _is_modern_license_doc(lic: dict) -> bool:
return "enc_key_wrapped_b64" in lic and "dev_pub_b64" in lic
def _verify_modern_manifest_license(manifest: dict, lic: dict) -> None:
core = manifest_core_from_dict(manifest)
sig = manifest_signature_from_dict(manifest)
ManifestSigner.verify_manifest(core, sig)
LicenseManager.verify_license(license_doc_from_dict(lic), sig, core=core)
def _unwrap_content_key_for_manifest(
manifest: dict,
license_path: Path,
player_privkey: Path,
legacy_dev_pubkey: Optional[Path] = None,
) -> bytes:
lic = json.loads(license_path.read_text())
if _is_modern_license_doc(lic):
core = manifest_core_from_dict(manifest)
sig = manifest_signature_from_dict(manifest)
ManifestSigner.verify_manifest(core, sig)
return LicenseManager.verify_and_unwrap(
license_doc_from_dict(lic),
sig,
player_privkey.read_bytes(),
core=core,
)
return _decrypt_content_key(license_path, legacy_dev_pubkey, player_privkey)
# ------------------------------
# General helpers (hashing, IO, URLs)
# ------------------------------
def _round_piece_len(n: int) -> int:
# Keep it power-of-two-ish later; for now clamp
return max(16 * 1024, min(4 * 1024 * 1024, int(n)))
def _compute_sha256(path: Path) -> Tuple[str, int]:
h = hashlib.sha256()
size = 0
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(1024 * 1024), b""):
size += len(chunk)
h.update(chunk)
return h.hexdigest(), size
def _sha1_to_hex(h) -> str:
try:
return h.to_bytes().hex()
except Exception:
pass
try:
s = h.to_string()
if isinstance(s, (bytes, bytearray)):
return bytes(s).hex()
if isinstance(s, str) and len(s) == 40 and all(c in "0123456789abcdefABCDEF" for c in s):
return s.lower()
except Exception:
pass
return ""
def _is_url(s: str) -> bool:
return s.startswith("http://") or s.startswith("https://")
def _read_text_from_uri(uri: str) -> str:
if _is_url(uri):
with urllib.request.urlopen(uri) as r:
return r.read().decode("utf-8")
return Path(uri).read_text()
def create_arcpack(input_path: Path, out_dir: Path, pack_basename: str) -> Tuple[Path, Optional[str]]:
"""Build an .arcpack ZIP. If input_path is a file, return (path, arcname)."""
out_dir.mkdir(parents=True, exist_ok=True)
arcpack_path = out_dir / f"{pack_basename}.arcpack"
if input_path.is_file():
arcname = input_path.name
with zipfile.ZipFile(arcpack_path, "w", zipfile.ZIP_DEFLATED) as z:
z.write(input_path, arcname)
return arcpack_path, arcname
with zipfile.ZipFile(arcpack_path, "w", zipfile.ZIP_DEFLATED) as z:
for root, _, files in os.walk(input_path):
files.sort()
for fn in files:
p = Path(root) / fn
z.write(p, p.relative_to(input_path).as_posix())
return arcpack_path, None
# ------------------------------
# DB (always-on, local SQLite)
# ------------------------------
def _db_path(role: str) -> Path:
"""
role: 'dev' for seeder-side metrics, 'client' for player-side metrics.
Env overrides:
ARCADIA_DEV_DB (defaults: ~/.arcadia/dev.db)
ARCADIA_CLIENT_DB (defaults: ~/.arcadia/library.db)
"""
if role == "dev":
return Path(os.environ.get("ARCADIA_DEV_DB", str(Path.home()/".arcadia"/"dev.db"))).expanduser()
return Path(os.environ.get("ARCADIA_CLIENT_DB", str(Path.home()/".arcadia"/"library.db"))).expanduser()
_DDL = """
PRAGMA journal_mode=WAL;
PRAGMA foreign_keys=ON;
CREATE TABLE IF NOT EXISTS transfer_session (
id INTEGER PRIMARY KEY AUTOINCREMENT,
role TEXT NOT NULL, -- 'client' | 'seeder'
game_id TEXT NOT NULL,
version TEXT NOT NULL,
infohash TEXT,
size_bytes INTEGER,
started_utc TEXT NOT NULL,
completed_utc TEXT,
result TEXT, -- 'ok' | 'timeout' | 'error' | 'cancel'
error_msg TEXT
);
CREATE TABLE IF NOT EXISTS transfer_progress (
sess_id INTEGER NOT NULL REFERENCES transfer_session(id) ON DELETE CASCADE,
ts_utc TEXT NOT NULL,
peers INTEGER,
down_bps INTEGER,
up_bps INTEGER,
progress_pct REAL
);
CREATE INDEX IF NOT EXISTS idx_tp_sess ON transfer_progress(sess_id, ts_utc);
CREATE TABLE IF NOT EXISTS launch_session (
id INTEGER PRIMARY KEY AUTOINCREMENT,
game_id TEXT NOT NULL,
version TEXT NOT NULL,
encrypted INTEGER NOT NULL,
started_utc TEXT NOT NULL,
completed_utc TEXT,
exit_code INTEGER,
result TEXT, -- 'ok' | 'verify-fail' | 'spawn-fail' | 'error'
error_msg TEXT
);
"""
def _db_init(dbp: Path) -> None:
dbp.parent.mkdir(parents=True, exist_ok=True)
with sqlite3.connect(dbp) as cx:
cx.executescript(_DDL)
cx.commit()
def _utc() -> str:
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
def _tx(dbp: Path):
"""Autocommit connection for quick inserts/updates."""
return sqlite3.connect(dbp, isolation_level=None)
def _infer_id_ver_from_name(name: str) -> tuple[str, str]:
"""
Best-effort: 'game42-1.0.0.arcpack' or 'game42-1.0.0.arcpack.enc' -> ('game42','1.0.0')
"""
stem = name
for suf in (".arcpack.enc", ".arcpack", ".zip", ".bin"):
if stem.endswith(suf):
stem = stem[: -len(suf)]
break
i = stem.rfind("-")
if i <= 0:
return stem, "0"
return stem[:i], stem[i+1:]
# ------------------------------
# Libtorrent helpers (create & download)
# ------------------------------
from urllib.parse import quote as _urlquote
def create_torrent_with_libtorrent(
payload: Path, trackers: List[str], piece_len_bytes: int, private: bool
) -> Tuple[bytes, str, str]:
"""Return (bencoded .torrent bytes, infohash_hex_v1, magnet_uri)."""
if lt is None:
raise RuntimeError("libtorrent not available")
fs = lt.file_storage()
fs.add_file(payload.name, payload.stat().st_size)
try:
flags = lt.create_torrent_flags.v1_only
except Exception:
flags = 0
try:
ct = lt.create_torrent(fs, piece_size=piece_len_bytes, flags=flags)
except TypeError:
ct = lt.create_torrent(fs, piece_len_bytes)
for tr in trackers or []:
try:
ct.add_tracker(tr)
except Exception:
LOGGER.debug("[pack] failed to add tracker %s", tr)
if private:
try:
ct.set_priv(True)
except Exception:
pass
lt.set_piece_hashes(ct, str(payload.parent))
tor = ct.generate()
data = lt.bencode(tor)
ti = lt.torrent_info(tor)
ih_hex = ""
try:
ih_hex = _sha1_to_hex(ti.info_hashes().v1) # libtorrent 2.x
except Exception:
try:
ih_hex = _sha1_to_hex(ti.info_hash()) # libtorrent 1.2.x
except Exception:
ih_hex = ""
try:
magnet = lt.make_magnet_uri(ti)
except Exception:
magnet = f"magnet:?xt=urn:btih:{ih_hex}&dn={_urlquote(payload.name)}"
for tr in trackers or []:
magnet += f"&tr={_urlquote(tr)}"
return data, ih_hex, magnet
class DownloadResult:
def __init__(self, path: Path, bytes_written: int, elapsed_s: float):
self.path = path
self.bytes_written = bytes_written
self.elapsed_s = elapsed_s
class TransportTimeoutError(TimeoutError):
def __init__(self, reason: str):
super().__init__(f"download timeout: {reason}")
self.reason = reason
class TransportDiagnostics:
def __init__(
self,
source: str,
save_dir: Path,
listen_port: int,
timeout_s: int,
peers: Optional[List[Tuple[str, int]]] = None,
):
self.started_utc = _utc()
self.completed_utc = ""
self.source = source
self.source_kind = "magnet" if source.startswith("magnet:") else "infohash"
self.save_dir = str(save_dir)
self.listen_port = int(listen_port)
self.timeout_s = int(timeout_s or 0)
self.direct_peers = [f"{ip}:{port}" for ip, port in (peers or [])]
self.session = {
"dht": True,
"lsd": True,
"upnp": False,
"natpmp": False,
"dht_routers": [],
}
self.events: list[dict] = []
self.alerts: list[str] = []
self.samples: list[dict] = []
self.max_peers = 0
self.max_progress_pct = 0.0
self.max_total_done = 0
self.first_peer_elapsed_s: Optional[float] = None
self.first_progress_elapsed_s: Optional[float] = None
self.last_progress_elapsed_s: Optional[float] = None
self.result = "running"
self.failure_reason = ""
self.error_msg = ""
self.output_path = ""
self.bytes_written = 0
self.elapsed_s = 0.0
def event(self, kind: str, message: str, **fields) -> None:
item = {"ts_utc": _utc(), "kind": kind, "message": message}
if fields:
item.update(fields)
self.events.append(item)
def add_alert(self, message: str) -> None:
if len(self.alerts) < 80:
self.alerts.append(message)
def observe(self, status, elapsed_s: float) -> None:
sample = _transport_status_snapshot(status, elapsed_s)
self.samples.append(sample)
if len(self.samples) > 240:
self.samples = self.samples[-240:]
peers = int(sample.get("peers") or 0)
progress_pct = float(sample.get("progress_pct") or 0.0)
total_done = int(sample.get("total_done") or 0)
old_max_progress = self.max_progress_pct
old_max_total_done = self.max_total_done
self.max_peers = max(self.max_peers, peers)
self.max_progress_pct = max(self.max_progress_pct, progress_pct)
self.max_total_done = max(self.max_total_done, total_done)
if peers > 0 and self.first_peer_elapsed_s is None:
self.first_peer_elapsed_s = round(elapsed_s, 2)
if progress_pct > 0 and self.first_progress_elapsed_s is None:
self.first_progress_elapsed_s = round(elapsed_s, 2)
if progress_pct > old_max_progress or total_done > old_max_total_done:
self.last_progress_elapsed_s = round(elapsed_s, 2)
def finish(
self,
result: str,
elapsed_s: float,
failure_reason: str = "",
error_msg: str = "",
output_path: str = "",
bytes_written: int = 0,
) -> None:
self.completed_utc = _utc()
self.result = result
self.elapsed_s = round(float(elapsed_s), 3)
self.failure_reason = failure_reason
self.error_msg = error_msg
self.output_path = output_path
self.bytes_written = int(bytes_written or 0)
def to_dict(self) -> dict:
return {
"started_utc": self.started_utc,
"completed_utc": self.completed_utc,
"result": self.result,
"failure_reason": self.failure_reason,
"error_msg": self.error_msg,
"elapsed_s": self.elapsed_s,
"source_kind": self.source_kind,
"source": self.source,
"save_dir": self.save_dir,
"listen_port": self.listen_port,
"timeout_s": self.timeout_s,
"direct_peers": self.direct_peers,
"session": self.session,
"summary": {
"max_peers": self.max_peers,
"max_progress_pct": round(self.max_progress_pct, 3),
"max_total_done": self.max_total_done,
"first_peer_elapsed_s": self.first_peer_elapsed_s,
"first_progress_elapsed_s": self.first_progress_elapsed_s,
"last_progress_elapsed_s": self.last_progress_elapsed_s,
"sample_count": len(self.samples),
"alert_count": len(self.alerts),
},
"output_path": self.output_path,
"bytes_written": self.bytes_written,
"events": self.events,
"alerts": self.alerts,
"samples": self.samples,
}
def _safe_status_value(status, name: str, default=None):
try:
value = getattr(status, name)
if callable(value):
return value()
return value
except Exception:
return default
def _transport_status_snapshot(status, elapsed_s: float) -> dict:
progress = float(_safe_status_value(status, "progress", 0.0) or 0.0)
state = _safe_status_value(status, "state", "")
return {
"elapsed_s": round(float(elapsed_s), 2),
"peers": int(_safe_status_value(status, "num_peers", 0) or 0),
"down_bps": int(_safe_status_value(status, "download_rate", 0) or 0),
"up_bps": int(_safe_status_value(status, "upload_rate", 0) or 0),
"progress_pct": round(progress * 100.0, 3),
"total_done": int(_safe_status_value(status, "total_done", 0) or 0),
"is_seeding": bool(_safe_status_value(status, "is_seeding", False)),
"has_metadata": bool(_safe_status_value(status, "has_metadata", False)),
"state": str(state),
}
def _collect_libtorrent_alerts(session, diagnostics: Optional[TransportDiagnostics]) -> None:
if diagnostics is None or not hasattr(session, "pop_alerts"):
return
try:
for alert in session.pop_alerts():
diagnostics.add_alert(str(alert))
except Exception:
pass
def _classify_transport_timeout(diagnostics: Optional[TransportDiagnostics]) -> str:
if diagnostics is None:
return "timeout"
if not diagnostics.samples:
return "no-status-samples"
if diagnostics.source_kind == "magnet" and not any(s.get("has_metadata") for s in diagnostics.samples):
return "metadata-timeout"
if diagnostics.max_peers <= 0:
return "no-peers"
if diagnostics.max_total_done <= 0 and diagnostics.max_progress_pct <= 0:
return "connected-no-progress"
return "stalled"
def _write_transport_diagnostics(path: Optional[str], diagnostics: Optional[TransportDiagnostics]) -> None:
if not path or diagnostics is None:
return
out = Path(path).expanduser()
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(diagnostics.to_dict(), indent=2), encoding="utf-8")
def _last_transport_elapsed(diagnostics: Optional[TransportDiagnostics]) -> float:
if diagnostics and diagnostics.samples:
return float(diagnostics.samples[-1].get("elapsed_s") or 0.0)
return 0.0
def _download_with_libtorrent(
magnet_or_info: str,
save_dir: Path,
listen_port: int,
timeout_s: int = 0,
peers: Optional[List[Tuple[str, int]]] = None,
progress_cb=None, # NEW: DB progress hook
diagnostics: Optional[TransportDiagnostics] = None,
) -> DownloadResult:
if lt is None:
raise RuntimeError("libtorrent not available")
save_dir.mkdir(parents=True, exist_ok=True)
# Session: DHT + LSD, no UPnP/NAT-PMP for simplicity
try:
sp = lt.settings_pack()
sp.set_str(lt.settings_pack.listen_interfaces, f"0.0.0.0:{listen_port}")
sp.set_bool(lt.settings_pack.enable_upnp, False)
sp.set_bool(lt.settings_pack.enable_natpmp, False)
sp.set_bool(lt.settings_pack.enable_lsd, True)
sp.set_bool(lt.settings_pack.enable_dht, True)
ses = lt.session(sp)
if diagnostics:
diagnostics.event("session", "created settings_pack session", listen_port=listen_port)
try:
for router in ("router.bittorrent.com", "router.utorrent.com", "dht.transmissionbt.com"):
ses.add_dht_router(router, 6881)
if diagnostics:
diagnostics.session["dht_routers"].append(f"{router}:6881")
ses.start_dht()
if diagnostics:
diagnostics.event("dht", "started DHT")
except Exception as e:
if diagnostics:
diagnostics.event("dht", "failed to start DHT", error=str(e))
except Exception:
ses = lt.session()
if diagnostics:
diagnostics.event("session", "created fallback session", listen_port=listen_port)
try:
ses.listen_on(listen_port, listen_port)
if diagnostics:
diagnostics.event("listen", "bound fallback listen port", listen_port=listen_port)
except Exception as e:
if diagnostics:
diagnostics.event("listen", "failed to bind fallback listen port", listen_port=listen_port, error=str(e))
params = lt.add_torrent_params()
if magnet_or_info.startswith("magnet:"):
params = lt.parse_magnet_uri(magnet_or_info)
if diagnostics:
diagnostics.event("torrent", "parsed magnet URI")
else:
params.info_hash = magnet_or_info # expecting 40-hex btih
if diagnostics:
diagnostics.event("torrent", "using infohash", infohash=magnet_or_info)
params.save_path = str(save_dir)
if peers:
try:
params.peers = [(ip, int(port)) for (ip, port) in peers]
if diagnostics:
diagnostics.event("peers", "added direct peers", peers=[f"{ip}:{port}" for ip, port in peers])
except Exception as e:
if diagnostics:
diagnostics.event("peers", "failed to add direct peers", error=str(e))
h = ses.add_torrent(params)
if diagnostics:
diagnostics.event("torrent", "added torrent to session")
start = time.time()
last_log = 0.0
while True:
s = h.status()
elapsed = time.time() - start
if diagnostics:
diagnostics.observe(s, elapsed)
try:
if hasattr(h, "has_metadata") and h.has_metadata():
diagnostics.samples[-1]["has_metadata"] = True
except Exception:
pass
_collect_libtorrent_alerts(ses, diagnostics)
if s.is_seeding:
break
if timeout_s and elapsed > timeout_s:
reason = _classify_transport_timeout(diagnostics)
if diagnostics:
diagnostics.finish("timeout", elapsed, failure_reason=reason, error_msg=f"download timeout: {reason}")
raise TransportTimeoutError(reason)
now = time.time()
if now - last_log > 1.0:
last_log = now
LOGGER.info("[get] peers=%d down=%.1f kB/s prog=%.1f%%",
s.num_peers, s.download_rate/1024.0, s.progress*100)
if progress_cb:
try:
progress_cb(s)
except Exception:
pass
time.sleep(0.25)
ti = h.get_torrent_info()
if ti.num_files() == 1:
out_path = save_dir / ti.files().file_path(0)
else:
out_path = save_dir / ti.name()
result = DownloadResult(out_path, h.status().total_done, time.time() - start)
if diagnostics:
diagnostics.finish("ok", result.elapsed_s, output_path=str(out_path), bytes_written=result.bytes_written)
return result
# ------------------------------
# Executable discovery helpers
# ------------------------------
def _is_probably_executable(p: Path) -> bool:
if not p.is_file():
return False
if os.name == "nt":
return p.suffix.lower() in (".exe", ".bat", ".cmd")
try:
st = p.stat().st_mode
if st & 0o111:
return True
with p.open("rb") as f:
head = f.read(4)
return head.startswith(b"#!") or head.startswith(b"\x7fELF")
except Exception:
return False
def _discover_executable(run_dir: Path, preferred_names: list[str]) -> Optional[Path]:
candidates: list[Path] = []
try:
for root, _, files in os.walk(run_dir):
files.sort()
for fn in files:
p = Path(root) / fn
if _is_probably_executable(p):
candidates.append(p)
except Exception:
return None
if not candidates:
return None
lowers = [n.lower() for n in preferred_names if n]
for p in candidates:
if p.name.lower() in lowers:
return p
for p in candidates:
if any(n in p.name.lower() for n in lowers):
return p
return candidates[0]
# ------------------------------
# Handlers: pack & seed
# ------------------------------
def handle_pack(args: argparse.Namespace) -> int:
LOGGER.info("[pack] name=%s id=%s ver=%s platform=%s", args.name, args.id, args.version, args.platform)
input_path = Path(args.input_dir).expanduser().resolve()
out_dir = Path(args.out_dir).expanduser().resolve()
if not input_path.exists():
LOGGER.error("[pack] input path not found: %s", input_path)
return 2
pack_basename = f"{args.id}-{args.version}"
LOGGER.info("[pack] creating arcpack → %s", out_dir / f"{pack_basename}.arcpack")
arcpack_path, single_arcname = create_arcpack(input_path, out_dir, pack_basename)
with zipfile.ZipFile(arcpack_path, "r") as z:
if len(z.namelist()) == 0:
LOGGER.error("[pack] empty archive; aborting.")
try: arcpack_path.unlink()
except Exception: pass
return 2
plaintext_sha256, _ = _compute_sha256(arcpack_path)
# Choose payload (plain vs encrypted)
if args.encrypt:
content_key = secrets.token_bytes(32)
enc_path = arcpack_path.with_suffix(".arcpack.enc")
enc_meta = _encrypt_file_aesgcm(arcpack_path, enc_path, content_key)
torrent_payload = enc_path
content_sha256 = enc_meta["ciphertext_sha256"]
nonce_b64 = enc_meta["nonce_b64"]
else:
torrent_payload = arcpack_path
content_sha256 = plaintext_sha256
nonce_b64 = ""
size_bytes = torrent_payload.stat().st_size
# Create torrent
magnet = ""
infohash = ""
if not args.no_torrent:
if lt is None:
LOGGER.error("[pack] libtorrent not available; cannot create torrent")
return 3
data, ih_hex, magnet = create_torrent_with_libtorrent(
torrent_payload, args.tracker or [], _round_piece_len(512 * 1024), args.private
)
infohash = ih_hex
(out_dir / f"{pack_basename}.torrent").write_bytes(data)
LOGGER.info("[pack] wrote torrent → %s", out_dir / f"{pack_basename}.torrent")
LOGGER.debug("[pack] infohash=%s magnet=%s", ih_hex, magnet)
# Infer launch_rel if not provided
inferred_launch = args.launch_rel or args.id
if not args.launch_rel:
if single_arcname is not None:
inferred_launch = single_arcname
else:
try:
execs = []
for root, _, files in os.walk(input_path):
for fn in files:
p = Path(root) / fn
if _is_probably_executable(p):
execs.append(p.relative_to(input_path).as_posix())
execs.sort()
if execs:
inferred_launch = execs[0]
LOGGER.info("[pack] inferred launch_rel: %s", inferred_launch)
except Exception:
pass
# Write manifest
manifest = {
"schema_version": "2",
"game_id": args.id,
"name": args.name,
"version": args.version,
"platforms": [args.platform],
"size_bytes": size_bytes,
"content_sha256": content_sha256,
"payload_sha256": content_sha256,
"plaintext_sha256": plaintext_sha256,
"torrent": ({"magnet": magnet, "infohash": infohash} if magnet else {}),
"launch": inferred_launch,
"encryption": {
"enabled": bool(args.encrypt),
"alg": "AES-256-GCM" if args.encrypt else "",
"nonce_b64": nonce_b64,
},
"created_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
}
if getattr(args, "dev_ed25519", None):
sig = SecurityContext().sign_manifest(
manifest_core_from_dict(manifest),
Path(args.dev_ed25519).expanduser().read_bytes(),
)
manifest["signature"] = manifest_signature_to_dict(sig)
manifest["developer"] = {
"key_alg": "ed25519",
"dev_pub_b64": sig.dev_pub_b64,
}
manifest_path = out_dir / f"{pack_basename}.arcmanifest"
manifest_path.write_text(json.dumps(manifest, indent=2))
LOGGER.info("[pack] wrote manifest → %s", manifest_path)
# Optional per-client license
if args.encrypt and getattr(args, "dev_ed25519", None) and args.client_pubkey:
lic_doc = SecurityContext().issue_license(
args.id,
args.version,
content_key,
Path(args.dev_ed25519).expanduser().read_bytes(),
Path(args.client_pubkey).expanduser().read_bytes(),
)
lic = license_doc_to_dict(lic_doc)
lic_path = out_dir / f"{pack_basename}.license.json"
lic_path.write_text(json.dumps(lic, indent=2))
LOGGER.info("[pack] wrote license → %s", lic_path)
elif args.encrypt and args.dev_privkey and args.client_pubkey:
lic = _make_license(args.id, args.version, content_key, Path(args.dev_privkey), Path(args.client_pubkey))
lic_path = out_dir / f"{pack_basename}.license.json"
lic_path.write_text(json.dumps(lic, indent=2))
LOGGER.info("[pack] wrote license → %s", lic_path)
if args.print_magnet and magnet:
print(magnet)
return 0
def handle_seed(args: argparse.Namespace) -> int:
if lt is None:
LOGGER.error("libtorrent is required for `seed`.")
return 2
torrent_path = Path(args.torrent).expanduser().resolve()
content_dir = Path(args.content_dir).expanduser().resolve()
if not torrent_path.exists():
LOGGER.error("[seed] .torrent not found: %s", torrent_path)
return 2
if not content_dir.exists():
LOGGER.error("[seed] content dir not found: %s", content_dir)
return 2
# Session: DHT + LSD, no UPnP/NAT-PMP
try:
sp = lt.settings_pack()
sp.set_str(lt.settings_pack.listen_interfaces, f"0.0.0.0:{args.listen_port}")
sp.set_bool(lt.settings_pack.enable_upnp, False)
sp.set_bool(lt.settings_pack.enable_natpmp, False)
sp.set_bool(lt.settings_pack.enable_lsd, True)
sp.set_bool(lt.settings_pack.enable_dht, True)
ses = lt.session(sp)
try:
ses.add_dht_router("router.bittorrent.com", 6881)
ses.add_dht_router("router.utorrent.com", 6881)
ses.add_dht_router("dht.transmissionbt.com", 6881)
ses.start_dht()
except Exception:
pass
except Exception:
ses = lt.session()
try:
ses.listen_on(args.listen_port, args.listen_port)
except Exception:
pass
ti = lt.torrent_info(str(torrent_path))
params = lt.add_torrent_params()
params.ti = ti
params.save_path = str(content_dir)
try:
params.flags |= lt.torrent_flags.seed_mode
except Exception:
pass
# --- DB: open dev/seeder session ---
name_inside = ti.name()
_seed_game_id, _seed_version = _infer_id_ver_from_name(name_inside)
_dev_db = _db_path("dev")
_db_init(_dev_db)
with _tx(_dev_db) as cx:
cur = cx.execute(
"INSERT INTO transfer_session(role,game_id,version,infohash,size_bytes,started_utc) VALUES(?,?,?,?,?,?)",
("seeder", _seed_game_id, _seed_version,
getattr(ti, "info_hash", lambda: "")() if hasattr(ti, "info_hash") else "",
int(getattr(ti, "total_size", lambda: 0)()), _utc())
)
_seed_sess_id = cur.lastrowid
h = ses.add_torrent(params)
LOGGER.info("[seed] Seeding %s on %s (Ctrl+C to stop)", ti.name(), args.listen_port)
last = 0.0
try:
while True:
s = h.status()
now = time.time()
if now - last > 1.0:
last = now
LOGGER.info("[seed] peers=%d up=%.1f kB/s", s.num_peers, s.upload_rate/1024.0)
# DB progress row
try:
with _tx(_dev_db) as cx:
cx.execute(
"INSERT INTO transfer_progress(sess_id,ts_utc,peers,down_bps,up_bps,progress_pct) VALUES(?,?,?,?,?,?)",
(_seed_sess_id, _utc(), int(s.num_peers), 0, int(s.upload_rate), 100.0 if s.is_seeding else None)
)
except Exception:
pass
time.sleep(0.25)
except KeyboardInterrupt:
LOGGER.info("[seed] stopping…")
finally:
try:
with _tx(_dev_db) as cx:
cx.execute("UPDATE transfer_session SET completed_utc=?, result='ok' WHERE id=?",
(_utc(), _seed_sess_id))
except Exception:
pass
return 0
# ------------------------------
# Handlers: get, list, launch, inspect
# ------------------------------
def handle_get(args: argparse.Namespace) -> int:
if lt is None:
LOGGER.error("libtorrent not available — install python bindings")
return 2
LOGGER.info("[get] manifest=%s install_root=%s", args.manifest, args.install_root)
# 1) Load manifest
try:
raw = _read_text_from_uri(args.manifest)