updater.php 13 KB

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