| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552 |
- <?php
- declare(strict_types=1);
- require_once __DIR__ . "/lib.php";
- if (session_status() === PHP_SESSION_NONE) {
- ini_set("session.use_strict_mode", "1");
- ini_set("session.cookie_httponly", "1");
- ini_set("session.cookie_samesite", "Lax");
- session_start();
- }
- $messages = [];
- $errors = [];
- function backupManageEscape($value): string
- {
- return htmlspecialchars((string) $value, ENT_QUOTES, "UTF-8");
- }
- function backupManagePasswordConfigured(): bool
- {
- return defined("BACKUP_SERVER_PASSWORD_HASH") || defined("BACKUP_SERVER_PASSWORD");
- }
- function backupManagePasswordMatches(string $password): bool
- {
- if (defined("BACKUP_SERVER_PASSWORD_HASH")) {
- return password_verify($password, (string) BACKUP_SERVER_PASSWORD_HASH);
- }
- if (defined("BACKUP_SERVER_PASSWORD")) {
- return hash_equals((string) BACKUP_SERVER_PASSWORD, $password);
- }
- return false;
- }
- function backupManageIsLoggedIn(): bool
- {
- return !empty($_SESSION["backup_server_logged_in"]);
- }
- function backupManageCsrfToken(): string
- {
- if (empty($_SESSION["backup_server_csrf_token"])) {
- $_SESSION["backup_server_csrf_token"] = bin2hex(random_bytes(32));
- }
- return $_SESSION["backup_server_csrf_token"];
- }
- function backupManageCsrfIsValid(string $token): bool
- {
- return !empty($_SESSION["backup_server_csrf_token"]) &&
- hash_equals($_SESSION["backup_server_csrf_token"], $token);
- }
- function backupManageValidateFilename(string $filename): string
- {
- $filename = basename(trim($filename));
- if (preg_match('/^backup-\d{8}-\d{6}(?:-\d+)?\.zip$/', $filename) !== 1) {
- throw new RuntimeException("Invalid backup filename.");
- }
- return $filename;
- }
- function backupManageFormatBytes(int $bytes): string
- {
- if ($bytes >= 1073741824) {
- return number_format($bytes / 1073741824, 2, ",", ".") . " GB";
- }
- if ($bytes >= 1048576) {
- return number_format($bytes / 1048576, 2, ",", ".") . " MB";
- }
- if ($bytes >= 1024) {
- return number_format($bytes / 1024, 1, ",", ".") . " KB";
- }
- return $bytes . " B";
- }
- function backupManageFindBackup(string $instance, string $filename): ?array
- {
- foreach (backupServerReadIndex()["backups"] as $backup) {
- if (!is_array($backup)) {
- continue;
- }
- if (($backup["instance"] ?? "") === $instance && ($backup["filename"] ?? "") === $filename) {
- return $backup;
- }
- }
- return null;
- }
- function backupManageSendDownload(string $instance, string $filename): void
- {
- $backup = backupManageFindBackup($instance, $filename);
- if ($backup === null) {
- throw new RuntimeException("Backup not found.");
- }
- $path = backupServerBackupPath($instance, $filename);
- if (is_file($path)) {
- $size = filesize($path);
- $handle = fopen($path, "rb");
- if ($size === false || $handle === false) {
- throw new RuntimeException("Backup cannot be opened.");
- }
- header("Content-Type: application/zip");
- header("Content-Disposition: attachment; filename=\"" . addcslashes($instance . "-" . $filename, "\"\\") . "\"");
- header("Content-Length: " . (string) $size);
- header("Cache-Control: private, no-store");
- header("X-Content-Type-Options: nosniff");
- fpassthru($handle);
- fclose($handle);
- exit;
- }
- if (!empty($backup["s3_uploaded_at"])) {
- if (!backupS3Enabled()) {
- throw new RuntimeException("Backup is stored in S3, but S3 is not configured. See config.php.");
- }
- $key = (string) ($backup["s3_key"] ?? "");
- if ($key === "") {
- $key = backupS3ObjectKey($instance, $filename);
- }
- backupS3SendObjectToOutput($key, $instance . "-" . $filename, (int) ($backup["size"] ?? 0));
- }
- throw new RuntimeException("Backup not found in any store.");
- }
- function backupManageDeleteBackup(string $instance, string $filename): void
- {
- $index = backupServerReadIndex();
- $kept = [];
- $found = null;
- foreach ($index["backups"] as $backup) {
- if (
- is_array($backup) &&
- ($backup["instance"] ?? "") === $instance &&
- ($backup["filename"] ?? "") === $filename
- ) {
- $found = $backup;
- continue;
- }
- $kept[] = $backup;
- }
- if ($found === null) {
- throw new RuntimeException("Backup not found.");
- }
- // Delete the S3 object first: if that fails, nothing is changed, so no
- // object is ever stranded in the bucket without an index record.
- if (!empty($found["s3_uploaded_at"])) {
- if (!backupS3Enabled()) {
- throw new RuntimeException("Backup has an S3 copy, but S3 is not configured. See config.php.");
- }
- $key = (string) ($found["s3_key"] ?? "");
- if ($key === "") {
- $key = backupS3ObjectKey($instance, $filename);
- }
- backupS3DeleteObject($key);
- }
- $path = backupServerBackupPath($instance, $filename);
- if (is_file($path)) {
- unlink($path);
- }
- backupServerWriteIndex($kept);
- }
- function backupManageAddInstance(string $instance): void
- {
- $instance = backupServerValidateInstance($instance);
- $settings = backupServerGetSettings();
- $settings["instances"][] = $instance;
- backupServerWriteSettings($settings);
- }
- function backupManageRemoveInstance(string $instance): void
- {
- $instance = backupServerValidateInstance($instance);
- $settings = backupServerGetSettings();
- $settings["instances"] = array_values(
- array_filter($settings["instances"], function ($existing) use ($instance) {
- return $existing !== $instance;
- }),
- );
- backupServerWriteSettings($settings);
- }
- function backupManageGroupBackupsByInstance(array $backups): array
- {
- $grouped = [];
- foreach ($backups as $backup) {
- if (!is_array($backup)) {
- continue;
- }
- $instance = (string) ($backup["instance"] ?? "");
- $filename = basename((string) ($backup["filename"] ?? ""));
- if ($instance === "" || $filename === "") {
- continue;
- }
- $backup["filename"] = $filename;
- $path = backupServerBackupPath($instance, $filename);
- $backup["local_exists"] = is_file($path);
- $backup["size"] = $backup["local_exists"]
- ? (int) (filesize($path) ?: ($backup["size"] ?? 0))
- : (int) ($backup["size"] ?? 0);
- $grouped[$instance][] = $backup;
- }
- ksort($grouped);
- foreach ($grouped as &$records) {
- usort($records, function ($left, $right) {
- return strcmp((string) ($right["uploaded_at"] ?? ""), (string) ($left["uploaded_at"] ?? ""));
- });
- }
- unset($records);
- return $grouped;
- }
- function backupManageStorageLabel(array $backup): string
- {
- $local = !empty($backup["local_exists"]);
- $inS3 = !empty($backup["s3_uploaded_at"]);
- if ($local && $inS3) {
- return "Local + S3";
- }
- if ($local && backupS3Enabled() && empty($backup["s3_expired"])) {
- return "Local (S3 pending)";
- }
- if ($local) {
- return "Local";
- }
- if ($inS3) {
- return "S3 only";
- }
- return "Missing";
- }
- function backupManageLogTail(int $lines): array
- {
- $file = (string) BACKUP_SERVER_LOG_FILE;
- if (!is_file($file)) {
- return [];
- }
- $content = @file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
- if (!is_array($content)) {
- return [];
- }
- return array_slice($content, -$lines);
- }
- if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $action = (string) ($_POST["action"] ?? "");
- if ($action === "login") {
- if (!backupManagePasswordConfigured()) {
- $errors[] = "No password is configured.";
- } elseif (backupManagePasswordMatches((string) ($_POST["password"] ?? ""))) {
- session_regenerate_id(true);
- $_SESSION["backup_server_logged_in"] = true;
- $messages[] = "Logged in.";
- } else {
- $errors[] = "Wrong password.";
- }
- } elseif ($action === "logout") {
- unset($_SESSION["backup_server_logged_in"], $_SESSION["backup_server_csrf_token"]);
- $messages[] = "Logged out.";
- } elseif (!backupManageIsLoggedIn()) {
- $errors[] = "Login required.";
- } elseif (!backupManageCsrfIsValid((string) ($_POST["csrf_token"] ?? ""))) {
- $errors[] = "Invalid token. Please reload the page and try again.";
- } else {
- try {
- if ($action === "update_retention") {
- $settings = backupServerGetSettings();
- $settings["retention"] = max(1, (int) ($_POST["retention"] ?? BACKUP_SERVER_RETENTION));
- if (isset($_POST["s3_retention"])) {
- $settings["s3_retention"] = max(1, (int) $_POST["s3_retention"]);
- }
- backupServerWriteSettings($settings);
- // May issue S3 deletes for backups that now age out of the archive.
- backupServerApplyRetentionAll();
- $messages[] = "Retention updated.";
- } elseif ($action === "add_instance") {
- backupManageAddInstance((string) ($_POST["instance"] ?? ""));
- $messages[] = "Instance added.";
- } elseif ($action === "remove_instance") {
- backupManageRemoveInstance((string) ($_POST["instance"] ?? ""));
- $messages[] = "Instance removed.";
- } elseif ($action === "download") {
- backupManageSendDownload(
- backupServerValidateInstance((string) ($_POST["instance"] ?? "")),
- backupManageValidateFilename((string) ($_POST["filename"] ?? "")),
- );
- } elseif ($action === "delete") {
- backupManageDeleteBackup(
- backupServerValidateInstance((string) ($_POST["instance"] ?? "")),
- backupManageValidateFilename((string) ($_POST["filename"] ?? "")),
- );
- $messages[] = "Backup deleted.";
- } elseif ($action === "s3_sync") {
- if (!backupS3Enabled()) {
- throw new RuntimeException("S3 is not configured. See config.php.");
- }
- $uploaded = 0;
- $pending = 0;
- foreach (backupServerIndexInstances() as $syncInstance) {
- $result = backupServerSyncInstanceS3($syncInstance);
- $uploaded += $result["uploaded"];
- $pending += $result["pending"];
- if ($result["error"] !== null) {
- $errors[] = "S3 upload for " . $syncInstance . " failed: " . $result["error"];
- }
- backupServerApplyRetention($syncInstance);
- }
- $messages[] = "S3 sync finished: " . $uploaded . " uploaded, " . $pending . " still pending.";
- }
- } catch (Throwable $exception) {
- $errors[] = $exception->getMessage();
- }
- }
- }
- try {
- $settings = backupServerGetSettings();
- $groupedBackups = backupManageGroupBackupsByInstance(backupServerReadIndex()["backups"]);
- } catch (Throwable $exception) {
- $settings = [
- "retention" => max(1, (int) BACKUP_SERVER_RETENTION),
- "s3_retention" => max(1, (int) BACKUP_SERVER_S3_RETENTION),
- "instances" => [],
- ];
- $groupedBackups = [];
- $errors[] = $exception->getMessage();
- }
- $s3Enabled = backupS3Enabled();
- $s3PendingCount = 0;
- $s3LastErrors = [];
- if ($s3Enabled) {
- foreach ($groupedBackups as $instanceBackups) {
- foreach ($instanceBackups as $backup) {
- if (!empty($backup["local_exists"]) && empty($backup["s3_uploaded_at"])) {
- $s3PendingCount++;
- }
- if (!empty($backup["s3_last_error"]) && count($s3LastErrors) < 5) {
- $s3LastErrors[] = ($backup["instance"] ?? "") . "/" . ($backup["filename"] ?? "") .
- ": " . $backup["s3_last_error"];
- }
- }
- }
- }
- $s3LogTail = backupManageLogTail(20);
- ?>
- <!DOCTYPE html>
- <html lang="de">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Backup Management</title>
- </head>
- <body>
- <h1>Backup Management</h1>
- <?php foreach ($messages as $message): ?>
- <p><strong><?php echo backupManageEscape($message); ?></strong></p>
- <?php endforeach; ?>
- <?php foreach ($errors as $error): ?>
- <p><strong>Error:</strong> <?php echo backupManageEscape($error); ?></p>
- <?php endforeach; ?>
- <?php if (!backupManageIsLoggedIn()): ?>
- <form method="POST">
- <input type="hidden" name="action" value="login">
- <p>
- <label for="password">Password</label><br>
- <input type="password" id="password" name="password" required>
- </p>
- <button type="submit">Login</button>
- </form>
- <?php else: ?>
- <form method="POST">
- <input type="hidden" name="action" value="logout">
- <button type="submit">Logout</button>
- </form>
- <h2>Settings</h2>
- <form method="POST">
- <input type="hidden" name="action" value="update_retention">
- <input type="hidden" name="csrf_token" value="<?php echo backupManageEscape(backupManageCsrfToken()); ?>">
- <p>
- <label for="retention">Local backups retained per instance</label><br>
- <input type="number" id="retention" name="retention" min="1" required value="<?php echo (int) $settings["retention"]; ?>">
- </p>
- <?php if ($s3Enabled): ?>
- <p>
- <label for="s3_retention">S3 backups retained per instance</label><br>
- <input type="number" id="s3_retention" name="s3_retention" min="1" required value="<?php echo (int) $settings["s3_retention"]; ?>">
- </p>
- <?php endif; ?>
- <button type="submit">Save retention</button>
- </form>
- <h2>S3 archive</h2>
- <?php if (!$s3Enabled): ?>
- <p>S3 storage is not configured. Set the <code>BACKUP_SERVER_S3_*</code> constants in <code>config.php</code> to enable it.</p>
- <?php else: ?>
- <p>
- Endpoint: <code><?php echo backupManageEscape(BACKUP_SERVER_S3_ENDPOINT); ?></code>,
- Bucket: <code><?php echo backupManageEscape(BACKUP_SERVER_S3_BUCKET); ?></code>
- <?php if (trim((string) BACKUP_SERVER_S3_PREFIX, "/") !== ""): ?>
- , Prefix: <code><?php echo backupManageEscape(trim((string) BACKUP_SERVER_S3_PREFIX, "/")); ?></code>
- <?php endif; ?>
- </p>
- <p>Pending uploads: <?php echo (int) $s3PendingCount; ?></p>
- <form method="POST">
- <input type="hidden" name="action" value="s3_sync">
- <input type="hidden" name="csrf_token" value="<?php echo backupManageEscape(backupManageCsrfToken()); ?>">
- <button type="submit">Retry S3 uploads now</button>
- </form>
- <?php if (!empty($s3LastErrors)): ?>
- <p><strong>Recent upload errors:</strong></p>
- <ul>
- <?php foreach ($s3LastErrors as $s3LastError): ?>
- <li><?php echo backupManageEscape($s3LastError); ?></li>
- <?php endforeach; ?>
- </ul>
- <?php endif; ?>
- <?php if (!empty($s3LogTail)): ?>
- <details>
- <summary>S3 log (last <?php echo count($s3LogTail); ?> lines)</summary>
- <pre><?php echo backupManageEscape(implode("\n", $s3LogTail)); ?></pre>
- </details>
- <?php endif; ?>
- <?php endif; ?>
- <h2>Upload endpoint</h2>
- <p>Distributed instances should upload to <code>upload.php</code>.</p>
- <h2>Allowed instances</h2>
- <form method="POST">
- <input type="hidden" name="action" value="add_instance">
- <input type="hidden" name="csrf_token" value="<?php echo backupManageEscape(backupManageCsrfToken()); ?>">
- <p>
- <label for="instance">Instance identifier</label><br>
- <input type="text" id="instance" name="instance" required pattern="[A-Za-z0-9][A-Za-z0-9._-]*" maxlength="120">
- </p>
- <button type="submit">Add instance</button>
- </form>
- <?php if (empty($settings["instances"])): ?>
- <p>No instances allowed. Uploads will be rejected until an instance is added.</p>
- <?php else: ?>
- <table border="1" cellpadding="6" cellspacing="0">
- <thead>
- <tr>
- <th>Instance</th>
- <th>Actions</th>
- </tr>
- </thead>
- <tbody>
- <?php foreach ($settings["instances"] as $instance): ?>
- <tr>
- <td><?php echo backupManageEscape($instance); ?></td>
- <td>
- <form method="POST" style="display:inline" onsubmit="return confirm('Remove this allowed instance? Existing backups remain visible; S3 objects remain until retention or manual delete.');">
- <input type="hidden" name="action" value="remove_instance">
- <input type="hidden" name="csrf_token" value="<?php echo backupManageEscape(backupManageCsrfToken()); ?>">
- <input type="hidden" name="instance" value="<?php echo backupManageEscape($instance); ?>">
- <button type="submit">Remove</button>
- </form>
- </td>
- </tr>
- <?php endforeach; ?>
- </tbody>
- </table>
- <?php endif; ?>
- <h2>Backups</h2>
- <?php if (empty($groupedBackups)): ?>
- <p>No backups uploaded.</p>
- <?php else: ?>
- <?php foreach ($groupedBackups as $instance => $backups): ?>
- <h3><?php echo backupManageEscape($instance); ?></h3>
- <table border="1" cellpadding="6" cellspacing="0">
- <thead>
- <tr>
- <th>Uploaded</th>
- <th>Filename</th>
- <th>Size</th>
- <th>Storage</th>
- <th>SHA-256</th>
- <th>Source IP</th>
- <th>Actions</th>
- </tr>
- </thead>
- <tbody>
- <?php foreach ($backups as $backup): ?>
- <tr>
- <td><?php echo backupManageEscape($backup["uploaded_at"] ?? ""); ?></td>
- <td><?php echo backupManageEscape($backup["filename"] ?? ""); ?></td>
- <td><?php echo backupManageEscape(backupManageFormatBytes((int) ($backup["size"] ?? 0))); ?></td>
- <td title="<?php echo backupManageEscape($backup["s3_last_error"] ?? ""); ?>"><?php echo backupManageEscape(backupManageStorageLabel($backup)); ?></td>
- <td><?php echo backupManageEscape($backup["sha256"] ?? ""); ?></td>
- <td><?php echo backupManageEscape($backup["source_ip"] ?? ""); ?></td>
- <td>
- <form method="POST" style="display:inline">
- <input type="hidden" name="action" value="download">
- <input type="hidden" name="csrf_token" value="<?php echo backupManageEscape(backupManageCsrfToken()); ?>">
- <input type="hidden" name="instance" value="<?php echo backupManageEscape($instance); ?>">
- <input type="hidden" name="filename" value="<?php echo backupManageEscape($backup["filename"] ?? ""); ?>">
- <button type="submit">Download</button>
- </form>
- <form method="POST" style="display:inline" onsubmit="return confirm('Delete this backup from all stores?');">
- <input type="hidden" name="action" value="delete">
- <input type="hidden" name="csrf_token" value="<?php echo backupManageEscape(backupManageCsrfToken()); ?>">
- <input type="hidden" name="instance" value="<?php echo backupManageEscape($instance); ?>">
- <input type="hidden" name="filename" value="<?php echo backupManageEscape($backup["filename"] ?? ""); ?>">
- <button type="submit">Delete</button>
- </form>
- </td>
- </tr>
- <?php endforeach; ?>
- </tbody>
- </table>
- <?php endforeach; ?>
- <?php endif; ?>
- <?php endif; ?>
- </body>
- </html>
|