Skip to content

Play your Steam library's Windows games on a jailbroken PS5.

C++

Add a paired API for a game's files

Leonardo Lobato1267375ebfc7
diff --git a/cmake/Web.cmake b/cmake/Web.cmake
index 35107ad..a8df5c7 100644
--- a/cmake/Web.cmake
+++ b/cmake/Web.cmake
@@ -44,11 +44,19 @@ add_custom_command(OUTPUT "${playden_web_assets_cpp}"
DEPENDS ${playden_web_asset_files} "${CMAKE_SOURCE_DIR}/cmake/EmbedWebAssets.cmake"
VERBATIM)
-add_library(playden_web STATIC "${CMAKE_SOURCE_DIR}/src/web/service.cpp" "${playden_web_assets_cpp}")
+add_library(playden_web STATIC
+ "${CMAKE_SOURCE_DIR}/src/web/service.cpp"
+ "${CMAKE_SOURCE_DIR}/src/web/files_api.cpp"
+ "${CMAKE_SOURCE_DIR}/src/web/file_policy.cpp"
+ "${CMAKE_SOURCE_DIR}/src/web/file_store.cpp"
+ "${CMAKE_SOURCE_DIR}/src/web/pairing.cpp"
+ "${playden_web_assets_cpp}")
target_include_directories(playden_web PUBLIC "${CMAKE_SOURCE_DIR}/src")
target_compile_features(playden_web PUBLIC cxx_std_17)
-target_link_libraries(playden_web PUBLIC playden_web_logs playden_web_http)
+target_link_libraries(playden_web PUBLIC playden_web_logs playden_web_http playden_managed_directory
+ playden_runtime_artifact_hash playden_storage)
if(PLAYDEN_PLATFORM_PS5)
+ target_compile_definitions(playden_web PRIVATE PLAYDEN_PLATFORM_PS5=1)
target_compile_options(playden_web PRIVATE -fno-exceptions -fno-rtti)
endif()
@@ -71,4 +79,28 @@ if(BUILD_TESTING AND NOT PLAYDEN_PLATFORM_PS5)
add_executable(web_service_test "${CMAKE_SOURCE_DIR}/tests/web_service_test.cpp")
target_link_libraries(web_service_test PRIVATE playden_web)
add_test(NAME web_service COMMAND web_service_test)
+ add_executable(web_pairing_test "${CMAKE_SOURCE_DIR}/tests/web_pairing_test.cpp")
+ target_link_libraries(web_pairing_test PRIVATE playden_web)
+ add_test(NAME web_pairing COMMAND web_pairing_test)
+ add_executable(web_file_policy_test "${CMAKE_SOURCE_DIR}/tests/web_file_policy_test.cpp")
+ target_link_libraries(web_file_policy_test PRIVATE playden_web)
+ add_test(NAME web_file_policy COMMAND web_file_policy_test)
+ add_executable(web_file_store_test "${CMAKE_SOURCE_DIR}/tests/web_file_store_test.cpp")
+ target_link_libraries(web_file_store_test PRIVATE playden_web)
+ add_test(NAME web_file_store COMMAND web_file_store_test)
+ add_executable(web_files_api_test "${CMAKE_SOURCE_DIR}/tests/web_files_api_test.cpp")
+ target_link_libraries(web_files_api_test PRIVATE playden_web)
+ add_test(NAME web_files_api COMMAND web_files_api_test)
+ # The console's path handling (no descriptor-relative opens), run on the host.
+ add_executable(web_file_store_native_policy_test
+ "${CMAKE_SOURCE_DIR}/tests/web_file_store_test.cpp"
+ "${CMAKE_SOURCE_DIR}/src/web/file_store.cpp"
+ "${CMAKE_SOURCE_DIR}/src/web/file_policy.cpp"
+ "${CMAKE_SOURCE_DIR}/src/web/zip.cpp"
+ "${CMAKE_SOURCE_DIR}/src/platform/managed_directory.cpp")
+ target_include_directories(web_file_store_native_policy_test PRIVATE "${CMAKE_SOURCE_DIR}/src")
+ target_compile_features(web_file_store_native_policy_test PRIVATE cxx_std_17)
+ target_compile_definitions(web_file_store_native_policy_test PRIVATE PLAYDEN_PLATFORM_PS5=1 PLAYDEN_TEST_AT_UNAVAILABLE=1)
+ target_link_libraries(web_file_store_native_policy_test PRIVATE playden_runtime_artifact_hash playden_storage playden_curl_8_22 Threads::Threads)
+ add_test(NAME web_file_store_native_policy COMMAND web_file_store_native_policy_test)
endif()
diff --git a/src/runtime/redist_install.cpp b/src/runtime/redist_install.cpp
index a89ef50..cc3ec49 100644
--- a/src/runtime/redist_install.cpp
+++ b/src/runtime/redist_install.cpp
@@ -1,5 +1,7 @@
#include "runtime/redist_install.h"
+#include "runtime/redist_names.h"
+
#include "platform/managed_directory.h"
#include "runtime/artifact_hash.h"
#include "runtime/burn_bundle.h"
@@ -26,8 +28,7 @@ using platform::ManagedDirectory;
constexpr std::size_t kMaxPackageBytes = 256u * 1024u * 1024u;
constexpr std::size_t kMaxScripts = 32;
-constexpr int kMaxDepth = 4;
-constexpr std::size_t kMaxPhysxPackages = 8;
+constexpr int kMaxDepth = kRedistMaxDepth;
constexpr const char* kStateFile = ".playden-redist";
constexpr const char* kPhysxNeededFile = ".playden-physx-needed";
constexpr const char* kMfcScanFile = ".playden-mfc";
@@ -81,15 +82,6 @@ bool ReadFile(const std::filesystem::path& path, std::size_t maximum, std::strin
return ok;
}
-// Folders where Steam games keep their redistributables, looked into below the game's top level.
-bool RedistFolder(const std::string& name) {
- static const std::set<std::string> kNames = {
- "_commonredist", "commonredist", "redist", "redists", "_redist", "redistributables", "redistributable",
- "support", "__installer", "_installer", "installer", "installers", "prerequisites", "prereqs", "physx",
- "directx", "vcredist", "dotnet"};
- return kNames.count(Lower(name)) != 0;
-}
-
bool ScriptName(const std::string& name) {
const auto lower = Lower(name);
return lower.rfind("installscript", 0) == 0 && lower.size() > 4 && lower.compare(lower.size() - 4, 4, ".vdf") == 0;
@@ -114,34 +106,6 @@ void FindScripts(const std::filesystem::path& folder, const std::string& relativ
}
}
-bool PhysxPackageName(const std::string& name) {
- const auto lower = Lower(name);
- if (lower.rfind("physx", 0) != 0 || lower.size() <= 4) return false;
- const auto extension = lower.substr(lower.size() - 4);
- return extension == ".msi" || extension == ".exe";
-}
-
-// PhysX's installers in the game's redistributable folders, top-level ones or ones a level down (a game whose
-// files sit in one folder of what was imported), by name.
-void FindPhysxPackages(const std::filesystem::path& folder, const std::string& relative, int depth, bool in_redist,
- std::vector<std::string>* packages) {
- std::error_code error;
- std::vector<std::pair<std::string, bool>> children;
- for (std::filesystem::directory_iterator it(folder, error), end; !error && it != end; it.increment(error)) {
- std::error_code type_error;
- if (it->is_symlink(type_error)) continue;
- children.emplace_back(it->path().filename().string(), it->is_directory(type_error));
- }
- std::sort(children.begin(), children.end());
- for (const auto& [name, directory] : children) {
- if (packages->size() >= kMaxPhysxPackages) return;
- const auto path = relative.empty() ? name : relative + "/" + name;
- if (!directory && in_redist && PhysxPackageName(name)) packages->push_back(path);
- else if (directory && depth < kMaxDepth && (in_redist || depth == 0 || RedistFolder(name)))
- FindPhysxPackages(folder / name, path, depth + 1, in_redist || RedistFolder(name), packages);
- }
-}
-
// Splits a command line into arguments (double quotes group, as Windows does for msiexec).
std::vector<std::string> Arguments(std::string_view command) {
std::vector<std::string> out;
diff --git a/src/runtime/redist_names.h b/src/runtime/redist_names.h
new file mode 100644
index 0000000..ff1fe88
--- /dev/null
+++ b/src/runtime/redist_names.h
@@ -0,0 +1,62 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+#pragma once
+// Where a game keeps its redistributables and what PhysX's installers are called. Play's search for a package
+// (runtime/redist_install.cpp) and the web page's list of folders use these same rules.
+#include <algorithm>
+#include <cstddef>
+#include <filesystem>
+#include <set>
+#include <string>
+#include <system_error>
+#include <utility>
+#include <vector>
+
+namespace playden::runtime {
+
+inline constexpr int kRedistMaxDepth = 4;
+inline constexpr std::size_t kMaxPhysxPackages = 8;
+
+inline std::string RedistLower(std::string text) {
+ for (auto& c : text)
+ if (c >= 'A' && c <= 'Z') c = static_cast<char>(c - 'A' + 'a');
+ return text;
+}
+
+// Folders where Steam games keep their redistributables, looked into below the game's top level.
+inline bool RedistFolder(const std::string& name) {
+ static const std::set<std::string> kNames = {
+ "_commonredist", "commonredist", "redist", "redists", "_redist", "redistributables", "redistributable",
+ "support", "__installer", "_installer", "installer", "installers", "prerequisites", "prereqs", "physx",
+ "directx", "vcredist", "dotnet"};
+ return kNames.count(RedistLower(name)) != 0;
+}
+
+inline bool PhysxPackageName(const std::string& name) {
+ const auto lower = RedistLower(name);
+ if (lower.rfind("physx", 0) != 0 || lower.size() <= 4) return false;
+ const auto extension = lower.substr(lower.size() - 4);
+ return extension == ".msi" || extension == ".exe";
+}
+
+// PhysX's installers in the game's redistributable folders, top-level ones or ones a level down (a game whose
+// files sit in one folder of what was imported), by name.
+inline void FindPhysxPackages(const std::filesystem::path& folder, const std::string& relative, int depth, bool in_redist,
+ std::vector<std::string>* packages) {
+ std::error_code error;
+ std::vector<std::pair<std::string, bool>> children;
+ for (std::filesystem::directory_iterator it(folder, error), end; !error && it != end; it.increment(error)) {
+ std::error_code type_error;
+ if (it->is_symlink(type_error)) continue;
+ children.emplace_back(it->path().filename().string(), it->is_directory(type_error));
+ }
+ std::sort(children.begin(), children.end());
+ for (const auto& [name, directory] : children) {
+ if (packages->size() >= kMaxPhysxPackages) return;
+ const auto path = relative.empty() ? name : relative + "/" + name;
+ if (!directory && in_redist && PhysxPackageName(name)) packages->push_back(path);
+ else if (directory && depth < kRedistMaxDepth && (in_redist || depth == 0 || RedistFolder(name)))
+ FindPhysxPackages(folder / name, path, depth + 1, in_redist || RedistFolder(name), packages);
+ }
+}
+
+} // namespace playden::runtime
diff --git a/src/web/file_policy.cpp b/src/web/file_policy.cpp
new file mode 100644
index 0000000..b917946
--- /dev/null
+++ b/src/web/file_policy.cpp
@@ -0,0 +1,97 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "web/file_policy.h"
+
+namespace playden::web {
+namespace {
+
+// Files holding a sign-in that can sit in a game folder. Add each new credential file a game folder gets here.
+constexpr const char* kSecretNames[] = {
+ "playden_online.txt", // the account's refresh token, for the online bridge
+ "socialclub_scauth.txt", // the Rockstar sign-in
+};
+
+} // namespace
+
+std::string LowerAscii(std::string_view text) {
+ std::string out(text);
+ for (auto& c : out)
+ if (c >= 'A' && c <= 'Z') c = static_cast<char>(c - 'A' + 'a');
+ return out;
+}
+
+bool ValidUtf8(std::string_view text) {
+ std::size_t i = 0;
+ while (i < text.size()) {
+ const auto first = static_cast<unsigned char>(text[i]);
+ std::size_t more = 0;
+ unsigned value = 0;
+ if (first < 0x80) { ++i; continue; }
+ if (first >= 0xc2 && first <= 0xdf) { more = 1; value = first & 0x1f; }
+ else if (first >= 0xe0 && first <= 0xef) { more = 2; value = first & 0x0f; }
+ else if (first >= 0xf0 && first <= 0xf4) { more = 3; value = first & 0x07; }
+ else return false;
+ if (text.size() - i <= more) return false;
+ for (std::size_t j = 1; j <= more; ++j) {
+ const auto next = static_cast<unsigned char>(text[i + j]);
+ if ((next & 0xc0) != 0x80) return false;
+ value = (value << 6) | (next & 0x3f);
+ }
+ if ((more == 2 && (value < 0x800 || (value >= 0xd800 && value <= 0xdfff))) ||
+ (more == 3 && (value < 0x10000 || value > 0x10ffff)))
+ return false;
+ i += more + 1;
+ }
+ return true;
+}
+
+bool HiddenName(std::string_view name) {
+ const auto lower = LowerAscii(name);
+ if (lower.rfind(".playden", 0) == 0) return true;
+ for (const char* secret : kSecretNames)
+ if (lower == secret) return true;
+ return false;
+}
+
+bool ReadOnlyFolderName(std::string_view name) { return LowerAscii(name) == "steam_settings"; }
+
+bool UsableName(std::string_view name) {
+ if (name.empty() || name == "." || name == ".." || name.size() > kMaxNameBytes) return false;
+ for (const unsigned char c : name)
+ if (c < 0x20 || c == 0x7f || c == '/' || c == '\\') return false;
+ return ValidUtf8(name);
+}
+
+bool NewName(std::string_view name) { return UsableName(name) && name.size() <= kMaxNewNameBytes && !HiddenName(name); }
+
+std::optional<std::vector<std::string>> SplitRelativePath(std::string_view path) {
+ std::vector<std::string> parts;
+ if (path.empty()) return parts;
+ std::size_t start = 0;
+ while (true) {
+ const auto slash = path.find('/', start);
+ const auto part = path.substr(start, slash == std::string_view::npos ? slash : slash - start);
+ if (!UsableName(part) || HiddenName(part)) return std::nullopt;
+ parts.emplace_back(part);
+ if (slash == std::string_view::npos) return parts;
+ start = slash + 1;
+ }
+}
+
+bool ReadOnlyPath(const std::vector<std::string>& parts) {
+ for (const auto& part : parts)
+ if (ReadOnlyFolderName(part)) return true;
+ return false;
+}
+
+bool PrivatePath(const std::vector<std::string>& parts, const std::vector<std::string>& private_paths) {
+ for (const auto& path : private_paths) {
+ const auto split = SplitRelativePath(path);
+ if (!split || split->empty() || split->size() > parts.size()) continue;
+ bool within = true;
+ for (std::size_t i = 0; i < split->size(); ++i) within = within && LowerAscii((*split)[i]) == LowerAscii(parts[i]);
+ if (within) return true;
+ }
+ return false;
+}
+
+} // namespace playden::web
diff --git a/src/web/file_policy.h b/src/web/file_policy.h
new file mode 100644
index 0000000..ee9fb3c
--- /dev/null
+++ b/src/web/file_policy.h
@@ -0,0 +1,43 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+#pragma once
+
+#include <cstddef>
+#include <optional>
+#include <string>
+#include <string_view>
+#include <vector>
+
+namespace playden::web {
+
+// What the page may see and change inside a game's folders. Pure: no file system access. Names compare without
+// regard to case, as exFAT and Wine do.
+
+// A name new files may have: the previous-version prefix must still fit in the file system's 255 bytes.
+inline constexpr std::size_t kMaxNewNameBytes = 230;
+inline constexpr std::size_t kMaxNameBytes = 255;
+
+// Playden's files beside the player's. Cloud sync skips names starting ".playden" (steam/backend/cloud_sync.cpp).
+inline constexpr const char* kPreviousPrefix = ".playden-bak.";
+inline constexpr const char* kUploadPrefix = ".playden-upload-";
+inline constexpr const char* kRestorePrefix = ".playden-restore-";
+
+std::string LowerAscii(std::string_view text);
+bool ValidUtf8(std::string_view text);
+// Hidden and refused: Playden's own files and secrets kept in a game's folder.
+bool HiddenName(std::string_view name);
+// Readable, never changed: Playden writes these folders each time it prepares the game.
+bool ReadOnlyFolderName(std::string_view name);
+// An existing entry the page may name: not ".", "..", no separators or control characters, valid UTF-8.
+bool UsableName(std::string_view name);
+// A name a new file or folder may take.
+bool NewName(std::string_view name);
+
+// A request's path, relative to a root: its parts, or nothing when any part isn't usable or is hidden. Empty text
+// is the root itself. No path that leaves a root, hidden or not, gets through.
+std::optional<std::vector<std::string>> SplitRelativePath(std::string_view path);
+// Whether a path passes through a read-only folder.
+bool ReadOnlyPath(const std::vector<std::string>& parts);
+// Whether parts is at or below one of the private paths (each '/'-separated, relative to the same root).
+bool PrivatePath(const std::vector<std::string>& parts, const std::vector<std::string>& private_paths);
+
+} // namespace playden::web
diff --git a/src/web/file_store.cpp b/src/web/file_store.cpp
new file mode 100644
index 0000000..3445c53
--- /dev/null
+++ b/src/web/file_store.cpp
@@ -0,0 +1,761 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "web/file_store.h"
+
+#include "platform/directory_walk.h"
+#include "platform/random_id.h"
+#include "runtime/artifact_hash.h"
+#include "runtime/redist_names.h"
+#include "web/zip.h"
+
+#include <algorithm>
+#include <cerrno>
+#include <chrono>
+#include <cstdlib>
+#include <cstring>
+#include <dirent.h>
+#include <fcntl.h>
+#include <sys/stat.h>
+#include <thread>
+#include <unistd.h>
+
+namespace playden::web {
+namespace {
+
+namespace fs = std::filesystem;
+using platform::DirectoryPolicy;
+using platform::ManagedDirectory;
+
+constexpr std::size_t kTransferBytes = 256 * 1024;
+constexpr std::uint64_t kSpaceMargin = 64ull * 1024 * 1024;
+constexpr std::size_t kMaxZipEntries = 65535;
+constexpr std::uint64_t kMaxZipBytes = 0x7fffffffu;
+constexpr std::size_t kMaxZipDepth = 32;
+
+const FileError kOk{};
+FileError Busy() { return {503, "Playden is busy. Try again in a moment."}; }
+FileError NotFound() { return {404, "That file or folder isn't there."}; }
+FileError BadPath() { return {400, "That name can't be used."}; }
+
+FileError FromErrno(int error, const std::string& what) {
+ switch (error) {
+ case ENOENT: return NotFound();
+ case EACCES: case EPERM: return {403, "This file belongs to another user, so Playden can't change it."};
+ case EEXIST: return {409, "A file or folder with that name is already there."};
+ case ENOTEMPTY: return {409, "This folder isn't empty."};
+ case ENOSPC: return {507, "There is no room left on this drive."};
+ case ENAMETOOLONG: return {400, "That name is too long."};
+ default: return {500, what + ": " + std::strerror(error)};
+ }
+}
+
+struct RawEntry {
+ std::string name;
+ struct stat info;
+};
+
+// Every regular file and folder a folder lists, links left out. Path operations: hold the lock.
+bool ReadFolder(const std::string& path, std::vector<RawEntry>* out, std::size_t limit, bool* truncated) {
+ DIR* directory = ::opendir(path.c_str());
+ if (!directory) return false;
+ while (true) {
+ if (out->size() >= limit) {
+ if (truncated) *truncated = true;
+ break;
+ }
+ const auto* entry = ::readdir(directory);
+ if (!entry) break;
+ const std::string name = entry->d_name;
+ if (name == "." || name == "..") continue;
+ struct stat info{};
+ if (::lstat((path + "/" + name).c_str(), &info) != 0) continue;
+ if (!S_ISREG(info.st_mode) && !S_ISDIR(info.st_mode)) continue;
+ out->push_back({name, info});
+ }
+ ::closedir(directory);
+ return true;
+}
+
+bool HardLinked(const struct stat& info) { return S_ISREG(info.st_mode) && info.st_nlink != 1; }
+
+std::string Join(const std::vector<std::string>& parts, std::size_t count) {
+ std::string out;
+ for (std::size_t i = 0; i < count; ++i) out += (i ? "/" : "") + parts[i];
+ return out;
+}
+
+struct FdCloser {
+ int fd = -1;
+ ~FdCloser() { if (fd >= 0) ::close(fd); }
+};
+
+} // namespace
+
+FileStore::FileStore(Options options) : options_(std::move(options)) {
+ if (!options_.random_id) options_.random_id = [] { return playden::RandomUuid(); };
+}
+
+std::shared_ptr<void> FileStore::Hold() {
+ if (!options_.try_hold) return std::make_shared<int>(0);
+ for (int attempt = 0; attempt < std::max(options_.hold_tries, 1); ++attempt) {
+ if (attempt) std::this_thread::sleep_for(std::chrono::milliseconds(options_.hold_retry_ms));
+ if (auto held = options_.try_hold()) return held;
+ }
+ return nullptr;
+}
+
+FileError FileStore::WithHold(const std::function<FileError()>& work) {
+ const auto held = Hold();
+ if (!held) return Busy();
+ return work();
+}
+
+bool FileStore::Step(const std::string& step) {
+ if (!options_.fault || options_.fault(step)) return true;
+ errno = EIO;
+ return false;
+}
+
+std::int64_t FileStore::Now() const {
+ if (options_.now) return options_.now();
+ return std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count();
+}
+
+std::optional<std::string> FileStore::RandomText() { return options_.random_id(); }
+
+std::optional<DirectoryPolicy> FileStore::WritePolicy(const FileRoot& root) {
+ if (!root.game_folder) return DirectoryPolicy::kApprovedTree;
+ std::lock_guard<std::mutex> lock(state_mutex_);
+ auto found = records_ownership_.find(root.path);
+ if (found == records_ownership_.end()) {
+ // Writes a probe file, so it waits for the first write. The answer can't change for a folder this session.
+ const auto records = platform::RecordsOwnership(root.path);
+ if (!records) return std::nullopt;
+ found = records_ownership_.emplace(root.path, *records).first;
+ }
+ return found->second ? DirectoryPolicy::kApprovedTree : DirectoryPolicy::kUnownedTree;
+}
+
+// Opens the root and steps down, one part at a time: every policy refuses a link in any component. Reads of a game
+// folder use the no-owners policy, so they never need the write probe. Hold the lock.
+FileError FileStore::Locate(const FileRoot& root, const std::vector<std::string>& parts, bool writing, bool create_root,
+ std::optional<ManagedDirectory>* out) {
+ DirectoryPolicy policy = root.game_folder ? DirectoryPolicy::kUnownedTree : DirectoryPolicy::kApprovedTree;
+ if (writing) {
+ const auto chosen = WritePolicy(root);
+ if (!chosen) return {500, "Playden couldn't write a test file in this folder."};
+ policy = *chosen;
+ }
+ auto current = ManagedDirectory::Open(root.path, policy);
+ if (!current && errno == ENOENT && create_root && !root.create_from.empty()) {
+ auto base = ManagedDirectory::Open(root.create_from, policy);
+ if (!base) return FromErrno(errno, "The game's folder can't be opened");
+ const auto relative = fs::path(root.path).lexically_relative(root.create_from);
+ for (const auto& part : relative) {
+ auto next = base->OpenChild(part.string(), policy, true, root.folder_mode);
+ if (!next || !next->Sync() || !base->Sync()) return FromErrno(errno, "The folder can't be made");
+ base = std::move(next);
+ }
+ current = std::move(base);
+ }
+ if (!current) return FromErrno(errno, "This folder can't be opened");
+ for (const auto& part : parts) {
+ auto next = current->OpenChild(part, policy);
+ if (!next) return FromErrno(errno, "This folder can't be opened");
+ current = std::move(next);
+ }
+ *out = std::move(current);
+ return kOk;
+}
+
+FileError FileStore::List(const FileRoot& root, const std::string& path, FileListing* out) {
+ const auto parts = SplitRelativePath(path);
+ if (!parts || PrivatePath(*parts, root.private_paths)) return NotFound();
+ const auto held = Hold();
+ if (!held) return Busy();
+ CleanUpDeferred();
+ *out = {};
+ std::optional<ManagedDirectory> folder;
+ if (auto error = Locate(root, *parts, false, false, &folder); !error.ok()) {
+ // A root that isn't made yet is an empty folder.
+ if (error.status == 404 && parts->empty()) return kOk;
+ return error;
+ }
+ out->exists = true;
+ out->read_only = ReadOnlyPath(*parts);
+ std::vector<RawEntry> raw;
+ if (!ReadFolder(folder->path().string(), &raw, kMaxListedEntries * 2, &out->truncated))
+ return FromErrno(errno, "This folder can't be listed");
+ // An upload cut off by a game's start leaves its partial file, which nothing else may ever come back for.
+ if (std::any_of(raw.begin(), raw.end(), [](const RawEntry& entry) { return entry.name.rfind(kUploadPrefix, 0) == 0 || entry.name.rfind(kRestorePrefix, 0) == 0; }))
+ Sweep(*folder);
+ std::map<std::string, PreviousVersion> previous;
+ const std::string prefix = kPreviousPrefix;
+ for (const auto& entry : raw) {
+ if (entry.name.rfind(prefix, 0) != 0 || entry.name.size() <= prefix.size()) continue;
+ if (!S_ISREG(entry.info.st_mode) || HardLinked(entry.info)) continue;
+ const auto name = entry.name.substr(prefix.size());
+ if (!UsableName(name) || HiddenName(name)) continue;
+ previous[LowerAscii(name)] = {static_cast<std::uint64_t>(entry.info.st_size), static_cast<std::int64_t>(entry.info.st_mtime)};
+ }
+ auto with_path = *parts;
+ with_path.emplace_back();
+ for (const auto& entry : raw) {
+ if (HiddenName(entry.name)) continue;
+ if (!UsableName(entry.name) || HardLinked(entry.info)) { ++out->unshown; continue; }
+ with_path.back() = entry.name;
+ if (PrivatePath(with_path, root.private_paths)) continue;
+ if (out->entries.size() >= kMaxListedEntries) { out->truncated = true; break; }
+ FileEntry listed;
+ listed.name = entry.name;
+ listed.directory = S_ISDIR(entry.info.st_mode);
+ listed.size = listed.directory ? 0 : static_cast<std::uint64_t>(entry.info.st_size);
+ listed.modified = entry.info.st_mtime;
+ listed.read_only = out->read_only || (listed.directory && ReadOnlyFolderName(entry.name));
+ if (!listed.directory) {
+ const auto found = previous.find(LowerAscii(entry.name));
+ if (found != previous.end()) {
+ listed.previous = found->second;
+ previous.erase(found);
+ }
+ }
+ out->entries.push_back(std::move(listed));
+ }
+ // A previous version with nothing beside it: all that's left of a replace a crash stopped.
+ for (const auto& entry : raw) {
+ if (entry.name.rfind(prefix, 0) != 0 || !S_ISREG(entry.info.st_mode) || HardLinked(entry.info)) continue;
+ const auto name = entry.name.substr(prefix.size());
+ const auto found = previous.find(LowerAscii(name));
+ if (found == previous.end()) continue;
+ FileEntry listed;
+ listed.name = name;
+ listed.size = found->second.size;
+ listed.modified = found->second.modified;
+ listed.read_only = out->read_only;
+ listed.previous = found->second;
+ listed.recoverable = true;
+ out->entries.push_back(std::move(listed));
+ previous.erase(found);
+ }
+ std::sort(out->entries.begin(), out->entries.end(), [](const FileEntry& left, const FileEntry& right) {
+ if (left.directory != right.directory) return left.directory;
+ return LowerAscii(left.name) < LowerAscii(right.name);
+ });
+ return kOk;
+}
+
+FileError FileStore::OpenForRead(const FileRoot& root, const std::string& path, bool previous, OpenedFile* out) {
+ auto parts = SplitRelativePath(path);
+ if (!parts || parts->empty() || PrivatePath(*parts, root.private_paths)) return NotFound();
+ const auto name = parts->back();
+ parts->pop_back();
+ const auto held = Hold();
+ if (!held) return Busy();
+ std::optional<ManagedDirectory> folder;
+ if (auto error = Locate(root, *parts, false, false, &folder); !error.ok()) return error;
+ // The walk for reads, not OpenRegularFile: exFAT numbers an empty file differently from one look to the next. It
+ // still refuses a link, and takes a regular file only from the folder's device.
+ const int walk = platform::OpenDirectoryWalk(folder->path());
+ if (walk < 0) return FromErrno(errno, "This folder can't be opened");
+ const std::string opened_name = previous ? kPreviousPrefix + name : name;
+ const int fd = platform::OpenWalkChildUnprivileged(walk, opened_name.c_str(), O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC);
+ const int open_error = errno;
+ ::close(walk);
+ if (fd < 0) return open_error == ELOOP || open_error == EMLINK ? NotFound() : FromErrno(open_error, "This file can't be opened");
+ struct stat info{};
+ if (::fstat(fd, &info) != 0 || !S_ISREG(info.st_mode) || HardLinked(info)) {
+ ::close(fd);
+ return NotFound();
+ }
+ // Reads stay blocking from here: a regular file's descriptor only needed the flag for the open.
+ const int flags = ::fcntl(fd, F_GETFL);
+ if (flags >= 0) ::fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
+ out->fd = fd;
+ out->size = static_cast<std::uint64_t>(info.st_size);
+ out->name = name;
+ return kOk;
+}
+
+FileError FileStore::ReadText(const FileRoot& root, const std::string& path, FileText* out) {
+ OpenedFile file;
+ if (auto error = OpenForRead(root, path, false, &file); !error.ok()) return error;
+ FdCloser closer{file.fd};
+ if (file.size > kMaxTextBytes) return {413, "This file is too large to edit here. Download it instead."};
+ std::string text(static_cast<std::size_t>(file.size), '\0');
+ std::size_t done = 0;
+ while (done < text.size()) {
+ const auto count = ::read(file.fd, text.data() + done, text.size() - done);
+ if (count < 0 && errno == EINTR) continue;
+ if (count <= 0) return FromErrno(errno, "This file can't be read");
+ done += static_cast<std::size_t>(count);
+ }
+ if (!ValidUtf8(text) || text.find('\0') != std::string::npos) return {415, "This isn't a text file. Download it instead."};
+ const auto hash = runtime::HashArtifactBytes(text);
+ if (!hash) return {500, "This file can't be read."};
+ out->text = std::move(text);
+ out->sha256 = *hash;
+ return kOk;
+}
+
+bool FileStore::RemoveTemporary(const std::string& folder, const std::string& name, DirectoryPolicy policy) {
+ auto opened = ManagedDirectory::Open(folder, policy);
+ if (!opened) return errno == ENOENT;
+ if (!opened->RemoveRegularFile(name)) return errno == ENOENT;
+ opened->Sync();
+ return true;
+}
+
+void FileStore::DeferCleanup(const FileRoot&, std::string folder, std::string name, DirectoryPolicy policy) {
+ std::lock_guard<std::mutex> lock(state_mutex_);
+ deferred_.push_back({std::move(folder), std::move(name), policy});
+}
+
+void FileStore::CleanUpDeferred() {
+ std::vector<Deferred> work;
+ {
+ std::lock_guard<std::mutex> lock(state_mutex_);
+ work.swap(deferred_);
+ }
+ if (work.empty()) return;
+ // One try: the caller's work goes on whether or not this can run now.
+ std::shared_ptr<void> held = options_.try_hold ? options_.try_hold() : std::make_shared<int>(0);
+ std::vector<Deferred> left;
+ for (auto& item : work)
+ if (!held || !RemoveTemporary(item.folder, item.name, item.policy)) left.push_back(std::move(item));
+ if (left.empty()) return;
+ std::lock_guard<std::mutex> lock(state_mutex_);
+ for (auto& item : left) deferred_.push_back(std::move(item));
+}
+
+std::size_t FileStore::DeferredCleanups() {
+ std::lock_guard<std::mutex> lock(state_mutex_);
+ return deferred_.size();
+}
+
+// Temporary files a crash or quit left in this folder, once they are old. An upload's is only part of a file. A
+// restore's is the player's file, so it finishes the swap, or undoes it if the restored file never arrived. It goes
+// only if the file and its previous version both came back since: that version was replaced as usual. Hold the lock.
+void FileStore::Sweep(const ManagedDirectory& folder) {
+ std::vector<RawEntry> raw;
+ if (!ReadFolder(folder.path().string(), &raw, kMaxListedEntries * 2, nullptr)) return;
+ const auto now = Now();
+ for (const auto& entry : raw) {
+ if (entry.name.rfind(kUploadPrefix, 0) != 0 && entry.name.rfind(kRestorePrefix, 0) != 0) continue;
+ if (!S_ISREG(entry.info.st_mode)) continue;
+ // A restore's temporary is the player's file, with its old time: its age is in its name.
+ std::int64_t made = entry.info.st_mtime;
+ if (entry.name.rfind(kRestorePrefix, 0) == 0) {
+ const auto digits = entry.name.substr(std::strlen(kRestorePrefix), entry.name.find('-', std::strlen(kRestorePrefix)) - std::strlen(kRestorePrefix));
+ if (!digits.empty() && digits.size() <= 18 && digits.find_first_not_of("0123456789") == std::string::npos) made = std::atoll(digits.c_str());
+ }
+ if (now - made < options_.stale_seconds) continue;
+ {
+ std::lock_guard<std::mutex> lock(state_mutex_);
+ if (active_uploads_.count((folder.path() / entry.name).string())) continue;
+ }
+ if (entry.name.rfind(kRestorePrefix, 0) == 0) {
+ const auto dot = entry.name.find('.', std::strlen(kRestorePrefix));
+ if (dot != std::string::npos && dot + 1 < entry.name.size()) {
+ const auto name = entry.name.substr(dot + 1);
+ const auto free = [&](const std::string& child) {
+ struct stat there{};
+ return !folder.InspectChild(child, &there) && errno == ENOENT;
+ };
+ const auto target = free(name) ? name : free(kPreviousPrefix + name) ? kPreviousPrefix + name : std::string();
+ if (!target.empty()) {
+ if (folder.RenameChild(entry.name, folder, target, false)) folder.Sync();
+ continue;
+ }
+ }
+ }
+ folder.RemoveRegularFile(entry.name);
+ }
+}
+
+FileError FileStore::Upload(const FileRoot& root, const std::string& path, const UploadOptions& upload,
+ const UploadReader& read, bool* replaced) {
+ if (replaced) *replaced = false;
+ auto parts = SplitRelativePath(path);
+ if (!parts || parts->empty() || PrivatePath(*parts, root.private_paths)) return BadPath();
+ if (ReadOnlyPath(*parts)) return {403, "Playden writes this folder itself, so it can't be changed here."};
+ const auto name = parts->back();
+ if (!NewName(name)) return BadPath();
+ parts->pop_back();
+ std::string temporary, folder_path;
+ DirectoryPolicy policy;
+ int fd = -1;
+ {
+ const auto held = Hold();
+ if (!held) return Busy();
+ CleanUpDeferred();
+ std::optional<ManagedDirectory> folder;
+ if (auto error = Locate(root, *parts, true, parts->empty(), &folder); !error.ok()) return error;
+ policy = folder->policy();
+ if (options_.free_space) {
+ const auto free = options_.free_space(folder->path().string());
+ if (free && upload.length + kSpaceMargin > *free) return {507, "There is no room for this file on this drive."};
+ }
+ struct stat existing{};
+ if (folder->InspectChild(name, &existing)) {
+ if (S_ISDIR(existing.st_mode)) return {409, "A folder with that name is already there."};
+ if (!upload.overwrite) return {409, "A file with that name is already there."};
+ if (policy != DirectoryPolicy::kUnownedTree && existing.st_uid != ::geteuid())
+ return FromErrno(EACCES, "");
+ } else if (errno != ENOENT) {
+ return FromErrno(errno, "This folder can't be read");
+ }
+ Sweep(*folder);
+ const auto id = RandomText();
+ if (!id) return {500, "Playden couldn't make a temporary name."};
+ temporary = kUploadPrefix + *id;
+ fd = folder->CreateExclusiveFile(temporary, root.file_mode);
+ if (fd < 0) return FromErrno(errno, "The file can't be made");
+ folder_path = folder->path().string();
+ std::lock_guard<std::mutex> lock(state_mutex_);
+ active_uploads_.insert(folder_path + "/" + temporary);
+ }
+ const auto finish = [&](FileError error) {
+ {
+ std::lock_guard<std::mutex> lock(state_mutex_);
+ active_uploads_.erase(folder_path + "/" + temporary);
+ }
+ if (!error.ok()) {
+ // Cleaned up now if the lock is free. A setup holds it for minutes: then at a later file request.
+ const auto held = options_.try_hold ? options_.try_hold() : std::make_shared<int>(0);
+ if (!held || !RemoveTemporary(folder_path, temporary, policy)) DeferCleanup(root, folder_path, temporary, policy);
+ }
+ return error;
+ };
+ // Bytes move with no lock held.
+ {
+ FdCloser closer{fd};
+ std::vector<char> buffer(kTransferBytes);
+ std::uint64_t left = upload.length;
+ while (left > 0) {
+ const auto want = static_cast<std::size_t>(std::min<std::uint64_t>(left, buffer.size()));
+ const auto count = read(buffer.data(), want);
+ if (count <= 0) return finish({408, "The upload stopped before the end."});
+ std::size_t written = 0;
+ while (written < static_cast<std::size_t>(count)) {
+ const auto wrote = ::write(fd, buffer.data() + written, static_cast<std::size_t>(count) - written);
+ if (wrote < 0 && errno == EINTR) continue;
+ if (wrote <= 0) return finish(FromErrno(errno, "The file can't be written"));
+ written += static_cast<std::size_t>(wrote);
+ }
+ left -= static_cast<std::uint64_t>(count);
+ }
+ if (!Step("sync-temporary") || ::fsync(fd) != 0) return finish(FromErrno(errno ? errno : EIO, "The file can't be saved"));
+ }
+ FileError error;
+ bool changed_disk = false;
+ {
+ std::lock_guard<std::mutex> commit(commit_mutex_);
+ parts->push_back(name);
+ // The editor's check: read and hashed with no path lock, as any file's bytes. Nothing of Playden's can change the
+ // file meanwhile (the commit lock), and the commit checks that its size and time are still those read.
+ struct stat checked{};
+ if (upload.if_sha256) {
+ FileText current;
+ if (const auto read_error = ReadText(root, path, &current); !read_error.ok())
+ return finish(read_error.status == 503 ? read_error : FileError{409, "This file changed since you opened it."});
+ if (current.sha256 != *upload.if_sha256) return finish({409, "This file changed since you opened it."});
+ const auto held = Hold();
+ if (!held) return finish(Busy());
+ std::optional<ManagedDirectory> folder;
+ const std::vector<std::string> above(parts->begin(), parts->end() - 1);
+ if (auto located = Locate(root, above, true, false, &folder); !located.ok()) return finish(located);
+ if (!folder->InspectChild(name, &checked)) return finish({409, "This file changed since you opened it."});
+ }
+ const auto held = Hold();
+ if (!held) return finish(Busy());
+ changed_disk = CommitUpload(root, *parts, temporary, upload, upload.if_sha256 ? &checked : nullptr, replaced, &error);
+ }
+ if (changed_disk) {
+ std::lock_guard<std::mutex> lock(state_mutex_);
+ active_uploads_.erase(folder_path + "/" + temporary);
+ return error;
+ }
+ return finish(error);
+}
+
+// The Replace sequence, each step followed by a sync of the folder. A crash leaves one of: the old file with the
+// temporary; the file with the old previous version gone; only the previous version (listed as Recoverable).
+// True when the temporary is gone or must stay as it is. Holds the commit lock and the path lock.
+bool FileStore::CommitUpload(const FileRoot& root, const std::vector<std::string>& parts, const std::string& temporary,
+ const UploadOptions& upload, const struct stat* expected, bool* replaced, FileError* error) {
+ const auto name = parts.back();
+ const std::vector<std::string> above(parts.begin(), parts.end() - 1);
+ std::optional<ManagedDirectory> folder;
+ if (auto located = Locate(root, above, true, false, &folder); !located.ok()) {
+ *error = located;
+ return false;
+ }
+ const auto policy = folder->policy();
+ struct stat existing{};
+ const bool exists = folder->InspectChild(name, &existing);
+ if (!exists && errno != ENOENT) {
+ *error = FromErrno(errno, "This folder can't be read");
+ return false;
+ }
+ if (exists && S_ISDIR(existing.st_mode)) { *error = {409, "A folder with that name is already there."}; return false; }
+ if (exists && !upload.overwrite) { *error = {409, "A file with that name is already there."}; return false; }
+ if (exists && policy != DirectoryPolicy::kUnownedTree && existing.st_uid != ::geteuid()) {
+ *error = FromErrno(EACCES, "");
+ return false;
+ }
+ if (expected && (!exists || existing.st_size != expected->st_size || existing.st_mtime != expected->st_mtime)) {
+ *error = {409, "This file changed since you opened it."};
+ return false;
+ }
+ const auto failed = [&](const char* step) {
+ // Something on disk already moved: the page lists the folder again, and shows what is there.
+ *error = {500, std::string("The save stopped at \"") + step + "\". Check this folder."};
+ return true;
+ };
+ if (exists) {
+ const auto backup = kPreviousPrefix + name;
+ struct stat old{};
+ if (folder->InspectChild(backup, &old)) {
+ if (!Step("remove-backup") || !folder->RemoveRegularFile(backup)) {
+ *error = FromErrno(errno ? errno : EIO, "The previous version can't be replaced");
+ return false;
+ }
+ }
+ if (!Step("move-current") || !folder->RenameChild(name, *folder, backup, false)) {
+ *error = FromErrno(errno ? errno : EIO, "The file can't be replaced");
+ return false;
+ }
+ if (!Step("sync-backup") || !folder->Sync()) return failed("sync");
+ }
+ if (!Step("publish") || !folder->RenameChild(temporary, *folder, name, false)) {
+ if (exists) return failed("publish");
+ *error = FromErrno(errno ? errno : EIO, "The file can't be saved");
+ return false;
+ }
+ if (!Step("sync-publish") || !folder->Sync()) return failed("sync");
+ if (replaced) *replaced = exists;
+ *error = {};
+ return true;
+}
+
+FileError FileStore::MakeFolder(const FileRoot& root, const std::string& path) {
+ auto parts = SplitRelativePath(path);
+ if (!parts || parts->empty() || PrivatePath(*parts, root.private_paths)) return BadPath();
+ if (ReadOnlyPath(*parts)) return {403, "Playden writes this folder itself, so it can't be changed here."};
+ const auto name = parts->back();
+ if (!NewName(name)) return BadPath();
+ parts->pop_back();
+ std::lock_guard<std::mutex> commit(commit_mutex_);
+ const auto held = Hold();
+ if (!held) return Busy();
+ std::optional<ManagedDirectory> folder;
+ if (auto error = Locate(root, *parts, true, parts->empty(), &folder); !error.ok()) return error;
+ struct stat existing{};
+ if (folder->InspectChild(name, &existing)) return FromErrno(EEXIST, "");
+ auto made = folder->OpenChild(name, folder->policy(), true, root.folder_mode);
+ if (!made) return FromErrno(errno, "The folder can't be made");
+ if (!made->Sync() || !folder->Sync()) return FromErrno(errno, "The folder can't be saved");
+ return kOk;
+}
+
+FileError FileStore::Delete(const FileRoot& root, const std::string& path) {
+ auto parts = SplitRelativePath(path);
+ if (!parts || parts->empty() || PrivatePath(*parts, root.private_paths)) return NotFound();
+ if (ReadOnlyPath(*parts)) return {403, "Playden writes this folder itself, so it can't be changed here."};
+ const auto name = parts->back();
+ parts->pop_back();
+ std::lock_guard<std::mutex> commit(commit_mutex_);
+ const auto held = Hold();
+ if (!held) return Busy();
+ std::optional<ManagedDirectory> folder;
+ if (auto error = Locate(root, *parts, true, false, &folder); !error.ok()) return error;
+ const auto backup = kPreviousPrefix + name;
+ struct stat target{}, old{};
+ const bool exists = folder->InspectChild(name, &target);
+ if (!exists && errno != ENOENT) return FromErrno(errno, "This folder can't be read");
+ const bool has_backup = folder->InspectChild(backup, &old);
+ if (!exists && !has_backup) return NotFound();
+ if (exists && S_ISDIR(target.st_mode)) {
+ // What a cut-off upload left in it mustn't keep a folder that looks empty.
+ if (auto inside = folder->OpenChild(name, folder->policy())) Sweep(*inside);
+ if (!folder->RemoveEmptyDirectory(name)) return FromErrno(errno, "The folder can't be deleted");
+ if (!folder->Sync()) return FromErrno(errno, "The change can't be saved");
+ return kOk;
+ }
+ if (exists && HardLinked(target)) return NotFound();
+ // The previous version first: a crash leaves the file, not a file the player thought was gone.
+ if (exists && folder->policy() != DirectoryPolicy::kUnownedTree && target.st_uid != ::geteuid()) return FromErrno(EACCES, "");
+ if (has_backup) {
+ if (!Step("delete-backup") || !folder->RemoveRegularFile(backup)) return FromErrno(errno ? errno : EIO, "The file can't be deleted");
+ if (!folder->Sync()) return FromErrno(errno, "The change can't be saved");
+ }
+ if (exists) {
+ if (!Step("delete-current") || !folder->RemoveRegularFile(name)) return FromErrno(errno ? errno : EIO, "The file can't be deleted");
+ if (!folder->Sync()) return FromErrno(errno, "The change can't be saved");
+ }
+ return kOk;
+}
+
+// Steps: file -> temporary; previous -> file; sync; temporary -> previous; sync. A crash leaves the previous version
+// listed as Recoverable, or the swap done with a temporary the sweep removes when it is old.
+FileError FileStore::Restore(const FileRoot& root, const std::string& path) {
+ auto parts = SplitRelativePath(path);
+ if (!parts || parts->empty() || PrivatePath(*parts, root.private_paths)) return NotFound();
+ if (ReadOnlyPath(*parts)) return {403, "Playden writes this folder itself, so it can't be changed here."};
+ const auto name = parts->back();
+ parts->pop_back();
+ std::lock_guard<std::mutex> commit(commit_mutex_);
+ const auto held = Hold();
+ if (!held) return Busy();
+ std::optional<ManagedDirectory> folder;
+ if (auto error = Locate(root, *parts, true, false, &folder); !error.ok()) return error;
+ const auto backup = kPreviousPrefix + name;
+ struct stat old{}, current{};
+ if (!folder->InspectChild(backup, &old) || !S_ISREG(old.st_mode) || HardLinked(old)) return {404, "There is no previous version of this file."};
+ const bool exists = folder->InspectChild(name, &current);
+ if (exists && !S_ISREG(current.st_mode)) return {409, "A folder with that name is already there."};
+ if (exists && folder->policy() != DirectoryPolicy::kUnownedTree && current.st_uid != ::geteuid()) return FromErrno(EACCES, "");
+ std::string swapped;
+ if (exists) {
+ const auto id = RandomText();
+ if (!id) return {500, "Playden couldn't make a temporary name."};
+ // The name is in here so the sweep can put the file back if the swap never finishes.
+ swapped = kRestorePrefix + std::to_string(Now()) + "-" + *id + "." + name;
+ if (!Step("restore-aside") || !folder->RenameChild(name, *folder, swapped, false))
+ return FromErrno(errno ? errno : EIO, "The file can't be restored");
+ }
+ if (!Step("restore-back") || !folder->RenameChild(backup, *folder, name, false))
+ return {500, "The restore stopped at \"back\". Check this folder."};
+ if (!Step("restore-sync") || !folder->Sync()) return {500, "The restore stopped at \"sync\". Check this folder."};
+ if (exists) {
+ if (!Step("restore-keep") || !folder->RenameChild(swapped, *folder, backup, false))
+ return {500, "The restore stopped at \"keep\". Check this folder."};
+ if (!folder->Sync()) return {500, "The restore stopped at \"sync\". Check this folder."};
+ }
+ return kOk;
+}
+
+FileError FileStore::RedistFolders(const FileRoot& root, std::vector<RedistFolderInfo>* out) {
+ out->clear();
+ fs::path top_path;
+ {
+ const auto held = Hold();
+ if (!held) return Busy();
+ std::optional<ManagedDirectory> top;
+ if (auto error = Locate(root, {}, false, false, &top); !error.ok()) return error;
+ top_path = top->path();
+ }
+ // A game folder can be large, so this looks with no path lock: it only reads a folder open to all, and a look that
+ // fails while root is raised elsewhere shows less until the page asks again.
+ std::vector<std::string> packages;
+ runtime::FindPhysxPackages(top_path, std::string(), 0, false, &packages);
+ const auto add = [&](const std::string& relative, const std::string& absolute) {
+ RedistFolderInfo info;
+ info.path = relative;
+ std::vector<RawEntry> raw;
+ if (ReadFolder(absolute, &raw, kMaxListedEntries, nullptr))
+ for (const auto& entry : raw) {
+ if (HiddenName(entry.name) || !UsableName(entry.name)) continue;
+ ++info.entries;
+ if (S_ISREG(entry.info.st_mode)) info.bytes += static_cast<std::uint64_t>(entry.info.st_size);
+ if (info.sample.size() < 3) info.sample.push_back(entry.name);
+ }
+ for (const auto& package : packages)
+ if (package.rfind(relative + "/", 0) == 0) info.physx_installer = package;
+ out->push_back(std::move(info));
+ };
+ std::vector<RawEntry> raw;
+ if (!ReadFolder(top_path.string(), &raw, kMaxListedEntries, nullptr)) return FromErrno(errno, "This folder can't be listed");
+ for (const auto& entry : raw) {
+ if (!S_ISDIR(entry.info.st_mode) || HiddenName(entry.name) || !UsableName(entry.name)) continue;
+ const auto absolute = (top_path / entry.name).string();
+ if (runtime::RedistFolder(entry.name)) {
+ add(entry.name, absolute);
+ continue;
+ }
+ std::vector<RawEntry> below;
+ if (!ReadFolder(absolute, &below, kMaxListedEntries, nullptr)) continue;
+ for (const auto& child : below)
+ if (S_ISDIR(child.info.st_mode) && !HiddenName(child.name) && UsableName(child.name) && runtime::RedistFolder(child.name))
+ add(entry.name + "/" + child.name, absolute + "/" + child.name);
+ }
+ std::sort(out->begin(), out->end(), [](const RedistFolderInfo& left, const RedistFolderInfo& right) {
+ return LowerAscii(left.path) < LowerAscii(right.path);
+ });
+ return kOk;
+}
+
+FileError FileStore::WriteZip(const FileRoot& root, const std::string& path, std::int64_t modified, const ByteWriter& write,
+ const std::function<bool()>& begin, bool* started) {
+ *started = false;
+ const auto parts = SplitRelativePath(path);
+ if (!parts || PrivatePath(*parts, root.private_paths)) return NotFound();
+ struct Item {
+ std::vector<std::string> parts; // relative to the root; the last is the file
+ std::string zip_name;
+ };
+ std::vector<Item> items;
+ std::uint64_t budget = 22;
+ const std::string top = parts->empty() ? fs::path(root.path).filename().string() : parts->back();
+ // Iterative, because worker stacks are small and a folder's depth is the player's. Each folder is opened under the
+ // lock on its own, so a long walk doesn't keep root from being raised.
+ std::vector<std::vector<std::string>> folders{*parts};
+ while (!folders.empty()) {
+ auto current = std::move(folders.back());
+ folders.pop_back();
+ std::vector<RawEntry> raw;
+ {
+ const auto held = Hold();
+ if (!held) return Busy();
+ std::optional<ManagedDirectory> folder;
+ if (auto error = Locate(root, current, false, false, &folder); !error.ok()) {
+ if (error.status == 404 && !current.empty() && current != *parts) continue;
+ return error;
+ }
+ if (!ReadFolder(folder->path().string(), &raw, kMaxZipEntries + 1, nullptr)) return FromErrno(errno, "This folder can't be listed");
+ }
+ for (const auto& entry : raw) {
+ if (HiddenName(entry.name) || !UsableName(entry.name) || HardLinked(entry.info)) continue;
+ auto child = current;
+ child.push_back(entry.name);
+ if (PrivatePath(child, root.private_paths)) continue;
+ if (S_ISDIR(entry.info.st_mode)) {
+ if (child.size() >= kMaxZipDepth + parts->size()) return {413, "This folder goes too deep for a zip. Download smaller folders."};
+ folders.push_back(std::move(child));
+ continue;
+ }
+ std::string zip_name = top;
+ for (std::size_t i = parts->size(); i < child.size(); ++i) zip_name += "/" + child[i];
+ budget += StoredZip::EntryOverhead(zip_name.size()) + static_cast<std::uint64_t>(entry.info.st_size);
+ if (items.size() >= kMaxZipEntries || budget > kMaxZipBytes)
+ return {413, "Too large for a zip. Download smaller folders."};
+ items.push_back({std::move(child), std::move(zip_name)});
+ }
+ }
+ std::sort(items.begin(), items.end(), [](const Item& left, const Item& right) { return left.zip_name < right.zip_name; });
+ if (!begin()) return kOk;
+ *started = true;
+ StoredZip zip(write, modified);
+ std::vector<char> buffer(kTransferBytes);
+ for (const auto& item : items) {
+ OpenedFile file;
+ if (const auto error = OpenForRead(root, Join(item.parts, item.parts.size()), false, &file); !error.ok()) {
+ if (error.status == 404) continue; // gone since the walk
+ return error;
+ }
+ FdCloser closer{file.fd};
+ if (!zip.BeginEntry(item.zip_name)) return {500, "The zip stopped."};
+ while (true) {
+ const auto count = ::read(file.fd, buffer.data(), buffer.size());
+ if (count < 0 && errno == EINTR) continue;
+ if (count < 0) return {500, "The zip stopped."};
+ if (count == 0) break;
+ // Refused past the archive limit (a file grew after the walk): the stream ends with no final chunk.
+ if (!zip.EntryData(buffer.data(), static_cast<std::size_t>(count))) return {500, "The zip stopped."};
+ }
+ if (!zip.EndEntry()) return {500, "The zip stopped."};
+ }
+ if (!zip.Finish()) return {500, "The zip stopped."};
+ return kOk;
+}
+
+} // namespace playden::web
diff --git a/src/web/file_store.h b/src/web/file_store.h
new file mode 100644
index 0000000..d4359a2
--- /dev/null
+++ b/src/web/file_store.h
@@ -0,0 +1,183 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+#pragma once
+
+#include "platform/managed_directory.h"
+#include "web/file_policy.h"
+
+#include <cstdint>
+#include <cstddef>
+#include <filesystem>
+#include <functional>
+#include <map>
+#include <memory>
+#include <mutex>
+#include <optional>
+#include <set>
+#include <string>
+#include <utility>
+#include <vector>
+#include <sys/stat.h>
+#include <sys/types.h>
+
+namespace playden::web {
+
+// One named folder of a game: the only places the Files tab reaches.
+struct FileRoot {
+ std::string path; // absolute, as this process opens it
+ std::string create_from; // existing folder below which a missing root is made; empty: never made
+ mode_t folder_mode = 0700;
+ mode_t file_mode = 0600;
+ bool game_folder = false; // may be on a file system with no owners (exFAT): asked at the first write
+ std::vector<std::string> private_paths; // '/'-separated, relative to the root: hidden like Playden's own files
+};
+
+// An answer other than success: an HTTP status and words for the player. status 0: success.
+struct FileError {
+ int status = 0;
+ std::string message;
+ bool ok() const { return status == 0; }
+};
+
+struct PreviousVersion {
+ std::uint64_t size = 0;
+ std::int64_t modified = 0;
+};
+
+struct FileEntry {
+ std::string name;
+ bool directory = false;
+ std::uint64_t size = 0;
+ std::int64_t modified = 0;
+ bool read_only = false;
+ std::optional<PreviousVersion> previous;
+ // Only a previous version is left (a crash between a replace's two renames): it can be restored.
+ bool recoverable = false;
+};
+
+inline constexpr std::size_t kMaxListedEntries = 5000;
+
+struct FileListing {
+ bool exists = false;
+ bool read_only = false;
+ bool truncated = false;
+ std::size_t unshown = 0; // names the page can't show (invalid UTF-8) and files with another hard link
+ std::vector<FileEntry> entries;
+};
+
+struct OpenedFile {
+ int fd = -1; // the caller's to close
+ std::uint64_t size = 0;
+ std::string name;
+};
+
+// A file read and hashed for the editor.
+struct FileText {
+ std::string text;
+ std::string sha256;
+};
+inline constexpr std::size_t kMaxTextBytes = 1024 * 1024;
+
+// A folder Play searches for a game's redistributables (runtime/redist_names.h), as far as the page needs.
+struct RedistFolderInfo {
+ std::string path; // relative to the game folder
+ std::size_t entries = 0;
+ std::uint64_t bytes = 0; // of the files directly in it
+ std::vector<std::string> sample; // a few of its names
+ std::string physx_installer; // what Play would install from here, relative to the game folder; empty: none
+};
+
+struct UploadOptions {
+ std::uint64_t length = 0;
+ bool overwrite = false;
+ std::optional<std::string> if_sha256; // the file must still have this hash at the commit
+};
+
+// Reads up to size bytes of the upload: the count, 0 at the end, -1 when the client went away.
+using UploadReader = std::function<std::ptrdiff_t(char* data, std::size_t size)>;
+// Writes bytes to the client; false when it went away.
+using ByteWriter = std::function<bool(const char* data, std::size_t size)>;
+
+// Reads and changes files under FileRoots. Called from the web server's workers, at the same time.
+//
+// Root is process-wide and has no permission bypass on /data: while another thread has raised it, opening a private
+// path fails, and a file made then belongs to root. So every path operation runs under try_hold, which keeps root
+// from being raised (ps5::TryHoldEffectiveUid). It is never held while bytes move, because the runtime worker and
+// durable storage wait on that same lock. The runtime worker holds it for a whole batch, such as a game's setup:
+// file operations then answer 503.
+//
+// This protects against a request that tries to leave a root. It doesn't protect against a program writing on the
+// console at the same time (FTP runs as root, games as this user): a folder swapped for a link in the middle of a
+// request can redirect it. Each step refuses a link it sees, and a failed check never cleans up through that context.
+class FileStore {
+ public:
+ struct Options {
+ // Keeps root from being raised while the result lives; null while another thread holds it. Empty: no such lock.
+ std::function<std::shared_ptr<void>()> try_hold;
+ int hold_retry_ms = 100;
+ int hold_tries = 50;
+ // Bytes that may still be written where this path is; nothing when unknown (the upload goes ahead).
+ std::function<std::optional<std::uint64_t>(const std::string& path)> free_space;
+ // Random text for temporary names. Empty: RandomUuid.
+ std::function<std::optional<std::string>()> random_id;
+ // Seconds since 1970, for the age of leftovers. Empty: the system clock.
+ std::function<std::int64_t()> now;
+ std::int64_t stale_seconds = 3600;
+ // Test hook: called before each step of a commit with its name; false fails the step as a disk error would.
+ std::function<bool(const std::string& step)> fault;
+ };
+
+ explicit FileStore(Options options);
+
+ FileError List(const FileRoot& root, const std::string& path, FileListing* out);
+ FileError OpenForRead(const FileRoot& root, const std::string& path, bool previous, OpenedFile* out);
+ FileError ReadText(const FileRoot& root, const std::string& path, FileText* out);
+ // A complete upload, or a refusal before anything changed (the old file stays). *replaced: a file was replaced.
+ FileError Upload(const FileRoot& root, const std::string& path, const UploadOptions& options, const UploadReader& read,
+ bool* replaced);
+ FileError MakeFolder(const FileRoot& root, const std::string& path);
+ // A file (with its previous version) or an empty folder.
+ FileError Delete(const FileRoot& root, const std::string& path);
+ // Swaps a file with its previous version, or brings back a previous version with no file.
+ FileError Restore(const FileRoot& root, const std::string& path);
+ // A folder as a zip, its entries named from the folder's own name down. Before any byte goes out, a folder too
+ // large for a zip is 413. *started: bytes went out, so a later failure can only cut the connection.
+ FileError WriteZip(const FileRoot& root, const std::string& path, std::int64_t modified, const ByteWriter& write,
+ const std::function<bool()>& begin, bool* started);
+ // The game folder's redistributable folders that exist, by Play's own rules.
+ FileError RedistFolders(const FileRoot& root, std::vector<RedistFolderInfo>* out);
+ // Removes the leftovers of an upload that could not be cleaned up at the time, when the lock is free now.
+ void CleanUpDeferred();
+ std::size_t DeferredCleanups();
+
+ // Runs work under try_hold, with the same retries as a file operation; 503 when it stays busy.
+ FileError WithHold(const std::function<FileError()>& work);
+
+ private:
+ std::shared_ptr<void> Hold();
+ FileError Locate(const FileRoot& root, const std::vector<std::string>& parts, bool writing, bool create_root,
+ std::optional<platform::ManagedDirectory>* out);
+ std::optional<platform::DirectoryPolicy> WritePolicy(const FileRoot& root);
+ bool Step(const std::string& step);
+ std::int64_t Now() const;
+ std::optional<std::string> RandomText();
+ void Sweep(const platform::ManagedDirectory& folder);
+ void DeferCleanup(const FileRoot& root, std::string folder, std::string name, platform::DirectoryPolicy policy);
+ bool RemoveTemporary(const std::string& folder, const std::string& name, platform::DirectoryPolicy policy);
+ bool CommitUpload(const FileRoot& root, const std::vector<std::string>& parts, const std::string& temporary,
+ const UploadOptions& options, const struct stat* expected, bool* replaced, FileError* error);
+
+ Options options_;
+ std::mutex state_mutex_;
+ // One commit at a time: its renames are separate steps, and a no-replace rename is only a check.
+ std::mutex commit_mutex_;
+ std::map<std::string, bool> records_ownership_; // game folder path -> file system keeps owners
+ std::set<std::string> active_uploads_; // absolute paths of temporary files being written
+ struct Deferred {
+ std::string folder;
+ std::string name;
+ platform::DirectoryPolicy policy;
+ };
+ std::vector<Deferred> deferred_;
+};
+
+} // namespace playden::web
diff --git a/src/web/files_api.cpp b/src/web/files_api.cpp
new file mode 100644
index 0000000..34ddf7d
--- /dev/null
+++ b/src/web/files_api.cpp
@@ -0,0 +1,386 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "web/files_api.h"
+
+#include <algorithm>
+#include <chrono>
+#include <cstdio>
+#include <unistd.h>
+#include <vector>
+
+namespace playden::web {
+namespace {
+
+const std::vector<std::pair<std::string, std::string>> kNoStore = {{"Cache-Control", "no-store"}};
+constexpr const char* kCookie = "playden_files";
+
+std::string Quoted(std::string_view text) {
+ std::string out = "\"";
+ for (const char raw : text) {
+ const auto c = static_cast<unsigned char>(raw);
+ if (c == '"' || c == '\\') { out += '\\'; out += raw; }
+ else if (c < 0x20) {
+ char code[8];
+ std::snprintf(code, sizeof code, "\\u%04x", c);
+ out += code;
+ } else out += raw;
+ }
+ return out + "\"";
+}
+
+std::string Field(std::string_view name, std::string_view text) { return Quoted(name) + ":" + Quoted(text); }
+std::string Field(std::string_view name, bool value) { return Quoted(name) + (value ? ":true" : ":false"); }
+std::string Number(std::string_view name, std::uint64_t value) { return Quoted(name) + ":" + std::to_string(value); }
+std::string Signed(std::string_view name, std::int64_t value) { return Quoted(name) + ":" + std::to_string(value); }
+
+void SendJson(Response& response, int status, const std::string& body,
+ std::vector<std::pair<std::string, std::string>> extra = kNoStore) {
+ response.Send(status, "application/json", body, extra);
+}
+
+void Fail(Response& response, const FileError& error) {
+ std::vector<std::pair<std::string, std::string>> headers = kNoStore;
+ if (error.status == 503) headers.emplace_back("Retry-After", "1");
+ response.Send(error.status, "text/plain; charset=utf-8", error.message + "\n", headers);
+}
+
+// A cookie's value from the Cookie header.
+std::string CookieValue(const Request& request, std::string_view name) {
+ const auto header = HeaderValue(request, "cookie");
+ if (!header) return {};
+ std::string_view text = *header;
+ while (!text.empty()) {
+ const auto semicolon = text.find(';');
+ auto pair = text.substr(0, semicolon);
+ text = semicolon == std::string_view::npos ? std::string_view() : text.substr(semicolon + 1);
+ while (!pair.empty() && pair.front() == ' ') pair.remove_prefix(1);
+ const auto equals = pair.find('=');
+ if (equals != std::string_view::npos && pair.substr(0, equals) == name) return std::string(pair.substr(equals + 1));
+ }
+ return {};
+}
+
+// RFC 5987: attr-chars stay, everything else is %XX of its UTF-8 bytes.
+std::string ContentDisposition(std::string_view name) {
+ std::string out = "attachment; filename*=UTF-8''";
+ for (const char raw : name) {
+ const auto c = static_cast<unsigned char>(raw);
+ if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '.' || c == '_' || c == '~') out += raw;
+ else {
+ char code[4];
+ std::snprintf(code, sizeof code, "%%%02X", c);
+ out += code;
+ }
+ }
+ return out;
+}
+
+// A game's file must never run on the origin that holds the cookie: always a download, always sandboxed.
+std::vector<std::pair<std::string, std::string>> DownloadHeaders(std::string_view name) {
+ return {{"Content-Disposition", ContentDisposition(name)},
+ {"Content-Security-Policy", "sandbox"},
+ {"Cache-Control", "no-store"}};
+}
+
+std::string EntryJson(const FileEntry& entry) {
+ std::string out = "{" + Field("name", entry.name) + "," + Field("directory", entry.directory) + "," + Number("size", entry.size) + "," +
+ Signed("modified", entry.modified) + "," + Field("read_only", entry.read_only);
+ if (entry.recoverable) out += "," + Field("recoverable", true);
+ if (entry.previous)
+ out += ",\"previous\":{" + Number("size", entry.previous->size) + "," + Signed("modified", entry.previous->modified) + "}";
+ return out + "}";
+}
+
+std::string GameJson(const FileGame& game) {
+ std::string out = "{" + Field("id", game.id) + "," + Field("name", game.name) + "," + Field("kind", game.kind) + "," + Number("app", game.app) + "," +
+ Field("drive", game.drive) + "," + Field("drive_absent", game.drive_absent) + "," + Field("installed", game.installed) + "," +
+ Field("running", game.running) + "," + Field("setting_up", game.setting_up) + "," + Field("cloud", game.cloud);
+ if (game.last_played) out += "," + Signed("last_played", *game.last_played);
+ if (game.windows_user_bytes) out += "," + Number("windows_user_bytes", *game.windows_user_bytes);
+ if (game.physx_needed) out += "," + Field("physx_needed", *game.physx_needed);
+ return out + "}";
+}
+
+FileStore::Options StoreOptions(const FilesConfig& config) {
+ auto options = config.store;
+ if (config.try_hold) options.try_hold = config.try_hold;
+ if (config.free_space) options.free_space = config.free_space;
+ return options;
+}
+
+} // namespace
+
+// One of the few transfers that may run at once. Lists and small actions don't count.
+class FilesApi::Transfer {
+ public:
+ explicit Transfer(std::atomic<int>& count) : count_(count) { held_ = count_.fetch_add(1) < kMaxTransfers; }
+ ~Transfer() { count_.fetch_sub(1); }
+ bool held() const { return held_; }
+
+ private:
+ std::atomic<int>& count_;
+ bool held_ = false;
+};
+
+FilesApi::FilesApi(FilesConfig config)
+ : config_(std::move(config)), pairing_(config_.pairing), store_(StoreOptions(config_)) {}
+
+void FilesApi::SetCatalog(FileCatalog catalog) {
+ std::lock_guard<std::mutex> lock(mutex_);
+ catalog_ = std::move(catalog);
+}
+
+std::string FilesApi::PairingCode() const { return pairing_.ActiveCode(); }
+
+void FilesApi::CancelPairing() { pairing_.Cancel(); }
+
+bool FilesApi::Paired(const Request& request) {
+ const auto token = CookieValue(request, kCookie);
+ return !token.empty() && pairing_.Paired(token);
+}
+
+bool FilesApi::RequirePaired(const Request& request, Response& response) {
+ if (Paired(request)) return true;
+ SendError(response, 401, "Pair this browser first.");
+ return false;
+}
+
+// A custom header makes a browser ask first (a CORS preflight, never answered), so another web page can't send it.
+bool FilesApi::RequireAction(const Request& request, Response& response) {
+ if (HeaderValue(request, "x-playden-action") == std::string("files")) return true;
+ SendError(response, 403, "Send X-Playden-Action: files.");
+ return false;
+}
+
+std::optional<FileGame> FilesApi::Game(const std::string& id) const {
+ std::lock_guard<std::mutex> lock(mutex_);
+ for (const auto& game : catalog_.games)
+ if (game.id == id) return game;
+ return std::nullopt;
+}
+
+std::vector<std::pair<std::string, FileRoot>> FilesApi::Roots(const FileGame& game) const {
+ std::vector<std::pair<std::string, FileRoot>> roots;
+ if (!game.bottle.empty()) {
+ const auto bottle_root = [&](const char* id, const std::string& below) {
+ FileRoot root;
+ root.path = game.bottle + "/" + below;
+ root.create_from = game.bottle;
+ if (std::string(id) == "user") root.private_paths = config_.private_profile_paths;
+ roots.emplace_back(id, std::move(root));
+ };
+ bottle_root("user", "drive_c/users/prospero");
+ bottle_root("steam", "drive_c/Program Files (x86)/Steam/userdata/0");
+ bottle_root("programdata", "drive_c/ProgramData");
+ bottle_root("public", "drive_c/users/Public/Documents");
+ }
+ if (!game.game_folder.empty() && !game.drive_absent) {
+ FileRoot root;
+ root.path = game.game_folder;
+ root.folder_mode = 0777;
+ root.file_mode = 0666;
+ root.game_folder = true;
+ roots.emplace_back("game", std::move(root));
+ }
+ return roots;
+}
+
+bool FilesApi::Find(const Request& request, Response& response, FileGame* game, FileRoot* root) {
+ const auto id = QueryValue(request.query, "game");
+ const auto named = QueryValue(request.query, "root");
+ const auto found = id ? Game(*id) : std::nullopt;
+ if (!found) {
+ SendError(response, 404, "No such game.");
+ return false;
+ }
+ *game = *found;
+ for (auto& [root_id, value] : Roots(*found))
+ if (named == root_id) {
+ *root = std::move(value);
+ return true;
+ }
+ SendError(response, 404, found->drive_absent ? "Connect this game's drive." : "This game has no such folder.");
+ return false;
+}
+
+void FilesApi::Register(Router& router) {
+ router.Post("/api/pair/start", [this](const Request& request, const std::string&, Response& response) {
+ if (!RequireAction(request, response)) return;
+ std::int64_t wait = 0;
+ const bool replace = QueryValue(request.query, "new") == std::string("1");
+ if (!pairing_.Start(replace, &wait)) {
+ if (wait > 0) {
+ response.Send(429, "text/plain; charset=utf-8", "Too many wrong codes. Try again in a moment.\n",
+ {{"Retry-After", std::to_string(wait / 1000 + 1)}, {"Cache-Control", "no-store"}});
+ return;
+ }
+ return SendError(response, 500, "Playden couldn't make a code.");
+ }
+ SendJson(response, 200, "{\"code_on_tv\":true}");
+ });
+ router.Post("/api/pair/confirm", [this](const Request& request, const std::string&, Response& response) {
+ if (!RequireAction(request, response)) return;
+ std::string token;
+ switch (pairing_.Confirm(QueryValue(request.query, "code").value_or(std::string()), &token)) {
+ case Pairing::ConfirmResult::kPaired:
+ SendJson(response, 200, "{\"paired\":true}",
+ {{"Set-Cookie", std::string(kCookie) + "=" + token + "; HttpOnly; SameSite=Strict; Path=/"},
+ {"Cache-Control", "no-store"}});
+ return;
+ case Pairing::ConfirmResult::kWrong: return SendError(response, 403, "That isn't the code on the TV.");
+ case Pairing::ConfirmResult::kLocked: return SendError(response, 429, "Too many wrong codes. Try again in a moment.");
+ case Pairing::ConfirmResult::kNoCode: return SendError(response, 409, "That code ended. Ask for a new one.");
+ case Pairing::ConfirmResult::kFailed: return SendError(response, 500, "Playden couldn't finish pairing.");
+ }
+ });
+ router.Exact("/api/pair/status", [this](const Request& request, const std::string&, Response& response) {
+ SendJson(response, 200, "{" + Field("paired", Paired(request)) + "}");
+ });
+
+ router.Exact("/api/files/games", [this](const Request& request, const std::string&, Response& response) {
+ if (!RequirePaired(request, response)) return;
+ FileCatalog catalog;
+ {
+ std::lock_guard<std::mutex> lock(mutex_);
+ catalog = catalog_;
+ }
+ std::string body = "{" + Field("known", catalog.known) + "," + Field("setting_up", catalog.setting_up) + ",\"games\":[";
+ for (std::size_t i = 0; i < catalog.games.size(); ++i) body += (i ? "," : "") + GameJson(catalog.games[i]);
+ SendJson(response, 200, body + "]}");
+ });
+ router.Exact("/api/files/game", [this](const Request& request, const std::string&, Response& response) {
+ if (!RequirePaired(request, response)) return;
+ const auto id = QueryValue(request.query, "game");
+ const auto game = id ? Game(*id) : std::nullopt;
+ if (!game) return SendError(response, 404, "No such game.");
+ std::string body = GameJson(*game);
+ body.pop_back();
+ body += ",\"game_folder\":" + Quoted(game->game_folder_shown) + ",\"roots\":[";
+ bool first = true;
+ std::vector<RedistFolderInfo> redist;
+ bool redist_busy = false;
+ for (const auto& [root_id, root] : Roots(*game)) {
+ FileListing listing;
+ // Only whether it exists: a busy lock leaves it unknown, and the page can still open it.
+ const auto error = store_.List(root, std::string(), &listing);
+ body += std::string(first ? "" : ",") + "{" + Field("id", root_id) + "," + Field("exists", error.ok() ? listing.exists : true) + "}";
+ first = false;
+ if (root_id == "game" && store_.RedistFolders(root, &redist).status == 503) redist_busy = true;
+ }
+ body += "],\"redist\":[";
+ for (std::size_t i = 0; i < redist.size(); ++i) {
+ const auto& folder = redist[i];
+ body += std::string(i ? "," : "") + "{" + Field("path", folder.path) + "," + Number("entries", folder.entries) + "," + Number("bytes", folder.bytes) + "," +
+ Field("physx_installer", folder.physx_installer) + ",\"sample\":[";
+ for (std::size_t j = 0; j < folder.sample.size(); ++j) body += (j ? "," : "") + Quoted(folder.sample[j]);
+ body += "]}";
+ }
+ SendJson(response, 200, body + "]," + Field("redist_busy", redist_busy) + "}");
+ });
+ router.Exact("/api/files/list", [this](const Request& request, const std::string&, Response& response) {
+ if (!RequirePaired(request, response)) return;
+ FileGame game;
+ FileRoot root;
+ if (!Find(request, response, &game, &root)) return;
+ FileListing listing;
+ const auto error = store_.List(root, QueryValue(request.query, "path").value_or(std::string()), &listing);
+ if (!error.ok()) return Fail(response, error);
+ std::string body = "{" + Field("exists", listing.exists) + "," + Field("read_only", listing.read_only) + "," + Field("truncated", listing.truncated) + "," +
+ Number("unshown", listing.unshown) + ",\"entries\":[";
+ for (std::size_t i = 0; i < listing.entries.size(); ++i) body += (i ? "," : "") + EntryJson(listing.entries[i]);
+ SendJson(response, 200, body + "]}");
+ });
+ router.Exact("/api/files/download", [this](const Request& request, const std::string&, Response& response) {
+ if (!RequirePaired(request, response)) return;
+ FileGame game;
+ FileRoot root;
+ if (!Find(request, response, &game, &root)) return;
+ Transfer transfer(transfers_);
+ if (!transfer.held()) return Fail(response, {503, "Other transfers are running. Try again in a moment."});
+ OpenedFile file;
+ const auto error = store_.OpenForRead(root, QueryValue(request.query, "path").value_or(std::string()),
+ QueryValue(request.query, "previous") == std::string("1"), &file);
+ if (!error.ok()) return Fail(response, error);
+ if (response.Start(200, "application/octet-stream", file.size, DownloadHeaders(file.name)) && request.method != Method::kHead) {
+ std::vector<char> buffer(256 * 1024);
+ std::uint64_t left = file.size;
+ while (left > 0) {
+ const auto count = ::read(file.fd, buffer.data(), static_cast<std::size_t>(std::min<std::uint64_t>(left, buffer.size())));
+ if (count <= 0 || !response.Body(buffer.data(), static_cast<std::size_t>(count))) break;
+ left -= static_cast<std::uint64_t>(count);
+ }
+ }
+ ::close(file.fd);
+ });
+ router.Exact("/api/files/zip", [this](const Request& request, const std::string&, Response& response) {
+ if (!RequirePaired(request, response)) return;
+ FileGame game;
+ FileRoot root;
+ if (!Find(request, response, &game, &root)) return;
+ Transfer transfer(transfers_);
+ if (!transfer.held()) return Fail(response, {503, "Other transfers are running. Try again in a moment."});
+ const auto path = QueryValue(request.query, "path").value_or(std::string());
+ const auto last_slash = path.rfind('/');
+ const auto base = path.empty() ? game.name : path.substr(last_slash == std::string::npos ? 0 : last_slash + 1);
+ bool started = false;
+ const auto modified = config_.now ? config_.now()
+ : std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count();
+ const auto error = store_.WriteZip(
+ root, path, modified, [&response](const char* data, std::size_t size) { return response.Body(data, size); },
+ [&] {
+ auto headers = DownloadHeaders(base + ".zip");
+ return response.StartChunked(200, "application/zip", headers) && request.method != Method::kHead;
+ },
+ &started);
+ if (!error.ok() && !started) return Fail(response, error);
+ // Cut without the final chunk on a failure: the browser shows the download as failed.
+ if (error.ok() && started) response.FinishChunks();
+ });
+ router.Exact("/api/files/text", [this](const Request& request, const std::string&, Response& response) {
+ if (!RequirePaired(request, response)) return;
+ FileGame game;
+ FileRoot root;
+ if (!Find(request, response, &game, &root)) return;
+ FileText text;
+ const auto error = store_.ReadText(root, QueryValue(request.query, "path").value_or(std::string()), &text);
+ if (!error.ok()) return Fail(response, error);
+ SendJson(response, 200, "{" + Field("sha256", text.sha256) + "," + Field("text", text.text) + "}");
+ });
+
+ router.Post("/api/files/upload", [this](const Request& request, const std::string&, Response& response) {
+ if (!RequirePaired(request, response) || !RequireAction(request, response)) return;
+ if (!request.content_length) return SendError(response, 411, "Send the file's length.");
+ if (!request.read_body) return SendError(response, 400, "No body.");
+ FileGame game;
+ FileRoot root;
+ if (!Find(request, response, &game, &root)) return;
+ Transfer transfer(transfers_);
+ if (!transfer.held()) return Fail(response, {503, "Other transfers are running. Try again in a moment."});
+ UploadOptions options;
+ options.length = *request.content_length;
+ options.overwrite = QueryValue(request.query, "overwrite") == std::string("1");
+ if (auto hash = QueryValue(request.query, "if_sha256"); hash && !hash->empty()) {
+ options.if_sha256 = std::move(*hash);
+ options.overwrite = true;
+ }
+ bool replaced = false;
+ const auto error = store_.Upload(root, QueryValue(request.query, "path").value_or(std::string()), options, request.read_body, &replaced);
+ if (!error.ok()) return Fail(response, error);
+ SendJson(response, 200, "{" + Field("replaced", replaced) + "}");
+ });
+ const auto action = [this](FileError (FileStore::*work)(const FileRoot&, const std::string&)) {
+ return [this, work](const Request& request, const std::string&, Response& response) {
+ if (!RequirePaired(request, response) || !RequireAction(request, response)) return;
+ FileGame game;
+ FileRoot root;
+ if (!Find(request, response, &game, &root)) return;
+ const auto error = (store_.*work)(root, QueryValue(request.query, "path").value_or(std::string()));
+ if (!error.ok()) return Fail(response, error);
+ SendJson(response, 200, "{\"ok\":true}");
+ };
+ };
+ router.Post("/api/files/mkdir", action(&FileStore::MakeFolder));
+ router.Post("/api/files/delete", action(&FileStore::Delete));
+ router.Post("/api/files/restore", action(&FileStore::Restore));
+}
+
+} // namespace playden::web
diff --git a/src/web/files_api.h b/src/web/files_api.h
new file mode 100644
index 0000000..9f07e73
--- /dev/null
+++ b/src/web/files_api.h
@@ -0,0 +1,85 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+#pragma once
+
+#include "web/file_store.h"
+#include "web/pairing.h"
+#include "web/router.h"
+
+#include <atomic>
+#include <cstdint>
+#include <functional>
+#include <mutex>
+#include <optional>
+#include <string>
+#include <vector>
+
+namespace playden::web {
+
+// A game the Files tab offers, as the controller reports it. No path comes from a request: a request names a game's
+// id and one of its roots, and these fields say where those are.
+struct FileGame {
+ std::string id; // "steam-220", "local-<uuid>"
+ std::string name;
+ std::string kind; // "steam" or "imported"
+ std::uint32_t app = 0; // a Steam game's app ID; 0: none
+ std::string bottle; // the private bottle (holding drive_c), as this process opens it; empty: none yet
+ std::string game_folder; // the game's folder, as this process opens it; empty: not installed
+ std::string game_folder_shown; // the same, as the console names it
+ std::string drive; // where the game folder is: "console", "usb", "m2"; empty: none
+ bool drive_absent = false; // its drive isn't connected
+ bool installed = true; // false: uninstalled, its bottle kept
+ bool running = false; // its PS5 title runs or is suspended
+ bool setting_up = false; // this game's setup is what's running
+ bool cloud = false; // Cloud sync is on for it
+ std::optional<std::int64_t> last_played;
+ std::optional<std::uint64_t> windows_user_bytes; // all of drive_c/users, measured earlier
+ std::optional<std::string> physx_needed; // needs PhysX: the version, empty when it isn't known
+};
+
+struct FileCatalog {
+ std::vector<FileGame> games;
+ bool setting_up = false; // a game's setup holds the path lock: file actions answer 503 meanwhile
+ bool known = false; // false until the controller has reported the library
+};
+
+struct FilesConfig {
+ std::function<std::shared_ptr<void>()> try_hold; // ps5::TryHoldEffectiveUid; empty on the host
+ std::function<std::optional<std::uint64_t>(const std::string& path)> free_space;
+ std::vector<std::string> private_profile_paths; // runtime::PrivateProfilePaths()
+ Pairing::Options pairing;
+ FileStore::Options store; // tests; try_hold and free_space above take its fields' place
+ std::function<std::int64_t()> now; // seconds since 1970, stamped on zip entries
+};
+
+// How many downloads, zips and uploads may run at once. The rest answer 503, so lists stay served.
+inline constexpr int kMaxTransfers = 2;
+
+// The Files tab's routes. Every route but pairing's needs a paired browser's cookie; everything that changes
+// something also needs X-Playden-Action: files (Service refuses another Origin, and a name in Host, before this).
+class FilesApi {
+ public:
+ explicit FilesApi(FilesConfig config);
+ void Register(Router& router);
+ void SetCatalog(FileCatalog catalog);
+ std::string PairingCode() const;
+ void CancelPairing();
+
+ private:
+ class Transfer;
+ bool Paired(const Request& request);
+ bool RequirePaired(const Request& request, Response& response);
+ bool RequireAction(const Request& request, Response& response);
+ // The game and root a request names. False: answered.
+ bool Find(const Request& request, Response& response, FileGame* game, FileRoot* root);
+ std::optional<FileGame> Game(const std::string& id) const;
+ std::vector<std::pair<std::string, FileRoot>> Roots(const FileGame& game) const;
+
+ FilesConfig config_;
+ mutable Pairing pairing_;
+ FileStore store_;
+ mutable std::mutex mutex_;
+ FileCatalog catalog_;
+ std::atomic<int> transfers_{0};
+};
+
+} // namespace playden::web
diff --git a/src/web/pairing.cpp b/src/web/pairing.cpp
new file mode 100644
index 0000000..033ba3d
--- /dev/null
+++ b/src/web/pairing.cpp
@@ -0,0 +1,116 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "web/pairing.h"
+
+#include "platform/random_id.h"
+
+#include <algorithm>
+#include <chrono>
+
+namespace playden::web {
+namespace {
+
+std::string RandomHexDigits(const std::function<std::optional<std::string>()>& source, std::size_t digits) {
+ std::string out;
+ while (out.size() < digits) {
+ const auto text = source();
+ if (!text) return {};
+ for (const char c : *text)
+ if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')) out += c;
+ if (text->empty()) return {};
+ }
+ out.resize(digits);
+ return out;
+}
+
+bool EqualConstantTime(const std::string& left, const std::string& right) {
+ if (left.size() != right.size()) return false;
+ unsigned char difference = 0;
+ for (std::size_t i = 0; i < left.size(); ++i)
+ difference = static_cast<unsigned char>(difference | (left[i] ^ right[i]));
+ return difference == 0;
+}
+
+} // namespace
+
+Pairing::Pairing(Options options) : options_(std::move(options)) {
+ if (!options_.random_hex) options_.random_hex = [] { return playden::RandomUuid(); };
+}
+
+std::int64_t Pairing::Now() const {
+ if (options_.now) return options_.now();
+ return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count();
+}
+
+void Pairing::Expire(std::int64_t now) {
+ if (!code_.empty() && now >= code_expires_) code_.clear();
+ if (locked_until_ != 0 && now >= locked_until_) {
+ locked_until_ = 0;
+ wrong_tries_ = 0;
+ }
+}
+
+bool Pairing::Start(bool replace, std::int64_t* wait) {
+ std::lock_guard<std::mutex> lock(mutex_);
+ const auto now = Now();
+ Expire(now);
+ if (wait) *wait = 0;
+ if (locked_until_ != 0) {
+ if (wait) *wait = locked_until_ - now;
+ return false;
+ }
+ if (!code_.empty() && !replace) return true;
+ // 12 hex digits are 48 bits: the bias of taking them modulo a million is far too small to matter.
+ const auto hex = RandomHexDigits(options_.random_hex, 12);
+ if (hex.empty()) return false;
+ std::uint64_t value = 0;
+ for (const char c : hex) value = value * 16 + static_cast<std::uint64_t>(c <= '9' ? c - '0' : c - 'a' + 10);
+ std::string code = std::to_string(value % 1000000);
+ code.insert(0, 6 - code.size(), '0');
+ code_ = std::move(code);
+ code_expires_ = now + options_.code_lifetime_ms;
+ return true;
+}
+
+void Pairing::Cancel() {
+ std::lock_guard<std::mutex> lock(mutex_);
+ code_.clear();
+}
+
+Pairing::ConfirmResult Pairing::Confirm(const std::string& code, std::string* token) {
+ std::lock_guard<std::mutex> lock(mutex_);
+ const auto now = Now();
+ Expire(now);
+ if (locked_until_ != 0) return ConfirmResult::kLocked;
+ if (code_.empty()) return ConfirmResult::kNoCode;
+ if (!EqualConstantTime(code, code_)) {
+ if (++wrong_tries_ >= options_.max_wrong_tries) {
+ locked_until_ = now + options_.lockout_ms;
+ code_.clear();
+ return ConfirmResult::kLocked;
+ }
+ return ConfirmResult::kWrong;
+ }
+ auto minted = RandomHexDigits(options_.random_hex, 64);
+ if (minted.empty()) return ConfirmResult::kFailed;
+ code_.clear();
+ wrong_tries_ = 0;
+ if (tokens_.size() >= options_.max_tokens) tokens_.erase(tokens_.begin());
+ tokens_.push_back(minted);
+ if (token) *token = std::move(minted);
+ return ConfirmResult::kPaired;
+}
+
+bool Pairing::Paired(const std::string& token) {
+ std::lock_guard<std::mutex> lock(mutex_);
+ bool found = false;
+ for (const auto& known : tokens_) found = EqualConstantTime(token, known) || found;
+ return found;
+}
+
+std::string Pairing::ActiveCode() {
+ std::lock_guard<std::mutex> lock(mutex_);
+ Expire(Now());
+ return code_;
+}
+
+} // namespace playden::web
diff --git a/src/web/pairing.h b/src/web/pairing.h
new file mode 100644
index 0000000..95f036c
--- /dev/null
+++ b/src/web/pairing.h
@@ -0,0 +1,53 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+#pragma once
+
+#include <cstdint>
+#include <functional>
+#include <mutex>
+#include <optional>
+#include <string>
+#include <vector>
+
+namespace playden::web {
+
+// Pairing a browser with Playden: the browser asks, the TV shows a 6-digit code, the player types it into the
+// browser, and the browser gets a token for this Playden session. Tokens live in memory only.
+class Pairing {
+ public:
+ struct Options {
+ // Milliseconds of a steady clock. Empty: the system's.
+ std::function<std::int64_t()> now;
+ // Fresh random hex digits, or nothing. Empty: /dev/urandom through RandomUuid.
+ std::function<std::optional<std::string>()> random_hex;
+ std::int64_t code_lifetime_ms = 120'000;
+ std::int64_t lockout_ms = 30'000;
+ int max_wrong_tries = 5;
+ std::size_t max_tokens = 4;
+ };
+ enum class ConfirmResult { kPaired, kWrong, kNoCode, kLocked, kFailed };
+
+ explicit Pairing(Options options);
+ // Shows a code on the TV: the current one, or a new one when asked. False with the lockout's remaining
+ // milliseconds in *wait, or when no random source is available (*wait 0).
+ bool Start(bool replace, std::int64_t* wait);
+ // Ends the code without pairing (the player dismissed it on the TV).
+ void Cancel();
+ ConfirmResult Confirm(const std::string& code, std::string* token);
+ bool Paired(const std::string& token);
+ // The code the TV should show now; empty when none.
+ std::string ActiveCode();
+
+ private:
+ std::int64_t Now() const;
+ void Expire(std::int64_t now);
+ Options options_;
+ std::mutex mutex_;
+ std::string code_;
+ std::int64_t code_expires_ = 0;
+ // Wrong tries count across codes, or asking for a new code would give unlimited guesses.
+ int wrong_tries_ = 0;
+ std::int64_t locked_until_ = 0;
+ std::vector<std::string> tokens_;
+};
+
+} // namespace playden::web
diff --git a/src/web/service.cpp b/src/web/service.cpp
index 571e2fc..5658702 100644
--- a/src/web/service.cpp
+++ b/src/web/service.cpp
@@ -40,7 +40,8 @@ bool SameOrigin(const Request& request) {
}
} // namespace
-Service::Service(ServiceConfig config) : config_(std::move(config)), logs_(config_.paths) {
+Service::Service(ServiceConfig config) : config_(std::move(config)), logs_(config_.paths), files_(config_.files) {
+ files_.Register(router_);
router_.Exact("/", [](const Request&, const std::string&, Response& response) {
const auto* page = FindEmbeddedAsset("/");
if (!page) return SendError(response, 404, "Not found.");
@@ -142,10 +143,17 @@ void Service::SetAccount(Redaction account) {
}
ServiceSnapshot Service::Snapshot() const {
+ auto code = files_.PairingCode();
std::lock_guard<std::mutex> lock(mutex_);
- return snapshot_;
+ auto snapshot = snapshot_;
+ snapshot.pairing_code = std::move(code);
+ return snapshot;
}
+void Service::SetFileCatalog(FileCatalog catalog) { files_.SetCatalog(std::move(catalog)); }
+
+void Service::CancelPairing() { files_.CancelPairing(); }
+
void Service::Shutdown() {
{
std::lock_guard<std::mutex> lock(mutex_);
diff --git a/src/web/service.h b/src/web/service.h
index ee67eef..ffad0db 100644
--- a/src/web/service.h
+++ b/src/web/service.h
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
+#include "web/files_api.h"
#include "web/logs_source.h"
#include "web/router.h"
#include "web/server.h"
@@ -24,6 +25,8 @@ struct ServiceConfig {
std::function<std::int64_t()> now;
// How often the address is looked up again while the server runs: the network can change.
std::chrono::milliseconds address_refresh{30'000};
+ // The Files tab: path lock, free space, and pairing's clock and random source.
+ FilesConfig files;
};
struct ServiceSnapshot {
@@ -33,11 +36,12 @@ struct ServiceSnapshot {
std::string address; // empty: unknown
std::string url; // http://<address>:<port>/ or empty
std::string error; // kFailed: why
+ std::string pairing_code; // a browser asked to pair: the code the TV shows now; empty when none
};
-// Web access, version 1: the page, the log index, single logs and the report, always redacted, and one
-// action: POST /api/quit asks Playden to quit. A worker starts and stops the server, so the caller never
-// waits on a socket.
+// Web access: the page, the log index, single logs and the report, always redacted; the action POST /api/quit asks
+// Playden to quit; and, for a paired browser, a game's files (files_api.h). A worker starts and stops the server, so
+// the caller never waits on a socket.
class Service {
public:
explicit Service(ServiceConfig config);
@@ -50,6 +54,10 @@ class Service {
// The signed-in account to redact exactly; empty when signed out (the patterns still apply).
void SetAccount(Redaction account);
ServiceSnapshot Snapshot() const;
+ // What the Files tab offers; the controller keeps it current.
+ void SetFileCatalog(FileCatalog catalog);
+ // The player dismissed the pairing code on the TV.
+ void CancelPairing();
// True once after the page asked Playden to quit; the caller quits.
bool TakeQuitRequest();
// Stops the server and the worker. Safe to call twice.
@@ -65,6 +73,7 @@ class Service {
std::string LookUpAddress() const;
ServiceConfig config_;
LogsSource logs_;
+ FilesApi files_;
Router router_;
Server server_;
mutable std::mutex mutex_;
diff --git a/src/web/zip.cpp b/src/web/zip.cpp
index 4487248..88b8c25 100644
--- a/src/web/zip.cpp
+++ b/src/web/zip.cpp
@@ -76,8 +76,9 @@ bool StoredZip::Put(const std::string& bytes) {
bool StoredZip::Add(std::string_view name, std::string_view data) {
if (failed_ || finished_ || name.empty() || name.size() > 0xffff || entries_.size() >= 0xffff) return false;
+ if (entry_open_) return false;
// The entry and the central directory record that follows must still fit.
- if (offset_ + 30 + name.size() + data.size() + 46 + name.size() + 22 > kMaxArchiveBytes) {
+ if (!Fits(30 + name.size() + data.size() + 46 + name.size())) {
failed_ = true;
return false;
}
@@ -102,12 +103,70 @@ bool StoredZip::Add(std::string_view name, std::string_view data) {
offset_ += data.size();
}
if (failed_) return false;
+ directory_bytes_ += 46 + name.size();
entries_.push_back(std::move(entry));
return true;
}
+bool StoredZip::Fits(std::uint64_t more) const { return offset_ + directory_bytes_ + more <= kMaxArchiveBytes; }
+
+std::uint64_t StoredZip::EntryOverhead(std::size_t name_size) { return 30 + name_size + 16 + 46 + name_size; }
+
+bool StoredZip::BeginEntry(std::string_view name) {
+ if (failed_ || finished_ || entry_open_ || name.empty() || name.size() > 0xffff || entries_.size() >= 0xffff) return false;
+ if (!Fits(EntryOverhead(name.size()))) {
+ failed_ = true;
+ return false;
+ }
+ open_ = Entry{std::string(name), 0, 0, static_cast<std::uint32_t>(offset_), true};
+ std::string header;
+ Put32(header, 0x04034b50);
+ Put16(header, 20);
+ Put16(header, (1u << 11) | (1u << 3)); // UTF-8 names; sizes and CRC in a data descriptor
+ Put16(header, 0);
+ Put16(header, dos_time_);
+ Put16(header, dos_date_);
+ Put32(header, 0);
+ Put32(header, 0);
+ Put32(header, 0);
+ Put16(header, static_cast<std::uint32_t>(name.size()));
+ Put16(header, 0);
+ header.append(name.data(), name.size());
+ if (!Put(header)) return false;
+ entry_open_ = true;
+ return true;
+}
+
+bool StoredZip::EntryData(const char* data, std::size_t size) {
+ if (failed_ || !entry_open_) return false;
+ if (!Fits(16 + 46 + open_.name.size() + size)) {
+ failed_ = true;
+ return false;
+ }
+ if (size == 0) return true;
+ open_.crc = Crc32(open_.crc, data, size);
+ open_.size += static_cast<std::uint32_t>(size);
+ if (!write_(data, size)) failed_ = true;
+ offset_ += size;
+ return !failed_;
+}
+
+bool StoredZip::EndEntry() {
+ if (failed_ || !entry_open_) return false;
+ std::string descriptor;
+ Put32(descriptor, 0x08074b50);
+ Put32(descriptor, open_.crc);
+ Put32(descriptor, open_.size);
+ Put32(descriptor, open_.size);
+ if (!Put(descriptor)) return false;
+ directory_bytes_ += 46 + open_.name.size();
+ entries_.push_back(std::move(open_));
+ entry_open_ = false;
+ return true;
+}
+
bool StoredZip::Finish() {
- if (failed_ || finished_) return false;
+ if (failed_ || finished_ || entry_open_) return false;
finished_ = true;
const auto directory_offset = static_cast<std::uint32_t>(offset_);
std::string directory;
@@ -115,7 +174,7 @@ bool StoredZip::Finish() {
Put32(directory, 0x02014b50);
Put16(directory, 20); // made by: 2.0, MS-DOS attributes
Put16(directory, 20);
- Put16(directory, 1u << 11);
+ Put16(directory, entry.descriptor ? (1u << 11) | (1u << 3) : 1u << 11);
Put16(directory, 0);
Put16(directory, dos_time_);
Put16(directory, dos_date_);
diff --git a/src/web/zip.h b/src/web/zip.h
index 0233b04..6e15d38 100644
--- a/src/web/zip.h
+++ b/src/web/zip.h
@@ -21,7 +21,14 @@ class StoredZip {
// modified: the time stamped on every entry, in seconds since 1970 (UTC).
StoredZip(Write write, std::int64_t modified);
bool Add(std::string_view name, std::string_view data);
+ // An entry written in pieces: its CRC and size follow it in a data descriptor. Nothing else may be added between
+ // BeginEntry and EndEntry. Each piece counts against the archive limit, with the directory that will follow it.
+ bool BeginEntry(std::string_view name);
+ bool EntryData(const char* data, std::size_t size);
+ bool EndEntry();
bool Finish();
+ // What an entry with this name adds besides its data: its headers, descriptor and directory record.
+ static std::uint64_t EntryOverhead(std::size_t name_size);
std::uint64_t bytes() const { return offset_; }
private:
@@ -30,13 +37,18 @@ class StoredZip {
std::uint32_t crc = 0;
std::uint32_t size = 0;
std::uint32_t offset = 0;
+ bool descriptor = false;
};
bool Put(const std::string& bytes);
+ bool Fits(std::uint64_t more) const;
Write write_;
std::uint16_t dos_time_ = 0;
std::uint16_t dos_date_ = 0;
std::uint64_t offset_ = 0;
+ std::uint64_t directory_bytes_ = 22; // the end record, and each entry's directory record so far
std::vector<Entry> entries_;
+ Entry open_;
+ bool entry_open_ = false;
bool failed_ = false;
bool finished_ = false;
};
diff --git a/tests/web_file_policy_test.cpp b/tests/web_file_policy_test.cpp
new file mode 100644
index 0000000..6ed421c
--- /dev/null
+++ b/tests/web_file_policy_test.cpp
@@ -0,0 +1,49 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "web/file_policy.h"
+
+#include <cstdio>
+#include <cstdlib>
+#include <string>
+
+using namespace playden::web;
+
+#define CHECK(condition) \
+ do { \
+ if (!(condition)) { \
+ std::fprintf(stderr, "%s:%d: CHECK failed: %s\n", __FILE__, __LINE__, #condition); \
+ std::exit(1); \
+ } \
+ } while (false)
+
+int main() {
+ // Hidden, in any case.
+ for (const char* name : {".playden-install.json", ".PLAYDEN-x", ".Playden", ".playden-bak.save", "playden_online.txt", "PLAYDEN_ONLINE.TXT", "SocialClub_ScAuth.txt"})
+ CHECK(HiddenName(name));
+ for (const char* name : {"playden", "my.playden", "save.dat", ".hidden", "steam_settings"}) CHECK(!HiddenName(name));
+
+ // Names.
+ for (const char* name : {"", ".", "..", "a/b", "a\\b", "a\tb", "a\x7f" "b", "\xff", "\xc0\x80", "\xed\xa0\x80", "\xf5\x80\x80\x80", "\xe2\x82"})
+ CHECK(!UsableName(name));
+ for (const char* name : {"save.dat", "Rockstar Games", "Café Étoile", "セーブ", "..hidden", "a..b", "😀"}) CHECK(UsableName(name));
+ CHECK(UsableName(std::string(255, 'a')) && !UsableName(std::string(256, 'a')));
+ CHECK(NewName(std::string(230, 'a')) && !NewName(std::string(231, 'a')));
+ CHECK(!NewName(".playden-x") && !NewName("playden_online.txt") && NewName("save.dat"));
+ CHECK(UsableName(std::string("a\0b", 3)) == false);
+
+ // Paths.
+ CHECK(SplitRelativePath("")->empty());
+ CHECK((*SplitRelativePath("Documents/Rockstar Games/GTA IV")).size() == 3);
+ for (const char* path : {"/etc", "a//b", "a/", "/", "..", "../x", "a/../b", "a/./b", ".", "a\\..\\b", "a/.playden-install.json", ".PLAYDEN-bak.x",
+ "x/playden_online.txt", "a/\xff"})
+ CHECK(!SplitRelativePath(path));
+
+ // Read-only folders, at any depth and in any case.
+ CHECK(ReadOnlyPath({"steam_settings"}) && ReadOnlyPath({"Bin", "x64", "Steam_Settings", "configs.main.ini"}));
+ CHECK(!ReadOnlyPath({"steam_appid.txt"}) && !ReadOnlyPath({}) && !ReadOnlyPath({"steam_settings2"}));
+
+ // Private paths, at or below, in any case.
+ const std::vector<std::string> secret = {"AppData/Local/Launcher"};
+ CHECK(PrivatePath({"AppData", "Local", "Launcher"}, secret) && PrivatePath({"appdata", "LOCAL", "launcher", "token"}, secret));
+ CHECK(!PrivatePath({"AppData", "Local"}, secret) && !PrivatePath({"AppData", "Local", "Other"}, secret) && !PrivatePath({}, secret));
+ std::puts("web_file_policy: ok");
+}
diff --git a/tests/web_file_store_test.cpp b/tests/web_file_store_test.cpp
new file mode 100644
index 0000000..3b8a933
--- /dev/null
+++ b/tests/web_file_store_test.cpp
@@ -0,0 +1,661 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "web/file_store.h"
+
+#include "runtime/artifact_hash.h"
+
+#include <atomic>
+#include <chrono>
+#include <cstdio>
+#include <cstdlib>
+#include <fcntl.h>
+#include <filesystem>
+#include <fstream>
+#include <set>
+#include <string>
+#include <sys/stat.h>
+#include <thread>
+#include <unistd.h>
+#include <vector>
+
+using namespace playden::web;
+namespace fs = std::filesystem;
+using playden::platform::SetOwnershipProbeForTesting;
+
+#define CHECK(condition) \
+ do { \
+ if (!(condition)) { \
+ std::fprintf(stderr, "%s:%d: CHECK failed: %s\n", __FILE__, __LINE__, #condition); \
+ std::exit(1); \
+ } \
+ } while (false)
+
+namespace {
+
+void Put(const fs::path& path, const std::string& text) {
+ fs::create_directories(path.parent_path());
+ std::ofstream(path, std::ios::binary) << text;
+}
+
+std::string Text(const fs::path& path) {
+ std::ifstream in(path, std::ios::binary);
+ return std::string(std::istreambuf_iterator<char>(in), {});
+}
+
+UploadReader Reader(const std::string& text) {
+ auto offset = std::make_shared<std::size_t>(0);
+ return [text, offset](char* data, std::size_t size) -> std::ptrdiff_t {
+ const auto count = std::min(size, text.size() - *offset);
+ std::copy_n(text.data() + *offset, count, data);
+ *offset += count;
+ return static_cast<std::ptrdiff_t>(count);
+ };
+}
+
+FileError Send(FileStore& store, const FileRoot& root, const std::string& path, const std::string& text, bool overwrite = false, bool* replaced = nullptr,
+ std::optional<std::string> hash = std::nullopt) {
+ UploadOptions options;
+ options.length = text.size();
+ options.overwrite = overwrite;
+ options.if_sha256 = std::move(hash);
+ return store.Upload(root, path, options, Reader(text), replaced);
+}
+
+std::vector<std::string> Names(const fs::path& folder) {
+ std::vector<std::string> names;
+ for (const auto& entry : fs::directory_iterator(folder)) names.push_back(entry.path().filename().string());
+ std::sort(names.begin(), names.end());
+ return names;
+}
+
+FileRoot Root(const fs::path& path) {
+ FileRoot root;
+ root.path = path.string();
+ return root;
+}
+
+const FileEntry* Entry(const FileListing& listing, const std::string& name) {
+ for (const auto& entry : listing.entries)
+ if (entry.name == name) return &entry;
+ return nullptr;
+}
+
+} // namespace
+
+int main() {
+ const auto base = fs::canonical(fs::temp_directory_path()) / ("playden-web-files-" + std::to_string(::getpid()));
+ fs::remove_all(base);
+ fs::create_directories(base);
+ const auto folder = base / "root";
+ fs::create_directories(folder);
+ FileRoot root = Root(folder);
+ std::vector<std::string> steps;
+ FileStore::Options options;
+ std::string fail_at;
+ options.fault = [&](const std::string& step) {
+ steps.push_back(step);
+ return step != fail_at;
+ };
+ FileStore store(options);
+
+ // Listing: folders first, hidden names and links out, unusable names counted.
+ Put(folder / "b.sav", "bb");
+ Put(folder / "A.sav", "a");
+ Put(folder / "Sub/inner.txt", "inner");
+ Put(folder / ".playden-install.json", "{}");
+ Put(folder / "playden_online.txt", "token");
+ Put(folder / "steam_settings/configs.user.ini", "name");
+ Put(base / "outside.txt", "secret");
+ fs::create_symlink(base / "outside.txt", folder / "link.txt");
+ fs::create_directory_symlink(base, folder / "linkdir");
+ FileListing listing;
+ CHECK(store.List(root, "", &listing).ok() && listing.exists && !listing.read_only);
+ CHECK(listing.entries.size() == 4);
+ CHECK(listing.entries[0].directory && listing.entries[2].name == "A.sav" && listing.entries[3].name == "b.sav" && listing.entries[3].size == 2);
+ CHECK(Entry(listing, "steam_settings")->read_only && !Entry(listing, "Sub")->read_only);
+ CHECK(!Entry(listing, "link.txt") && !Entry(listing, "linkdir") && !Entry(listing, "playden_online.txt"));
+
+ // A request can't reach out of the root, into a link, or a hidden name.
+ OpenedFile opened;
+ for (const char* path : {"../outside.txt", "link.txt", "linkdir/outside.txt", ".playden-install.json", "playden_online.txt", "PLAYDEN_ONLINE.TXT", "/etc/hosts", "Sub/../../outside.txt"})
+ CHECK(store.OpenForRead(root, path, false, &opened).status != 0);
+ FileListing refused;
+ CHECK(store.List(root, "linkdir", &refused).status != 0 && store.List(root, "..", &refused).status != 0);
+ CHECK(!Send(store, root, "../escape.txt", "x").ok() && !fs::exists(base / "escape.txt"));
+ CHECK(!Send(store, root, "linkdir/escape.txt", "x").ok() && !fs::exists(base / "escape.txt"));
+ CHECK(!Send(store, root, "link.txt", "x", true).ok() && Text(base / "outside.txt") == "secret");
+ CHECK(!store.Delete(root, "link.txt").ok() && fs::is_symlink(folder / "link.txt"));
+ CHECK(!store.MakeFolder(root, "../made").ok() && !fs::exists(base / "made"));
+ fs::remove(folder / "link.txt");
+ fs::remove(folder / "linkdir");
+
+ // A file with another hard link can hold a secret under an innocent name: hidden everywhere.
+ fs::create_hard_link(base / "outside.txt", folder / "innocent.txt");
+ CHECK(store.List(root, "", &listing).ok() && !Entry(listing, "innocent.txt") && listing.unshown == 1);
+ CHECK(store.OpenForRead(root, "innocent.txt", false, &opened).status == 404);
+ FileText text;
+ CHECK(store.ReadText(root, "innocent.txt", &text).status == 404);
+ CHECK(store.Delete(root, "innocent.txt").status == 404);
+ fs::remove(folder / "innocent.txt");
+
+ // A download.
+ CHECK(store.OpenForRead(root, "Sub/inner.txt", false, &opened).ok() && opened.size == 5 && opened.name == "inner.txt");
+ ::close(opened.fd);
+ // The descriptor reads as blocking from here on.
+ CHECK(store.OpenForRead(root, "Sub/inner.txt", false, &opened).ok() && (::fcntl(opened.fd, F_GETFL) & O_NONBLOCK) == 0);
+ ::close(opened.fd);
+ CHECK(store.OpenForRead(root, "Sub", false, &opened).status == 404);
+
+ // Private paths are hidden, too.
+ {
+ FileRoot secret = root;
+ secret.private_paths = {"Sub"};
+ CHECK(store.List(secret, "", &listing).ok() && !Entry(listing, "Sub"));
+ CHECK(store.List(secret, "Sub", &listing).status == 404 && store.OpenForRead(secret, "Sub/inner.txt", false, &opened).status == 404);
+ CHECK(!Send(store, secret, "Sub/new.txt", "x").ok() && !store.Delete(secret, "Sub/inner.txt").ok());
+ bool started = false;
+ std::string zip;
+ CHECK(store.WriteZip(secret, "", 0, [&](const char* d, std::size_t n) { zip.append(d, n); return true; }, [] { return true; }, &started).ok());
+ CHECK(zip.find("inner.txt") == std::string::npos);
+ }
+
+ // A new file: no previous version, and no temporary left.
+ bool replaced = true;
+ CHECK(Send(store, root, "new.sav", "first", false, &replaced).ok() && !replaced);
+ CHECK(Text(folder / "new.sav") == "first");
+ for (const auto& name : Names(folder)) CHECK(name.rfind(".playden-upload-", 0) != 0 && name.rfind(".playden-bak", 0) != 0);
+ CHECK((fs::status(folder / "new.sav").permissions() & fs::perms::all) == (fs::perms::owner_read | fs::perms::owner_write));
+
+ // Taken: refused unless asked to replace; a folder is never replaced.
+ CHECK(Send(store, root, "new.sav", "x").status == 409 && Text(folder / "new.sav") == "first");
+ CHECK(Send(store, root, "Sub", "x", true).status == 409 && fs::is_directory(folder / "Sub"));
+
+ // Replacing keeps one previous version, listed on the file's row.
+ CHECK(Send(store, root, "new.sav", "second", true, &replaced).ok() && replaced);
+ CHECK(Text(folder / "new.sav") == "second" && Text(folder / ".playden-bak.new.sav") == "first");
+ CHECK(Send(store, root, "new.sav", "third", true).ok());
+ CHECK(Text(folder / "new.sav") == "third" && Text(folder / ".playden-bak.new.sav") == "second");
+ CHECK(store.List(root, "", &listing).ok());
+ CHECK(Entry(listing, "new.sav")->previous && Entry(listing, "new.sav")->previous->size == 6 && !Entry(listing, "new.sav")->recoverable);
+ CHECK(!Entry(listing, ".playden-bak.new.sav"));
+ CHECK(store.OpenForRead(root, "new.sav", true, &opened).ok() && opened.size == 6);
+ ::close(opened.fd);
+
+ // Restore swaps the two, and again.
+ CHECK(store.Restore(root, "new.sav").ok());
+ CHECK(Text(folder / "new.sav") == "second" && Text(folder / ".playden-bak.new.sav") == "third");
+ CHECK(store.Restore(root, "new.sav").ok());
+ CHECK(Text(folder / "new.sav") == "third" && Text(folder / ".playden-bak.new.sav") == "second");
+ CHECK(store.Restore(root, "b.sav").status == 404);
+
+ // Read-only folders.
+ CHECK(Send(store, root, "steam_settings/x", "x").status == 403 && Send(store, root, "Steam_Settings/configs.user.ini", "x", true).status == 403);
+ CHECK(store.Delete(root, "steam_settings/configs.user.ini").status == 403 && store.Delete(root, "steam_settings").status == 403);
+ CHECK(store.MakeFolder(root, "steam_settings/x").status == 403 && store.Restore(root, "steam_settings/x").status == 403);
+ CHECK(store.List(root, "steam_settings", &listing).ok() && listing.read_only && Entry(listing, "configs.user.ini")->read_only);
+ CHECK(store.OpenForRead(root, "steam_settings/configs.user.ini", false, &opened).ok());
+ ::close(opened.fd);
+
+ // Each step of a replace failing: the file or its previous version always remains, named by a state.
+ for (const char* step : {"sync-temporary", "remove-backup", "move-current", "sync-backup", "publish", "sync-publish"}) {
+ Put(folder / "fault.sav", "old");
+ Put(folder / ".playden-bak.fault.sav", "older");
+ fail_at = step;
+ const auto error = Send(store, root, "fault.sav", "new", true);
+ fail_at.clear();
+ CHECK(!error.ok());
+ const bool current = fs::exists(folder / "fault.sav");
+ const bool backup = fs::exists(folder / ".playden-bak.fault.sav");
+ CHECK(current || backup);
+ const std::string kept = current ? Text(folder / "fault.sav") : Text(folder / ".playden-bak.fault.sav");
+ CHECK(kept == "old" || kept == "new");
+ // Everything visible after the failure can be listed, and whatever the state, a retry succeeds.
+ CHECK(store.List(root, "", &listing).ok() && Entry(listing, "fault.sav"));
+ CHECK(Send(store, root, "fault.sav", "again", true).ok() && Text(folder / "fault.sav") == "again");
+ fs::remove(folder / "fault.sav");
+ fs::remove(folder / ".playden-bak.fault.sav");
+ for (const auto& name : Names(folder))
+ if (name.rfind(".playden-upload-", 0) == 0) fs::remove(folder / name);
+ }
+
+ // Crash states, as a fresh store finds them on disk.
+ {
+ FileStore fresh{FileStore::Options{}};
+ // Only the previous version: Recoverable, downloadable, restorable.
+ Put(folder / ".playden-bak.crash.sav", "saved");
+ CHECK(fresh.List(root, "", &listing).ok());
+ CHECK(Entry(listing, "crash.sav") && Entry(listing, "crash.sav")->recoverable && Entry(listing, "crash.sav")->size == 5);
+ CHECK(fresh.OpenForRead(root, "crash.sav", true, &opened).ok());
+ ::close(opened.fd);
+ CHECK(fresh.Restore(root, "crash.sav").ok() && Text(folder / "crash.sav") == "saved" && !fs::exists(folder / ".playden-bak.crash.sav"));
+ fs::remove(folder / "crash.sav");
+ // Delete of only a previous version.
+ Put(folder / ".playden-bak.crash.sav", "saved");
+ CHECK(fresh.Delete(root, "crash.sav").ok() && !fs::exists(folder / ".playden-bak.crash.sav"));
+ // A restore's leftovers stay hidden until old; a previous version with them is still restorable.
+ Put(folder / ".playden-restore-abc", "aside");
+ Put(folder / ".playden-bak.crash.sav", "saved");
+ CHECK(fresh.List(root, "", &listing).ok() && !Entry(listing, ".playden-restore-abc") && Entry(listing, "crash.sav")->recoverable);
+ CHECK(fresh.Restore(root, "crash.sav").ok() && Text(folder / "crash.sav") == "saved");
+ fs::remove(folder / "crash.sav");
+ fs::remove(folder / ".playden-restore-abc");
+ }
+
+ // A restore failing at each step keeps the data, under a name a later request finds or the sweep puts back.
+ for (const char* step : {"restore-aside", "restore-back", "restore-sync", "restore-keep"}) {
+ Put(folder / "swap.sav", "cur");
+ Put(folder / ".playden-bak.swap.sav", "bak");
+ fail_at = step;
+ CHECK(!store.Restore(root, "swap.sav").ok());
+ fail_at.clear();
+ std::set<std::string> texts;
+ for (const auto& name : Names(folder))
+ if (name.find("swap.sav") != std::string::npos || name.rfind(".playden-restore-", 0) == 0) texts.insert(Text(folder / name));
+ CHECK(texts.count("bak") == 1 && texts.count("cur") == 1);
+ fs::remove(folder / "swap.sav");
+ fs::remove(folder / ".playden-bak.swap.sav");
+ for (const auto& name : Names(folder))
+ if (name.rfind(".playden-restore-", 0) == 0) fs::remove(folder / name);
+ }
+
+ // Leftovers: old ones go at the next upload; a new one stays, and so does an upload's own temporary.
+ {
+ std::int64_t now = 100000;
+ FileStore::Options timed;
+ timed.now = [&] { return now; };
+ FileStore clock(timed);
+ now = ::time(nullptr) + 7200;
+ Put(folder / ".playden-upload-old", "x");
+ Put(folder / ".playden-restore-old", "x");
+ CHECK(Send(clock, root, "sweep.sav", "x").ok());
+ CHECK(!fs::exists(folder / ".playden-upload-old") && !fs::exists(folder / ".playden-restore-old"));
+ now = ::time(nullptr);
+ Put(folder / ".playden-upload-new", "x");
+ CHECK(Send(clock, root, "sweep.sav", "y", true).ok() && fs::exists(folder / ".playden-upload-new"));
+ fs::remove(folder / ".playden-upload-new");
+ // Opening a folder removes what a cut-off upload left, and it doesn't keep a folder that looks empty from going.
+ now = ::time(nullptr) + 7200;
+ Put(folder / ".playden-upload-cut", "x");
+ {
+ FileListing swept;
+ CHECK(clock.List(root, "", &swept).ok() && !fs::exists(folder / ".playden-upload-cut"));
+ }
+ Put(folder / "looks-empty/.playden-upload-cut", "x");
+ CHECK(clock.Delete(root, "looks-empty").ok() && !fs::exists(folder / "looks-empty"));
+ fs::create_directories(folder / "not-empty");
+ Put(folder / "not-empty/.playden-bak.keep", "x");
+ CHECK(clock.Delete(root, "not-empty").status == 409 && fs::exists(folder / "not-empty/.playden-bak.keep"));
+ fs::remove_all(folder / "not-empty");
+ now = ::time(nullptr);
+ // An active upload is never swept, however old: the clock jumps while it streams, and another upload sweeps.
+ now = ::time(nullptr) + 7200;
+ std::atomic<int> phase{0};
+ UploadOptions slow;
+ slow.length = 4;
+ std::thread uploading([&] {
+ std::size_t sent = 0;
+ const auto error = clock.Upload(root, "slow.sav", slow, [&](char* data, std::size_t) -> std::ptrdiff_t {
+ if (sent++ == 1) {
+ phase = 1;
+ while (phase != 2) std::this_thread::sleep_for(std::chrono::milliseconds(5));
+ }
+ if (sent > 4) return 0;
+ data[0] = 'z';
+ return 1;
+ }, nullptr);
+ CHECK(error.ok());
+ });
+ while (phase != 1) std::this_thread::sleep_for(std::chrono::milliseconds(5));
+ CHECK(Send(clock, root, "other.sav", "x").ok());
+ phase = 2;
+ uploading.join();
+ CHECK(Text(folder / "slow.sav") == "zzzz");
+ fs::remove(folder / "slow.sav");
+ fs::remove(folder / "other.sav");
+ fs::remove(folder / "sweep.sav");
+ fs::remove(folder / ".playden-bak.sweep.sav");
+ }
+
+ // A restore that stopped, on a save last changed long ago: its temporary is the player's file, and stays until
+ // the temporary itself is old. Then it goes back where it belongs.
+ {
+ std::int64_t later = ::time(nullptr);
+ std::string stop_at = "restore-back";
+ FileStore::Options timed;
+ timed.now = [&] { return later; };
+ timed.fault = [&](const std::string& step) { return step != stop_at; };
+ FileStore clock(timed);
+ Put(folder / "old.sav", "newest");
+ Put(folder / ".playden-bak.old.sav", "older");
+ fs::last_write_time(folder / "old.sav", fs::file_time_type::clock::now() - std::chrono::hours(48));
+ CHECK(!clock.Restore(root, "old.sav").ok());
+ std::string aside;
+ for (const auto& name : Names(folder))
+ if (name.rfind(".playden-restore-", 0) == 0) aside = name;
+ CHECK(!aside.empty() && Text(folder / aside) == "newest");
+ stop_at.clear();
+ CHECK(Send(clock, root, "other.sav", "x").ok());
+ CHECK(fs::exists(folder / aside));
+ later += 7200;
+ CHECK(Send(clock, root, "other.sav", "y", true).ok());
+ CHECK(!fs::exists(folder / aside) && Text(folder / "old.sav") == "newest" && Text(folder / ".playden-bak.old.sav") == "older");
+ // Stopped after the previous version came back: the swap finishes.
+ stop_at = "restore-keep";
+ CHECK(!clock.Restore(root, "old.sav").ok());
+ stop_at.clear();
+ CHECK(Text(folder / "old.sav") == "older" && !fs::exists(folder / ".playden-bak.old.sav"));
+ later += 7200;
+ {
+ FileListing swept;
+ CHECK(clock.List(root, "", &swept).ok());
+ }
+ CHECK(Text(folder / "old.sav") == "older" && Text(folder / ".playden-bak.old.sav") == "newest");
+ // The file and its previous version are both back: the temporary was replaced as usual.
+ Put(folder / ".playden-restore-1-x.old.sav", "oldest");
+ CHECK(Send(clock, root, "other.sav", "z", true).ok());
+ CHECK(!fs::exists(folder / ".playden-restore-1-x.old.sav") && Text(folder / "old.sav") == "older" && Text(folder / ".playden-bak.old.sav") == "newest");
+ fs::remove(folder / "old.sav");
+ fs::remove(folder / "other.sav");
+ fs::remove(folder / ".playden-bak.other.sav");
+ fs::remove(folder / ".playden-bak.old.sav");
+ }
+
+ // A cut upload: the old file stays, and its temporary goes.
+ {
+ Put(folder / "cut.sav", "old");
+ UploadOptions cut;
+ cut.length = 100;
+ cut.overwrite = true;
+ int reads = 0;
+ CHECK(store.Upload(root, "cut.sav", cut, [&](char* data, std::size_t) -> std::ptrdiff_t {
+ if (reads++ > 0) return -1;
+ data[0] = 'n';
+ return 1;
+ }, nullptr).status == 408);
+ CHECK(Text(folder / "cut.sav") == "old");
+ for (const auto& name : Names(folder)) CHECK(name.rfind(".playden-upload-", 0) != 0);
+ CHECK(!fs::exists(folder / ".playden-bak.cut.sav"));
+ fs::remove(folder / "cut.sav");
+ }
+
+ // The path lock: never held while bytes move; busy answers 503; a failed upload's cleanup waits for it.
+ {
+ std::atomic<bool> busy{false};
+ std::atomic<int> holds_live{0};
+ FileStore::Options locked;
+ locked.hold_tries = 2;
+ locked.hold_retry_ms = 1;
+ locked.try_hold = [&]() -> std::shared_ptr<void> {
+ if (busy) return nullptr;
+ ++holds_live;
+ return std::shared_ptr<void>(new int(0), [&](void* held) { delete static_cast<int*>(held); --holds_live; });
+ };
+ FileStore guarded(locked);
+ busy = true;
+ CHECK(guarded.List(root, "", &listing).status == 503);
+ CHECK(guarded.OpenForRead(root, "b.sav", false, &opened).status == 503);
+ CHECK(Send(guarded, root, "held.sav", "x").status == 503);
+ CHECK(guarded.Delete(root, "b.sav").status == 503 && guarded.MakeFolder(root, "held").status == 503 && guarded.Restore(root, "b.sav").status == 503);
+ busy = false;
+ CHECK(guarded.OpenForRead(root, "b.sav", false, &opened).ok() && holds_live == 0);
+ ::close(opened.fd);
+ UploadOptions watched;
+ watched.length = 4;
+ int reads = 0;
+ CHECK(guarded.Upload(root, "held.sav", watched, [&](char* data, std::size_t) -> std::ptrdiff_t {
+ CHECK(holds_live == 0);
+ if (++reads > 4) return 0;
+ data[0] = 'h';
+ return 1;
+ }, nullptr).ok());
+ CHECK(Text(folder / "held.sav") == "hhhh" && holds_live == 0);
+ fs::remove(folder / "held.sav");
+ // The lock taken during the upload, and the client goes away: the temporary waits, then goes.
+ watched.overwrite = false;
+ reads = 0;
+ CHECK(guarded.Upload(root, "held.sav", watched, [&](char* data, std::size_t) -> std::ptrdiff_t {
+ if (reads++ == 1) { busy = true; return -1; }
+ data[0] = 'h';
+ return 1;
+ }, nullptr).status == 408);
+ CHECK(guarded.DeferredCleanups() == 1);
+ bool left = false;
+ for (const auto& name : Names(folder)) left = left || name.rfind(".playden-upload-", 0) == 0;
+ CHECK(left);
+ busy = false;
+ CHECK(guarded.List(root, "", &listing).ok() && guarded.DeferredCleanups() == 0);
+ for (const auto& name : Names(folder)) CHECK(name.rfind(".playden-upload-", 0) != 0);
+ // Busy at the commit, after the bytes arrived: the old file stays, and the upload says busy.
+ Put(folder / "late.sav", "old");
+ watched.overwrite = true;
+ reads = 0;
+ CHECK(guarded.Upload(root, "late.sav", watched, [&](char* data, std::size_t) -> std::ptrdiff_t {
+ if (++reads > 4) return 0;
+ if (reads == 4) busy = true;
+ data[0] = 'n';
+ return 1;
+ }, nullptr).status == 503);
+ CHECK(Text(folder / "late.sav") == "old");
+ busy = false;
+ CHECK(guarded.List(root, "", &listing).ok());
+ fs::remove(folder / "late.sav");
+ }
+
+ // Two uploads racing for a free name: one wins, one gets 409, and the winner's bytes are whole.
+ {
+ for (int round = 0; round < 20; ++round) {
+ const auto name = "race" + std::to_string(round) + ".sav";
+ std::atomic<int> ready{0};
+ FileError results[2];
+ std::thread racers[2];
+ for (int i = 0; i < 2; ++i)
+ racers[i] = std::thread([&, i] {
+ const std::string body(1024, static_cast<char>('a' + i));
+ UploadOptions race;
+ race.length = body.size();
+ auto next = Reader(body);
+ bool waited = false;
+ results[i] = store.Upload(root, name, race, [&](char* data, std::size_t size) -> std::ptrdiff_t {
+ if (!waited) {
+ waited = true;
+ ++ready;
+ while (ready != 2) std::this_thread::yield();
+ }
+ return next(data, size);
+ }, nullptr);
+ });
+ for (auto& racer : racers) racer.join();
+ CHECK(results[0].ok() != results[1].ok());
+ CHECK((results[0].ok() ? results[1] : results[0]).status == 409);
+ const auto saved = Text(folder / name);
+ CHECK(saved == std::string(1024, results[0].ok() ? 'a' : 'b'));
+ fs::remove(folder / name);
+ }
+ for (const auto& name : Names(folder)) CHECK(name.rfind(".playden-upload-", 0) != 0);
+ }
+ // Restore and delete racing: at the end the data is either gone by request or whole, never half swapped.
+ {
+ for (int round = 0; round < 20; ++round) {
+ Put(folder / "both.sav", "cur");
+ Put(folder / ".playden-bak.both.sav", "bak");
+ std::thread restoring([&] { store.Restore(root, "both.sav"); });
+ std::thread deleting([&] { store.Delete(root, "both.sav"); });
+ restoring.join();
+ deleting.join();
+ CHECK(!fs::exists(folder / "both.sav") && !fs::exists(folder / ".playden-bak.both.sav"));
+ for (const auto& name : Names(folder)) CHECK(name.rfind(".playden-restore-", 0) != 0);
+ }
+ }
+
+ // The hash an editor saw: refused once the file changed, with the same size and time too.
+ {
+ Put(folder / "conf.ini", "a=1\n");
+ CHECK(store.ReadText(root, "conf.ini", &text).ok() && text.text == "a=1\n");
+ const auto hash = text.sha256;
+ CHECK(Send(store, root, "conf.ini", "a=2\n", true, nullptr, hash).ok() && Text(folder / "conf.ini") == "a=2\n");
+ const auto written = fs::last_write_time(folder / "conf.ini");
+ Put(folder / "conf.ini", "a=3\n");
+ fs::last_write_time(folder / "conf.ini", written);
+ CHECK(Send(store, root, "conf.ini", "a=4\n", true, nullptr, hash).status == 409 && Text(folder / "conf.ini") == "a=3\n");
+ // Changed while the upload was on its way: refused at the commit, and no lock held for the read.
+ CHECK(store.ReadText(root, "conf.ini", &text).ok());
+ {
+ UploadOptions during;
+ during.length = 4;
+ during.overwrite = true;
+ during.if_sha256 = text.sha256;
+ const std::string payload = "a=5\n";
+ std::size_t sent = 0;
+ CHECK(store.Upload(root, "conf.ini", during, [&](char* data, std::size_t) -> std::ptrdiff_t {
+ if (sent == 0) Put(folder / "conf.ini", "a=9\n");
+ if (sent >= payload.size()) return 0;
+ data[0] = payload[sent++];
+ return 1;
+ }, nullptr).status == 409);
+ CHECK(Text(folder / "conf.ini") == "a=9\n");
+ }
+ fs::remove(folder / ".playden-bak.conf.ini");
+ fs::remove(folder / "conf.ini");
+ CHECK(Send(store, root, "conf.ini", "a=4\n", true, nullptr, hash).status == 409 && !fs::exists(folder / "conf.ini"));
+ Put(folder / "binary.dat", std::string("\xff\xfe\0", 3));
+ CHECK(store.ReadText(root, "binary.dat", &text).status == 415);
+ Put(folder / "large.txt", std::string(kMaxTextBytes + 1, 'a'));
+ CHECK(store.ReadText(root, "large.txt", &text).status == 413);
+ fs::remove(folder / "binary.dat");
+ fs::remove(folder / "large.txt");
+ }
+
+ // New folders and deletes.
+ CHECK(store.MakeFolder(root, "made").ok() && fs::is_directory(folder / "made"));
+ CHECK(store.MakeFolder(root, "made").status == 409 && store.MakeFolder(root, "a/b").status == 404);
+ CHECK(store.MakeFolder(root, ".playden-x").status == 400 && store.MakeFolder(root, "bad\\name").status == 400);
+ CHECK(Send(store, root, "made/f.txt", "x").ok());
+ CHECK(store.Delete(root, "made").status == 409 && fs::exists(folder / "made/f.txt"));
+ CHECK(Send(store, root, "made/f.txt", "y", true).ok() && fs::exists(folder / "made/.playden-bak.f.txt"));
+ CHECK(store.Delete(root, "made/f.txt").ok() && !fs::exists(folder / "made/f.txt") && !fs::exists(folder / "made/.playden-bak.f.txt"));
+ CHECK(store.Delete(root, "made").ok() && !fs::exists(folder / "made"));
+ CHECK(store.Delete(root, "made").status == 404);
+
+ // A root not made yet: empty to read, made by the first write, from an existing folder only.
+ {
+ const auto bottle = base / "bottle";
+ fs::create_directories(bottle / "drive_c");
+ FileRoot steam;
+ steam.path = (bottle / "drive_c/Program Files (x86)/Steam/userdata/0").string();
+ steam.create_from = bottle.string();
+ CHECK(store.List(steam, "", &listing).ok() && !listing.exists && listing.entries.empty());
+ CHECK(Send(store, steam, "sub/x.sav", "x").status == 404);
+ CHECK(Send(store, steam, "x.sav", "x").ok() && Text(steam.path + "/x.sav") == "x");
+ CHECK((fs::status(steam.path).permissions() & fs::perms::all) == fs::perms::owner_all);
+ FileRoot never = steam;
+ never.path = (base / "nothing/here").string();
+ never.create_from.clear();
+ CHECK(Send(store, never, "x.sav", "x").status == 404 && !fs::exists(base / "nothing"));
+ // Bottle modes: a shared profile and a private one both work.
+ for (const auto mode : {fs::perms::owner_all, fs::perms::all}) {
+ const auto profile = bottle / "drive_c/users/prospero";
+ fs::create_directories(profile);
+ fs::permissions(profile, mode);
+ fs::permissions(bottle / "drive_c/users", fs::perms::owner_all | fs::perms::group_exec | fs::perms::others_exec);
+ CHECK(store.List(Root(profile), "", &listing).ok());
+ CHECK(Send(store, Root(profile), "m.sav", "x", true).ok());
+ }
+ }
+
+ // A game folder with no owners (exFAT): the write asks once; a reader never makes it ask.
+ {
+ static int probes = 0;
+ SetOwnershipProbeForTesting([](const fs::path&) -> std::optional<bool> { ++probes; return false; });
+ FileStore game_store{FileStore::Options{}};
+ const auto game = base / "game";
+ Put(game / "bin/game.exe", "exe");
+ Put(game / "empty.dat", "");
+ FileRoot game_root = Root(game);
+ game_root.game_folder = true;
+ game_root.file_mode = 0666;
+ game_root.folder_mode = 0777;
+ CHECK(game_store.List(game_root, "", &listing).ok() && Entry(listing, "empty.dat")->size == 0);
+ CHECK(game_store.OpenForRead(game_root, "empty.dat", false, &opened).ok());
+ ::close(opened.fd);
+ CHECK(probes == 0);
+ CHECK(Send(game_store, game_root, "bin/mod.dll", "m").ok() && probes == 1);
+ CHECK(Send(game_store, game_root, "bin/mod.dll", "n", true).ok() && probes == 1);
+ CHECK(Text(game / "bin/mod.dll") == "n" && Text(game / "bin/.playden-bak.mod.dll") == "m");
+ CHECK(game_store.Restore(game_root, "bin/mod.dll").ok() && Text(game / "bin/mod.dll") == "m");
+ CHECK(game_store.MakeFolder(game_root, "_Redist").ok());
+ SetOwnershipProbeForTesting(nullptr);
+ // Keeping owners: the modes of a game folder.
+ FileStore owned{FileStore::Options{}};
+ CHECK(Send(owned, game_root, "bin/own.dll", "o").ok());
+ CHECK((fs::status(game / "bin/own.dll").permissions() & fs::perms::all) ==
+ (fs::perms::owner_read | fs::perms::owner_write | fs::perms::group_read | fs::perms::group_write | fs::perms::others_read | fs::perms::others_write));
+ CHECK(owned.MakeFolder(game_root, "owned").ok());
+ CHECK((fs::status(game / "owned").permissions() & fs::perms::all) == fs::perms::all);
+
+ // Redistributable folders, by Play's rules: at the top and one level down.
+ Put(game / "_Redist/PhysX_9.09.msi", "p");
+ Put(game / "Inner/DirectX/DXSETUP.exe", "d");
+ Put(game / "Inner/Bin/PhysX_9.exe", "not in a redist folder");
+ Put(game / "Inner/Other/Support/deep.txt", "too far down");
+ std::vector<RedistFolderInfo> redist;
+ CHECK(owned.RedistFolders(game_root, &redist).ok() && redist.size() == 2);
+ CHECK(redist[0].path == "_Redist" && redist[0].physx_installer == "_Redist/PhysX_9.09.msi" && redist[0].entries == 1);
+ CHECK(redist[1].path == "Inner/DirectX" && redist[1].physx_installer.empty() && redist[1].sample[0] == "DXSETUP.exe");
+ }
+
+ // A file another user owns can't be replaced or deleted, in plain words. Only root can arrange it.
+ if (::geteuid() == 0) {
+ Put(folder / "theirs.sav", "x");
+ CHECK(::chown((folder / "theirs.sav").c_str(), 12345, 12345) == 0);
+ CHECK(Send(store, root, "theirs.sav", "y", true).status == 403);
+ CHECK(store.Delete(root, "theirs.sav").status == 403);
+ }
+
+ // A folder as a zip.
+ {
+ const auto zipped = base / "zipped";
+ Put(zipped / "a.txt", "alpha");
+ Put(zipped / "deep/er/b.txt", "bravo");
+ Put(zipped / ".playden-bak.a.txt", "hidden");
+ Put(zipped / "playden_online.txt", "token");
+ Put(base / "outside2.txt", "secret");
+ fs::create_symlink(base / "outside2.txt", zipped / "link.txt");
+ fs::create_hard_link(base / "outside2.txt", zipped / "hard.txt");
+ std::string zip;
+ bool started = false, began = false;
+ const auto error = store.WriteZip(Root(zipped), "", 1700000000, [&](const char* data, std::size_t size) { zip.append(data, size); return true; },
+ [&] { began = true; return true; }, &started);
+ CHECK(error.ok() && began && started);
+ CHECK(zip.find("zipped/a.txt") != std::string::npos && zip.find("zipped/deep/er/b.txt") != std::string::npos);
+ CHECK(zip.find("alpha") != std::string::npos && zip.find("bravo") != std::string::npos);
+ for (const char* absent : {"hidden", "token", "secret", "link.txt", "hard.txt", ".playden"}) CHECK(zip.find(absent) == std::string::npos);
+ const auto archive = base / "out.zip";
+ std::ofstream(archive, std::ios::binary) << zip;
+ const auto check = "python3 -I -c \"import zipfile,sys; z=zipfile.ZipFile(sys.argv[1]); assert z.testzip() is None; assert sorted(z.namelist())==['zipped/a.txt','zipped/deep/er/b.txt']; "
+ "assert z.read('zipped/a.txt')==b'alpha'; assert all(i.flag_bits & 8 for i in z.infolist())\" '" + archive.string() + "'";
+ CHECK(std::system(check.c_str()) == 0);
+ // A subfolder is named from itself.
+ zip.clear();
+ CHECK(store.WriteZip(Root(zipped), "deep", 0, [&](const char* data, std::size_t size) { zip.append(data, size); return true; }, [] { return true; }, &started).ok());
+ CHECK(zip.find("deep/er/b.txt") != std::string::npos && zip.find("zipped/") == std::string::npos);
+ // A folder deeper than a zip goes is refused before the first byte, not left out.
+ {
+ auto deep = base / "deep";
+ for (int i = 0; i < 40; ++i) deep /= "d";
+ Put(deep / "lost.txt", "x");
+ began = false;
+ CHECK(store.WriteZip(Root(base / "deep"), "", 0, [&](const char*, std::size_t) { return true; }, [&] { began = true; return true; }, &started).status == 413);
+ CHECK(!began && !started);
+ }
+ // Nothing goes out when it won't fit: a sparse file past the limit is 413 before the first byte.
+ const auto large = base / "large";
+ fs::create_directories(large);
+ { std::ofstream(large / "big.bin"); }
+ fs::resize_file(large / "big.bin", 0x80000000ull);
+ began = false;
+ CHECK(store.WriteZip(Root(large), "", 0, [&](const char*, std::size_t) { return true; }, [&] { began = true; return true; }, &started).status == 413);
+ CHECK(!began && !started);
+ }
+
+ fs::remove_all(base);
+ std::puts("web_file_store: ok");
+}
diff --git a/tests/web_files_api_test.cpp b/tests/web_files_api_test.cpp
new file mode 100644
index 0000000..509352d
--- /dev/null
+++ b/tests/web_files_api_test.cpp
@@ -0,0 +1,301 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "web/service.h"
+
+#include <arpa/inet.h>
+#include <chrono>
+#include <cstdio>
+#include <cstdlib>
+#include <filesystem>
+#include <fstream>
+#include <netinet/in.h>
+#include <string>
+#include <sys/socket.h>
+#include <thread>
+#include <unistd.h>
+#include <vector>
+
+using namespace playden::web;
+namespace fs = std::filesystem;
+
+#define CHECK(condition) \
+ do { \
+ if (!(condition)) { \
+ std::fprintf(stderr, "%s:%d: CHECK failed: %s\n", __FILE__, __LINE__, #condition); \
+ std::exit(1); \
+ } \
+ } while (false)
+
+namespace {
+void Put(const fs::path& path, const std::string& text) {
+ fs::create_directories(path.parent_path());
+ std::ofstream(path, std::ios::binary) << text;
+}
+std::string Text(const fs::path& path) {
+ std::ifstream in(path, std::ios::binary);
+ return std::string(std::istreambuf_iterator<char>(in), {});
+}
+int Open(std::uint16_t port) {
+ const int fd = ::socket(AF_INET, SOCK_STREAM, 0);
+ sockaddr_in address{};
+ address.sin_family = AF_INET;
+ address.sin_port = htons(port);
+ address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
+ CHECK(fd >= 0 && ::connect(fd, reinterpret_cast<sockaddr*>(&address), sizeof address) == 0);
+ return fd;
+}
+std::string Exchange(std::uint16_t port, const std::string& text) {
+ const int fd = Open(port);
+ CHECK(::send(fd, text.data(), text.size(), 0) == static_cast<ssize_t>(text.size()));
+ std::string answer;
+ char buffer[8192];
+ ssize_t count;
+ while ((count = ::recv(fd, buffer, sizeof buffer, 0)) > 0) answer.append(buffer, static_cast<std::size_t>(count));
+ ::close(fd);
+ return answer;
+}
+int Status(const std::string& answer) { return answer.size() > 12 ? std::atoi(answer.c_str() + 9) : 0; }
+std::string Body(const std::string& answer) {
+ const auto end = answer.find("\r\n\r\n");
+ return end == std::string::npos ? std::string() : answer.substr(end + 4);
+}
+std::string Encode(const std::string& text) {
+ std::string out;
+ for (const char raw : text) {
+ const auto c = static_cast<unsigned char>(raw);
+ if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '.' || c == '_') out += raw;
+ else { char code[4]; std::snprintf(code, sizeof code, "%%%02X", c); out += code; }
+ }
+ return out;
+}
+} // namespace
+
+int main() {
+ const auto base = fs::canonical(fs::temp_directory_path()) / ("playden-web-api-" + std::to_string(::getpid()));
+ fs::remove_all(base);
+ const auto bottle = base / "games/steam-12210/library/prefixes/game";
+ const auto profile = bottle / "drive_c/users/prospero";
+ Put(profile / "Documents/Rockstar Games/GTA IV/Profiles/ABC/SGTA400", "save");
+ fs::create_directories(bottle / "drive_c/ProgramData");
+ const auto game_folder = base / "usb/playden/import/Game";
+ Put(game_folder / "game.exe", "exe");
+ Put(game_folder / "page.html", "<script>alert(1)</script>");
+ Put(game_folder / "steam_settings/configs.user.ini", "account");
+ Put(game_folder / ".playden-install.json", "{}");
+ Put(game_folder / "_Redist/PhysX.msi", "p");
+
+ ServiceConfig config;
+ config.paths = {(base / "logs").string(), (base / "homebrew").string(), (base / "kits").string(), (base / "app").string()};
+ config.server.first_port = config.server.last_port = 0;
+ config.server.loopback_only = true;
+ config.server.poll_interval_ms = 20;
+ config.server.body_timeout_ms = 500;
+ config.files.private_profile_paths = {"AppData/Local/Launcher"};
+ fs::create_directories(base / "logs");
+ Service service(std::move(config));
+ FileCatalog catalog;
+ catalog.known = true;
+ {
+ FileGame gta;
+ gta.id = "steam-12210";
+ gta.name = "Grand \"Theft\" Auto IV";
+ gta.kind = "steam";
+ gta.app = 12210;
+ gta.bottle = bottle.string();
+ gta.game_folder = game_folder.string();
+ gta.game_folder_shown = "/mnt/usb0/playden/import/Game";
+ gta.drive = "usb";
+ gta.running = true;
+ gta.windows_user_bytes = 123;
+ gta.physx_needed = "2.8.1";
+ catalog.games.push_back(gta);
+ FileGame kept;
+ kept.id = "steam-274520";
+ kept.name = "Darkwood";
+ kept.kind = "steam";
+ kept.bottle = bottle.string();
+ kept.installed = false;
+ catalog.games.push_back(kept);
+ FileGame gone;
+ gone.id = "local-gone";
+ gone.name = "Unplugged";
+ gone.kind = "imported";
+ gone.bottle = bottle.string();
+ gone.game_folder = (base / "absent").string();
+ gone.drive = "usb";
+ gone.drive_absent = true;
+ catalog.games.push_back(gone);
+ }
+ service.SetFileCatalog(catalog);
+ service.SetEnabled(true);
+ ServiceSnapshot snapshot;
+ for (int i = 0; i < 200 && snapshot.state != ServiceSnapshot::State::kOn; ++i) {
+ snapshot = service.Snapshot();
+ std::this_thread::sleep_for(std::chrono::milliseconds(10));
+ }
+ CHECK(snapshot.state == ServiceSnapshot::State::kOn);
+ const auto port = snapshot.port;
+ const std::string host = "Host: 127.0.0.1:" + std::to_string(port) + "\r\n";
+
+ const auto get = [&](const std::string& target, const std::string& cookie = {}) {
+ return Exchange(port, "GET " + target + " HTTP/1.1\r\n" + host + (cookie.empty() ? "" : "Cookie: " + cookie + "\r\n") + "\r\n");
+ };
+ const auto post = [&](const std::string& target, const std::string& cookie, const std::string& body = {}, const std::string& more = "X-Playden-Action: files\r\n") {
+ return Exchange(port, "POST " + target + " HTTP/1.1\r\n" + host + more + (cookie.empty() ? "" : "Cookie: " + cookie + "\r\n") +
+ "Content-Length: " + std::to_string(body.size()) + "\r\n\r\n" + body);
+ };
+ const std::string game = "game=steam-12210&root=";
+
+ // Unpaired: nothing about a game, nothing changes.
+ CHECK(Body(get("/api/pair/status")).find("\"paired\":false") != std::string::npos);
+ for (const std::string& target : std::vector<std::string>{"/api/files/games", "/api/files/game?game=steam-12210", "/api/files/list?" + game + "user", "/api/files/download?" + game + "game&path=game.exe",
+ "/api/files/zip?" + game + "game", "/api/files/text?" + game + "game&path=game.exe"})
+ CHECK(Status(get(target)) == 401);
+ for (const std::string& target : std::vector<std::string>{"/api/files/upload?" + game + "game&path=x", "/api/files/mkdir?" + game + "game&path=x", "/api/files/delete?" + game + "game&path=game.exe", "/api/files/restore?" + game + "game&path=x"}) {
+ CHECK(Status(post(target, "", "data")) == 401);
+ CHECK(Status(post(target, "playden_files=0123456789", "data")) == 401);
+ }
+ CHECK(fs::exists(game_folder / "game.exe") && !fs::exists(game_folder / "x"));
+
+ // Pairing needs the header, a code the TV shows, and answers with a cookie the page's scripts can't read.
+ CHECK(Status(post("/api/pair/start", "", "", "")) == 403);
+ CHECK(service.Snapshot().pairing_code.empty());
+ CHECK(Status(post("/api/pair/start", "")) == 200);
+ const auto code = service.Snapshot().pairing_code;
+ CHECK(code.size() == 6);
+ CHECK(Status(post("/api/pair/confirm?code=" + code, "", "", "")) == 403);
+ const std::string wrong = code == "000000" ? "000001" : "000000";
+ CHECK(Status(post("/api/pair/confirm?code=" + wrong, "")) == 403);
+ const auto paired = post("/api/pair/confirm?code=" + code, "");
+ CHECK(Status(paired) == 200 && service.Snapshot().pairing_code.empty());
+ const auto cookie_start = paired.find("Set-Cookie: ");
+ CHECK(cookie_start != std::string::npos);
+ const auto cookie_line = paired.substr(cookie_start, paired.find("\r\n", cookie_start) - cookie_start);
+ CHECK(cookie_line.find("HttpOnly") != std::string::npos && cookie_line.find("SameSite=Strict") != std::string::npos);
+ const auto cookie = cookie_line.substr(12, cookie_line.find(';') - 12);
+ CHECK(Body(get("/api/pair/status", cookie)).find("\"paired\":true") != std::string::npos);
+ // Among other cookies, too.
+ CHECK(Status(get("/api/files/games", "a=b; " + cookie + "; c=d")) == 200);
+
+ // Games.
+ auto answer = get("/api/files/games", cookie);
+ CHECK(Status(answer) == 200);
+ auto body = Body(answer);
+ CHECK(body.find("\"name\":\"Grand \\\"Theft\\\" Auto IV\"") != std::string::npos && body.find("\"running\":true") != std::string::npos);
+ CHECK(body.find(game_folder.string()) == std::string::npos);
+ // The game's page: roots, redistributable folders, what it needs.
+ body = Body(get("/api/files/game?game=steam-12210", cookie));
+ for (const char* part : {"\"id\":\"user\"", "\"id\":\"steam\"", "\"id\":\"programdata\"", "\"id\":\"public\"", "\"id\":\"game\"", "\"physx_needed\":\"2.8.1\"", "\"path\":\"_Redist\"",
+ "\"physx_installer\":\"_Redist/PhysX.msi\"", "/mnt/usb0/playden/import/Game"})
+ CHECK(body.find(part) != std::string::npos);
+ CHECK(Status(get("/api/files/game?game=nope", cookie)) == 404);
+ // A kept bottle has its saves and no game folder; an unplugged drive the same, with why.
+ CHECK(Status(get("/api/files/list?game=steam-274520&root=user", cookie)) == 200);
+ CHECK(Status(get("/api/files/list?game=steam-274520&root=game", cookie)) == 404);
+ CHECK(Status(get("/api/files/list?game=local-gone&root=user", cookie)) == 200);
+ answer = get("/api/files/list?game=local-gone&root=game", cookie);
+ CHECK(Status(answer) == 404 && Body(answer).find("Connect this game's drive") != std::string::npos);
+ CHECK(Body(get("/api/files/game?game=local-gone", cookie)).find("\"id\":\"game\"") == std::string::npos);
+
+ // Lists and paths.
+ body = Body(get("/api/files/list?" + game + "user&path=" + Encode("Documents/Rockstar Games/GTA IV/Profiles/ABC"), cookie));
+ CHECK(body.find("\"name\":\"SGTA400\"") != std::string::npos);
+ body = Body(get("/api/files/list?" + game + "game", cookie));
+ CHECK(body.find(".playden") == std::string::npos && body.find("\"name\":\"steam_settings\"") != std::string::npos);
+ CHECK(Status(get("/api/files/list?" + game + "nope", cookie)) == 404);
+ CHECK(Status(get("/api/files/list?" + game + "user&path=" + Encode("../../.."), cookie)) == 404);
+ CHECK(Status(get("/api/files/list?game=steam-12210&root=" + Encode(base.string()), cookie)) == 404);
+
+ // A download: an attachment, sandboxed; a game's page can't run on this origin.
+ answer = get("/api/files/download?" + game + "game&path=page.html", cookie);
+ CHECK(Status(answer) == 200 && Body(answer) == "<script>alert(1)</script>");
+ CHECK(answer.find("Content-Type: application/octet-stream") != std::string::npos);
+ CHECK(answer.find("Content-Disposition: attachment; filename*=UTF-8''page.html") != std::string::npos);
+ CHECK(answer.find("Content-Security-Policy: sandbox") != std::string::npos && answer.find("X-Content-Type-Options: nosniff") != std::string::npos);
+ CHECK(Status(get("/api/files/download?" + game + "game&path=.playden-install.json", cookie)) == 404);
+ answer = Exchange(port, "HEAD /api/files/download?" + game + "game&path=game.exe HTTP/1.1\r\n" + host + "Cookie: " + cookie + "\r\n\r\n");
+ CHECK(Status(answer) == 200 && Body(answer).empty() && answer.find("Content-Length: 3") != std::string::npos);
+
+ // Changes need the header, whatever the cookie.
+ CHECK(Status(post("/api/files/delete?" + game + "game&path=game.exe", cookie, "", "")) == 403);
+ CHECK(fs::exists(game_folder / "game.exe"));
+ // Upload, with the header split across packets as a browser may send it.
+ CHECK(Status(post("/api/files/upload?" + game + "user&path=Documents/new.sav", cookie, "hello")) == 200);
+ CHECK(Text(profile / "Documents/new.sav") == "hello");
+ CHECK(Status(post("/api/files/upload?" + game + "user&path=Documents/new.sav", cookie, "other")) == 409);
+ answer = post("/api/files/upload?" + game + "user&path=Documents/new.sav&overwrite=1", cookie, "other");
+ CHECK(Status(answer) == 200 && Body(answer).find("\"replaced\":true") != std::string::npos);
+ CHECK(Status(post("/api/files/upload?" + game + "game&path=steam_settings/x", cookie, "x")) == 403);
+ CHECK(Status(post("/api/files/upload?" + game + "game&path=.playden-x", cookie, "x")) == 400);
+ CHECK(Status(Exchange(port, "POST /api/files/upload?" + game + "user&path=nolength HTTP/1.1\r\n" + host + "X-Playden-Action: files\r\nCookie: " + cookie + "\r\n\r\n")) == 411);
+ // A body that stops: the file doesn't appear.
+ {
+ const int fd = Open(port);
+ const std::string head = "POST /api/files/upload?" + game + "user&path=short.sav HTTP/1.1\r\n" + host + "X-Playden-Action: files\r\nCookie: " + cookie + "\r\nContent-Length: 100\r\n\r\nabc";
+ CHECK(::send(fd, head.data(), head.size(), 0) == static_cast<ssize_t>(head.size()));
+ ::shutdown(fd, SHUT_WR);
+ char buffer[512];
+ while (::recv(fd, buffer, sizeof buffer, 0) > 0) {}
+ ::close(fd);
+ CHECK(!fs::exists(profile / "short.sav"));
+ for (const auto& entry : fs::directory_iterator(profile)) CHECK(entry.path().filename().string().rfind(".playden-upload", 0) != 0);
+ }
+ // Previous version, restore, new folder, delete.
+ answer = get("/api/files/download?" + game + "user&path=Documents/new.sav&previous=1", cookie);
+ CHECK(Body(answer) == "hello");
+ CHECK(Body(get("/api/files/list?" + game + "user&path=Documents", cookie)).find("\"previous\":{\"size\":5") != std::string::npos);
+ CHECK(Status(post("/api/files/restore?" + game + "user&path=Documents/new.sav", cookie)) == 200 && Text(profile / "Documents/new.sav") == "hello");
+ CHECK(Status(post("/api/files/mkdir?" + game + "game&path=_Redist2", cookie)) == 200 && fs::is_directory(game_folder / "_Redist2"));
+ CHECK(Status(post("/api/files/delete?" + game + "game&path=_Redist2", cookie)) == 200 && !fs::exists(game_folder / "_Redist2"));
+ CHECK(Status(post("/api/files/delete?" + game + "user&path=Documents/new.sav", cookie)) == 200 && !fs::exists(profile / "Documents/new.sav"));
+ // A POST from another origin never reaches these.
+ CHECK(Status(post("/api/files/mkdir?" + game + "game&path=evil", cookie, "", "X-Playden-Action: files\r\nOrigin: http://evil.example\r\n")) == 403);
+ CHECK(!fs::exists(game_folder / "evil"));
+ // A name in Host never reaches these either, cookie or not.
+ CHECK(Status(Exchange(port, "GET /api/files/games HTTP/1.1\r\nHost: evil.example\r\nCookie: " + cookie + "\r\n\r\n")) == 403);
+
+ // The editor's text, as JSON.
+ Put(game_folder / "autoexec.cfg", "a \"b\"\n");
+ body = Body(get("/api/files/text?" + game + "game&path=autoexec.cfg", cookie));
+ CHECK(body.find("\"text\":\"a \\\"b\\\"\\u000a\"") != std::string::npos);
+ const auto hash_at = body.find("\"sha256\":\"") + 10;
+ const auto hash = body.substr(hash_at, body.find('"', hash_at) - hash_at);
+ CHECK(Status(post("/api/files/upload?" + game + "game&path=autoexec.cfg&if_sha256=" + hash, cookie, "new")) == 200 && Text(game_folder / "autoexec.cfg") == "new");
+ CHECK(Status(post("/api/files/upload?" + game + "game&path=autoexec.cfg&if_sha256=" + hash, cookie, "stale")) == 409 && Text(game_folder / "autoexec.cfg") == "new");
+
+ // A zip, chunked: decoded, it opens.
+ answer = get("/api/files/zip?" + game + "game&path=_Redist", cookie);
+ CHECK(Status(answer) == 200 && answer.find("Transfer-Encoding: chunked") != std::string::npos);
+ CHECK(answer.find("filename*=UTF-8''_Redist.zip") != std::string::npos);
+ std::string chunks = Body(answer), zip;
+ while (true) {
+ const auto line_end = chunks.find("\r\n");
+ CHECK(line_end != std::string::npos);
+ const auto size = std::strtoul(chunks.substr(0, line_end).c_str(), nullptr, 16);
+ if (size == 0) break;
+ zip += chunks.substr(line_end + 2, size);
+ chunks.erase(0, line_end + 2 + size + 2);
+ }
+ CHECK(zip.find("_Redist/PhysX.msi") != std::string::npos);
+
+ // Only a couple of transfers at once; the next answers 503 and a list still works.
+ {
+ Put(game_folder / "big.bin", std::string(16 * 1024 * 1024, 'b'));
+ const std::string request = "GET /api/files/download?" + game + "game&path=big.bin HTTP/1.1\r\n" + host + "Cookie: " + cookie + "\r\n\r\n";
+ const int first = Open(port), second = Open(port);
+ CHECK(::send(first, request.data(), request.size(), 0) > 0 && ::send(second, request.data(), request.size(), 0) > 0);
+ std::this_thread::sleep_for(std::chrono::milliseconds(200)); // both blocked sending to clients that don't read
+ answer = get("/api/files/download?" + game + "game&path=game.exe", cookie);
+ CHECK(Status(answer) == 503 && answer.find("Retry-After: 1") != std::string::npos);
+ const auto started = std::chrono::steady_clock::now();
+ CHECK(Status(get("/api/files/list?" + game + "game", cookie)) == 200);
+ CHECK(std::chrono::steady_clock::now() - started < std::chrono::seconds(1));
+ ::close(first);
+ ::close(second);
+ std::this_thread::sleep_for(std::chrono::milliseconds(300));
+ CHECK(Status(get("/api/files/download?" + game + "game&path=game.exe", cookie)) == 200);
+ }
+
+ service.Shutdown();
+ fs::remove_all(base);
+ std::puts("web_files_api: ok");
+}
diff --git a/tests/web_pairing_test.cpp b/tests/web_pairing_test.cpp
new file mode 100644
index 0000000..615d14c
--- /dev/null
+++ b/tests/web_pairing_test.cpp
@@ -0,0 +1,93 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "web/pairing.h"
+
+#include <cstdio>
+#include <cstdlib>
+#include <string>
+
+using namespace playden::web;
+
+#define CHECK(condition) \
+ do { \
+ if (!(condition)) { \
+ std::fprintf(stderr, "%s:%d: CHECK failed: %s\n", __FILE__, __LINE__, #condition); \
+ std::exit(1); \
+ } \
+ } while (false)
+
+int main() {
+ std::int64_t now = 1000;
+ int sequence = 0;
+ Pairing::Options options;
+ options.now = [&] { return now; };
+ options.random_hex = [&]() -> std::optional<std::string> {
+ char text[33];
+ std::snprintf(text, sizeof text, "%08x%024x", ++sequence * 7919, sequence);
+ return std::string(text);
+ };
+ Pairing pairing(options);
+ std::int64_t wait = 0;
+ std::string token;
+
+ // Nothing to confirm yet, and no code on the TV.
+ CHECK(pairing.Confirm("000000", &token) == Pairing::ConfirmResult::kNoCode);
+ CHECK(pairing.ActiveCode().empty());
+ CHECK(!pairing.Paired("") && !pairing.Paired("x"));
+
+ // A code: six digits; asking again keeps it unless a new one is wanted.
+ CHECK(pairing.Start(false, &wait));
+ const auto code = pairing.ActiveCode();
+ CHECK(code.size() == 6 && code.find_first_not_of("0123456789") == std::string::npos);
+ CHECK(pairing.Start(false, &wait) && pairing.ActiveCode() == code);
+ CHECK(pairing.Start(true, &wait) && pairing.ActiveCode() != code);
+
+ // Right: a token that stays valid, and the code is used up.
+ const auto second = pairing.ActiveCode();
+ CHECK(pairing.Confirm(second, &token) == Pairing::ConfirmResult::kPaired);
+ CHECK(token.size() == 64 && pairing.Paired(token));
+ CHECK(pairing.ActiveCode().empty());
+ CHECK(pairing.Confirm(second, nullptr) == Pairing::ConfirmResult::kNoCode);
+
+ // Expiry.
+ CHECK(pairing.Start(false, &wait));
+ now += options.code_lifetime_ms;
+ CHECK(pairing.ActiveCode().empty());
+ CHECK(pairing.Paired(token));
+
+ // Wrong tries count across new codes: asking for another doesn't give more guesses.
+ const auto wrong_of = [](const std::string& right) { return right == "000000" ? std::string("000001") : std::string("000000"); };
+ for (int i = 0; i < options.max_wrong_tries - 1; ++i) {
+ CHECK(pairing.Start(true, &wait));
+ CHECK(pairing.Confirm(wrong_of(pairing.ActiveCode()), nullptr) == Pairing::ConfirmResult::kWrong);
+ }
+ CHECK(pairing.Start(true, &wait));
+ const auto last = pairing.ActiveCode();
+ CHECK(pairing.Confirm(wrong_of(last), nullptr) == Pairing::ConfirmResult::kLocked);
+ CHECK(pairing.ActiveCode().empty());
+ CHECK(!pairing.Start(true, &wait) && wait == options.lockout_ms);
+ CHECK(pairing.Confirm(last, nullptr) == Pairing::ConfirmResult::kLocked);
+ now += options.lockout_ms;
+ CHECK(pairing.Start(false, &wait));
+
+ // Cancel from the TV.
+ pairing.Cancel();
+ CHECK(pairing.ActiveCode().empty());
+
+ // At most a few browsers: the oldest goes first.
+ std::string first_token;
+ for (std::size_t i = 0; i <= options.max_tokens; ++i) {
+ CHECK(pairing.Start(true, &wait));
+ std::string minted;
+ CHECK(pairing.Confirm(pairing.ActiveCode(), &minted) == Pairing::ConfirmResult::kPaired);
+ if (i == 0) first_token = minted;
+ CHECK(pairing.Paired(minted));
+ }
+ CHECK(!pairing.Paired(first_token));
+
+ // No random source: no code, and no wait to report.
+ Pairing::Options broken = options;
+ broken.random_hex = []() -> std::optional<std::string> { return std::nullopt; };
+ Pairing none(broken);
+ CHECK(!none.Start(false, &wait) && wait == 0);
+ std::puts("web_pairing: ok");
+}