Play your Steam library's Windows games on a jailbroken PS5.
C++
Check and fix Playden's folders before it writes
Leonardo Lobato18ff2414adbd
diff --git a/cmake/HomebrewUI.cmake b/cmake/HomebrewUI.cmakeindex 3845e90..7ccc076 100644--- a/cmake/HomebrewUI.cmake+++ b/cmake/HomebrewUI.cmake@@ -240,7 +240,8 @@ target_link_libraries(playden_homebrew_controller PUBLICplayden_homebrew_runtime_host playden_self_update)# 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")+add_library(playden_homebrew_runtime_host STATIC "${CMAKE_SOURCE_DIR}/src/homebrew/runtime_host.cpp"+ "${CMAKE_SOURCE_DIR}/src/runtime/writable_folders.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@@ -419,6 +420,11 @@ if(BUILD_TESTING)add_executable(homebrew_runtime_host_test "${CMAKE_SOURCE_DIR}/tests/homebrew_runtime_host_test.cpp")target_link_libraries(homebrew_runtime_host_test PRIVATE playden_homebrew_runtime_host playden_runtime_artifact_hash)add_test(NAME homebrew_runtime_host COMMAND homebrew_runtime_host_test "${CMAKE_SOURCE_DIR}/runtime")+ add_executable(runtime_writable_folders_test "${CMAKE_SOURCE_DIR}/tests/runtime_writable_folders_test.cpp"+ "${CMAKE_SOURCE_DIR}/src/runtime/writable_folders.cpp")+ target_compile_features(runtime_writable_folders_test PRIVATE cxx_std_20)+ target_include_directories(runtime_writable_folders_test PRIVATE "${CMAKE_SOURCE_DIR}/src")+ add_test(NAME runtime_writable_folders COMMAND runtime_writable_folders_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/ps5.cpp b/src/homebrew/ps5.cppindex 01b3058..4dfd71f 100644--- a/src/homebrew/ps5.cpp+++ b/src/homebrew/ps5.cpp@@ -11,6 +11,7 @@#include "platform/ps5/title_runtime.h"#include "platform/ps5/native_startup.h"#include "runtime/settings_storage.h"+#include "runtime/writable_folders.h"#include "homebrew/runtime_host.hpp"#include "homebrew/title_icon.hpp"#include "platform/ps5/title_allow_list.h"@@ -310,6 +311,15 @@ int main() {playden::app::AppendLogLine(log_root, "install.log", "volume id=" + volume.id + " root=" + volume.games_root +" writable=" + (volume.available ? "1" : "0"));playden::steam::InstallService installs(install_runner, install_sessions, std::move(install_volumes));+ // A games folder made over FTP is often root's and 0755: checked (and opened up) as a download starts.+ // Only the games folder itself: the primary volume's parent is /data, never chmodded.+ installs.SetFolderCheck([](const std::string& games_root) {+ const std::filesystem::path root(games_root);+ return playden::runtime::EnsureWritableFolders(+ {root},+ [](const std::function<bool()>& work) { return playden::ps5::WithRoot(work); },+ [](const std::string& line) { playden::app::AppendLogLine(log_root, "install.log", line); });+ });playden::steam::CmClient cloud_cm(paths.trust_store, library_storage);cloud_cm.SetOwner("cloud");cloud_cm.SetSharedSession(steam_cm);@@ -378,6 +388,9 @@ int main() {config.boundary = "/data";config.state_root = std::filesystem::path(paths.runtime_data_root) / "runtime-state";config.homebrew_root = "/data/homebrew";+ config.as_root = [](const std::function<bool()>& work) { return playden::ps5::WithRoot(work); };+ config.writable_folders = {"/data/homebrew", "/data/playden", "/data/playden-games", "/data/playden/user",+ "/data/playden/logs"};config.registry_transport = playden::ps5::ShadowMountPost;config.admit_kit = [](std::string* reason) -> std::optional<playden::homebrew::RuntimeKit> {const auto firmware = playden::ps5::ConsoleFirmwareVersion();diff --git a/src/homebrew/runtime_host.cpp b/src/homebrew/runtime_host.cppindex f678761..e8c0baa 100644--- a/src/homebrew/runtime_host.cpp+++ b/src/homebrew/runtime_host.cpp@@ -14,6 +14,7 @@#include "runtime/session_storage.h"#include "runtime/steam_stub.h"#include "runtime/steamworks.h"+#include "runtime/writable_folders.h"#include "steam/backend/cloud_mapping.h"#include "steam/backend/json.h"@@ -853,6 +854,19 @@ std::string RuntimeHost::TightenWorkingFolder(const std::filesystem::path& root,return {};}+std::string RuntimeHost::EnsureWritable(const std::string& install_path, const std::string& working) {+ std::vector<std::filesystem::path> folders;+ for (const auto& folder : config_.writable_folders) folders.push_back(HostPath(folder));+ if (!install_path.empty()) {+ folders.push_back(HostPath(install_path));+ const std::filesystem::path relative(working);+ if (!working.empty() && working != "." && relative.is_relative() &&+ std::none_of(relative.begin(), relative.end(), [](const auto& part) { return part == ".."; }))+ folders.push_back(HostPath(install_path) / relative);+ }+ return rt::EnsureWritableFolders(folders, config_.as_root, [this](const std::string& line) { Log(line); });+}+std::string RuntimeHost::RepublishSettings(Composition& c, const rt::RuntimeInstall& record, bool* published) {if (published) *published = false;const auto saved = config_.settings_record ? config_.settings_record(record.app_id).value_or(rt::GameSettingsRecord{})@@ -1092,6 +1106,10 @@ void RuntimeHost::RunPlay(Composition& c, std::uint32_t app_id) {result = rt::LaunchResult::Failure(rt::LaunchError::kNotFound, "This game has no PS5 title yet.");} else if (const auto replaced = KitReplaced(c); !replaced.empty()) {result = rt::LaunchResult::Failure(rt::LaunchError::kPreflight, replaced);+ } else if (const auto unwritable = EnsureWritable(record->install_path,+ WorkingFolder(record->launch_working_directory, record->launch_path, record->launch_in_install_root));+ !unwritable.empty()) {+ result = rt::LaunchResult::Failure(rt::LaunchError::kPreflight, unwritable);} else {// Settings changed since the title's publication take effect now, while nothing of// the game runs: Home and Playden then start the same published profile.@@ -1390,6 +1408,8 @@ std::string RuntimeHost::RunPrepare(Composition& c, const RuntimePrepareRequest&if (pending.session && pending.session->install_id == InstallId(request.app_id))return "Close the game before updating or repairing its PS5 title.";}+ // Before anything is written (or a managed folder opened): folders made over FTP may need a fix.+ if (const auto unwritable = EnsureWritable(request.install_path, {}); !unwritable.empty()) return unwritable;std::optional<rt::RuntimeInstall> existing;for (const auto& record : c.repository.Snapshot())if (record.app_id == request.app_id) existing = record;@@ -1421,6 +1441,9 @@ std::string RuntimeHost::RunPrepare(Composition& c, const RuntimePrepareRequest&rt::InstallServiceResult started = rt::InstallServiceResult::Success();bool game_root_owned = true;const auto tighten_working = [&](const std::string& working) -> std::string {+ // The root was checked above; the working folder is known only now (it is where dxvk.conf goes).+ if (!working.empty())+ if (auto unwritable = EnsureWritable(request.install_path, working); !unwritable.empty()) return unwritable;return game_root_owned ? TightenWorkingFolder(HostPath(request.install_path), working) : std::string();};// Settings publication writes dxvk.conf into the game folder and requires that@@ -1707,6 +1730,7 @@ std::string RuntimeHost::RunPrepare(Composition& c, const RuntimePrepareRequest&" ok=" + std::to_string(step.ok()) + " error=" + std::to_string(static_cast<int>(step.error())) +" state=" + (after_step ? std::to_string(static_cast<int>(after_step->state)) : std::string("-")) +" to=" + (after_step && after_step->journal ? after_step->journal->step : std::string{}) ++ " code=" + (after_step && after_step->last_failure ? after_step->last_failure->code : std::string("-")) +" message=" + step.message);// A submitted registration is not polled: ShadowMountPlus registers titles only// while no title runs, Playden included. The console is asked once more right@@ -1957,6 +1981,10 @@ std::string RuntimeHost::RunMaintenance(Composition& c, std::uint32_t app, Runtireturn "Shader cache cleared. Shaders compile again on the next start.";}case RuntimeMaintenance::kRepair: {+ if (const auto unwritable = EnsureWritable(record->install_path,+ WorkingFolder(record->launch_working_directory, record->launch_path, record->launch_in_install_root));+ !unwritable.empty())+ return unwritable;const auto repaired = c.installer->RepairBottle(*record);const auto admission = c.installer->AdmissionDiagnostic(*record);c.admission[record->install_id] = admission;diff --git a/src/homebrew/runtime_host.hpp b/src/homebrew/runtime_host.hppindex e3c04bb..e2f4e5d 100644--- a/src/homebrew/runtime_host.hpp+++ b/src/homebrew/runtime_host.hpp@@ -89,6 +89,12 @@ struct RuntimeHostConfig {// else may raise root, which is process-wide and would fail the worker's ownership checks// (ps5::HoldEffectiveUid). Empty holds nothing.std::function<std::shared_ptr<void>()> hold_effective_uid;+ // Runs work with root raised (ps5::WithRoot), as UpdateConfig::as_root; used on the worker,+ // whose batch hold keeps other threads from raising root meanwhile. Empty: folders can't be fixed.+ std::function<bool(const std::function<bool()>& work)> as_root;+ // Console folders Prepare, Repair and Play check (and fix with as_root) before writing, with the+ // game's root and working folder (runtime/writable_folders.h). Missing ones are skipped.+ std::vector<std::string> writable_folders;// Receives each prepared title's newest wrapper session log (bounded tail) at// startup. The wrapper writes it inside the private bottle tree, which only// the app user can read.@@ -347,6 +353,10 @@ class RuntimeHost {std::string KitReplaced(const Composition& composition) const;// Makes an owned, world-writable folder from root down to working 0755 (dxvk.conf goes there).std::string TightenWorkingFolder(const std::filesystem::path& root, const std::string& working);+ // Checks (and fixes, as root) config.writable_folders, the game's root and its working folder+ // (relative to the root; empty: none) before anything is written; empty, or which can't be written.+ // Call before any ManagedDirectory of the operation is opened.+ std::string EnsureWritable(const std::string& install_path, const std::string& working);runtime::LaunchPreflight Preflight(Composition& composition, const runtime::RuntimeInstall& record);runtime::LaunchEvidence Evidence(Composition& composition, const runtime::RuntimeInstall& record,const std::string& session_id);diff --git a/src/platform/managed_directory.cpp b/src/platform/managed_directory.cppindex 1ec028e..abab784 100644--- a/src/platform/managed_directory.cpp+++ b/src/platform/managed_directory.cpp@@ -184,9 +184,10 @@ bool ManagedDirectory::InspectChild(const std::string& name, struct stat* result}std::optional<ManagedDirectory> ManagedDirectory::OpenChild(- const std::string& name, DirectoryPolicy policy, bool create) const {+ const std::string& name, DirectoryPolicy policy, bool create, mode_t created_mode) const {if (!ValidName(name) || !Validate()) return std::nullopt;- if (policy_ == DirectoryPolicy::kPrivate && policy != DirectoryPolicy::kPrivate) {+ if ((created_mode & ~0777) != 0 || (policy == DirectoryPolicy::kPrivate && created_mode != 0700) ||+ (policy_ == DirectoryPolicy::kPrivate && policy != DirectoryPolicy::kPrivate)) {errno = EINVAL;return std::nullopt;}@@ -202,6 +203,26 @@ std::optional<ManagedDirectory> ManagedDirectory::OpenChild(made = ::mkdir((path_ / name).c_str(), 0700);// No taking over an unexpected path that appeared during creation.if (made != 0 || !Validate() || !Inspect(name, &before)) return std::nullopt;+ // Before the identity is recorded, so the new mode is the observed one.+ if (S_ISDIR(before.st_mode) && before.st_uid == uid_ && (before.st_mode & 07777) != created_mode) {+ // By descriptor, and only the folder just made: a swapped-in link is never followed.+ int made_fd;+#if !PLAYDEN_MANAGED_NATIVE+ if (backend_ == DirectoryBackend::kDescriptorRelative)+ made_fd = ::openat(fd_, name.c_str(), kDirectoryFlags);+ else+#endif+ made_fd = ::open((path_ / name).c_str(), kDirectoryFlags);+ if (made_fd < 0) return std::nullopt;+ struct stat opened{};+ bool changed = ::fstat(made_fd, &opened) == 0;+ if (changed && (!S_ISDIR(opened.st_mode) || opened.st_dev != before.st_dev ||+ opened.st_ino != before.st_ino || opened.st_uid != uid_))+ changed = Refuse(ESTALE);+ if (changed) changed = ::fchmod(made_fd, created_mode) == 0;+ ClosePreservingError(made_fd);+ if (!changed || !Validate() || !Inspect(name, &before)) return std::nullopt;+ }}if (!S_ISDIR(before.st_mode)) {errno = S_ISLNK(before.st_mode) ? ELOOP : ENOTDIR;diff --git a/src/platform/managed_directory.h b/src/platform/managed_directory.hindex 465046a..153ac4e 100644--- a/src/platform/managed_directory.h+++ b/src/platform/managed_directory.h@@ -46,9 +46,12 @@ class ManagedDirectory {ManagedDirectory(const ManagedDirectory&) = delete;ManagedDirectory& operator=(const ManagedDirectory&) = delete;+ // A folder it creates gets created_mode exactly (umask ignored); an existing+ // folder is never chmodded. kPrivate children are always created 0700.std::optional<ManagedDirectory> OpenChild(const std::string& name,DirectoryPolicy policy,- bool create = false) const;+ bool create = false,+ mode_t created_mode = 0700) const;// Open/OpenChild never sync implicitly. After creation the caller must sync// the new directory and its parent before recording durable completion.bool Validate() const;diff --git a/src/runtime/package_installer.cpp b/src/runtime/package_installer.cppindex ac69f92..1408633 100644--- a/src/runtime/package_installer.cpp+++ b/src/runtime/package_installer.cpp@@ -724,9 +724,8 @@ FilesystemPackageInstaller::TemplateMappings() const {namespace {bool TitleDirectoriesPublished(const fs::path& title);-// Creates the missing folders of path with an explicit mode: console titles run-// with umask 0, so the default would leave them writable by everyone. Existing-// folders are left as they are.+// Creates the missing folders of path with an explicit mode, whatever the umask+// (console titles run with umask 0). Existing folders are left as they are.void CreateDirectoriesWithMode(const fs::path& path, mode_t mode, std::error_code& error) {error.clear();std::vector<fs::path> missing;@@ -1111,7 +1110,8 @@ PackageActionResult FilesystemPackageInstaller::CopyMappings(if (staging_parent_relative.empty() ||!PathComponentsHaveNoSymlink(paths_.host_data_root, staging_parent_relative, true))return Failed("staging-unavailable", "owned staging root is unavailable");- CreateDirectoriesWithMode(staging.parent_path(), 0755, error);+ // /data/playden and its staging folder are shared parents: 0777 when created here.+ CreateDirectoriesWithMode(staging.parent_path(), 0777, error);if (error)return Failed("staging-unavailable", "owned staging root is unavailable");if (!SyncAncestors(staging.parent_path()))@@ -1288,9 +1288,13 @@ PackageActionResult FilesystemPackageInstaller::CopyMappings(} else {CreateDirectoriesWithMode(final.parent_path(), 0755, error);}+ if (error)+ return Failed("destination-unwritable", "Playden can't create " + final.parent_path().string() ++ " (errno=" + std::to_string(error.value()) ++ " message=" + error.message() + ")");bool final_known = false;const bool final_exists = ExistsNoThrow(final, &final_known);- if (error || !final_known || final_exists)+ if (!final_known || final_exists)return Failed("destination-collision", "final package path already exists");if (!SyncAncestors(final.parent_path()))return Failed("sync-failed", "destination parent was not durably synced before rename");@@ -1317,11 +1321,15 @@ PackageActionResult FilesystemPackageInstaller::CopyMappings(" to=" + final.string() + " " + detail);const bool transient = error == std::errc::device_or_resource_busy || error == std::errc::interrupted ||error == std::errc::resource_unavailable_try_again;+ const bool denied = error == std::errc::permission_denied || error == std::errc::operation_not_permitted;if (!transient || attempt == kRenameAttempts)return Failed("atomic-rename-failed",std::string(error == std::errc::cross_device_link? "package staging and destination must be on the same filesystem"- : "package staging rename failed") + " (" + detail + ")");+ : denied ? "Playden can't write to " + final.parent_path().string() ++ " (permission denied)"+ : "package staging rename into " + final.parent_path().string() ++ " failed") + " (" + detail + ")");std::this_thread::sleep_for(std::chrono::milliseconds(100 * attempt));}if (!SyncTree(final, false) || !SyncAncestors(final.parent_path()) ||diff --git a/src/runtime/private_directories.cpp b/src/runtime/private_directories.cppindex 2325583..5381bf6 100644--- a/src/runtime/private_directories.cpp+++ b/src/runtime/private_directories.cpp@@ -51,8 +51,10 @@ bool EnsurePrivateDirectories(const fs::path& boundary, const fs::path& private_for (const auto& part : relative) {path /= part;if (path == private_root) in_private = true;- auto next = current->OpenChild(part.string(), in_private ? DirectoryPolicy::kPrivate- : DirectoryPolicy::kApprovedTree, true);+ // Shared parents it creates above the private root are 0777, so FTP and other+ // apps can write beside them; existing ones keep their mode.+ auto next = in_private ? current->OpenChild(part.string(), DirectoryPolicy::kPrivate, true)+ : current->OpenChild(part.string(), DirectoryPolicy::kApprovedTree, true, 0777);if (!next)return fail("cannot open/create private directory (wrong owner or permissions): " + path.string() + ": " + strerror(errno));// Flush the directory and its parent entry before journaled preparation.diff --git a/src/runtime/private_directories.h b/src/runtime/private_directories.hindex 10401a9..a0402f8 100644--- a/src/runtime/private_directories.h+++ b/src/runtime/private_directories.h@@ -5,7 +5,8 @@ namespace playden::runtime {// Creates directories as the current effective user, without credential changes.// boundary is an existing trusted directory; private_root and descendants must// belong to that user and have mode 0700. Existing foreign/public directories-// in the private tree are rejected, never chmodded or taken over.+// in the private tree are rejected, never chmodded or taken over. Missing+// folders between boundary and private_root are created 0777.bool EnsurePrivateDirectories(const std::filesystem::path& boundary,const std::filesystem::path& private_root,const std::filesystem::path& directory,diff --git a/src/runtime/writable_folders.cpp b/src/runtime/writable_folders.cppnew file mode 100644index 0000000..f86ed49--- /dev/null+++ b/src/runtime/writable_folders.cpp@@ -0,0 +1,84 @@+// writable_folders.cpp - Checks (and fixes) the folders Playden writes into before it writes.+// Copyright (c) 2026 Playden contributors+// SPDX-License-Identifier: MIT+#include "runtime/writable_folders.h"++#include <atomic>+#include <cerrno>+#include <cstdio>+#include <cstring>+#include <fcntl.h>+#include <sys/stat.h>+#include <unistd.h>++namespace playden::runtime {+namespace {+// access(2) is refused in the PS5 sandbox: create and remove a file instead. 0 or the errno.+int Probe(const std::filesystem::path& folder) {+ static std::atomic<unsigned long long> sequence{0};+ for (unsigned attempt = 0; attempt < 8; ++attempt) {+ const auto probe = folder / (".playden-writable-" + std::to_string(getpid()) + "-" ++ std::to_string(sequence.fetch_add(1)));+ const int fd = open(probe.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0600);+ if (fd < 0) {+ if (errno == EEXIST) continue;+ return errno;+ }+ const bool closed = close(fd) == 0;+ if (unlink(probe.c_str()) != 0) return errno;+ return closed ? 0 : EIO;+ }+ return EEXIST;+}++std::string Error(int error) { return std::to_string(error) + " (" + std::strerror(error) + ")"; }+} // namespace++std::string EnsureWritableFolders(const std::vector<std::filesystem::path>& folders,+ const WritableFoldersAsRoot& as_root,+ const std::function<void(const std::string&)>& log) {+ const auto note = [&log](const std::string& line) { if (log) log(line); };+ for (const auto& folder : folders) {+ if (folder.empty()) continue;+ struct stat info{};+ // Missing folders are made by their owners; links are never followed.+ if (lstat(folder.c_str(), &info) != 0) {+ if (errno != ENOENT) note("writable folder skipped path=" + folder.string() + " lstat=" + Error(errno));+ continue;+ }+ if (!S_ISDIR(info.st_mode)) continue;+ const int first = Probe(folder);+ if (first == 0) continue;+ int fix_error = 0;+ bool ran = false;+ const bool fixed = as_root && as_root([&] {+ ran = true;+ // By descriptor: a link swapped in after the lstat is refused, never followed as root.+ const int fd = open(folder.c_str(), O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);+ if (fd < 0) { fix_error = errno; return false; }+ struct stat current{};+ bool ok = fstat(fd, ¤t) == 0 || (fix_error = errno, false);+ if (ok && !S_ISDIR(current.st_mode)) ok = (fix_error = ENOTDIR, false);+ if (ok && fchmod(fd, 0777) != 0) ok = (fix_error = errno, false);+ close(fd);+ return ok;+ });+ const int second = fixed ? Probe(folder) : first;+ if (fixed && second == 0) {+ char mode[8]; std::snprintf(mode, sizeof(mode), "%04o", unsigned(info.st_mode & 07777));+ note("writable folder fixed path=" + folder.string() + " mode=" + mode + " -> 0777 uid=" ++ std::to_string(info.st_uid) + " probe=" + Error(first));+ continue;+ }+ note("writable folder failed path=" + folder.string() + " uid=" + std::to_string(info.st_uid) ++ " probe=" + Error(first) ++ (!as_root ? " fix=unavailable"+ : !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.";+ }+ return {};+}++} // namespace playden::runtimediff --git a/src/runtime/writable_folders.h b/src/runtime/writable_folders.hnew file mode 100644index 0000000..af684d0--- /dev/null+++ b/src/runtime/writable_folders.h@@ -0,0 +1,25 @@+#pragma once+// writable_folders.h - Checks (and fixes) the folders Playden writes into before it writes.+// Copyright (c) 2026 Playden contributors+// SPDX-License-Identifier: MIT+#include <filesystem>+#include <functional>+#include <string>+#include <vector>++namespace playden::runtime {++// Runs work with root raised (ps5::WithRoot on the console); false when root could not be raised+// or the work failed. Empty: nothing can be fixed.+using WritableFoldersAsRoot = std::function<bool(const std::function<bool()>& work)>;++// Folders made over FTP belong to root and are often 0755, so the app user can't write into them.+// For each existing folder (missing ones and links are skipped), a probe file is created and+// removed as the app user. When that fails, the folder is made 0777 as root (root owns it, so no+// permission bypass is needed) and probed again. Returns an empty string when every folder can be+// written, or a message naming the first folder that still can't. Each fix and failure is logged.+std::string EnsureWritableFolders(const std::vector<std::filesystem::path>& folders,+ const WritableFoldersAsRoot& as_root,+ const std::function<void(const std::string&)>& log);++} // namespace playden::runtimediff --git a/src/steam/install_service.cpp b/src/steam/install_service.cppindex f97c668..b18bf8d 100644--- a/src/steam/install_service.cpp+++ b/src/steam/install_service.cpp@@ -538,6 +538,7 @@ void InstallService::Run() {for (;;) {std::optional<GameId> next;std::string next_root;+ std::string next_games_root;std::optional<std::string> removal;{std::unique_lock<std::mutex> lock(mutex_);@@ -567,6 +568,7 @@ void InstallService::Run() {job.view.step_since = std::chrono::steady_clock::now();next = job.view.id;next_root = RootOn(job.view.volume_id, job.view.id);+ next_games_root = volume->games_root;active_ = next;active_cancel_.store(false);Publish();@@ -582,6 +584,21 @@ void InstallService::Run() {}if (!next) continue;+ // The volume's folder may have been made over FTP and not be writable by the app user.+ if (folder_check_) {+ const std::string unwritable = folder_check_(next_games_root);+ if (!unwritable.empty()) {+ std::lock_guard<std::mutex> lock(mutex_);+ active_.reset();+ if (auto* job = Find(*next); job && job->view.state == InstallJobState::kRunning) {+ job->view.state = InstallJobState::kFailed;+ job->view.failure = unwritable;+ }+ Publish();+ continue;+ }+ }+InstallRunner::Result result;const auto session = sessions_.Load();if (!session.ok() || !session.value()) {diff --git a/src/steam/install_service.h b/src/steam/install_service.hindex 56f54df..15782bc 100644--- a/src/steam/install_service.h+++ b/src/steam/install_service.h@@ -146,6 +146,9 @@ class InstallService {void DismissCompleted(GameId id);void ClearCompleted();InstallSnapshot Snapshot();+ // Checks the volume's games folder (and may fix it) when a download starts; a non-empty answer+ // fails the download with it as the message. Set before the first Install; empty: no check.+ void SetFolderCheck(std::function<std::string(const std::string& games_root)> check) { folder_check_ = std::move(check); }void Shutdown();// The folder a game uses (or would use if installed now); empty if its volume is unknown.@@ -174,6 +177,7 @@ class InstallService {InstallRunner& runner_;SessionRepository& sessions_;+ std::function<std::string(const std::string&)> folder_check_;std::vector<InstallVolume> volumes_;std::string default_volume_id_;bool default_volume_saved_ = true;diff --git a/tests/homebrew_runtime_host_test.cpp b/tests/homebrew_runtime_host_test.cppindex 06f1800..03ff900 100644--- a/tests/homebrew_runtime_host_test.cpp+++ b/tests/homebrew_runtime_host_test.cpp@@ -517,6 +517,87 @@ void PreparesExistingDownloadToReady() {host.Shutdown();}+// A folder made over FTP belongs to root and is 0755, so the app user can't write into it+// (#70): Prepare makes it 0777 as root first. Here 0555 stands in for it.+RuntimeHostConfig WritableFoldersConfig(Fixture& fixture, const RuntimeKit& kit) {+ auto config = fixture.Config();+ config.host_namespace_prefix = fixture.root;+ config.package_paths.console_data_root = "/data";+ config.package_paths.host_data_root = fixture.root / "data";+ config.package_operations.hash_file = HashArtifactFile;+ config.package_operations.hash_bytes = HashArtifactBytes;+ config.package_operations.free_space_unverifiable = true;+ config.package_operations.validate_bottle = [](const fs::path& bottle) {+ return fs::is_regular_file(bottle / "system.reg") && fs::is_regular_file(bottle / "user.reg");+ };+ config.admit_kit = [&kit](std::string*) { return std::optional<RuntimeKit>(kit); };+ config.uuid = [] { return std::optional<std::string>("00000000-0000-4000-8000-000000000001"); };+ config.unix_time = [] { return std::int64_t{1760000000}; };+ config.writable_folders = {"/data/homebrew", "/data/playden", "/data/playden-games", "/data/playden/user",+ "/data/playden/logs"};+ return config;+}++void PrepareFixesRootOwnedHomebrewFolder() {+ if (geteuid() == 0) return; // root writes anywhere+ Fixture fixture;+ const auto kit = SyntheticKit(fixture.root / "kit");+ auto config = WritableFoldersConfig(fixture, kit);+ std::atomic<int> raises{0};+ config.as_root = [&raises](const std::function<bool()>& work) { ++raises; return work(); };+ const auto game = fixture.root / "data/homebrew/FAKE77031/games/220";+ Write(game / "hl2.exe", "existing-game", 0644);+ const auto homebrew = fixture.root / "data/homebrew";+ CHECK(chmod(homebrew.c_str(), 0555) == 0);++ RuntimeHost host(config);+ CHECK(host.Start());+ CHECK(WaitFor(host, Started).kit_available);+ host.Prepare(Hl2());+ const auto done = WaitFor(host, [](const RuntimeSnapshot& s) {+ return !s.preparing_app && (s.refusals.count(220) ||+ (!s.installs.empty() && s.installs[0].state == PreparationState::kReady));+ }, 60);+ if (done.refusals.count(220)) std::fprintf(stderr, "Prepare refused: %s\n", done.refusals.at(220).c_str());+ CHECK(!done.refusals.count(220));+ CHECK(done.installs.size() == 1 && done.installs[0].state == PreparationState::kReady);+ CHECK(raises == 1); // only the folder that failed its probe+ struct stat info{};+ CHECK(stat(homebrew.c_str(), &info) == 0 && (info.st_mode & 07777) == 0777);+ CHECK(fs::is_regular_file(fixture.root / "data/homebrew/FAKE78001/game-launch.json"));+ host.Shutdown();+}++void PrepareNamesUnfixableFolder() {+ if (geteuid() == 0) return; // root writes anywhere+ Fixture fixture;+ const auto kit = SyntheticKit(fixture.root / "kit");+ auto config = WritableFoldersConfig(fixture, kit);+ std::atomic<int> raises{0};+ config.as_root = [&raises](const std::function<bool()>&) { ++raises; return false; }; // root refused+ const auto game = fixture.root / "data/homebrew/FAKE77031/games/220";+ Write(game / "hl2.exe", "existing-game", 0644);+ const auto homebrew = fixture.root / "data/homebrew";+ CHECK(chmod(homebrew.c_str(), 0555) == 0);++ RuntimeHost host(config);+ CHECK(host.Start());+ CHECK(WaitFor(host, Started).kit_available);+ 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.");+ CHECK(raises == 1);+ CHECK(done.installs.empty());+ struct stat info{};+ CHECK(stat(homebrew.c_str(), &info) == 0 && (info.st_mode & 07777) == 0555);+ CHECK(!fs::exists(fixture.root / "data/homebrew/FAKE78001"));+ CHECK(!fs::exists(fixture.root / "data/playden"));+ CHECK(fixture.registry_mutations == 0);+ host.Shutdown();+ CHECK(chmod(homebrew.c_str(), 0755) == 0); // so the fixture can clean up+}+// A capture refused after control setup (the console's world-writable game// folder) leaves a settings-control journal. An explicit Prepare resumes the// saved request and reaches Ready with one registration.@@ -2156,6 +2237,8 @@ int main(int argc, char** argv) {PublicStateRootIsUnavailable();PreparesExistingDownloadToReady();PreparesGameOnUnownedDrive();+ PrepareFixesRootOwnedHomebrewFolder();+ PrepareNamesUnfixableFolder();AnyTitleKitMakesTheGameItsOwnTitle();PreparationEndsAwaitingRegistration();PreparesGameWithoutShippedRecipe();diff --git a/tests/install_service_test.cpp b/tests/install_service_test.cppindex e6f0946..aec64a7 100644--- a/tests/install_service_test.cpp+++ b/tests/install_service_test.cpp@@ -330,7 +330,40 @@ void RunningJobReportsItsStep(const std::filesystem::path& root) {std::filesystem::remove_all(root);}+// A folder check that names a problem fails the download before the runner starts; an empty answer proceeds.+void FolderCheckGuardsDownloadStart(const std::filesystem::path& root) {+ std::filesystem::remove_all(root);+ Sessions sessions;+ Runner runner;+ InstallService service(runner, sessions, root.string());+ std::mutex mutex;+ std::string answer = "The folder /games is not writable.";+ std::string checked;+ service.SetFolderCheck([&](const std::string& games_root) {+ std::lock_guard<std::mutex> lock(mutex);+ checked = games_root;+ return answer;+ });+ service.Install(90);+ AwaitAt(__LINE__, service, [](const InstallSnapshot& s) {+ const auto* job = JobOf(s, 90);+ return job && job->state == InstallJobState::kFailed;+ });+ CHECK(JobOf(service.Snapshot(), 90)->failure == "The folder /games is not writable.");+ CHECK(runner.installs == 0);+ {+ std::lock_guard<std::mutex> lock(mutex);+ CHECK(checked == root.string());+ answer.clear();+ }+ service.Install(91);+ AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { return Installed(s, 91); });+ CHECK(runner.installs == 1);+ std::filesystem::remove_all(root);+}+int main() {+ FolderCheckGuardsDownloadStart(std::filesystem::temp_directory_path() / ("playden-foldercheck-service-" + std::to_string(::getpid())));RunningJobReportsItsStep(std::filesystem::temp_directory_path() / ("playden-step-service-" + std::to_string(::getpid())));SpaceAdmission(std::filesystem::temp_directory_path() / ("playden-space-service-" + std::to_string(::getpid())));LiveTelemetryDecaysWithoutCallbacks(std::filesystem::temp_directory_path() / ("playden-rate-service-" + std::to_string(::getpid())));diff --git a/tests/runtime_package_installer_test.cpp b/tests/runtime_package_installer_test.cppindex 84c1cdb..f04bfcb 100644--- a/tests/runtime_package_installer_test.cpp+++ b/tests/runtime_package_installer_test.cpp@@ -12,6 +12,7 @@#include <memory>#endif+#include <cerrno>#include <cstdio>#include <cstdlib>#include <filesystem>@@ -786,16 +787,53 @@ void PrivateTitleFoldersAreRepublished() {CHECK(installer.Inspect(Record()).manifest_matches);}-// Console titles run with umask 0: folders the installer creates still get an-// explicit mode that others cannot write.+// Folders the installer creates get an explicit mode whatever the umask: the+// shared staging parents are 0777, the title stays 0755.void CreatedFoldersIgnoreUmask() {- const auto previous = ::umask(0);+ for (const mode_t mask : {mode_t{0}, mode_t{077}}) {+ const auto previous = ::umask(mask);+ Fixture fixture;+ auto installer = fixture.Installer();+ CHECK(installer.StageTitle(Record()).state == PackageActionState::kComplete);+ ::umask(previous);+ struct stat info{};+ for (const auto* shared : {"playden", "playden/staging"})+ CHECK(::stat((fixture.host_data / shared).c_str(), &info) == 0 && (info.st_mode & 07777) == 0777);+ CHECK(::stat((fixture.host_data / "homebrew/FAKE78001").c_str(), &info) == 0 && (info.st_mode & 07777) == 0755);+ }+}++// A rename refused by the title's parent names the folder and the errno.+void RenameFailureReportsErrno() {+ if (::geteuid() == 0) return; // root ignores folder modesFixture fixture;+ const auto homebrew = fixture.host_data / "homebrew";+ std::filesystem::create_directories(homebrew);+ CHECK(::chmod(homebrew.c_str(), 0555) == 0);auto installer = fixture.Installer();- CHECK(installer.StageTitle(Record()).state == PackageActionState::kComplete);- ::umask(previous);- struct stat info{};- CHECK(::stat((fixture.host_data / "playden/staging").c_str(), &info) == 0 && (info.st_mode & 07777) == 0755);+ const auto result = installer.StageTitle(Record());+ CHECK(::chmod(homebrew.c_str(), 0755) == 0);+ CHECK(result.state == PackageActionState::kFailed);+ CHECK(result.code == "atomic-rename-failed");+ CHECK(result.message.find("Playden can't write to " + homebrew.string() + " (permission denied)") != std::string::npos);+ CHECK(result.message.find("errno=" + std::to_string(EACCES)) != std::string::npos);+ CHECK(result.message.find(std::make_error_code(std::errc::permission_denied).message()) != std::string::npos);+ CHECK(!std::filesystem::exists(homebrew / "FAKE78001"));+}++// A title parent that cannot be created is reported as unwritable, not as a collision.+void UnwritableParentIsNotACollision() {+ if (::geteuid() == 0) return; // root ignores folder modes+ Fixture fixture;+ std::filesystem::create_directories(fixture.host_data / "playden/staging");+ CHECK(::chmod(fixture.host_data.c_str(), 0555) == 0);+ auto installer = fixture.Installer();+ const auto result = installer.StageTitle(Record());+ CHECK(::chmod(fixture.host_data.c_str(), 0755) == 0);+ CHECK(result.state == PackageActionState::kFailed);+ CHECK(result.code == "destination-unwritable");+ CHECK(result.message.find((fixture.host_data / "homebrew").string()) != std::string::npos);+ CHECK(result.message.find("errno=" + std::to_string(EACCES)) != std::string::npos);}// A staging folder left empty by a stop before its owner marker is reclaimed; one@@ -1200,6 +1238,8 @@ int main() {AnyTitleVariantServesEveryTitle();FixedTitleRefreshesToAnyTitleShell();CreatedFoldersIgnoreUmask();+ RenameFailureReportsErrno();+ UnwritableParentIsNotACollision();EmptyUnmarkedStagingIsReclaimed();EarlierInstallStagingIsReclaimed();CollisionsTraversalSymlinksAndModesFailClosed();diff --git a/tests/runtime_private_directories_native_policy_test.cpp b/tests/runtime_private_directories_native_policy_test.cppindex f7ef310..4a3f525 100644--- a/tests/runtime_private_directories_native_policy_test.cpp+++ b/tests/runtime_private_directories_native_policy_test.cpp@@ -11,8 +11,32 @@extern "C" int openat(int, const char*, int, ...) { errno = EINVAL; return -1; }extern "C" int mkdirat(int, const char*, mode_t) { errno = EINVAL; return -1; }+namespace fs = std::filesystem;++// Folders created above the private root are shared (0777) whatever the umask;+// existing ones keep their mode, and the private tree stays 0700.+void CreatedPublicAncestorsAreShared(const fs::path& boundary) {+ const auto mode = [](const fs::path& path) {+ struct stat info{};+ assert(stat(path.c_str(), &info) == 0);+ return info.st_mode & 07777;+ };+ const auto previous = umask(022);+ std::string error;+ const auto root = boundary / "shared/parent/install";+ assert(playden::runtime::EnsurePrivateDirectories(boundary, root, root / "child", &error));+ assert(mode(boundary / "shared") == 0777 && mode(boundary / "shared/parent") == 0777);+ assert(mode(root) == 0700 && mode(root / "child") == 0700);+ assert(fs::create_directory(boundary / "existing") && chmod((boundary / "existing").c_str(), 0755) == 0);+ const auto kept = boundary / "existing/new/install";+ assert(playden::runtime::EnsurePrivateDirectories(boundary, kept, kept, &error));+ assert(mode(boundary / "existing") == 0755 && mode(boundary / "existing/new") == 0777 && mode(kept) == 0700);+ // Opening again finds the recorded modes unchanged.+ assert(playden::runtime::EnsurePrivateDirectories(boundary, kept, kept / "child", &error));+ umask(previous);+}+int main() {- namespace fs = std::filesystem;char scratch[] = "/tmp/playden-private-policy-XXXXXX";const char* made = mkdtemp(scratch);assert(made);@@ -31,6 +55,7 @@ int main() {assert(!playden::runtime::EnsurePrivateDirectories(boundary, root, root / "escape/child", &error));assert(!fs::exists(boundary / "child"));assert(!playden::runtime::EnsurePrivateDirectories(boundary, root, root / "../outside", &error));+ CreatedPublicAncestorsAreShared(boundary);fs::remove_all(boundary);std::cout << "private directory callers pass with native relative operations unavailable\n";}diff --git a/tests/runtime_writable_folders_test.cpp b/tests/runtime_writable_folders_test.cppnew file mode 100644index 0000000..0d62b6f--- /dev/null+++ b/tests/runtime_writable_folders_test.cpp@@ -0,0 +1,106 @@+#include "runtime/writable_folders.h"++#include <cstdio>+#include <cstdlib>+#include <filesystem>+#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;+}+bool Empty(const fs::path& path) { return fs::is_empty(path); }+} // namespace++int main() {+ char name[] = "/tmp/playden-writable-XXXXXX";+ CHECK(mkdtemp(name));+ const fs::path root = fs::canonical(name);+ const auto open = root / "open", locked = root / "locked", target = root / "target", link = root / "link";+ fs::create_directories(open);+ fs::create_directories(locked);+ fs::create_directories(target);+ fs::create_directory_symlink(target, link);+ std::vector<std::string> lines;+ const auto log = [&lines](const std::string& line) { lines.push_back(line); };+ 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; };++ // Writable, missing and linked folders need nothing; the probe leaves no file behind.+ CHECK(EnsureWritableFolders({open, root / "missing", link, {}}, runs, log).empty());+ CHECK(calls == 0 && lines.empty() && Empty(open));++ if (geteuid() != 0) {+ // A linked folder is never followed (nor fixed), even when its target can't be written.+ CHECK(chmod(target.c_str(), 0555) == 0);+ CHECK(EnsureWritableFolders({link}, runs, log).empty());+ CHECK(calls == 0 && Mode(target) == 0555);+ CHECK(chmod(target.c_str(), 0755) == 0);++ // A link swapped in between the probe and the fix is refused, its target left alone.+ const auto swapped = root / "swapped";+ fs::create_directories(swapped);+ CHECK(chmod(swapped.c_str(), 0555) == 0 && chmod(target.c_str(), 0555) == 0);+ const WritableFoldersAsRoot swaps = [&](const std::function<bool()>& work) {+ ++calls;+ fs::rename(swapped, root / "swapped-away");+ fs::create_directory_symlink(target, swapped);+ return work();+ };+ CHECK(!EnsureWritableFolders({swapped}, swaps, log).empty());+ CHECK(calls == 1 && Mode(target) == 0555 && Mode(root / "swapped-away") == 0555);+ CHECK(lines.size() == 1 && lines[0].find("chmod=") != std::string::npos);+ CHECK(chmod(target.c_str(), 0755) == 0 && chmod((root / "swapped-away").c_str(), 0755) == 0);+ lines.clear();+ calls = 0;++ // No way to raise root: the folder is named.+ CHECK(chmod(locked.c_str(), 0555) == 0);+ auto message = EnsureWritableFolders({open, locked}, {}, log);+ CHECK(message.find("can't write to " + locked.string() + ".") != std::string::npos);+ CHECK(Mode(locked) == 0555 && lines.size() == 1 && lines[0].find("fix=unavailable") != std::string::npos);++ // Root refused.+ lines.clear();+ message = EnsureWritableFolders({locked}, refuses, log);+ CHECK(calls == 1 && message.find(locked.string()) != std::string::npos && Mode(locked) == 0555);+ CHECK(lines.size() == 1 && lines[0].find("fix=root-refused") != std::string::npos);++ // The fix ran but the folder still can't be written.+ lines.clear();+ calls = 0;+ const WritableFoldersAsRoot undone = [&](const std::function<bool()>& work) {+ ++calls;+ const bool ok = work();+ chmod(locked.c_str(), 0555);+ return ok;+ };+ message = EnsureWritableFolders({locked}, undone, log);+ CHECK(calls == 1 && message.find(locked.string()) != std::string::npos);+ CHECK(lines.size() == 1 && lines[0].find("after-fix=") != std::string::npos);++ // Fixed: 0777, logged, then writable without another raise.+ lines.clear();+ calls = 0;+ CHECK(EnsureWritableFolders({open, locked}, runs, log).empty());+ CHECK(calls == 1 && Mode(locked) == 0777 && Empty(locked));+ CHECK(lines.size() == 1 && lines[0].find("writable folder fixed") != std::string::npos &&+ lines[0].find("mode=0555 -> 0777") != std::string::npos);+ CHECK(EnsureWritableFolders({locked}, runs, log).empty() && calls == 1);+ }++ std::error_code ignored;+ fs::remove_all(root, ignored);+ std::puts("writable folders tests passed");+ return 0;+}