manage.php 21 KB

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