updater.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. <?php
  2. declare(strict_types=1);
  3. // Update pipeline: check, download, verify, extract, deploy, post-update hook.
  4. //
  5. // Ported from the PSA order system (admin/updater.php) with the HTML stripped
  6. // out and three hardcoded assumptions made configurable:
  7. // - the version file (was includes/version.php with APP_VERSION)
  8. // - the protected paths (was config.php, data/, .git/)
  9. // - the package sanity marker (was index.php / admin/ / includes/)
  10. //
  11. // Deployment is an overlay copy: every file in the package is written over the
  12. // application root, with each overwritten file copied aside first. Files that
  13. // disappeared between releases are NOT removed, and there is no restore path —
  14. // the aside copies exist for manual recovery only.
  15. function manageUpdateWorkDir(): string
  16. {
  17. return rtrim((string) MANAGE_WORK_DIR, "/\\") . DIRECTORY_SEPARATOR;
  18. }
  19. function manageUpdateBackupRoot(): string
  20. {
  21. return rtrim((string) MANAGE_UPDATE_BACKUP_DIR, "/\\") . DIRECTORY_SEPARATOR;
  22. }
  23. // ---------------------------------------------------------------------------
  24. // Manifest
  25. // ---------------------------------------------------------------------------
  26. /**
  27. * Fetches and strictly validates the manifest.
  28. *
  29. * Every field is re-checked here because the response decides which code the
  30. * instance will execute next.
  31. */
  32. function manageUpdateFetchManifest(): array
  33. {
  34. $decoded = manageClientRequestJson("GET", "manifest.php", null, (int) MANAGE_HTTP_TIMEOUT);
  35. $version = trim((string) ($decoded["version"] ?? $decoded["latest"] ?? ""));
  36. $packageUrl = trim((string) ($decoded["package_url"] ?? ""));
  37. $sha256 = strtolower(trim((string) ($decoded["sha256"] ?? "")));
  38. $size = isset($decoded["size"]) ? (int) $decoded["size"] : 0;
  39. $publishedAt = trim((string) ($decoded["published_at"] ?? ""));
  40. if (!manageIsVersionString($version)) {
  41. throw new RuntimeException("Version im Manifest ist ungültig.");
  42. }
  43. if (!filter_var($packageUrl, FILTER_VALIDATE_URL)) {
  44. throw new RuntimeException("Paket-URL im Manifest ist ungültig.");
  45. }
  46. if (preg_match('/^[a-f0-9]{64}$/', $sha256) !== 1) {
  47. throw new RuntimeException("Prüfsumme im Manifest ist ungültig.");
  48. }
  49. return [
  50. "version" => $version,
  51. "package_url" => $packageUrl,
  52. "sha256" => $sha256,
  53. "size" => $size,
  54. "published_at" => $publishedAt,
  55. ];
  56. }
  57. /**
  58. * Checks whether a newer release is available.
  59. *
  60. * @return array{current: string, latest: string, available: bool, manifest: array}
  61. */
  62. function manageUpdateCheck(): array
  63. {
  64. $manifest = manageUpdateFetchManifest();
  65. $current = manageClientVersion();
  66. $available = $current === ""
  67. ? true
  68. : version_compare(
  69. manageVersionCompareValue($manifest["version"]),
  70. manageVersionCompareValue($current),
  71. ">",
  72. );
  73. return [
  74. "current" => $current,
  75. "latest" => $manifest["version"],
  76. "available" => $available,
  77. "manifest" => $manifest,
  78. ];
  79. }
  80. // ---------------------------------------------------------------------------
  81. // Download and extraction
  82. // ---------------------------------------------------------------------------
  83. function manageUpdateDownloadPackage(array $manifest, string $targetFile): void
  84. {
  85. manageEnsureDir(dirname($targetFile));
  86. $version = (string) $manifest["version"];
  87. $response = manageClientRequest(
  88. "GET",
  89. "package.php?version=" . rawurlencode($version),
  90. null,
  91. "application/json",
  92. (int) MANAGE_HTTP_TIMEOUT_LONG,
  93. );
  94. if ($response["status"] < 200 || $response["status"] >= 300) {
  95. throw new RuntimeException(manageClientErrorMessage($response["status"], $response["body"]));
  96. }
  97. if ($response["body"] === "") {
  98. throw new RuntimeException("Das heruntergeladene Paket ist leer.");
  99. }
  100. if (file_put_contents($targetFile, $response["body"], LOCK_EX) === false) {
  101. throw new RuntimeException("Das heruntergeladene Paket konnte nicht gespeichert werden.");
  102. }
  103. if ($manifest["size"] > 0 && filesize($targetFile) !== $manifest["size"]) {
  104. unlink($targetFile);
  105. throw new RuntimeException("Größe des heruntergeladenen Pakets stimmt nicht überein.");
  106. }
  107. $actualHash = strtolower(hash_file("sha256", $targetFile) ?: "");
  108. if ($actualHash !== $manifest["sha256"]) {
  109. unlink($targetFile);
  110. throw new RuntimeException("Prüfsumme des Pakets stimmt nicht überein.");
  111. }
  112. }
  113. // Rejects zip-slip and anything else that would escape the stage directory.
  114. function manageUpdateValidateZipEntry(string $entry): bool
  115. {
  116. $entry = str_replace("\\", "/", $entry);
  117. $normalized = trim($entry, "/");
  118. if (
  119. $normalized === "" ||
  120. str_contains($entry, "\0") ||
  121. str_starts_with($entry, "/") ||
  122. preg_match('/^[A-Za-z]:\//', $entry) === 1
  123. ) {
  124. return false;
  125. }
  126. foreach (explode("/", $normalized) as $segment) {
  127. if ($segment === "" || $segment === "." || $segment === "..") {
  128. return false;
  129. }
  130. }
  131. return true;
  132. }
  133. function manageUpdateExtractPackage(string $zipFile, string $stageDir): void
  134. {
  135. if (!class_exists("ZipArchive")) {
  136. throw new RuntimeException("Die PHP-Erweiterung ZipArchive ist nicht verfügbar.");
  137. }
  138. manageRemoveDir($stageDir);
  139. manageEnsureDir($stageDir);
  140. $zip = new ZipArchive();
  141. if ($zip->open($zipFile) !== true) {
  142. throw new RuntimeException("Das heruntergeladene Paket ist keine lesbare ZIP-Datei.");
  143. }
  144. $sanityPaths = is_array(MANAGE_UPDATE_SANITY_PATHS) ? MANAGE_UPDATE_SANITY_PATHS : [];
  145. $hasAppFile = $sanityPaths === [];
  146. for ($i = 0; $i < $zip->numFiles; $i++) {
  147. $name = (string) $zip->getNameIndex($i);
  148. if (!manageUpdateValidateZipEntry($name)) {
  149. $zip->close();
  150. throw new RuntimeException("Das Paket enthält einen unsicheren Pfad: " . $name);
  151. }
  152. foreach ($sanityPaths as $sanityPath) {
  153. $sanityPath = trim(str_replace("\\", "/", (string) $sanityPath), "/");
  154. if ($sanityPath === "") {
  155. continue;
  156. }
  157. if ($name === $sanityPath || str_starts_with($name, $sanityPath . "/")) {
  158. $hasAppFile = true;
  159. }
  160. }
  161. }
  162. if (!$hasAppFile) {
  163. $zip->close();
  164. throw new RuntimeException(
  165. "Das Paket sieht nicht wie ein Release dieser Anwendung aus (erwartet: " .
  166. implode(", ", array_map("strval", $sanityPaths)) . ").",
  167. );
  168. }
  169. if (!$zip->extractTo($stageDir)) {
  170. $zip->close();
  171. throw new RuntimeException("Das Paket konnte nicht entpackt werden.");
  172. }
  173. $zip->close();
  174. }
  175. // ---------------------------------------------------------------------------
  176. // Deployment
  177. // ---------------------------------------------------------------------------
  178. function manageUpdateRelativePath(string $path, string $baseDir): string
  179. {
  180. return ltrim(str_replace("\\", "/", substr($path, strlen($baseDir))), "/");
  181. }
  182. /**
  183. * Whether a path from the package must be left alone.
  184. *
  185. * A configured entry ending in "/" protects the directory and everything below
  186. * it; anything else matches the exact path.
  187. */
  188. function manageUpdateShouldSkipPath(string $relativePath): bool
  189. {
  190. $relativePath = trim(str_replace("\\", "/", $relativePath), "/");
  191. if ($relativePath === "") {
  192. return true;
  193. }
  194. $protected = is_array(MANAGE_UPDATE_PROTECTED_PATHS) ? MANAGE_UPDATE_PROTECTED_PATHS : [];
  195. foreach ($protected as $entry) {
  196. $entry = str_replace("\\", "/", (string) $entry);
  197. $isDirectory = str_ends_with($entry, "/");
  198. $entry = trim($entry, "/");
  199. if ($entry === "") {
  200. continue;
  201. }
  202. if ($relativePath === $entry) {
  203. return true;
  204. }
  205. if ($isDirectory && str_starts_with($relativePath, $entry . "/")) {
  206. return true;
  207. }
  208. // A protected directory named without a trailing slash still protects
  209. // its contents; the trailing slash only documents the intent.
  210. if (!$isDirectory && str_starts_with($relativePath, $entry . "/")) {
  211. return true;
  212. }
  213. }
  214. return false;
  215. }
  216. function manageUpdateCopyWithBackup(string $stageDir, string $appRoot, string $backupDir): array
  217. {
  218. manageEnsureDir($backupDir);
  219. $copied = 0;
  220. $backedUp = 0;
  221. $skipped = 0;
  222. $items = new RecursiveIteratorIterator(
  223. new RecursiveDirectoryIterator($stageDir, FilesystemIterator::SKIP_DOTS),
  224. RecursiveIteratorIterator::SELF_FIRST,
  225. );
  226. foreach ($items as $item) {
  227. $relativePath = manageUpdateRelativePath($item->getPathname(), $stageDir);
  228. if (manageUpdateShouldSkipPath($relativePath)) {
  229. $skipped++;
  230. continue;
  231. }
  232. $targetPath = $appRoot . DIRECTORY_SEPARATOR . $relativePath;
  233. if ($item->isDir()) {
  234. manageEnsureDir($targetPath);
  235. continue;
  236. }
  237. manageEnsureDir(dirname($targetPath));
  238. if (file_exists($targetPath)) {
  239. $backupPath = $backupDir . DIRECTORY_SEPARATOR . $relativePath;
  240. manageEnsureDir(dirname($backupPath));
  241. if (!copy($targetPath, $backupPath)) {
  242. throw new RuntimeException("Datei konnte nicht gesichert werden: " . $relativePath);
  243. }
  244. $backedUp++;
  245. }
  246. if (!copy($item->getPathname(), $targetPath)) {
  247. throw new RuntimeException("Datei konnte nicht ausgerollt werden: " . $relativePath);
  248. }
  249. @chmod($targetPath, fileperms($item->getPathname()) & 0777);
  250. $copied++;
  251. }
  252. return ["copied" => $copied, "backed_up" => $backedUp, "skipped" => $skipped];
  253. }
  254. // Keeps only the backup directory of the run that just finished.
  255. function manageUpdateCleanupOldBackups(string $keepBackupDir): int
  256. {
  257. $backupRoot = rtrim(manageUpdateBackupRoot(), "/\\");
  258. if (!is_dir($backupRoot)) {
  259. return 0;
  260. }
  261. $keepRealPath = realpath($keepBackupDir);
  262. $backupRootRealPath = realpath($backupRoot);
  263. if ($keepRealPath === false || $backupRootRealPath === false) {
  264. return 0;
  265. }
  266. $removed = 0;
  267. foreach (new DirectoryIterator($backupRootRealPath) as $item) {
  268. if ($item->isDot() || !$item->isDir()) {
  269. continue;
  270. }
  271. $path = $item->getPathname();
  272. if (realpath($path) === $keepRealPath) {
  273. continue;
  274. }
  275. manageRemoveDir($path);
  276. if (is_dir($path)) {
  277. throw new RuntimeException("Altes Backup-Verzeichnis konnte nicht entfernt werden: " . $path);
  278. }
  279. $removed++;
  280. }
  281. return $removed;
  282. }
  283. /**
  284. * Downloads, verifies and deploys one release, then runs the post-update step.
  285. *
  286. * $options:
  287. * force bool redeploy even when no newer version is available
  288. * skip_hook bool deploy files only, run neither migrations nor the callback
  289. *
  290. * The returned array always reports deployment and post-update separately:
  291. * a failed hook does not undo a successful deployment.
  292. */
  293. function manageUpdateApply(array $options = []): array
  294. {
  295. $force = !empty($options["force"]);
  296. $skipHook = !empty($options["skip_hook"]);
  297. $appRoot = manageClientAppRoot();
  298. $check = manageUpdateCheck();
  299. $manifest = $check["manifest"];
  300. if (!$check["available"] && !$force) {
  301. throw new RuntimeException(
  302. "Es ist kein neueres Update verfügbar. Mit der Option \"force\" kann dasselbe Paket erneut ausgerollt werden.",
  303. );
  304. }
  305. $runId = date("Ymd-His");
  306. $workDir = manageUpdateWorkDir() . $runId;
  307. $stageDir = $workDir . DIRECTORY_SEPARATOR . "stage";
  308. $zipFile = $workDir . DIRECTORY_SEPARATOR . "package.zip";
  309. $backupDir = manageUpdateBackupRoot() . $runId . "-" . $manifest["version"];
  310. manageEnsureDir($workDir);
  311. try {
  312. manageUpdateDownloadPackage($manifest, $zipFile);
  313. manageUpdateExtractPackage($zipFile, $stageDir);
  314. $result = manageUpdateCopyWithBackup($stageDir, $appRoot, $backupDir);
  315. } finally {
  316. manageRemoveDir($workDir);
  317. }
  318. $removedBackups = manageUpdateCleanupOldBackups($backupDir);
  319. manageClientLog("INFO", "Update deployed", [
  320. "from_version" => $check["current"],
  321. "to_version" => $manifest["version"],
  322. "copied" => $result["copied"],
  323. "backed_up" => $result["backed_up"],
  324. "backup_dir" => $backupDir,
  325. ]);
  326. $report = [
  327. "deployed" => true,
  328. "from_version" => $check["current"],
  329. "to_version" => $manifest["version"],
  330. "version" => manageClientVersion(),
  331. "copied" => $result["copied"],
  332. "backed_up" => $result["backed_up"],
  333. "skipped" => $result["skipped"],
  334. "removed_backups" => $removedBackups,
  335. "backup_dir" => $backupDir,
  336. "hook" => null,
  337. ];
  338. if ($skipHook) {
  339. $report["hook"] = [
  340. "success" => true,
  341. "skipped" => true,
  342. "migrations" => ["applied" => [], "pending" => count(manageUpdatePendingMigrations())],
  343. ];
  344. return $report;
  345. }
  346. // The version constant may already be loaded in this process from the old
  347. // code, so to_version is taken from the manifest rather than re-read.
  348. $report["hook"] = manageUpdateRunPostHook([
  349. "from_version" => $check["current"],
  350. "to_version" => $manifest["version"],
  351. "backup_dir" => $backupDir,
  352. "run_id" => $runId,
  353. ]);
  354. return $report;
  355. }