Play your Steam library's Windows games on a jailbroken PS5.
C++
Heal Playden's data after a recursive chmod over FTP
Leonardo Lobatoa4cb8b18dd4c
diff --git a/cmake/HomebrewUI.cmake b/cmake/HomebrewUI.cmakeindex db20c51..f4ce91d 100644--- a/cmake/HomebrewUI.cmake+++ b/cmake/HomebrewUI.cmake@@ -244,7 +244,7 @@ target_link_libraries(playden_homebrew_controller PUBLIC# Worker-owned per-game runtime composition (OWNER records, native inventory, kit layer).add_library(playden_homebrew_runtime_host STATIC "${CMAKE_SOURCE_DIR}/src/homebrew/runtime_host.cpp"- "${CMAKE_SOURCE_DIR}/src/runtime/writable_folders.cpp")+ "${CMAKE_SOURCE_DIR}/src/runtime/writable_folders.cpp" "${CMAKE_SOURCE_DIR}/src/runtime/self_heal.cpp")target_compile_features(playden_homebrew_runtime_host PUBLIC cxx_std_20)target_include_directories(playden_homebrew_runtime_host PUBLIC "${CMAKE_SOURCE_DIR}/src")target_link_libraries(playden_homebrew_runtime_host PUBLIC playden_native_coordinator playden_runtime_settings_publication@@ -441,6 +441,21 @@ if(BUILD_TESTING)target_include_directories(runtime_writable_folders_native_policy_test PRIVATE "${CMAKE_SOURCE_DIR}/src")target_compile_definitions(runtime_writable_folders_native_policy_test PRIVATE PLAYDEN_PLATFORM_PS5=1)add_test(NAME runtime_writable_folders_native_policy COMMAND runtime_writable_folders_native_policy_test)+ add_executable(runtime_self_heal_test "${CMAKE_SOURCE_DIR}/tests/runtime_self_heal_test.cpp"+ "${CMAKE_SOURCE_DIR}/src/runtime/self_heal.cpp")+ target_compile_features(runtime_self_heal_test PRIVATE cxx_std_20)+ target_include_directories(runtime_self_heal_test PRIVATE "${CMAKE_SOURCE_DIR}/src")+ target_link_libraries(runtime_self_heal_test PRIVATE playden_steam_protocol)+ add_test(NAME runtime_self_heal COMMAND runtime_self_heal_test)+ add_executable(runtime_self_heal_native_policy_test+ "${CMAKE_SOURCE_DIR}/tests/runtime_self_heal_test.cpp"+ "${CMAKE_SOURCE_DIR}/tests/directory_gateway_host.cpp"+ "${CMAKE_SOURCE_DIR}/src/runtime/self_heal.cpp")+ target_compile_features(runtime_self_heal_native_policy_test PRIVATE cxx_std_20)+ target_include_directories(runtime_self_heal_native_policy_test PRIVATE "${CMAKE_SOURCE_DIR}/src")+ target_link_libraries(runtime_self_heal_native_policy_test PRIVATE playden_steam_protocol)+ target_compile_definitions(runtime_self_heal_native_policy_test PRIVATE PLAYDEN_PLATFORM_PS5=1)+ add_test(NAME runtime_self_heal_native_policy COMMAND runtime_self_heal_native_policy_test)add_executable(homebrew_title_icon_test "${CMAKE_SOURCE_DIR}/tests/homebrew_title_icon_test.cpp")target_compile_features(homebrew_title_icon_test PRIVATE cxx_std_20)target_include_directories(homebrew_title_icon_test PRIVATE "${PLAYDEN_STB_IMAGE_INCLUDE_DIR}")diff --git a/src/homebrew/runtime_host.cpp b/src/homebrew/runtime_host.cppindex 4acac91..36a2ef4 100644--- a/src/homebrew/runtime_host.cpp+++ b/src/homebrew/runtime_host.cpp@@ -17,6 +17,7 @@#include "runtime/session_storage.h"#include "runtime/steam_stub.h"#include "runtime/steamworks.h"+#include "runtime/self_heal.h"#include "runtime/writable_folders.h"#include "platform/managed_file_lock.h"#include "steam/backend/cloud_mapping.h"@@ -2177,8 +2178,28 @@ RuntimeRelocationResult RuntimeHost::RunRelocate(Composition& c, const RuntimeRe// Fresh facts for one launch, from the package layer, the bottle's start check// and the console's inventory and activity. Runs on the worker; the application// thread reuses the worker's latest result while it is fresh.+// A bottle opened up over FTP (a recursive chmod) fails the title's start check and Playden's own:+// its modes go back first. The title can't have started from it like that, but one that is running+// or suspended (a chmod while it played) keeps its bottle as it is: a mode change reads as ESTALE there.+void RuntimeHost::HealBottle(Composition& c, const std::string& data_root, const std::string& title_id) {+ const auto bottle = HostPath(data_root);+ if (!rt::BottleTooOpen(bottle)) return;+ if (!title_id.empty()) {+ const auto activity = c.coordinator->Activity(title_id);+ if (activity != rt::NativeActivity::kStopped) {+ Log("bottle heal skipped path=" + data_root + " title=" + title_id + " activity=" ++ std::to_string(static_cast<int>(activity)));+ return;+ }+ }+ const auto healed = rt::TightenBottleModes(bottle, [this](const std::string& line) { Log(line); });+ Log("bottle heal path=" + data_root + " tightened=" + std::to_string(healed.tightened) ++ " left=" + std::to_string(healed.foreign) + " failed=" + std::to_string(healed.failed));+}+rt::LaunchPreflight RuntimeHost::Preflight(Composition& c, const rt::RuntimeInstall& record) {if (!pthread_equal(pthread_self(), application_thread_)) {+ HealBottle(c, record.data_root, record.title_id);rt::LaunchPreflight p;p.capability_available = c.kit.has_value() && static_cast<bool>(config_.launch_title);const auto root = config_.host_namespace_prefix.empty()@@ -2669,6 +2690,9 @@ std::string RuntimeHost::RunPrepare(Composition& c, const RuntimePrepareRequest&std::optional<rt::RuntimeInstall> existing;for (const auto& record : c.repository.Snapshot())if (record.runtime_number == request.runtime_number) existing = record;+ HealBottle(c, config_.package_paths.console_data_root + "/playden/games/" ++ (existing ? existing->install_id : ToInstallId(GameOf(request.game, request.runtime_number))),+ existing ? existing->title_id : std::string());// A title being removed because its game moved drives is finished here; any other removal by Uninstall.const bool moving = existing && existing->state == rt::PreparationState::kRemoving && existing->journal &&existing->journal->operation == "remove-move";diff --git a/src/homebrew/runtime_host.hpp b/src/homebrew/runtime_host.hppindex 323abcd..8055daa 100644--- a/src/homebrew/runtime_host.hpp+++ b/src/homebrew/runtime_host.hpp@@ -627,6 +627,8 @@ class RuntimeHost {// while no ManagedDirectory of the bottle is open. Failures are logged; the start check decides.void SettleBottle(Composition& composition, const runtime::RuntimeInstall& record, const char* when);runtime::LaunchPreflight Preflight(Composition& composition, const runtime::RuntimeInstall& record);+ // Worker only. Tightens the bottle at data_root (console path) when it looks opened up and its title is stopped.+ void HealBottle(Composition& composition, const std::string& data_root, const std::string& title_id);runtime::LaunchEvidence Evidence(Composition& composition, const runtime::RuntimeInstall& record,const std::string& session_id);void RunPlay(Composition& composition, std::uint32_t runtime_number);diff --git a/src/homebrew/simulation.cpp b/src/homebrew/simulation.cppindex 830c2e1..bd99c37 100644--- a/src/homebrew/simulation.cpp+++ b/src/homebrew/simulation.cpp@@ -741,7 +741,8 @@ StartupProblem describe_startup_problem(const std::string& detail, bool granted)"The Playden that started is not the copy in /data/homebrew. If you just copied a new version, ""restart the PS5; if it stays, copy the whole app folder to /data/homebrew again."};return {"Playden can't start", "Playden has root access but can't use its data in /data/playden. "- "Restart Playden; if it stays, check that folder's permissions over FTP."};+ "Restart Playden. Don't change permissions inside /data/playden over FTP: its private folders "+ "must stay owner-only. If it stays, send logs/native-startup.log from Playden's app folder."};}if (has("launcher source is invalid") || has("launcher source identity is unavailable") ||stage({"find-helper", "validate-helper", "open-helper", "stat-helper"}))diff --git a/src/platform/managed_directory.h b/src/platform/managed_directory.hindex 1ed927a..5e7bba7 100644--- a/src/platform/managed_directory.h+++ b/src/platform/managed_directory.h@@ -52,7 +52,8 @@ class ManagedDirectory {// A folder it creates gets created_mode exactly (umask ignored); an existing// folder is never chmodded. kPrivate children are always created 0700,- // kPrivateTraversable ones 0700 or 0711.+ // kPrivateTraversable ones 0700 or 0711. (Startup's self-heal, runtime/self_heal.h,+ // tightens the app's own private state before anything opens it.)std::optional<ManagedDirectory> OpenChild(const std::string& name,DirectoryPolicy policy,bool create = false,diff --git a/src/platform/ps5/native_startup.cpp b/src/platform/ps5/native_startup.cppindex 2592c53..1e5f306 100644--- a/src/platform/ps5/native_startup.cpp+++ b/src/platform/ps5/native_startup.cpp@@ -2,7 +2,9 @@#include "platform/ps5/native_access_posix.h"#include "platform/ps5/title_activity.h"#include "platform/ps5/title_allow_list.h"+#include "runtime/kit_trust.h"#include "runtime/layout_migration.h"+#include "runtime/self_heal.h"#include "runtime/writable_folders.h"#include <EGL/egl.h>#include "steam/backend/native_network.h"@@ -175,6 +177,11 @@ NativeAccessResult PrepareNativeStartup(const std::string& title_id) {if (result.runtime_ready && !result.paths.runtime_data_root.empty()) {namespace fs = std::filesystem;const fs::path data_root = result.paths.runtime_data_root;+ const auto layout_log = [&layout_lines](const std::string& line) { layout_lines.push_back(line); };+ // A recursive chmod over FTP leaves the private state and the kit too open to be accepted:+ // given back their modes before anything reads them.+ runtime::TightenPrivateModes(data_root, layout_log);+ runtime::TightenKitModes(runtime::kDevelopmentKitRoot, WithRoot, layout_log);// The app folder's empty stubs, before the move writes MOVED.txt into them. A failure is only// logged: the move takes a missing one.runtime::PrepareAppFolderStubs(result.paths.title_root, WithRoot,diff --git a/src/runtime/layout_migration.cpp b/src/runtime/layout_migration.cppindex b211906..7540cb7 100644--- a/src/runtime/layout_migration.cpp+++ b/src/runtime/layout_migration.cpp@@ -409,6 +409,20 @@ LayoutResult MigrateLayout(const LayoutPaths& paths, const LayoutOps& ops) {if (!loaded && !error.empty()) return hold("the move record " + (paths.state_root / kLayoutJournal).string() +" can't be read (" + error + ")");LayoutJournal journal = loaded.value_or(LayoutJournal{});+ // A lost move record (runtime-state deleted or replaced by hand) after a move that plainly+ // happened: the app folder has no user data left and /data/playden/user has it. Written again,+ // or the user step would hold on Playden's own moved data. Data on both sides is still held.+ // It resumes at the logs step (moving what the app folder's logs hold now, as every later start+ // does), so a record lost between the user and logs steps loses no logs. Both folders must list.+ const auto old_entries = Kind(old_user) == 0 ? std::optional<std::vector<std::string>>(std::vector<std::string>{})+ : Entries(old_user);+ const auto user_entries = Kind(paths.user_root) == 1 ? Entries(paths.user_root) : std::nullopt;+ if (!loaded && old_entries && old_entries->empty() && user_entries && !user_entries->empty()) {+ LayoutJournal rebuilt{"logs", old_logs.string(), paths.log_root.string(), 0};+ if (!SaveJournal(paths.state_root, rebuilt, &error)) return hold("the move record can't be written (" + error + ")");+ Log(ops, "move record rebuilt step=logs");+ journal = rebuilt;+ }// Once the games step is done the games folder exists, shared: a fresh install has// none to move. One that came with the moved games keeps its mode.const auto ensure_games_root = [&] {diff --git a/src/runtime/private_directories.h b/src/runtime/private_directories.hindex c55a786..1c1e179 100644--- a/src/runtime/private_directories.h+++ b/src/runtime/private_directories.h@@ -18,7 +18,8 @@ struct PrivateTraversal {// boundary is an existing trusted directory; private_root and descendants must// belong to that user and have mode 0700 (or 0711 for traversal folders).// Existing foreign/public directories in the private tree are rejected, never-// chmodded or taken over. Missing folders between boundary and private_root are+// chmodded or taken over (startup's self-heal, runtime/self_heal.h, only takes extra+// bits away from the app's own). Missing folders between boundary and private_root are// created 01777.bool EnsurePrivateDirectories(const std::filesystem::path& boundary,const std::filesystem::path& private_root,diff --git a/src/runtime/self_heal.cpp b/src/runtime/self_heal.cppnew file mode 100644index 0000000..5fe205e--- /dev/null+++ b/src/runtime/self_heal.cpp@@ -0,0 +1,245 @@+// SPDX-License-Identifier: GPL-3.0-or-later+#include "runtime/self_heal.h"+#include "platform/directory_walk.h"+#include "steam/backend/json.h"++#include <cerrno>+#include <cstdio>+#include <cstring>+#include <dirent.h>+#include <fcntl.h>+#include <string>+#include <sys/stat.h>+#include <unistd.h>+#include <vector>++namespace playden::runtime {+namespace fs = std::filesystem;+namespace {+using Log = std::function<void(const std::string&)>;++std::string Octal(mode_t mode) {+ char text[8];+ std::snprintf(text, sizeof(text), "%04o", unsigned(mode & 07777));+ return text;+}++void Note(const Log& log, const std::string& line) { if (log) log(line); }++// Takes away the bits of info's mode that `allowed` lacks, through fd. Only the owner's entries,+// and never a file with another link (someone else's file linked in).+void Tighten(int fd, const struct stat& info, mode_t allowed, const fs::path& path, const Log& log,+ SelfHealResult* result) {+ const mode_t current = info.st_mode & 07777;+ const mode_t wanted = current & allowed;+ if (wanted == current) return;+ if (info.st_uid != ::geteuid()) {+ ++result->foreign;+ Note(log, "self-heal left path=" + path.string() + " mode=" + Octal(current) + " uid=" + std::to_string(info.st_uid));+ return;+ }+ if (S_ISREG(info.st_mode) && info.st_nlink != 1) {+ ++result->foreign;+ Note(log, "self-heal left path=" + path.string() + " links=" + std::to_string(info.st_nlink));+ return;+ }+ if (::fchmod(fd, wanted) != 0) {+ ++result->failed;+ Note(log, "self-heal failed path=" + path.string() + " chmod=" + std::strerror(errno));+ return;+ }+ ++result->tightened;+ Note(log, "self-heal path=" + path.string() + " mode=" + Octal(current) + " -> " + Octal(wanted));+}++// The folder at path (missing: nothing to do) back to 0700 when `folder`, and the regular files+// directly in it back to 0600 when `files`. Subfolders are not entered. `traversable`: a folder+// at 0711 (a kit that lets others pass through bottles) is left as it is. `chmodded_files`: only+// files with an execute bit, which Playden never writes there but a recursive chmod leaves (a+// folder of private and ordinary files, like user/).+void TightenFolder(const fs::path& path, bool folder, bool files, const Log& log, SelfHealResult* result,+ bool traversable = false, bool chmodded_files = false) {+ const int fd = platform::OpenDirectoryWalk(path);+ if (fd < 0) {+ if (errno != ENOENT) {+ ++result->failed;+ Note(log, "self-heal failed path=" + path.string() + " open=" + std::strerror(errno));+ }+ return;+ }+ struct stat info{};+ if (::fstat(fd, &info) != 0 || !S_ISDIR(info.st_mode)) {+ ::close(fd);+ return;+ }+ const int listing_fd = files ? ::dup(fd) : -1;+ DIR* listing = listing_fd >= 0 ? ::fdopendir(listing_fd) : nullptr;+ if (files && !listing) {+ if (listing_fd >= 0) ::close(listing_fd);+ ++result->failed;+ Note(log, "self-heal failed path=" + path.string() + " list=" + std::strerror(errno));+ }+ while (listing) {+ errno = 0;+ const auto* entry = ::readdir(listing);+ if (!entry) break;+ const std::string name = entry->d_name;+ if (name == "." || name == ".." || entry->d_type == DT_DIR || entry->d_type == DT_LNK) continue;+ // O_NOFOLLOW: a link swapped in is refused, never followed.+ const int child = platform::OpenWalkChild(fd, name.c_str(), O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC,+ entry->d_fileno);+ if (child < 0) {+ if (errno != ELOOP && errno != ENOENT) {+ ++result->failed;+ Note(log, "self-heal failed path=" + (path / name).string() + " open=" + std::strerror(errno));+ }+ continue;+ }+ struct stat opened{};+ if (::fstat(child, &opened) == 0 && S_ISREG(opened.st_mode) && (!chmodded_files || (opened.st_mode & 0111)))+ Tighten(child, opened, 0600, path / name, log, result);+ ::close(child);+ }+ if (listing) ::closedir(listing);+ // The folder last: one that still looks open is looked at again, so an interrupted pass is finished later.+ if (folder && !(traversable && (info.st_mode & 07777) == 0711)) Tighten(fd, info, 0700, path, log, result);+ ::close(fd);+}++bool SafeRelative(const fs::path& path) {+ if (path.empty() || path.is_absolute()) return false;+ for (const auto& part : path)+ if (part.empty() || part == "." || part == "..") return false;+ return true;+}++std::optional<std::string> ReadManifest(const fs::path& path, std::size_t max_bytes) {+ const int fd = ::open(path.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC);+ if (fd < 0) return std::nullopt;+ std::string bytes;+ char buffer[65536];+ for (;;) {+ const auto count = ::read(fd, buffer, sizeof(buffer));+ if (count < 0 && errno == EINTR) continue;+ if (count < 0 || bytes.size() + static_cast<std::size_t>(count) > max_bytes) { ::close(fd); return std::nullopt; }+ if (count == 0) break;+ bytes.append(buffer, static_cast<std::size_t>(count));+ }+ ::close(fd);+ return bytes;+}+} // namespace++SelfHealResult TightenPrivateModes(const fs::path& data_root, const Log& log) {+ SelfHealResult result;+ const auto state = data_root / "runtime-state";+ TightenFolder(state, true, true, log, &result);+ TightenFolder(state / "requests", true, true, log, &result);+ // Retired title trees inside trash/ are 0755 on purpose: only the folder itself.+ TightenFolder(state / "trash", true, false, log, &result);+ // user/ is shared (01777); its private files hold the sign-in, beside ordinary 0666 caches.+ TightenFolder(data_root / "user", false, true, log, &result, false, true);+ TightenFolder(data_root / "user/game-settings-private", true, true, log, &result);+ TightenFolder(data_root / "art", true, false, log, &result);+ return result;+}++bool BottleTooOpen(const fs::path& data_root) {+ for (const auto* relative : {"", "library", ".playden-control"}) {+ struct stat info{};+ const auto path = *relative ? data_root / relative : data_root;+ if (::lstat(path.c_str(), &info) != 0 || !S_ISDIR(info.st_mode)) continue;+ const mode_t mode = info.st_mode & 07777;+ if (mode != 0700 && mode != 0711) return true;+ }+ return false;+}++SelfHealResult TightenBottleModes(const fs::path& data_root, const Log& log) {+ SelfHealResult result;+ // The folders the title's start check wants owner-only; drive_c and below are the game's. Deepest+ // first and the bottle itself last, and only when everything else went: until then the title's+ // start check refuses the bottle (no game starts from a half-repaired one), and BottleTooOpen+ // brings the next Prepare or Play back here.+ for (const auto* relative : {"title-metadata/sce_sys", "title-metadata", "logs/sessions", "logs", ".playden-control",+ "library/profiles", "library/input"})+ TightenFolder(data_root / relative, true, true, log, &result);+ TightenFolder(data_root / "library/prefixes/game", true, true, log, &result, true);+ TightenFolder(data_root / "library/prefixes", true, false, log, &result, true);+ TightenFolder(data_root / "library", true, false, log, &result, true);+ if (result.failed == 0) TightenFolder(data_root, true, false, log, &result, true);+ return result;+}++SelfHealResult TightenKitModes(const fs::path& kit_root, const WritableFoldersAsRoot& as_root, const Log& log) {+ SelfHealResult result;+ constexpr std::size_t kMaxManifestBytes = 8 * 1024 * 1024, kMaxFiles = 32768;+ const auto bytes = ReadManifest(kit_root / "manifest.json", kMaxManifestBytes);+ if (!bytes) return result; // no kit yet, or one admission will refuse anyway+ const auto manifest = steam::json::Parse(*bytes, {kMaxManifestBytes, 16, kMaxFiles * 8, 1024 * 1024});+ const auto* files = manifest && manifest->is_object() ? manifest->Find("files") : nullptr;+ if (!files || !files->is_array()) return result;+ struct Change { fs::path path; mode_t current, expected; };+ std::vector<Change> changes;+ for (const auto& entry : files->array()) {+ const auto* path_value = entry.is_object() ? entry.Find("path") : nullptr;+ const auto* mode_value = entry.is_object() ? entry.Find("mode") : nullptr;+ if (!path_value || !path_value->is_string() || !mode_value || !mode_value->is_string()) continue;+ const fs::path relative = path_value->text();+ const auto& mode_text = mode_value->text();+ if (!SafeRelative(relative) || mode_text.size() != 4 ||+ mode_text.find_first_not_of("01234567") != std::string::npos)+ continue;+ const mode_t expected = static_cast<mode_t>(std::stoul(mode_text, nullptr, 8));+ // A cheap look first: a kit with the right modes is not walked.+ struct stat seen{};+ const auto path = kit_root / relative;+ if (::lstat(path.c_str(), &seen) != 0 || !S_ISREG(seen.st_mode)) continue;+ const mode_t current = seen.st_mode & 07777;+ // Only extra bits are taken away; a file missing bits is the kit's problem, not a chmod's.+ if (current == expected || (expected & ~current) != 0) continue;+ changes.push_back({path, current, expected});+ }+ if (changes.empty()) return result;+ std::vector<bool> done(changes.size(), false);+ // One root section for the whole kit. The folder is opened again for each file: the by-path+ // walk reads the parent's listing, whose offset a second lookup through it would continue from.+ // The kit is root's when made by the upload tool or a download, the app user's when copied by+ // hand from an earlier layout; anything else is not the kit's.+ const uid_t app_user = ::geteuid();+ const bool ran = as_root && as_root([&] {+ for (std::size_t index = 0; index < changes.size(); ++index) {+ const auto& change = changes[index];+ const int parent = platform::OpenDirectoryWalk(change.path.parent_path());+ if (parent < 0) continue;+ const int fd = platform::OpenWalkChild(parent, change.path.filename().c_str(),+ O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC);+ ::close(parent);+ if (fd < 0) continue;+ struct stat info{};+ // Still the file looked at: a regular file with one link and the mode seen.+ done[index] = ::fstat(fd, &info) == 0 && S_ISREG(info.st_mode) && info.st_nlink == 1 &&+ (info.st_uid == 0 || info.st_uid == app_user) &&+ (info.st_mode & 07777) == change.current && ::fchmod(fd, change.expected) == 0;+ ::close(fd);+ }+ return true;+ });+ // A whole kit can need it (thousands of files): one line, and only the first few failures by name.+ constexpr std::size_t kNamedFailures = 10;+ for (std::size_t index = 0; index < changes.size(); ++index) {+ const auto& change = changes[index];+ if (ran && done[index]) {+ ++result.tightened;+ continue;+ }+ if (++result.failed <= kNamedFailures)+ Note(log, "self-heal failed path=" + change.path.string() + " mode=" + Octal(change.current) ++ " kit=" + Octal(change.expected) + (ran ? "" : " root=refused"));+ }+ Note(log, "self-heal kit=" + kit_root.string() + " files=" + std::to_string(result.tightened) ++ " failed=" + std::to_string(result.failed));+ return result;+}++} // namespace playden::runtimediff --git a/src/runtime/self_heal.h b/src/runtime/self_heal.hnew file mode 100644index 0000000..097e901--- /dev/null+++ b/src/runtime/self_heal.h@@ -0,0 +1,46 @@+// SPDX-License-Identifier: GPL-3.0-or-later+#pragma once+// Undoes a recursive chmod over FTP (often 777 on all of /data/playden) on what Playden owns.+// Private folders and files must be owner-only, and kit files must have their manifest modes,+// or startup and the runtime refuse them. Only tightens: no bit is ever added, entries of other+// owners and files with other links are left alone, links are never followed, and every change+// goes through a descriptor opened without following a link.+#include "runtime/writable_folders.h"++#include <cstddef>+#include <filesystem>+#include <functional>+#include <string>++namespace playden::runtime {++struct SelfHealResult {+ std::size_t tightened = 0; // folders and files given back their mode+ std::size_t foreign = 0; // open or wrong entries of another owner: left, and logged+ std::size_t failed = 0; // entries that could not be opened or changed+};++// Under data_root (/data/playden): runtime-state, its requests/ and trash/ folders,+// user/game-settings-private and art/ back to 0700; the files directly in runtime-state,+// requests/, user/ and game-settings-private back to 0600. user/ itself stays shared. Bottles in+// games/ are not touched: a suspended game can hold them open.+SelfHealResult TightenPrivateModes(const std::filesystem::path& data_root,+ const std::function<void(const std::string&)>& log);++// Whether a bottle (/data/playden/games/<install id>) looks opened up: its root, library or+// control folder is neither 0700 nor 0711. One lstat each; a missing bottle is not.+bool BottleTooOpen(const std::filesystem::path& data_root);++// The bottle at data_root: the folders the title's start check wants owner-only back to 0700 (0711+// kept), and the files directly in the game prefix, profiles, input presets, control folder, logs+// and title metadata back to 0600. drive_c is not entered. Only while the game's title is stopped.+SelfHealResult TightenBottleModes(const std::filesystem::path& data_root,+ const std::function<void(const std::string&)>& log);++// Files of the kit at kit_root whose mode has more bits than its manifest.json gives them get+// the manifest's mode, as root (the kit is often root's). The manifest's hash is checked when the+// kit is admitted; here it only says which bits to take away.+SelfHealResult TightenKitModes(const std::filesystem::path& kit_root, const WritableFoldersAsRoot& as_root,+ const std::function<void(const std::string&)>& log);++} // namespace playden::runtimediff --git a/src/runtime/writable_folders.cpp b/src/runtime/writable_folders.cppindex 79e9148..bfac006 100644--- a/src/runtime/writable_folders.cpp+++ b/src/runtime/writable_folders.cpp@@ -96,7 +96,7 @@ std::string EnsureWritableFolders(const std::vector<std::filesystem::path>& fold: !ran ? " fix=root-refused": fixed ? " after-fix=" + Error(second) : " chmod=" + Error(fix_error)));return "Playden can't write to " + folder.string() +- ". Make the folder writable over FTP (permissions 777), then try again.";+ ". Make that folder writable over FTP (777 on the folder only, not its contents), then try again.";}return {};}@@ -136,7 +136,7 @@ std::string PrepareRuntimeRoot(const std::filesystem::path& root, const Writableconst std::string detail = failed + " failed" + (failed_error ? " error=" + Error(failed_error) : "");if (log) log("runtime root repair failed path=" + root.string() + " " + detail);return "Playden can't write to " + root.string() + " (" + detail +- "). Make the folder writable over FTP (permissions 777), then try again.";+ "). Make that folder writable over FTP (777 on the folder only, not its contents), then try again.";}std::string PrepareDropFolder(const std::filesystem::path& folder, const WritableFoldersAsRoot& as_root,diff --git a/tests/homebrew_live_model_test.cpp b/tests/homebrew_live_model_test.cppindex 636859d..1a18a33 100644--- a/tests/homebrew_live_model_test.cpp+++ b/tests/homebrew_live_model_test.cpp@@ -1101,7 +1101,8 @@ void live_root_access_missing() {const auto& data_view = granted.view();check(data_view.title == "Playden can't start", "root access: a data failure after the grant has its own title");check(data_view.subtitle == "Playden has root access but can't use its data in /data/playden. "- "Restart Playden; if it stays, check that folder's permissions over FTP.",+ "Restart Playden. Don't change permissions inside /data/playden over FTP: its private folders "+ "must stay owner-only. If it stays, send logs/native-startup.log from Playden's app folder.","root access: the body points at /data/playden");check(data_view.subtitle.find("kstuff") == std::string::npos, "root access: no kstuff advice after the grant");const auto data_detail = std::find_if(data_view.rows.begin(), data_view.rows.end(),diff --git a/tests/homebrew_runtime_host_test.cpp b/tests/homebrew_runtime_host_test.cppindex 799157b..3ac9818 100644--- a/tests/homebrew_runtime_host_test.cpp+++ b/tests/homebrew_runtime_host_test.cpp@@ -739,7 +739,7 @@ void PrepareNamesUnfixableFolder() {host.Prepare(Hl2());const auto done = WaitFor(host, [](const RuntimeSnapshot& s) { return !s.preparing_app && s.refusals.count(220); }, 60);CHECK(done.refusals.at(220) == "Playden can't write to " + homebrew.string() +- ". Make the folder writable over FTP (permissions 777), then try again.");+ ". Make that folder writable over FTP (777 on the folder only, not its contents), then try again.");CHECK(raises == 1);CHECK(done.installs.empty());struct stat info{};diff --git a/tests/layout_migration_test.cpp b/tests/layout_migration_test.cppindex 8189c34..13baabf 100644--- a/tests/layout_migration_test.cpp+++ b/tests/layout_migration_test.cpp@@ -451,6 +451,38 @@ void StartupDefersGamesWithoutActivityChecks() {CHECK(LoadLayoutJournal(f->paths.state_root)->step == "games");}+// runtime-state deleted or replaced by hand after the move: the record is written again from what+// the folders show, and startup goes on instead of holding on its own moved data.+void RebuildsALostMoveRecord() {+ bool rebuilt = false;+ {+ auto f = Make("lost-record");+ CHECK(MigrateLayout(f->paths, f->ops).games_moved && MarkLayoutDone(f->paths.state_root));+ fs::remove_all(f->paths.state_root);+ Write(f->paths.app_root / "logs" / "native-startup.log", "pre-grant\n"); // every start writes one+ const auto result = MigrateLayout(f->paths, f->ops);+ CHECK(result.runtime_ready && result.user_moved && result.logs_moved && result.games_moved && result.notice.empty());+ CHECK(result.user_root == f->paths.user_root && Read(f->paths.user_root / "session.v1") == "credentials");+ const auto journal = LoadLayoutJournal(f->paths.state_root);+ CHECK(journal && journal->step == "games-moved" && journal->to == f->paths.games_root.string());+ for (const auto& line : f->lines) rebuilt = rebuilt || line.find("move record rebuilt") != std::string::npos;+ CHECK(rebuilt);+ // It resumed at the logs step: the app folder's new log moved too, beside the one already there.+ CHECK(!fs::exists(f->paths.app_root / "logs" / "native-startup.log"));+ CHECK(Read(f->paths.log_root / "native-startup.log.moved") == "pre-grant\n");+ }+ {+ // Lost while the games still waited in the app folder: their move goes on later.+ auto f = Make("lost-record-deferred");+ f->ops.defer_games = true;+ CHECK(MigrateLayout(f->paths, f->ops).user_moved);+ fs::remove_all(f->paths.state_root);+ const auto result = MigrateLayout(f->paths, f->ops);+ CHECK(result.runtime_ready && result.user_moved && !result.games_moved);+ CHECK(LoadLayoutJournal(f->paths.state_root)->step == "games" && fs::exists(f->paths.app_root / "games/220"));+ }+}+void PartialUserMoveBlocksServicesAndOnlyMovesForward() {auto f = Make("partial-user");const auto old = f->paths.app_root / "playden-data";@@ -553,6 +585,7 @@ int main() {RunningGameFromHomeHoldsTheMove();MovesReadyGameWithCommittedPublication();RefusesToMergeIntoNonEmptyTarget();+ RebuildsALostMoveRecord();AbortsOnCrossDevice();RevertsTheMove();RevertKeepsConflictsAndJournal();diff --git a/tests/runtime_self_heal_test.cpp b/tests/runtime_self_heal_test.cppnew file mode 100644index 0000000..cba286b--- /dev/null+++ b/tests/runtime_self_heal_test.cpp@@ -0,0 +1,187 @@+// SPDX-License-Identifier: GPL-3.0-or-later+#include "runtime/self_heal.h"++#include <cstdio>+#include <cstdlib>+#include <filesystem>+#include <fstream>+#include <string>+#include <sys/stat.h>+#include <unistd.h>+#include <vector>++using namespace playden::runtime;+#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "%s:%d: CHECK failed: %s\n", __FILE__, __LINE__, #x); std::exit(1); } } while (0)++namespace fs = std::filesystem;+namespace {+unsigned Mode(const fs::path& path) {+ struct stat info{};+ CHECK(lstat(path.c_str(), &info) == 0);+ return info.st_mode & 07777;+}+void Folder(const fs::path& path, mode_t mode) {+ fs::create_directories(path);+ CHECK(chmod(path.c_str(), mode) == 0);+}+void File(const fs::path& path, mode_t mode, const std::string& text = "x") {+ std::ofstream(path) << text;+ CHECK(chmod(path.c_str(), mode) == 0);+}+} // namespace++int main() {+ char name[] = "/tmp/playden-self-heal-XXXXXX";+ CHECK(mkdtemp(name));+ const fs::path root = fs::canonical(name);+ std::vector<std::string> lines;+ const auto log = [&lines](const std::string& line) { lines.push_back(line); };++ // Nothing there yet (a first start): nothing to do, nothing failed.+ auto result = TightenPrivateModes(root / "data/playden", log);+ CHECK(result.tightened == 0 && result.failed == 0 && lines.empty());++ // What a recursive chmod 777 over FTP leaves behind.+ const auto data = root / "data/playden";+ const auto state = data / "runtime-state";+ Folder(data, 0777);+ Folder(state, 0777);+ File(state / "layout-0.6.json", 0777);+ File(state / "installs.json", 0777);+ File(state / "legacy.json", 0644);+ File(state / "read-only", 0400);+ Folder(state / "requests", 0777);+ File(state / "requests/settings-request-1.v1", 0777);+ Folder(state / "trash", 0777);+ Folder(state / "trash/FAKE00001-op", 0755);+ File(state / "trash/FAKE00001-op/eboot.bin", 0755);+ Folder(state / "unknown", 0777);+ File(state / "unknown/file", 0777);+ Folder(data / "user", 0777);+ File(data / "user/session.v1", 0777);+ File(data / "user/library-1.cache", 0666); // an ordinary cache, written 0666+ Folder(data / "user/game-settings-private", 0777);+ File(data / "user/game-settings-private/game-settings.json", 0777);+ Folder(data / "art", 0777);+ File(data / "art/cover.png", 0777);+ Folder(data / "logs", 0777);+ File(data / "logs/playden.log", 0777);+ // A link in a private folder is never followed; a file with another link is left alone.+ File(root / "outside", 0777);+ fs::create_symlink(root / "outside", state / "link");+ File(root / "shared", 0777);+ fs::create_hard_link(root / "shared", state / "hard");++ result = TightenPrivateModes(data, log);+ CHECK(Mode(state) == 0700);+ CHECK(Mode(state / "layout-0.6.json") == 0600 && Mode(state / "installs.json") == 0600);+ CHECK(Mode(state / "legacy.json") == 0600);+ CHECK(Mode(state / "read-only") == 0400); // never given bits it lacked+ CHECK(Mode(state / "requests") == 0700 && Mode(state / "requests/settings-request-1.v1") == 0600);+ CHECK(Mode(state / "trash") == 0700);+ CHECK(Mode(state / "trash/FAKE00001-op") == 0755 && Mode(state / "trash/FAKE00001-op/eboot.bin") == 0755);+ CHECK(Mode(state / "unknown") == 0777 && Mode(state / "unknown/file") == 0777);+ CHECK(Mode(data / "user") == 0777); // shared+ CHECK(Mode(data / "user/session.v1") == 0600 && Mode(data / "user/library-1.cache") == 0666);+ CHECK(Mode(data / "user/game-settings-private") == 0700);+ CHECK(Mode(data / "user/game-settings-private/game-settings.json") == 0600);+ CHECK(Mode(data / "art") == 0700 && Mode(data / "art/cover.png") == 0777);+ CHECK(Mode(data / "logs") == 0777 && Mode(data / "logs/playden.log") == 0777);+ CHECK(Mode(root / "outside") == 0777 && Mode(root / "shared") == 0777);+ CHECK(result.tightened == 11);+ CHECK(result.foreign == 1 && result.failed == 0);+ CHECK(lines.size() == 12);++ // A second start finds nothing to change and says nothing.+ lines.clear();+ result = TightenPrivateModes(data, log);+ CHECK(result.tightened == 0 && result.failed == 0 && result.foreign == 1 && lines.size() == 1);++ // A bottle after a recursive 777: the title's private folders and files go back, drive_c stays.+ const auto bottle = data / "games/steam-274520";+ CHECK(!BottleTooOpen(bottle)); // missing+ for (const auto* folder : {"", "library", "library/prefixes", "library/prefixes/game/drive_c/users/prospero",+ "library/profiles", "library/input", ".playden-control", "logs/sessions",+ "title-metadata/sce_sys"})+ Folder(bottle / folder, 0777);+ for (const auto* folder : {"", "library", "library/prefixes", "library/prefixes/game", "library/prefixes/game/drive_c",+ "library/prefixes/game/drive_c/users", "logs", "title-metadata"})+ CHECK(chmod((bottle / folder).c_str(), 0777) == 0);+ for (const auto* file : {".playden-control/publication-state.v1", ".playden-control/settings-operation.v1",+ "library/profiles/profiles.lst", "library/input/pad.ini", "library/prefixes/game/user.reg",+ "logs/sessions/one.json", "title-metadata/param.json", "title-metadata/sce_sys/icon0.png",+ "library/prefixes/game/drive_c/users/prospero/save.dat"})+ File(bottle / file, 0777);+ CHECK(BottleTooOpen(bottle));+ if (geteuid() != 0) {+ // A part that can't be repaired keeps the bottle itself open, so the next Play comes back.+ CHECK(chmod((bottle / "logs").c_str(), 0000) == 0);+ result = TightenBottleModes(bottle, log);+ CHECK(result.failed == 2 && Mode(bottle) == 0777 && BottleTooOpen(bottle)); // logs and logs/sessions+ CHECK(Mode(bottle / ".playden-control/publication-state.v1") == 0600);+ CHECK(chmod((bottle / "logs").c_str(), 0777) == 0);+ }+ lines.clear();+ result = TightenBottleModes(bottle, log);+ for (const auto* folder : {"", "library", "library/prefixes", "library/prefixes/game", "library/profiles",+ "library/input", ".playden-control", "logs", "logs/sessions", "title-metadata",+ "title-metadata/sce_sys"})+ CHECK(Mode(bottle / folder) == 0700);+ for (const auto* file : {".playden-control/publication-state.v1", ".playden-control/settings-operation.v1",+ "library/profiles/profiles.lst", "library/input/pad.ini", "library/prefixes/game/user.reg",+ "logs/sessions/one.json", "title-metadata/param.json", "title-metadata/sce_sys/icon0.png"})+ CHECK(Mode(bottle / file) == 0600);+ CHECK(Mode(bottle / "library/prefixes/game/drive_c") == 0777);+ CHECK(Mode(bottle / "library/prefixes/game/drive_c/users/prospero/save.dat") == 0777);+ CHECK(result.failed == 0 && !BottleTooOpen(bottle));+ // A bottle a kit keeps traversable (0711) is left as it is.+ CHECK(chmod(bottle.c_str(), 0711) == 0 && chmod((bottle / "library").c_str(), 0711) == 0);+ CHECK(!BottleTooOpen(bottle));+ result = TightenBottleModes(bottle, log);+ CHECK(result.tightened == 0 && Mode(bottle) == 0711 && Mode(bottle / "library") == 0711);++ // The kit: extra bits go, missing bits are not added, links are not followed.+ const auto kit = data / "kits/playden-kit";+ Folder(kit / "bin", 0777);+ Folder(kit / "lib", 0777);+ File(kit / "bin/a.dll", 0777);+ File(kit / "bin/run", 0777);+ File(kit / "lib/short", 0400);+ File(kit / "lib/right", 0644);+ fs::create_symlink(root / "outside", kit / "lib/linked");+ File(kit / "manifest.json", 0644,+ R"({"files":[{"path":"bin/a.dll","size":1,"sha256":"","mode":"0644"},)"+ R"({"path":"bin/run","size":1,"sha256":"","mode":"0755"},)"+ R"({"path":"lib/linked","size":1,"sha256":"","mode":"0644"},)"+ R"({"path":"lib/right","size":1,"sha256":"","mode":"0644"},)"+ R"({"path":"lib/short","size":1,"sha256":"","mode":"0644"},)"+ R"({"path":"../outside","size":1,"sha256":"","mode":"0600"}]})");+ unsigned calls = 0;+ const WritableFoldersAsRoot runs = [&calls](const std::function<bool()>& work) { ++calls; return work(); };+ const WritableFoldersAsRoot refuses = [&calls](const std::function<bool()>&) { ++calls; return false; };++ lines.clear();+ result = TightenKitModes(kit, refuses, log);+ CHECK(calls == 1 && result.tightened == 0 && result.failed == 2 && Mode(kit / "bin/a.dll") == 0777);+ result = TightenKitModes(kit, {}, log);+ CHECK(result.failed == 2 && Mode(kit / "bin/a.dll") == 0777);++ lines.clear();+ result = TightenKitModes(kit, runs, log);+ CHECK(calls == 2 && result.tightened == 2 && result.failed == 0 && lines.size() == 1); // one summary line+ CHECK(Mode(kit / "bin/a.dll") == 0644 && Mode(kit / "bin/run") == 0755);+ CHECK(Mode(kit / "lib/short") == 0400 && Mode(kit / "lib/right") == 0644);+ CHECK(Mode(root / "outside") == 0777);++ // A kit with its modes is not entered as root.+ result = TightenKitModes(kit, runs, log);+ CHECK(calls == 2 && result.tightened == 0 && result.failed == 0);+ // No kit, or a broken manifest: nothing to do.+ CHECK(TightenKitModes(data / "kits/missing", runs, log).tightened == 0);+ File(kit / "manifest.json", 0644, "{not json");+ CHECK(TightenKitModes(kit, runs, log).failed == 0 && calls == 2);++ fs::remove_all(root);+ std::puts("runtime_self_heal ok");+ return 0;+}