manage.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. <?php
  2. declare(strict_types=1);
  3. $baseDir = __DIR__;
  4. $configFile = $baseDir . "/config.php";
  5. if (is_file($configFile)) {
  6. require_once $configFile;
  7. }
  8. if (!defined("BACKUP_SERVER_RETENTION")) {
  9. define("BACKUP_SERVER_RETENTION", 30);
  10. }
  11. if (!defined("BACKUP_SERVER_BACKUP_DIR")) {
  12. define("BACKUP_SERVER_BACKUP_DIR", $baseDir . "/backups/");
  13. }
  14. if (!defined("BACKUP_SERVER_INDEX_FILE")) {
  15. define("BACKUP_SERVER_INDEX_FILE", rtrim((string) BACKUP_SERVER_BACKUP_DIR, "/\\") . "/index.json");
  16. }
  17. if (!defined("BACKUP_SERVER_SETTINGS_FILE")) {
  18. define("BACKUP_SERVER_SETTINGS_FILE", rtrim((string) BACKUP_SERVER_BACKUP_DIR, "/\\") . "/settings.json");
  19. }
  20. if (session_status() === PHP_SESSION_NONE) {
  21. ini_set("session.use_strict_mode", "1");
  22. ini_set("session.cookie_httponly", "1");
  23. ini_set("session.cookie_samesite", "Lax");
  24. session_start();
  25. }
  26. $messages = [];
  27. $errors = [];
  28. function backupManageEscape($value): string
  29. {
  30. return htmlspecialchars((string) $value, ENT_QUOTES, "UTF-8");
  31. }
  32. function backupManagePasswordConfigured(): bool
  33. {
  34. return defined("BACKUP_SERVER_PASSWORD_HASH") || defined("BACKUP_SERVER_PASSWORD");
  35. }
  36. function backupManagePasswordMatches(string $password): bool
  37. {
  38. if (defined("BACKUP_SERVER_PASSWORD_HASH")) {
  39. return password_verify($password, (string) BACKUP_SERVER_PASSWORD_HASH);
  40. }
  41. if (defined("BACKUP_SERVER_PASSWORD")) {
  42. return hash_equals((string) BACKUP_SERVER_PASSWORD, $password);
  43. }
  44. return false;
  45. }
  46. function backupManageIsLoggedIn(): bool
  47. {
  48. return !empty($_SESSION["backup_server_logged_in"]);
  49. }
  50. function backupManageCsrfToken(): string
  51. {
  52. if (empty($_SESSION["backup_server_csrf_token"])) {
  53. $_SESSION["backup_server_csrf_token"] = bin2hex(random_bytes(32));
  54. }
  55. return $_SESSION["backup_server_csrf_token"];
  56. }
  57. function backupManageCsrfIsValid(string $token): bool
  58. {
  59. return !empty($_SESSION["backup_server_csrf_token"]) &&
  60. hash_equals($_SESSION["backup_server_csrf_token"], $token);
  61. }
  62. function backupManageEnsureDirectory(string $dir): void
  63. {
  64. if (!is_dir($dir) && !mkdir($dir, 02775, true) && !is_dir($dir)) {
  65. throw new RuntimeException("Directory cannot be created: " . $dir);
  66. }
  67. @chmod($dir, 02775);
  68. }
  69. function backupManageReadJsonFile(string $file): array
  70. {
  71. if (!is_file($file)) {
  72. return [];
  73. }
  74. $decoded = json_decode((string) file_get_contents($file), true);
  75. if (!is_array($decoded)) {
  76. throw new RuntimeException("JSON file is invalid: " . basename($file));
  77. }
  78. return $decoded;
  79. }
  80. function backupManageWriteJsonFile(string $file, array $data): void
  81. {
  82. backupManageEnsureDirectory(dirname($file));
  83. $json = json_encode(
  84. $data,
  85. JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE,
  86. );
  87. if ($json === false) {
  88. throw new RuntimeException("JSON cannot be encoded.");
  89. }
  90. $tmpFile = $file . ".tmp";
  91. if (file_put_contents($tmpFile, $json . PHP_EOL, LOCK_EX) === false) {
  92. throw new RuntimeException("JSON cannot be written.");
  93. }
  94. @chmod($tmpFile, 0664);
  95. if (!rename($tmpFile, $file)) {
  96. @unlink($tmpFile);
  97. throw new RuntimeException("JSON cannot be saved.");
  98. }
  99. @chmod($file, 0664);
  100. }
  101. function backupManageReadIndex(): array
  102. {
  103. $index = backupManageReadJsonFile((string) BACKUP_SERVER_INDEX_FILE);
  104. $backups = isset($index["backups"]) && is_array($index["backups"])
  105. ? $index["backups"]
  106. : [];
  107. return ["backups" => array_values($backups)];
  108. }
  109. function backupManageWriteIndex(array $backups): void
  110. {
  111. backupManageWriteJsonFile((string) BACKUP_SERVER_INDEX_FILE, [
  112. "backups" => array_values($backups),
  113. ]);
  114. }
  115. function backupManageReadSettings(): array
  116. {
  117. $settings = backupManageReadJsonFile((string) BACKUP_SERVER_SETTINGS_FILE);
  118. $retention = isset($settings["retention"])
  119. ? max(1, (int) $settings["retention"])
  120. : max(1, (int) BACKUP_SERVER_RETENTION);
  121. $instances =
  122. isset($settings["instances"]) && is_array($settings["instances"])
  123. ? $settings["instances"]
  124. : [];
  125. $allowedInstances = [];
  126. foreach ($instances as $instance) {
  127. try {
  128. $allowedInstances[] = backupManageValidateInstance((string) $instance);
  129. } catch (Throwable $exception) {
  130. continue;
  131. }
  132. }
  133. $allowedInstances = array_values(array_unique($allowedInstances));
  134. sort($allowedInstances);
  135. return [
  136. "retention" => $retention,
  137. "instances" => $allowedInstances,
  138. ];
  139. }
  140. function backupManageWriteSettings(array $settings): void
  141. {
  142. $instances =
  143. isset($settings["instances"]) && is_array($settings["instances"])
  144. ? $settings["instances"]
  145. : backupManageReadSettings()["instances"];
  146. $allowedInstances = [];
  147. foreach ($instances as $instance) {
  148. $allowedInstances[] = backupManageValidateInstance((string) $instance);
  149. }
  150. $allowedInstances = array_values(array_unique($allowedInstances));
  151. sort($allowedInstances);
  152. backupManageWriteJsonFile((string) BACKUP_SERVER_SETTINGS_FILE, [
  153. "retention" => max(1, (int) ($settings["retention"] ?? BACKUP_SERVER_RETENTION)),
  154. "instances" => $allowedInstances,
  155. ]);
  156. }
  157. function backupManageInstanceDir(string $instance): string
  158. {
  159. return rtrim((string) BACKUP_SERVER_BACKUP_DIR, "/\\") . DIRECTORY_SEPARATOR . $instance;
  160. }
  161. function backupManageValidateInstance(string $instance): string
  162. {
  163. $instance = trim($instance);
  164. if (
  165. $instance === "" ||
  166. strlen($instance) > 120 ||
  167. preg_match('/^[A-Za-z0-9][A-Za-z0-9._-]*$/', $instance) !== 1
  168. ) {
  169. throw new RuntimeException("Invalid instance.");
  170. }
  171. return $instance;
  172. }
  173. function backupManageValidateFilename(string $filename): string
  174. {
  175. $filename = basename(trim($filename));
  176. if (preg_match('/^backup-\d{8}-\d{6}(?:-\d+)?\.zip$/', $filename) !== 1) {
  177. throw new RuntimeException("Invalid backup filename.");
  178. }
  179. return $filename;
  180. }
  181. function backupManageFormatBytes(int $bytes): string
  182. {
  183. if ($bytes >= 1073741824) {
  184. return number_format($bytes / 1073741824, 2, ",", ".") . " GB";
  185. }
  186. if ($bytes >= 1048576) {
  187. return number_format($bytes / 1048576, 2, ",", ".") . " MB";
  188. }
  189. if ($bytes >= 1024) {
  190. return number_format($bytes / 1024, 1, ",", ".") . " KB";
  191. }
  192. return $bytes . " B";
  193. }
  194. function backupManageFindBackup(string $instance, string $filename): ?array
  195. {
  196. foreach (backupManageReadIndex()["backups"] as $backup) {
  197. if (!is_array($backup)) {
  198. continue;
  199. }
  200. if (($backup["instance"] ?? "") === $instance && ($backup["filename"] ?? "") === $filename) {
  201. return $backup;
  202. }
  203. }
  204. return null;
  205. }
  206. function backupManageBackupPath(string $instance, string $filename): string
  207. {
  208. return backupManageInstanceDir($instance) . DIRECTORY_SEPARATOR . $filename;
  209. }
  210. function backupManageSendDownload(string $instance, string $filename): void
  211. {
  212. $backup = backupManageFindBackup($instance, $filename);
  213. if ($backup === null) {
  214. throw new RuntimeException("Backup not found.");
  215. }
  216. $path = backupManageBackupPath($instance, $filename);
  217. $size = filesize($path);
  218. $handle = fopen($path, "rb");
  219. if ($size === false || $handle === false) {
  220. throw new RuntimeException("Backup cannot be opened.");
  221. }
  222. header("Content-Type: application/zip");
  223. header("Content-Disposition: attachment; filename=\"" . addcslashes($instance . "-" . $filename, "\"\\") . "\"");
  224. header("Content-Length: " . (string) $size);
  225. header("Cache-Control: private, no-store");
  226. header("X-Content-Type-Options: nosniff");
  227. fpassthru($handle);
  228. fclose($handle);
  229. exit;
  230. }
  231. function backupManageDeleteBackup(string $instance, string $filename): void
  232. {
  233. $index = backupManageReadIndex();
  234. $kept = [];
  235. $found = false;
  236. foreach ($index["backups"] as $backup) {
  237. if (
  238. is_array($backup) &&
  239. ($backup["instance"] ?? "") === $instance &&
  240. ($backup["filename"] ?? "") === $filename
  241. ) {
  242. $found = true;
  243. continue;
  244. }
  245. $kept[] = $backup;
  246. }
  247. if (!$found) {
  248. throw new RuntimeException("Backup not found.");
  249. }
  250. $path = backupManageBackupPath($instance, $filename);
  251. if (is_file($path)) {
  252. unlink($path);
  253. }
  254. backupManageWriteIndex($kept);
  255. }
  256. function backupManageApplyRetentionForInstance(string $instance): void
  257. {
  258. $index = backupManageReadIndex();
  259. $retention = backupManageReadSettings()["retention"];
  260. $instanceBackups = [];
  261. $otherBackups = [];
  262. foreach ($index["backups"] as $backup) {
  263. if (!is_array($backup)) {
  264. continue;
  265. }
  266. if (($backup["instance"] ?? "") === $instance) {
  267. $instanceBackups[] = $backup;
  268. } else {
  269. $otherBackups[] = $backup;
  270. }
  271. }
  272. usort($instanceBackups, function ($left, $right) {
  273. return strcmp((string) ($right["uploaded_at"] ?? ""), (string) ($left["uploaded_at"] ?? ""));
  274. });
  275. $keep = array_slice($instanceBackups, 0, $retention);
  276. $remove = array_slice($instanceBackups, $retention);
  277. foreach ($remove as $backup) {
  278. $filename = basename((string) ($backup["filename"] ?? ""));
  279. if ($filename !== "") {
  280. $path = backupManageBackupPath($instance, $filename);
  281. if (is_file($path)) {
  282. @unlink($path);
  283. }
  284. }
  285. }
  286. backupManageWriteIndex(array_merge($otherBackups, $keep));
  287. }
  288. function backupManageApplyRetentionAll(): void
  289. {
  290. $instances = [];
  291. foreach (backupManageReadIndex()["backups"] as $backup) {
  292. if (is_array($backup)) {
  293. $instance = (string) ($backup["instance"] ?? "");
  294. if ($instance !== "") {
  295. $instances[$instance] = true;
  296. }
  297. }
  298. }
  299. foreach (array_keys($instances) as $instance) {
  300. backupManageApplyRetentionForInstance($instance);
  301. }
  302. }
  303. function backupManageAddInstance(string $instance): void
  304. {
  305. $instance = backupManageValidateInstance($instance);
  306. $settings = backupManageReadSettings();
  307. $settings["instances"][] = $instance;
  308. backupManageWriteSettings($settings);
  309. }
  310. function backupManageRemoveInstance(string $instance): void
  311. {
  312. $instance = backupManageValidateInstance($instance);
  313. $settings = backupManageReadSettings();
  314. $settings["instances"] = array_values(
  315. array_filter($settings["instances"], function ($existing) use ($instance) {
  316. return $existing !== $instance;
  317. }),
  318. );
  319. backupManageWriteSettings($settings);
  320. }
  321. function backupManageGroupBackupsByInstance(array $backups): array
  322. {
  323. $grouped = [];
  324. foreach ($backups as $backup) {
  325. if (!is_array($backup)) {
  326. continue;
  327. }
  328. $instance = (string) ($backup["instance"] ?? "");
  329. $filename = basename((string) ($backup["filename"] ?? ""));
  330. if ($instance === "" || $filename === "" || !is_file(backupManageBackupPath($instance, $filename))) {
  331. continue;
  332. }
  333. $backup["filename"] = $filename;
  334. $backup["size"] = (int) (filesize(backupManageBackupPath($instance, $filename)) ?: ($backup["size"] ?? 0));
  335. $grouped[$instance][] = $backup;
  336. }
  337. ksort($grouped);
  338. foreach ($grouped as &$records) {
  339. usort($records, function ($left, $right) {
  340. return strcmp((string) ($right["uploaded_at"] ?? ""), (string) ($left["uploaded_at"] ?? ""));
  341. });
  342. }
  343. unset($records);
  344. return $grouped;
  345. }
  346. if ($_SERVER["REQUEST_METHOD"] === "POST") {
  347. $action = (string) ($_POST["action"] ?? "");
  348. if ($action === "login") {
  349. if (!backupManagePasswordConfigured()) {
  350. $errors[] = "No password is configured.";
  351. } elseif (backupManagePasswordMatches((string) ($_POST["password"] ?? ""))) {
  352. session_regenerate_id(true);
  353. $_SESSION["backup_server_logged_in"] = true;
  354. $messages[] = "Logged in.";
  355. } else {
  356. $errors[] = "Wrong password.";
  357. }
  358. } elseif ($action === "logout") {
  359. unset($_SESSION["backup_server_logged_in"], $_SESSION["backup_server_csrf_token"]);
  360. $messages[] = "Logged out.";
  361. } elseif (!backupManageIsLoggedIn()) {
  362. $errors[] = "Login required.";
  363. } elseif (!backupManageCsrfIsValid((string) ($_POST["csrf_token"] ?? ""))) {
  364. $errors[] = "Invalid token. Please reload the page and try again.";
  365. } else {
  366. try {
  367. if ($action === "update_retention") {
  368. $retention = max(1, (int) ($_POST["retention"] ?? BACKUP_SERVER_RETENTION));
  369. $settings = backupManageReadSettings();
  370. $settings["retention"] = $retention;
  371. backupManageWriteSettings($settings);
  372. backupManageApplyRetentionAll();
  373. $messages[] = "Retention updated.";
  374. } elseif ($action === "add_instance") {
  375. backupManageAddInstance((string) ($_POST["instance"] ?? ""));
  376. $messages[] = "Instance added.";
  377. } elseif ($action === "remove_instance") {
  378. backupManageRemoveInstance((string) ($_POST["instance"] ?? ""));
  379. $messages[] = "Instance removed.";
  380. } elseif ($action === "download") {
  381. backupManageSendDownload(
  382. backupManageValidateInstance((string) ($_POST["instance"] ?? "")),
  383. backupManageValidateFilename((string) ($_POST["filename"] ?? "")),
  384. );
  385. } elseif ($action === "delete") {
  386. backupManageDeleteBackup(
  387. backupManageValidateInstance((string) ($_POST["instance"] ?? "")),
  388. backupManageValidateFilename((string) ($_POST["filename"] ?? "")),
  389. );
  390. $messages[] = "Backup deleted.";
  391. }
  392. } catch (Throwable $exception) {
  393. $errors[] = $exception->getMessage();
  394. }
  395. }
  396. }
  397. try {
  398. $settings = backupManageReadSettings();
  399. $groupedBackups = backupManageGroupBackupsByInstance(backupManageReadIndex()["backups"]);
  400. } catch (Throwable $exception) {
  401. $settings = ["retention" => max(1, (int) BACKUP_SERVER_RETENTION)];
  402. $groupedBackups = [];
  403. $errors[] = $exception->getMessage();
  404. }
  405. ?>
  406. <!DOCTYPE html>
  407. <html lang="de">
  408. <head>
  409. <meta charset="UTF-8">
  410. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  411. <title>Backup Management</title>
  412. </head>
  413. <body>
  414. <h1>Backup Management</h1>
  415. <?php foreach ($messages as $message): ?>
  416. <p><strong><?php echo backupManageEscape($message); ?></strong></p>
  417. <?php endforeach; ?>
  418. <?php foreach ($errors as $error): ?>
  419. <p><strong>Error:</strong> <?php echo backupManageEscape($error); ?></p>
  420. <?php endforeach; ?>
  421. <?php if (!backupManageIsLoggedIn()): ?>
  422. <form method="POST">
  423. <input type="hidden" name="action" value="login">
  424. <p>
  425. <label for="password">Password</label><br>
  426. <input type="password" id="password" name="password" required>
  427. </p>
  428. <button type="submit">Login</button>
  429. </form>
  430. <?php else: ?>
  431. <form method="POST">
  432. <input type="hidden" name="action" value="logout">
  433. <button type="submit">Logout</button>
  434. </form>
  435. <h2>Settings</h2>
  436. <form method="POST">
  437. <input type="hidden" name="action" value="update_retention">
  438. <input type="hidden" name="csrf_token" value="<?php echo backupManageEscape(backupManageCsrfToken()); ?>">
  439. <p>
  440. <label for="retention">Backups retained per instance</label><br>
  441. <input type="number" id="retention" name="retention" min="1" required value="<?php echo (int) $settings["retention"]; ?>">
  442. </p>
  443. <button type="submit">Save retention</button>
  444. </form>
  445. <h2>Upload endpoint</h2>
  446. <p>Distributed instances should upload to <code>upload.php</code>.</p>
  447. <h2>Allowed instances</h2>
  448. <form method="POST">
  449. <input type="hidden" name="action" value="add_instance">
  450. <input type="hidden" name="csrf_token" value="<?php echo backupManageEscape(backupManageCsrfToken()); ?>">
  451. <p>
  452. <label for="instance">Instance identifier</label><br>
  453. <input type="text" id="instance" name="instance" required pattern="[A-Za-z0-9][A-Za-z0-9._-]*" maxlength="120">
  454. </p>
  455. <button type="submit">Add instance</button>
  456. </form>
  457. <?php if (empty($settings["instances"])): ?>
  458. <p>No instances allowed. Uploads will be rejected until an instance is added.</p>
  459. <?php else: ?>
  460. <table border="1" cellpadding="6" cellspacing="0">
  461. <thead>
  462. <tr>
  463. <th>Instance</th>
  464. <th>Actions</th>
  465. </tr>
  466. </thead>
  467. <tbody>
  468. <?php foreach ($settings["instances"] as $instance): ?>
  469. <tr>
  470. <td><?php echo backupManageEscape($instance); ?></td>
  471. <td>
  472. <form method="POST" style="display:inline" onsubmit="return confirm('Remove this allowed instance? Existing backups remain visible.');">
  473. <input type="hidden" name="action" value="remove_instance">
  474. <input type="hidden" name="csrf_token" value="<?php echo backupManageEscape(backupManageCsrfToken()); ?>">
  475. <input type="hidden" name="instance" value="<?php echo backupManageEscape($instance); ?>">
  476. <button type="submit">Remove</button>
  477. </form>
  478. </td>
  479. </tr>
  480. <?php endforeach; ?>
  481. </tbody>
  482. </table>
  483. <?php endif; ?>
  484. <h2>Backups</h2>
  485. <?php if (empty($groupedBackups)): ?>
  486. <p>No backups uploaded.</p>
  487. <?php else: ?>
  488. <?php foreach ($groupedBackups as $instance => $backups): ?>
  489. <h3><?php echo backupManageEscape($instance); ?></h3>
  490. <table border="1" cellpadding="6" cellspacing="0">
  491. <thead>
  492. <tr>
  493. <th>Uploaded</th>
  494. <th>Filename</th>
  495. <th>Size</th>
  496. <th>SHA-256</th>
  497. <th>Source IP</th>
  498. <th>Actions</th>
  499. </tr>
  500. </thead>
  501. <tbody>
  502. <?php foreach ($backups as $backup): ?>
  503. <tr>
  504. <td><?php echo backupManageEscape($backup["uploaded_at"] ?? ""); ?></td>
  505. <td><?php echo backupManageEscape($backup["filename"] ?? ""); ?></td>
  506. <td><?php echo backupManageEscape(backupManageFormatBytes((int) ($backup["size"] ?? 0))); ?></td>
  507. <td><?php echo backupManageEscape($backup["sha256"] ?? ""); ?></td>
  508. <td><?php echo backupManageEscape($backup["source_ip"] ?? ""); ?></td>
  509. <td>
  510. <form method="POST" style="display:inline">
  511. <input type="hidden" name="action" value="download">
  512. <input type="hidden" name="csrf_token" value="<?php echo backupManageEscape(backupManageCsrfToken()); ?>">
  513. <input type="hidden" name="instance" value="<?php echo backupManageEscape($instance); ?>">
  514. <input type="hidden" name="filename" value="<?php echo backupManageEscape($backup["filename"] ?? ""); ?>">
  515. <button type="submit">Download</button>
  516. </form>
  517. <form method="POST" style="display:inline" onsubmit="return confirm('Delete this backup?');">
  518. <input type="hidden" name="action" value="delete">
  519. <input type="hidden" name="csrf_token" value="<?php echo backupManageEscape(backupManageCsrfToken()); ?>">
  520. <input type="hidden" name="instance" value="<?php echo backupManageEscape($instance); ?>">
  521. <input type="hidden" name="filename" value="<?php echo backupManageEscape($backup["filename"] ?? ""); ?>">
  522. <button type="submit">Delete</button>
  523. </form>
  524. </td>
  525. </tr>
  526. <?php endforeach; ?>
  527. </tbody>
  528. </table>
  529. <?php endforeach; ?>
  530. <?php endif; ?>
  531. <?php endif; ?>
  532. </body>
  533. </html>