feat(server): add self-hosted fws Arch repo server and Caddy config
Publishes the Python stdlib server (admin UI, upload API, repo-add compatible DB generation) with its deployed Caddyfile, install script and pacman client snippet, so the whole fws repository stack lives next to the package sources. 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com>
This commit is contained in:
1 parent
a73a901389
commit
c903e28254
10 files changed
+1851
No files matched your search
Executable
+505
@@ -0,0 +1,505 @@
|
||||
#!/usr/bin/env python3
|
||||
"""archrepo — petit serveur pour un dépôt pacman auto-hébergé.
|
||||
|
||||
Gère l'interface d'administration (/admin/) et l'API JSON (/api/*) qui permet
|
||||
d'envoyer des paquets, de les supprimer et de reconstruire <repo>.db / .files.
|
||||
Les paquets et les bases eux-mêmes sont servis directement par Caddy depuis
|
||||
$ARCHREPO_ROOT/$ARCHREPO_ARCH, ce processus ne traite que l'administration.
|
||||
|
||||
Dépendances : Python >= 3.10 et les binaires zstd / xz (selon les formats reçus).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import signal
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
import urllib.parse
|
||||
import uuid
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
import repo # noqa: E402 (module local)
|
||||
|
||||
API_TOKEN_HEADERS = ("Authorization", "X-Repo-Token")
|
||||
PUBLIC_PACKAGE_FIELDS = (
|
||||
"name",
|
||||
"version",
|
||||
"arch",
|
||||
"desc",
|
||||
"filename",
|
||||
"csize",
|
||||
"isize",
|
||||
"builddate",
|
||||
"packager",
|
||||
"md5sum",
|
||||
"sha256sum",
|
||||
"depends",
|
||||
"mtime",
|
||||
"warnings",
|
||||
)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Configuration
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def _int(value: str | None, default: int) -> int:
|
||||
try:
|
||||
return int(value) if value not in (None, "") else default
|
||||
except ValueError:
|
||||
return default
|
||||
|
||||
|
||||
def _split_bind(value: str) -> tuple[str, int]:
|
||||
host, _, port = value.rpartition(":")
|
||||
if not host:
|
||||
host = "127.0.0.1"
|
||||
return host, _int(port, 8099)
|
||||
|
||||
|
||||
class Config:
|
||||
def __init__(self) -> None:
|
||||
env = os.environ.get
|
||||
self.root = os.path.abspath(env("ARCHREPO_ROOT", "/var/www/fws"))
|
||||
self.arch = env("ARCHREPO_ARCH", "x86_64")
|
||||
self.name = env("ARCHREPO_NAME", "fws")
|
||||
self.bind_host, self.bind_port = _split_bind(
|
||||
env("ARCHREPO_BIND", "127.0.0.1:8099")
|
||||
)
|
||||
self.token_file = env("ARCHREPO_TOKEN_FILE", "/etc/archrepo/token")
|
||||
self.state_dir = os.path.abspath(env("ARCHREPO_STATE_DIR", "/var/lib/archrepo"))
|
||||
self.max_upload = _int(env("ARCHREPO_MAX_UPLOAD"), 4 * 1024 ** 3)
|
||||
self.static_dir = os.path.join(
|
||||
os.path.dirname(os.path.abspath(__file__)), "static"
|
||||
)
|
||||
self.packages_dir = os.path.join(self.root, self.arch)
|
||||
self.index_file = os.path.join(self.state_dir, "index.json")
|
||||
self.db_file = os.path.join(self.packages_dir, self.name + ".db.tar.gz")
|
||||
|
||||
|
||||
def _load_token(path: str) -> str:
|
||||
try:
|
||||
with open(path, encoding="utf-8") as handle:
|
||||
token = handle.read().strip()
|
||||
if token:
|
||||
return token
|
||||
raise RuntimeError(f"jeton vide : {path}")
|
||||
except FileNotFoundError as exc:
|
||||
raise RuntimeError(
|
||||
f"jeton introuvable : {path} (lancez install.sh pour le générer)"
|
||||
) from exc
|
||||
|
||||
|
||||
def _sha256_file(path: str) -> str:
|
||||
return repo.checksums(path)[1]
|
||||
|
||||
|
||||
def _unlink(path: str) -> None:
|
||||
try:
|
||||
os.unlink(path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# État applicatif
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
class App:
|
||||
def __init__(self, config: Config) -> None:
|
||||
self.cfg = config
|
||||
self.lock = threading.RLock()
|
||||
self.cache: dict[str, dict] = {}
|
||||
os.makedirs(config.packages_dir, exist_ok=True)
|
||||
os.makedirs(config.state_dir, exist_ok=True)
|
||||
self.token = _load_token(config.token_file)
|
||||
self._load_index()
|
||||
if not os.path.exists(config.db_file):
|
||||
try:
|
||||
self.rebuild()
|
||||
print("archrepo: base initiale créée", flush=True)
|
||||
except Exception:
|
||||
traceback.print_exc()
|
||||
|
||||
# -- index disque (évite de re-hacher tous les paquets à chaque scan) --
|
||||
def _load_index(self) -> None:
|
||||
try:
|
||||
with open(self.cfg.index_file, encoding="utf-8") as handle:
|
||||
payload = json.load(handle)
|
||||
cached = payload.get("packages")
|
||||
if isinstance(cached, dict):
|
||||
# On ne fait confiance qu'aux entrées connues du répertoire.
|
||||
present = set(os.listdir(self.cfg.packages_dir))
|
||||
self.cache = {
|
||||
name: entry
|
||||
for name, entry in cached.items()
|
||||
if name in present and isinstance(entry, dict)
|
||||
}
|
||||
except (OSError, ValueError, AttributeError):
|
||||
self.cache = {}
|
||||
|
||||
def _save_index(self) -> None:
|
||||
tmp = self.cfg.index_file + ".new"
|
||||
with open(tmp, "w", encoding="utf-8") as handle:
|
||||
json.dump({"version": 1, "packages": self.cache}, handle, sort_keys=True)
|
||||
os.replace(tmp, self.cfg.index_file)
|
||||
|
||||
def scan(self) -> dict[str, dict]:
|
||||
with self.lock:
|
||||
self.cache = repo.scan_packages(self.cfg.packages_dir, self.cache)
|
||||
return dict(self.cache)
|
||||
|
||||
def rebuild(self) -> tuple[list[dict], dict]:
|
||||
with self.lock:
|
||||
self.cache = repo.scan_packages(self.cfg.packages_dir, self.cache)
|
||||
latest = repo.latest_by_name(self.cache.values())
|
||||
stats = repo.build_databases(self.cfg.packages_dir, self.cfg.name, latest)
|
||||
self._save_index()
|
||||
return latest, stats
|
||||
|
||||
def stats(self) -> dict:
|
||||
try:
|
||||
stat = os.stat(self.cfg.db_file)
|
||||
db_size, db_updated = stat.st_size, int(stat.st_mtime)
|
||||
except OSError:
|
||||
db_size, db_updated = 0, 0
|
||||
return {"db_size": db_size, "db_updated": db_updated}
|
||||
|
||||
|
||||
def _public(pkg: dict) -> dict:
|
||||
data = {key: pkg.get(key) for key in PUBLIC_PACKAGE_FIELDS}
|
||||
data["file_count"] = len(pkg.get("files") or [])
|
||||
return data
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# HTTP
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
server_version = "archrepo/1.0"
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
@property
|
||||
def app(self) -> App:
|
||||
return self.server.app # type: ignore[attr-defined]
|
||||
|
||||
def log_message(self, fmt: str, *args) -> None:
|
||||
sys.stderr.write("%s - %s\n" % (self.address_string(), fmt % args))
|
||||
|
||||
# -- réponses -----------------------------------------------------------
|
||||
def _json(self, status: int, payload: dict, close: bool = False) -> None:
|
||||
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
if close:
|
||||
self.close_connection = True
|
||||
self.send_header("Connection", "close")
|
||||
self.end_headers()
|
||||
try:
|
||||
self.wfile.write(body)
|
||||
except (BrokenPipeError, ConnectionResetError):
|
||||
self.close_connection = True
|
||||
|
||||
def _error(self, status: int, message: str, close: bool = False) -> None:
|
||||
self._json(status, {"ok": False, "error": message}, close=close)
|
||||
|
||||
def _file(self, path: str, content_type: str) -> None:
|
||||
try:
|
||||
with open(path, "rb") as handle:
|
||||
body = handle.read()
|
||||
except OSError:
|
||||
return self._error(404, "fichier introuvable")
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", content_type)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.send_header("Cache-Control", "no-cache")
|
||||
self.end_headers()
|
||||
try:
|
||||
self.wfile.write(body)
|
||||
except (BrokenPipeError, ConnectionResetError):
|
||||
self.close_connection = True
|
||||
|
||||
def _redirect(self, location: str) -> None:
|
||||
self.send_response(302)
|
||||
self.send_header("Location", location)
|
||||
self.send_header("Content-Length", "0")
|
||||
self.end_headers()
|
||||
|
||||
# -- authentification ---------------------------------------------------
|
||||
def _token_from_request(self) -> str:
|
||||
for header in API_TOKEN_HEADERS:
|
||||
value = (self.headers.get(header) or "").strip()
|
||||
if not value:
|
||||
continue
|
||||
if header == "Authorization":
|
||||
scheme, _, rest = value.partition(" ")
|
||||
if scheme.lower() == "bearer" and rest.strip():
|
||||
return rest.strip()
|
||||
continue
|
||||
return value
|
||||
return ""
|
||||
|
||||
def _authorized(self) -> bool:
|
||||
token = self._token_from_request()
|
||||
return bool(token) and hmac.compare_digest(token, self.app.token)
|
||||
|
||||
def _require_auth(self) -> bool:
|
||||
if self._authorized():
|
||||
return True
|
||||
self.close_connection = True
|
||||
self._error(401, "jeton invalide ou absent", close=True)
|
||||
return False
|
||||
|
||||
# -- routes -------------------------------------------------------------
|
||||
def do_HEAD(self) -> None:
|
||||
self.do_GET()
|
||||
|
||||
def do_GET(self) -> None:
|
||||
path = urllib.parse.urlsplit(self.path).path
|
||||
try:
|
||||
if path == "/":
|
||||
return self._redirect("/admin/")
|
||||
if path in ("/admin", "/admin/"):
|
||||
return self._file(
|
||||
os.path.join(self.app.cfg.static_dir, "index.html"),
|
||||
"text/html; charset=utf-8",
|
||||
)
|
||||
if path == "/api/health":
|
||||
cfg = self.app.cfg
|
||||
return self._json(
|
||||
200,
|
||||
{
|
||||
"ok": True,
|
||||
"repo": cfg.name,
|
||||
"arch": cfg.arch,
|
||||
"service": self.server_version,
|
||||
"time": int(time.time()),
|
||||
},
|
||||
)
|
||||
if path == "/api/packages":
|
||||
if not self._require_auth():
|
||||
return None
|
||||
return self._list_packages()
|
||||
if path.startswith("/api/"):
|
||||
if not self._require_auth():
|
||||
return None
|
||||
return self._error(404, "route inconnue")
|
||||
return self._error(404, "introuvable")
|
||||
except (BrokenPipeError, ConnectionResetError):
|
||||
self.close_connection = True
|
||||
except Exception:
|
||||
traceback.print_exc()
|
||||
self._error(500, "erreur interne du serveur")
|
||||
|
||||
def do_POST(self) -> None:
|
||||
path = urllib.parse.urlsplit(self.path).path
|
||||
try:
|
||||
if path == "/api/packages":
|
||||
return self._upload()
|
||||
if path == "/api/rebuild":
|
||||
if not self._require_auth():
|
||||
return None
|
||||
return self._rebuild()
|
||||
return self._error(404, "route inconnue")
|
||||
except (BrokenPipeError, ConnectionResetError):
|
||||
self.close_connection = True
|
||||
except Exception:
|
||||
traceback.print_exc()
|
||||
self.close_connection = True
|
||||
self._error(500, "erreur interne du serveur")
|
||||
|
||||
def do_DELETE(self) -> None:
|
||||
path = urllib.parse.urlsplit(self.path).path
|
||||
try:
|
||||
prefix = "/api/packages/"
|
||||
if not path.startswith(prefix):
|
||||
return self._error(404, "route inconnue")
|
||||
if not self._require_auth():
|
||||
return None
|
||||
filename = os.path.basename(urllib.parse.unquote(path[len(prefix):]))
|
||||
return self._delete(filename)
|
||||
except (BrokenPipeError, ConnectionResetError):
|
||||
self.close_connection = True
|
||||
except Exception:
|
||||
traceback.print_exc()
|
||||
self._error(500, "erreur interne du serveur")
|
||||
|
||||
# -- implémentations ----------------------------------------------------
|
||||
def _list_packages(self) -> None:
|
||||
app = self.app
|
||||
found = app.scan()
|
||||
packages = sorted(
|
||||
(_public(pkg) for pkg in found.values()),
|
||||
key=lambda pkg: pkg["name"].lower(),
|
||||
)
|
||||
latest = {pkg["filename"] for pkg in repo.latest_by_name(found.values())}
|
||||
for pkg in packages:
|
||||
pkg["current"] = pkg["filename"] in latest
|
||||
stats = app.stats()
|
||||
stats.update(
|
||||
{
|
||||
"count": len(packages),
|
||||
"total_size": sum(int(pkg.get("csize") or 0) for pkg in packages),
|
||||
}
|
||||
)
|
||||
self._json(
|
||||
200,
|
||||
{
|
||||
"ok": True,
|
||||
"repo": app.cfg.name,
|
||||
"arch": app.cfg.arch,
|
||||
"packages": packages,
|
||||
"stats": stats,
|
||||
},
|
||||
)
|
||||
|
||||
def _rebuild(self) -> None:
|
||||
latest, stats = self.app.rebuild()
|
||||
self._json(200, {"ok": True, "count": len(latest), "stats": stats})
|
||||
|
||||
def _delete(self, filename: str) -> None:
|
||||
if not repo.is_pkg_filename(filename):
|
||||
return self._error(400, "nom de fichier invalide")
|
||||
target = os.path.join(self.app.cfg.packages_dir, filename)
|
||||
if not os.path.isfile(target) or os.path.islink(target):
|
||||
return self._error(404, "paquet introuvable")
|
||||
os.unlink(target)
|
||||
with self.app.lock:
|
||||
self.app.cache.pop(filename, None)
|
||||
latest, stats = self.app.rebuild()
|
||||
self.log_message("supprimé %s", filename)
|
||||
self._json(
|
||||
200,
|
||||
{"ok": True, "deleted": filename, "count": len(latest), "stats": stats},
|
||||
)
|
||||
|
||||
def _upload(self) -> None:
|
||||
app = self.app
|
||||
cfg = app.cfg
|
||||
if not self._authorized():
|
||||
return self._error(401, "jeton invalide ou absent", close=True)
|
||||
|
||||
raw_name = self.headers.get("X-Filename") or ""
|
||||
filename = os.path.basename(urllib.parse.unquote(raw_name).strip())
|
||||
if not filename:
|
||||
return self._error(
|
||||
400, "en-tête X-Filename manquant", close=True
|
||||
)
|
||||
if not repo.is_pkg_filename(filename):
|
||||
return self._error(
|
||||
400,
|
||||
"nom de fichier invalide (attendu : <nom>-<version>-<arch>.pkg.tar.zst)",
|
||||
close=True,
|
||||
)
|
||||
|
||||
try:
|
||||
length = int(self.headers.get("Content-Length", ""))
|
||||
except ValueError:
|
||||
return self._error(411, "Content-Length requis", close=True)
|
||||
if length <= 0:
|
||||
return self._error(400, "corps de requête vide", close=True)
|
||||
if length > cfg.max_upload:
|
||||
return self._error(
|
||||
413,
|
||||
f"fichier trop volumineux (maximum {cfg.max_upload} octets)",
|
||||
close=True,
|
||||
)
|
||||
|
||||
expected_sha = (self.headers.get("X-Checksum-Sha256") or "").strip().lower()
|
||||
tmp = os.path.join(cfg.packages_dir, f".upload-{uuid.uuid4().hex}.part")
|
||||
received = 0
|
||||
try:
|
||||
with open(tmp, "wb") as handle:
|
||||
while received < length:
|
||||
chunk = self.rfile.read(min(1024 * 1024, length - received))
|
||||
if not chunk:
|
||||
raise ConnectionError("envoi interrompu par le client")
|
||||
handle.write(chunk)
|
||||
received += len(chunk)
|
||||
if expected_sha:
|
||||
actual = _sha256_file(tmp)
|
||||
if not hmac.compare_digest(actual, expected_sha):
|
||||
raise ValueError("le SHA256 annoncé ne correspond pas au fichier reçu")
|
||||
metadata = repo.read_package_metadata(tmp, filename)
|
||||
os.replace(tmp, os.path.join(cfg.packages_dir, filename))
|
||||
except (ValueError, RuntimeError, ConnectionError, OSError) as exc:
|
||||
_unlink(tmp)
|
||||
self.log_message("envoi refusé : %s", exc)
|
||||
return self._error(400, str(exc), close=True)
|
||||
|
||||
try:
|
||||
latest, stats = app.rebuild()
|
||||
except Exception:
|
||||
traceback.print_exc()
|
||||
return self._json(
|
||||
500,
|
||||
{
|
||||
"ok": False,
|
||||
"error": "paquet enregistré, mais reconstruction de la base impossible",
|
||||
"package": _public(metadata),
|
||||
},
|
||||
close=True,
|
||||
)
|
||||
|
||||
self.log_message(
|
||||
"publié %s (%d octets, %d paquets dans la base)",
|
||||
filename,
|
||||
received,
|
||||
len(latest),
|
||||
)
|
||||
self._json(
|
||||
200,
|
||||
{
|
||||
"ok": True,
|
||||
"package": _public(metadata),
|
||||
"warnings": metadata.get("warnings", []),
|
||||
"count": len(latest),
|
||||
"stats": stats,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
config = Config()
|
||||
try:
|
||||
app = App(config)
|
||||
except RuntimeError as exc:
|
||||
print(f"archrepo: {exc}", file=sys.stderr, flush=True)
|
||||
return 1
|
||||
|
||||
server = ThreadingHTTPServer((config.bind_host, config.bind_port), Handler)
|
||||
server.daemon_threads = True
|
||||
server.app = app # type: ignore[attr-defined]
|
||||
|
||||
def stop(signum, frame) -> None: # noqa: ARG001
|
||||
threading.Thread(target=server.shutdown, daemon=True).start()
|
||||
|
||||
signal.signal(signal.SIGTERM, stop)
|
||||
signal.signal(signal.SIGINT, stop)
|
||||
|
||||
print(
|
||||
f"archrepo: {config.packages_dir} — http://{config.bind_host}:"
|
||||
f"{config.bind_port}/admin/ (dépôt {config.name}/{config.arch})",
|
||||
flush=True,
|
||||
)
|
||||
try:
|
||||
server.serve_forever()
|
||||
finally:
|
||||
server.server_close()
|
||||
print("archrepo: arrêt", flush=True)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in new issue
Block a user