manage.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. <?php
  2. // DEPRECATED: The bundled managed backup server is deprecated and unmaintained.
  3. // It is kept for reference only and will be removed in a future release.
  4. // Do not deploy it for new installations.
  5. declare(strict_types=1);
  6. require_once __DIR__ . "/lib.php";
  7. if (session_status() === PHP_SESSION_NONE) {
  8. ini_set("session.use_strict_mode", "1");
  9. ini_set("session.cookie_httponly", "1");
  10. ini_set("session.cookie_samesite", "Lax");
  11. session_start();
  12. }
  13. $messages = [];
  14. $errors = [];
  15. function backupManageEscape($value): string
  16. {
  17. return htmlspecialchars((string) $value, ENT_QUOTES, "UTF-8");
  18. }
  19. function backupManagePasswordConfigured(): bool
  20. {
  21. return defined("BACKUP_SERVER_PASSWORD_HASH") || defined("BACKUP_SERVER_PASSWORD");
  22. }
  23. function backupManagePasswordMatches(string $password): bool
  24. {
  25. if (defined("BACKUP_SERVER_PASSWORD_HASH")) {
  26. return password_verify($password, (string) BACKUP_SERVER_PASSWORD_HASH);
  27. }
  28. if (defined("BACKUP_SERVER_PASSWORD")) {
  29. return hash_equals((string) BACKUP_SERVER_PASSWORD, $password);
  30. }
  31. return false;
  32. }
  33. function backupManageIsLoggedIn(): bool
  34. {
  35. return !empty($_SESSION["backup_server_logged_in"]);
  36. }
  37. function backupManageCsrfToken(): string
  38. {
  39. if (empty($_SESSION["backup_server_csrf_token"])) {
  40. $_SESSION["backup_server_csrf_token"] = bin2hex(random_bytes(32));
  41. }
  42. return $_SESSION["backup_server_csrf_token"];
  43. }
  44. function backupManageCsrfIsValid(string $token): bool
  45. {
  46. return !empty($_SESSION["backup_server_csrf_token"]) &&
  47. hash_equals($_SESSION["backup_server_csrf_token"], $token);
  48. }
  49. function backupManageValidateFilename(string $filename): string
  50. {
  51. $filename = basename(trim($filename));
  52. if (preg_match('/^backup-\d{8}-\d{6}(?:-\d+)?\.zip$/', $filename) !== 1) {
  53. throw new RuntimeException("Invalid backup filename.");
  54. }
  55. return $filename;
  56. }
  57. function backupManageFormatBytes(int $bytes): string
  58. {
  59. if ($bytes >= 1073741824) {
  60. return number_format($bytes / 1073741824, 2, ",", ".") . " GB";
  61. }
  62. if ($bytes >= 1048576) {
  63. return number_format($bytes / 1048576, 2, ",", ".") . " MB";
  64. }
  65. if ($bytes >= 1024) {
  66. return number_format($bytes / 1024, 1, ",", ".") . " KB";
  67. }
  68. return $bytes . " B";
  69. }
  70. function backupManageFindBackup(string $instance, string $filename): ?array
  71. {
  72. foreach (backupServerReadIndex()["backups"] as $backup) {
  73. if (!is_array($backup)) {
  74. continue;
  75. }
  76. if (($backup["instance"] ?? "") === $instance && ($backup["filename"] ?? "") === $filename) {
  77. return $backup;
  78. }
  79. }
  80. return null;
  81. }
  82. function backupManageSendDownload(string $instance, string $filename): void
  83. {
  84. $backup = backupManageFindBackup($instance, $filename);
  85. if ($backup === null) {
  86. throw new RuntimeException("Backup not found.");
  87. }
  88. $path = backupServerBackupPath($instance, $filename);
  89. if (is_file($path)) {
  90. $size = filesize($path);
  91. $handle = fopen($path, "rb");
  92. if ($size === false || $handle === false) {
  93. throw new RuntimeException("Backup cannot be opened.");
  94. }
  95. header("Content-Type: application/zip");
  96. header("Content-Disposition: attachment; filename=\"" . addcslashes($instance . "-" . $filename, "\"\\") . "\"");
  97. header("Content-Length: " . (string) $size);
  98. header("Cache-Control: private, no-store");
  99. header("X-Content-Type-Options: nosniff");
  100. fpassthru($handle);
  101. fclose($handle);
  102. exit;
  103. }
  104. if (!empty($backup["s3_uploaded_at"])) {
  105. if (!backupS3Enabled()) {
  106. throw new RuntimeException("Backup is stored in S3, but S3 is not configured. See config.php.");
  107. }
  108. $key = (string) ($backup["s3_key"] ?? "");
  109. if ($key === "") {
  110. $key = backupS3ObjectKey($instance, $filename);
  111. }
  112. backupS3SendObjectToOutput($key, $instance . "-" . $filename, (int) ($backup["size"] ?? 0));
  113. }
  114. throw new RuntimeException("Backup not found in any store.");
  115. }
  116. function backupManageDeleteBackup(string $instance, string $filename): void
  117. {
  118. $index = backupServerReadIndex();
  119. $kept = [];
  120. $found = null;
  121. foreach ($index["backups"] as $backup) {
  122. if (
  123. is_array($backup) &&
  124. ($backup["instance"] ?? "") === $instance &&
  125. ($backup["filename"] ?? "") === $filename
  126. ) {
  127. $found = $backup;
  128. continue;
  129. }
  130. $kept[] = $backup;
  131. }
  132. if ($found === null) {
  133. throw new RuntimeException("Backup not found.");
  134. }
  135. // Delete the S3 object first: if that fails, nothing is changed, so no
  136. // object is ever stranded in the bucket without an index record.
  137. if (!empty($found["s3_uploaded_at"])) {
  138. if (!backupS3Enabled()) {
  139. throw new RuntimeException("Backup has an S3 copy, but S3 is not configured. See config.php.");
  140. }
  141. $key = (string) ($found["s3_key"] ?? "");
  142. if ($key === "") {
  143. $key = backupS3ObjectKey($instance, $filename);
  144. }
  145. backupS3DeleteObject($key);
  146. }
  147. $path = backupServerBackupPath($instance, $filename);
  148. if (is_file($path)) {
  149. unlink($path);
  150. }
  151. backupServerWriteIndex($kept);
  152. }
  153. function backupManageAddInstance(string $instance): void
  154. {
  155. $instance = backupServerValidateInstance($instance);
  156. $settings = backupServerGetSettings();
  157. $settings["instances"][] = $instance;
  158. backupServerWriteSettings($settings);
  159. }
  160. function backupManageRemoveInstance(string $instance): void
  161. {
  162. $instance = backupServerValidateInstance($instance);
  163. $settings = backupServerGetSettings();
  164. $settings["instances"] = array_values(
  165. array_filter($settings["instances"], function ($existing) use ($instance) {
  166. return $existing !== $instance;
  167. }),
  168. );
  169. backupServerWriteSettings($settings);
  170. }
  171. function backupManageGroupBackupsByInstance(array $backups): array
  172. {
  173. $grouped = [];
  174. foreach ($backups as $backup) {
  175. if (!is_array($backup)) {
  176. continue;
  177. }
  178. $instance = (string) ($backup["instance"] ?? "");
  179. $filename = basename((string) ($backup["filename"] ?? ""));
  180. if ($instance === "" || $filename === "") {
  181. continue;
  182. }
  183. $backup["filename"] = $filename;
  184. $path = backupServerBackupPath($instance, $filename);
  185. $backup["local_exists"] = is_file($path);
  186. $backup["size"] = $backup["local_exists"]
  187. ? (int) (filesize($path) ?: ($backup["size"] ?? 0))
  188. : (int) ($backup["size"] ?? 0);
  189. $grouped[$instance][] = $backup;
  190. }
  191. ksort($grouped);
  192. foreach ($grouped as &$records) {
  193. usort($records, function ($left, $right) {
  194. return strcmp((string) ($right["uploaded_at"] ?? ""), (string) ($left["uploaded_at"] ?? ""));
  195. });
  196. }
  197. unset($records);
  198. return $grouped;
  199. }
  200. function backupManageStorageLabel(array $backup): string
  201. {
  202. $local = !empty($backup["local_exists"]);
  203. $inS3 = !empty($backup["s3_uploaded_at"]);
  204. if ($local && $inS3) {
  205. return "Local + S3";
  206. }
  207. if ($local && backupS3Enabled() && empty($backup["s3_expired"])) {
  208. return "Local (S3 pending)";
  209. }
  210. if ($local) {
  211. return "Local";
  212. }
  213. if ($inS3) {
  214. return "S3 only";
  215. }
  216. return "Missing";
  217. }
  218. function backupManageLogTail(int $lines): array
  219. {
  220. $file = (string) BACKUP_SERVER_LOG_FILE;
  221. if (!is_file($file)) {
  222. return [];
  223. }
  224. $content = @file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
  225. if (!is_array($content)) {
  226. return [];
  227. }
  228. return array_slice($content, -$lines);
  229. }
  230. if ($_SERVER["REQUEST_METHOD"] === "POST") {
  231. $action = (string) ($_POST["action"] ?? "");
  232. if ($action === "login") {
  233. if (!backupManagePasswordConfigured()) {
  234. $errors[] = "No password is configured.";
  235. } elseif (backupManagePasswordMatches((string) ($_POST["password"] ?? ""))) {
  236. session_regenerate_id(true);
  237. $_SESSION["backup_server_logged_in"] = true;
  238. $messages[] = "Logged in.";
  239. } else {
  240. $errors[] = "Wrong password.";
  241. }
  242. } elseif ($action === "logout") {
  243. unset($_SESSION["backup_server_logged_in"], $_SESSION["backup_server_csrf_token"]);
  244. $messages[] = "Logged out.";
  245. } elseif (!backupManageIsLoggedIn()) {
  246. $errors[] = "Login required.";
  247. } elseif (!backupManageCsrfIsValid((string) ($_POST["csrf_token"] ?? ""))) {
  248. $errors[] = "Invalid token. Please reload the page and try again.";
  249. } else {
  250. try {
  251. if ($action === "update_retention") {
  252. $settings = backupServerGetSettings();
  253. $settings["retention"] = max(1, (int) ($_POST["retention"] ?? BACKUP_SERVER_RETENTION));
  254. if (isset($_POST["s3_retention"])) {
  255. $settings["s3_retention"] = max(1, (int) $_POST["s3_retention"]);
  256. }
  257. backupServerWriteSettings($settings);
  258. // May issue S3 deletes for backups that now age out of the archive.
  259. backupServerApplyRetentionAll();
  260. $messages[] = "Retention updated.";
  261. } elseif ($action === "add_instance") {
  262. backupManageAddInstance((string) ($_POST["instance"] ?? ""));
  263. $messages[] = "Instance added.";
  264. } elseif ($action === "remove_instance") {
  265. backupManageRemoveInstance((string) ($_POST["instance"] ?? ""));
  266. $messages[] = "Instance removed.";
  267. } elseif ($action === "download") {
  268. backupManageSendDownload(
  269. backupServerValidateInstance((string) ($_POST["instance"] ?? "")),
  270. backupManageValidateFilename((string) ($_POST["filename"] ?? "")),
  271. );
  272. } elseif ($action === "delete") {
  273. backupManageDeleteBackup(
  274. backupServerValidateInstance((string) ($_POST["instance"] ?? "")),
  275. backupManageValidateFilename((string) ($_POST["filename"] ?? "")),
  276. );
  277. $messages[] = "Backup deleted.";
  278. } elseif ($action === "s3_sync") {
  279. if (!backupS3Enabled()) {
  280. throw new RuntimeException("S3 is not configured. See config.php.");
  281. }
  282. $uploaded = 0;
  283. $pending = 0;
  284. foreach (backupServerIndexInstances() as $syncInstance) {
  285. $result = backupServerSyncInstanceS3($syncInstance);
  286. $uploaded += $result["uploaded"];
  287. $pending += $result["pending"];
  288. if ($result["error"] !== null) {
  289. $errors[] = "S3 upload for " . $syncInstance . " failed: " . $result["error"];
  290. }
  291. backupServerApplyRetention($syncInstance);
  292. }
  293. $messages[] = "S3 sync finished: " . $uploaded . " uploaded, " . $pending . " still pending.";
  294. }
  295. } catch (Throwable $exception) {
  296. $errors[] = $exception->getMessage();
  297. }
  298. }
  299. }
  300. try {
  301. $settings = backupServerGetSettings();
  302. $groupedBackups = backupManageGroupBackupsByInstance(backupServerReadIndex()["backups"]);
  303. } catch (Throwable $exception) {
  304. $settings = [
  305. "retention" => max(1, (int) BACKUP_SERVER_RETENTION),
  306. "s3_retention" => max(1, (int) BACKUP_SERVER_S3_RETENTION),
  307. "instances" => [],
  308. ];
  309. $groupedBackups = [];
  310. $errors[] = $exception->getMessage();
  311. }
  312. $s3Enabled = backupS3Enabled();
  313. $s3PendingCount = 0;
  314. $s3LastErrors = [];
  315. if ($s3Enabled) {
  316. foreach ($groupedBackups as $instanceBackups) {
  317. foreach ($instanceBackups as $backup) {
  318. if (!empty($backup["local_exists"]) && empty($backup["s3_uploaded_at"])) {
  319. $s3PendingCount++;
  320. }
  321. if (!empty($backup["s3_last_error"]) && count($s3LastErrors) < 5) {
  322. $s3LastErrors[] = ($backup["instance"] ?? "") . "/" . ($backup["filename"] ?? "") .
  323. ": " . $backup["s3_last_error"];
  324. }
  325. }
  326. }
  327. }
  328. $s3LogTail = backupManageLogTail(20);
  329. ?>
  330. <!DOCTYPE html>
  331. <html lang="de">
  332. <head>
  333. <meta charset="UTF-8">
  334. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  335. <title>Backup Management</title>
  336. </head>
  337. <body>
  338. <h1>Backup Management</h1>
  339. <p><strong>Deprecated:</strong> This backup server is no longer maintained and will be removed in a future release.</p>
  340. <?php foreach ($messages as $message): ?>
  341. <p><strong><?php echo backupManageEscape($message); ?></strong></p>
  342. <?php endforeach; ?>
  343. <?php foreach ($errors as $error): ?>
  344. <p><strong>Error:</strong> <?php echo backupManageEscape($error); ?></p>
  345. <?php endforeach; ?>
  346. <?php if (!backupManageIsLoggedIn()): ?>
  347. <form method="POST">
  348. <input type="hidden" name="action" value="login">
  349. <p>
  350. <label for="password">Password</label><br>
  351. <input type="password" id="password" name="password" required>
  352. </p>
  353. <button type="submit">Login</button>
  354. </form>
  355. <?php else: ?>
  356. <form method="POST">
  357. <input type="hidden" name="action" value="logout">
  358. <button type="submit">Logout</button>
  359. </form>
  360. <h2>Settings</h2>
  361. <form method="POST">
  362. <input type="hidden" name="action" value="update_retention">
  363. <input type="hidden" name="csrf_token" value="<?php echo backupManageEscape(backupManageCsrfToken()); ?>">
  364. <p>
  365. <label for="retention">Local backups retained per instance</label><br>
  366. <input type="number" id="retention" name="retention" min="1" required value="<?php echo (int) $settings["retention"]; ?>">
  367. </p>
  368. <?php if ($s3Enabled): ?>
  369. <p>
  370. <label for="s3_retention">S3 backups retained per instance</label><br>
  371. <input type="number" id="s3_retention" name="s3_retention" min="1" required value="<?php echo (int) $settings["s3_retention"]; ?>">
  372. </p>
  373. <?php endif; ?>
  374. <button type="submit">Save retention</button>
  375. </form>
  376. <h2>S3 archive</h2>
  377. <?php if (!$s3Enabled): ?>
  378. <p>S3 storage is not configured. Set the <code>BACKUP_SERVER_S3_*</code> constants in <code>config.php</code> to enable it.</p>
  379. <?php else: ?>
  380. <p>
  381. Endpoint: <code><?php echo backupManageEscape(BACKUP_SERVER_S3_ENDPOINT); ?></code>,
  382. Bucket: <code><?php echo backupManageEscape(BACKUP_SERVER_S3_BUCKET); ?></code>
  383. <?php if (trim((string) BACKUP_SERVER_S3_PREFIX, "/") !== ""): ?>
  384. , Prefix: <code><?php echo backupManageEscape(trim((string) BACKUP_SERVER_S3_PREFIX, "/")); ?></code>
  385. <?php endif; ?>
  386. </p>
  387. <p>Pending uploads: <?php echo (int) $s3PendingCount; ?></p>
  388. <form method="POST">
  389. <input type="hidden" name="action" value="s3_sync">
  390. <input type="hidden" name="csrf_token" value="<?php echo backupManageEscape(backupManageCsrfToken()); ?>">
  391. <button type="submit">Retry S3 uploads now</button>
  392. </form>
  393. <?php if (!empty($s3LastErrors)): ?>
  394. <p><strong>Recent upload errors:</strong></p>
  395. <ul>
  396. <?php foreach ($s3LastErrors as $s3LastError): ?>
  397. <li><?php echo backupManageEscape($s3LastError); ?></li>
  398. <?php endforeach; ?>
  399. </ul>
  400. <?php endif; ?>
  401. <?php if (!empty($s3LogTail)): ?>
  402. <details>
  403. <summary>S3 log (last <?php echo count($s3LogTail); ?> lines)</summary>
  404. <pre><?php echo backupManageEscape(implode("\n", $s3LogTail)); ?></pre>
  405. </details>
  406. <?php endif; ?>
  407. <?php endif; ?>
  408. <h2>Upload endpoint</h2>
  409. <p>Distributed instances should upload to <code>upload.php</code>.</p>
  410. <h2>Allowed instances</h2>
  411. <form method="POST">
  412. <input type="hidden" name="action" value="add_instance">
  413. <input type="hidden" name="csrf_token" value="<?php echo backupManageEscape(backupManageCsrfToken()); ?>">
  414. <p>
  415. <label for="instance">Instance identifier</label><br>
  416. <input type="text" id="instance" name="instance" required pattern="[A-Za-z0-9][A-Za-z0-9._-]*" maxlength="120">
  417. </p>
  418. <button type="submit">Add instance</button>
  419. </form>
  420. <?php if (empty($settings["instances"])): ?>
  421. <p>No instances allowed. Uploads will be rejected until an instance is added.</p>
  422. <?php else: ?>
  423. <table border="1" cellpadding="6" cellspacing="0">
  424. <thead>
  425. <tr>
  426. <th>Instance</th>
  427. <th>Actions</th>
  428. </tr>
  429. </thead>
  430. <tbody>
  431. <?php foreach ($settings["instances"] as $instance): ?>
  432. <tr>
  433. <td><?php echo backupManageEscape($instance); ?></td>
  434. <td>
  435. <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.');">
  436. <input type="hidden" name="action" value="remove_instance">
  437. <input type="hidden" name="csrf_token" value="<?php echo backupManageEscape(backupManageCsrfToken()); ?>">
  438. <input type="hidden" name="instance" value="<?php echo backupManageEscape($instance); ?>">
  439. <button type="submit">Remove</button>
  440. </form>
  441. </td>
  442. </tr>
  443. <?php endforeach; ?>
  444. </tbody>
  445. </table>
  446. <?php endif; ?>
  447. <h2>Backups</h2>
  448. <?php if (empty($groupedBackups)): ?>
  449. <p>No backups uploaded.</p>
  450. <?php else: ?>
  451. <?php foreach ($groupedBackups as $instance => $backups): ?>
  452. <h3><?php echo backupManageEscape($instance); ?></h3>
  453. <table border="1" cellpadding="6" cellspacing="0">
  454. <thead>
  455. <tr>
  456. <th>Uploaded</th>
  457. <th>Filename</th>
  458. <th>Size</th>
  459. <th>Storage</th>
  460. <th>SHA-256</th>
  461. <th>Source IP</th>
  462. <th>Actions</th>
  463. </tr>
  464. </thead>
  465. <tbody>
  466. <?php foreach ($backups as $backup): ?>
  467. <tr>
  468. <td><?php echo backupManageEscape($backup["uploaded_at"] ?? ""); ?></td>
  469. <td><?php echo backupManageEscape($backup["filename"] ?? ""); ?></td>
  470. <td><?php echo backupManageEscape(backupManageFormatBytes((int) ($backup["size"] ?? 0))); ?></td>
  471. <td title="<?php echo backupManageEscape($backup["s3_last_error"] ?? ""); ?>"><?php echo backupManageEscape(backupManageStorageLabel($backup)); ?></td>
  472. <td><?php echo backupManageEscape($backup["sha256"] ?? ""); ?></td>
  473. <td><?php echo backupManageEscape($backup["source_ip"] ?? ""); ?></td>
  474. <td>
  475. <form method="POST" style="display:inline">
  476. <input type="hidden" name="action" value="download">
  477. <input type="hidden" name="csrf_token" value="<?php echo backupManageEscape(backupManageCsrfToken()); ?>">
  478. <input type="hidden" name="instance" value="<?php echo backupManageEscape($instance); ?>">
  479. <input type="hidden" name="filename" value="<?php echo backupManageEscape($backup["filename"] ?? ""); ?>">
  480. <button type="submit">Download</button>
  481. </form>
  482. <form method="POST" style="display:inline" onsubmit="return confirm('Delete this backup from all stores?');">
  483. <input type="hidden" name="action" value="delete">
  484. <input type="hidden" name="csrf_token" value="<?php echo backupManageEscape(backupManageCsrfToken()); ?>">
  485. <input type="hidden" name="instance" value="<?php echo backupManageEscape($instance); ?>">
  486. <input type="hidden" name="filename" value="<?php echo backupManageEscape($backup["filename"] ?? ""); ?>">
  487. <button type="submit">Delete</button>
  488. </form>
  489. </td>
  490. </tr>
  491. <?php endforeach; ?>
  492. </tbody>
  493. </table>
  494. <?php endforeach; ?>
  495. <?php endif; ?>
  496. <?php endif; ?>
  497. </body>
  498. </html>