Play your Steam library's Windows games on a jailbroken PS5.
C++
Add web access: Playden's logs on the local network
Leonardo Lobato49427896db72
diff --git a/CMakeLists.txt b/CMakeLists.txtindex f3cfb3e..1cb147d 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -45,6 +45,7 @@ include(CTest)include(cmake/PlaydenCore.cmake)include(cmake/SteamBackend.cmake)playden_register_steam_backend_tests()+include(cmake/Web.cmake)include(cmake/ProsperoRuntime.cmake)include(cmake/SelfUpdate.cmake)include(cmake/HomebrewUI.cmake)diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex 478bd69..5a464ac 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -30,7 +30,8 @@ These are compiled into Playden's PS5 package (`FAKE77031`) or copied into it.| Barlow, Barlow Condensed | — | SIL Open Font License 1.1 | [jpt/barlow](https://github.com/jpt/barlow) || Noto Sans, Noto Sans CJK SC, Noto Sans Arabic | — | SIL Open Font License 1.1 | [notofonts](https://github.com/notofonts) |-The font licenses are shipped next to the fonts, in `assets/fonts/` of the package.+The font licenses are shipped next to the fonts, in `assets/fonts/` of the package. The web access page serves two+Barlow faces from inside the app, with the license at `/assets/barlow-OFL.txt`.## Shipped with Playden for gamesdiff --git a/cmake/EmbedWebAssets.cmake b/cmake/EmbedWebAssets.cmakenew file mode 100644index 0000000..45b0284--- /dev/null+++ b/cmake/EmbedWebAssets.cmake@@ -0,0 +1,31 @@+# Turns the web page and its fonts into byte arrays: cmake -DOUTPUT=<file.cpp> -DASSETS=<path|kind|file;...> -P this.+# kind: html, ttf or text (a content type would bring its own ";" into the list).+cmake_minimum_required(VERSION 3.24)+set(body "")+set(table "")+set(index 0)+foreach(asset IN LISTS ASSETS)+ string(REPLACE "|" ";" parts "${asset}")+ list(GET parts 0 served)+ list(GET parts 1 kind)+ if(kind STREQUAL "html")+ set(type "text/html; charset=utf-8")+ elseif(kind STREQUAL "ttf")+ set(type "font/ttf")+ elseif(kind STREQUAL "text")+ set(type "text/plain; charset=utf-8")+ else()+ message(FATAL_ERROR "Unknown web asset kind: ${kind}")+ endif()+ list(GET parts 2 source)+ file(READ "${source}" hex HEX)+ string(LENGTH "${hex}" hex_length)+ math(EXPR size "${hex_length} / 2")+ string(REGEX REPLACE "([0-9a-f][0-9a-f])" "0x\\1," bytes "${hex}")+ string(APPEND body "const unsigned char kAsset${index}[] = {${bytes}0x00};\n")+ string(APPEND table " {\"${served}\", \"${type}\", kAsset${index}, ${size}},\n")+ math(EXPR index "${index} + 1")+endforeach()+file(WRITE "${OUTPUT}.tmp" "// Generated by cmake/EmbedWebAssets.cmake; do not edit.\n#include \"web/assets.h\"\n\nnamespace playden::web {\nnamespace {\n${body}} // namespace\n\nconst EmbeddedAsset kEmbeddedAssets[] = {\n${table}};\nconst std::size_t kEmbeddedAssetCount = ${index};\n\n} // namespace playden::web\n")+file(COPY_FILE "${OUTPUT}.tmp" "${OUTPUT}" ONLY_IF_DIFFERENT)+file(REMOVE "${OUTPUT}.tmp")diff --git a/cmake/HomebrewPS5.cmake b/cmake/HomebrewPS5.cmakeindex c977a41..ffb465e 100644--- a/cmake/HomebrewPS5.cmake+++ b/cmake/HomebrewPS5.cmake@@ -93,7 +93,7 @@ function(playden_add_homebrew_ps5_title)--wrap=openat --wrap=mkdirat)add_library(playden_ps5_app OBJECT src/homebrew/ps5.cpp src/homebrew/usb_keyboard.cpp src/platform/ps5/title_runtime.cpp- src/platform/ps5/native_startup.cpp src/platform/ps5/console_services.cpp src/platform/ps5/system_keyboard.cpp+ src/platform/ps5/native_startup.cpp src/platform/ps5/console_services.cpp src/platform/ps5/console_address.cpp src/platform/ps5/system_keyboard.cpp"${PLAYDEN_HUI_SOURCE_DIR}/src/platform/ps5/display_egl.cpp""${PLAYDEN_HUI_SOURCE_DIR}/src/platform/ps5/pad.cpp""${PLAYDEN_HUI_SOURCE_DIR}/src/platform/ps5/system.cpp")@@ -135,7 +135,7 @@ function(playden_add_homebrew_ps5_title)$<$<COMPILE_LANGUAGE:CXX>:-fno-exceptions;-fno-rtti>)target_compile_features(playden_ps5_app PRIVATE cxx_std_20)target_link_libraries(playden_ps5_app PRIVATE playden_hui playden_library playden_steam_auth- playden_homebrew_controller playden_local_session_repository playden_steam_library playden_steam_cm playden_native_access playden_runtime_layout_migration playden_local_store playden_local_copy)+ playden_homebrew_controller playden_local_session_repository playden_steam_library playden_steam_cm playden_native_access playden_runtime_layout_migration playden_local_store playden_local_copy playden_web_http)set(host_tool "${host}/ps5-native-tool")set(libc_prx "${host}/libc.prx")@@ -163,7 +163,7 @@ function(playden_add_homebrew_ps5_title)$<TARGET_FILE:playden_local_session_repository> $<TARGET_FILE:playden_auth_diagnostics> $<TARGET_FILE:playden_local_store> $<TARGET_FILE:playden_local_copy>$<TARGET_FILE:playden_self_update> $<TARGET_FILE:playden_miniz> $<TARGET_FILE:playden_steam_http> $<TARGET_FILE:playden_steam_protocol>$<TARGET_FILE:playden_steam_auth>- $<TARGET_FILE:playden_steam_core> $<TARGET_FILE:playden_diagnostic_log> $<TARGET_FILE:playden_storage>+ $<TARGET_FILE:playden_steam_core> $<TARGET_FILE:playden_web> $<TARGET_FILE:playden_web_logs> $<TARGET_FILE:playden_web_http> $<TARGET_FILE:playden_diagnostic_log> $<TARGET_FILE:playden_storage>$<TARGET_FILE:playden_library> $<TARGET_FILE:playden_native_access> $<TARGET_FILE:playden_managed_directory> $<TARGET_FILE:playden_runtime_steamworks> $<TARGET_FILE:playden_runtime_artifact_hash> $<TARGET_FILE:playden_runtime_settings_storage> $<TARGET_FILE:playden_runtime_private_directories> $<TARGET_FILE:playden_runtime_session_reconciler> $<TARGET_FILE:playden_runtime_launch_service> $<TARGET_FILE:playden_runtime_install_service> $<TARGET_FILE:playden_runtime_installs> $<TARGET_FILE:playden_runtime_layout_migration> $<TARGET_FILE:playden_game_paths>${PLAYDEN_STEAM_LINK_ARCHIVES} ${title_database_archives}--end-group --as-needed ${link_stubs}@@ -171,7 +171,7 @@ function(playden_add_homebrew_ps5_title)DEPENDS "${common_dialog_stub}" playden_ps5_runtime playden_ps5_shims playden_ps5_app playden_hui playden_homebrew_ui playden_homebrew_model ${title_database_targets}playden_homebrew_qr playden_homebrew_controller playden_local_session_repository playden_auth_diagnostics playden_local_store playden_local_copyplayden_homebrew_artwork_cache playden_homebrew_artwork playden_persistence_controller playden_persistence_service playden_preferences playden_library_controller playden_library_service playden_steam_library playden_steam_cm playden_steam_cm_codec playden_depot_codec- playden_library playden_self_update playden_miniz playden_steam_auth playden_steam_http playden_steam_protocol playden_steam_core playden_diagnostic_log playden_storage playden_native_access playden_managed_directory playden_runtime_steamworks playden_runtime_artifact_hash playden_runtime_settings_storage playden_runtime_private_directories playden_runtime_session_reconciler playden_runtime_launch_service playden_runtime_install_service playden_runtime_installs playden_runtime_layout_migration playden_game_paths+ playden_library playden_self_update playden_miniz playden_steam_auth playden_steam_http playden_steam_protocol playden_steam_core playden_web playden_web_logs playden_web_http playden_diagnostic_log playden_storage playden_native_access playden_managed_directory playden_runtime_steamworks playden_runtime_artifact_hash playden_runtime_settings_storage playden_runtime_private_directories playden_runtime_session_reconciler playden_runtime_launch_service playden_runtime_install_service playden_runtime_installs playden_runtime_layout_migration playden_game_paths$<TARGET_OBJECTS:playden_ps5_runtime> $<TARGET_OBJECTS:playden_ps5_shims>$<TARGET_OBJECTS:playden_ps5_app>$<TARGET_FILE:playden_self_update> $<TARGET_FILE:playden_miniz> $<TARGET_FILE:playden_steam_http> $<TARGET_FILE:playden_steam_protocol>diff --git a/cmake/HomebrewUI.cmake b/cmake/HomebrewUI.cmakeindex f4ce91d..1afe97a 100644--- a/cmake/HomebrewUI.cmake+++ b/cmake/HomebrewUI.cmake@@ -240,7 +240,7 @@ target_compile_features(playden_homebrew_controller PUBLIC cxx_std_20)target_include_directories(playden_homebrew_controller PUBLIC "${CMAKE_SOURCE_DIR}/src")target_link_libraries(playden_homebrew_controller PUBLICplayden_homebrew_model playden_steam_core playden_auth_diagnostics playden_library_controller playden_persistence_controller playden_runtime_settings_storage- playden_homebrew_runtime_host playden_self_update playden_local_store)+ playden_homebrew_runtime_host playden_self_update playden_local_store playden_web)# Worker-owned per-game runtime composition (OWNER records, native inventory, kit layer).add_library(playden_homebrew_runtime_host STATIC "${CMAKE_SOURCE_DIR}/src/homebrew/runtime_host.cpp"@@ -691,6 +691,7 @@ if(BUILD_TESTING)find_package(Python3 REQUIRED COMPONENTS Interpreter)add_test(NAME native_startup_order COMMAND "${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/tests/test_native_startup_order.py")add_test(NAME console_kit_upload COMMAND "${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/tests/test_console_kit_upload.py")+ add_test(NAME collect_logs COMMAND "${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/tests/test_collect_logs.py")add_test(NAME ui_comparison_fixtureCOMMAND "${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/tools/verify_ui_comparison.py""${CMAKE_SOURCE_DIR}/fixtures/ui-comparison")diff --git a/cmake/Web.cmake b/cmake/Web.cmakenew file mode 100644index 0000000..35107ad--- /dev/null+++ b/cmake/Web.cmake@@ -0,0 +1,74 @@+# Playden's read-only web access on the local network (src/web/): the HTTP server, its routes and the page.++add_library(playden_web_http STATIC+ "${CMAKE_SOURCE_DIR}/src/web/address.cpp"+ "${CMAKE_SOURCE_DIR}/src/web/http.cpp"+ "${CMAKE_SOURCE_DIR}/src/web/router.cpp"+ "${CMAKE_SOURCE_DIR}/src/web/server.cpp"+ "${CMAKE_SOURCE_DIR}/src/web/zip.cpp")+target_include_directories(playden_web_http PUBLIC "${CMAKE_SOURCE_DIR}/src")+target_compile_features(playden_web_http PUBLIC cxx_std_17)+target_link_libraries(playden_web_http PUBLIC Threads::Threads)+if(PLAYDEN_PLATFORM_PS5)+ target_compile_options(playden_web_http PRIVATE -fno-exceptions -fno-rtti)+endif()++# The logs a report holds, read and redacted as tools/collect_logs.py does.+add_library(playden_web_logs STATIC "${CMAKE_SOURCE_DIR}/src/web/logs_source.cpp")+target_include_directories(playden_web_logs PUBLIC "${CMAKE_SOURCE_DIR}/src")+target_compile_features(playden_web_logs PUBLIC cxx_std_17)+target_link_libraries(playden_web_logs PUBLIC playden_web_http PRIVATE playden_diagnostic_log playden_steam_protocol)+if(PLAYDEN_PLATFORM_PS5)+ target_compile_definitions(playden_web_logs PRIVATE PLAYDEN_PLATFORM_PS5=1)+ target_compile_options(playden_web_logs PRIVATE -fno-exceptions -fno-rtti)+endif()++# The page (CSS and JS inline) and two Barlow faces (OFL), baked into the binary.+set(playden_web_fonts "${CMAKE_SOURCE_DIR}/fixtures/ui-comparison/assets/fonts")+set(playden_web_assets+ "/|html|${CMAKE_SOURCE_DIR}/src/web/page/index.html"+ "/assets/barlow-regular.ttf|ttf|${playden_web_fonts}/Barlow-Regular.ttf"+ "/assets/barlow-semibold.ttf|ttf|${playden_web_fonts}/Barlow-SemiBold.ttf"+ "/assets/barlow-OFL.txt|text|${playden_web_fonts}/barlow-OFL.txt")+set(playden_web_asset_files)+foreach(asset IN LISTS playden_web_assets)+ string(REPLACE "|" ";" parts "${asset}")+ list(GET parts 2 source)+ list(APPEND playden_web_asset_files "${source}")+endforeach()+set(playden_web_assets_cpp "${CMAKE_BINARY_DIR}/generated/web_assets.cpp")+add_custom_command(OUTPUT "${playden_web_assets_cpp}"+ COMMAND "${CMAKE_COMMAND}" -E make_directory "${CMAKE_BINARY_DIR}/generated"+ COMMAND "${CMAKE_COMMAND}" "-DOUTPUT=${playden_web_assets_cpp}" "-DASSETS=${playden_web_assets}"+ -P "${CMAKE_SOURCE_DIR}/cmake/EmbedWebAssets.cmake"+ 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}")+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)+if(PLAYDEN_PLATFORM_PS5)+ target_compile_options(playden_web PRIVATE -fno-exceptions -fno-rtti)+endif()++if(BUILD_TESTING AND NOT PLAYDEN_PLATFORM_PS5)+ foreach(test_name web_request web_router web_zip web_server)+ add_executable(${test_name}_test "${CMAKE_SOURCE_DIR}/tests/${test_name}_test.cpp")+ target_link_libraries(${test_name}_test PRIVATE playden_web_http)+ add_test(NAME ${test_name} COMMAND ${test_name}_test)+ endforeach()+ add_executable(web_logs_source_test "${CMAKE_SOURCE_DIR}/tests/web_logs_source_test.cpp")+ target_link_libraries(web_logs_source_test PRIVATE playden_web_logs)+ add_test(NAME web_logs_source COMMAND web_logs_source_test)+ # The console's walk by path (no descriptor-relative opens), run on the host.+ add_executable(web_logs_source_native_policy_test+ "${CMAKE_SOURCE_DIR}/tests/web_logs_source_test.cpp"+ "${CMAKE_SOURCE_DIR}/src/web/logs_source.cpp")+ target_compile_definitions(web_logs_source_native_policy_test PRIVATE PLAYDEN_PLATFORM_PS5=1)+ target_link_libraries(web_logs_source_native_policy_test PRIVATE playden_web_http playden_diagnostic_log playden_steam_protocol)+ add_test(NAME web_logs_source_native_policy COMMAND web_logs_source_native_policy_test)+ 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)+endif()diff --git a/src/app/preferences.cpp b/src/app/preferences.cppindex 191a8b1..15f98dd 100644--- a/src/app/preferences.cpp+++ b/src/app/preferences.cpp@@ -1,6 +1,7 @@#include "app/preferences.h"#include <algorithm>+#include <iterator>#include <string>#include <string_view>#include <vector>@@ -14,10 +15,11 @@ std::string ToString(const Bytes& bytes) {return std::string(bytes.begin(), bytes.end());}-// Version 8: one "key=value" line per field, in this order, each ending in a newline.-constexpr const char* kVersionEightKeys[] = {"reduce_motion", "title_store_suffix", "cloud_saves_auto",- "steam_sign_in_password", "downloads_slow_network", "steam_stay_signed_in",- "beta_updates", "download_server"};+// Versions 8 and 9: one "key=value" line per field, in this order, each ending in a newline. Version 9 adds+// web_access (on in older files).+constexpr const char* kVersionNineKeys[] = {"reduce_motion", "title_store_suffix", "cloud_saves_auto",+ "steam_sign_in_password", "downloads_slow_network", "steam_stay_signed_in",+ "beta_updates", "download_server", "web_access"};bool ParseFlag(const std::string& value, bool* flag) {if (value != "0" && value != "1") return false;@@ -32,12 +34,14 @@ bool ValidDownloadServer(const std::string& host) {});}-bool ParseVersionEight(const std::string& serialized, Preferences* preferences) {- constexpr std::string_view kHeader = "version=8\n";- if (serialized.compare(0, kHeader.size(), kHeader) != 0 || serialized.back() != '\n') return false;+bool ParseKeyed(const std::string& serialized, int version, Preferences* preferences) {+ const std::string header = "version=" + std::to_string(version) + "\n";+ if (serialized.compare(0, header.size(), header) != 0 || serialized.back() != '\n') return false;std::vector<std::string> values;- std::size_t start = kHeader.size();- for (const char* key : kVersionEightKeys) {+ std::size_t start = header.size();+ const std::size_t count = version == 9 ? std::size(kVersionNineKeys) : std::size(kVersionNineKeys) - 1;+ for (std::size_t field = 0; field < count; ++field) {+ const char* key = kVersionNineKeys[field];const std::string prefix = std::string(key) + "=";const auto end = serialized.find('\n', start);if (end == std::string::npos || serialized.compare(start, prefix.size(), prefix) != 0) return false;@@ -49,7 +53,7 @@ bool ParseVersionEight(const std::string& serialized, Preferences* preferences)if (!ParseFlag(values[0], &parsed.reduce_motion) || !ParseFlag(values[1], &parsed.title_store_suffix) ||!ParseFlag(values[2], &parsed.cloud_saves_auto) || !ParseFlag(values[3], &parsed.steam_sign_in_password) ||!ParseFlag(values[4], &parsed.downloads_slow_network) || !ParseFlag(values[5], &parsed.steam_stay_signed_in) ||- !ParseFlag(values[6], &parsed.beta_updates))+ !ParseFlag(values[6], &parsed.beta_updates) || (version == 9 && !ParseFlag(values[8], &parsed.web_access)))return false;// A host the current rule refuses is dropped without resetting unrelated preferences.if (ValidDownloadServer(values[7])) parsed.download_server = values[7];@@ -77,9 +81,9 @@ PreferencesLoadResult PreferencesStore::Load() const {}std::string serialized = ToString(read.value());- Preferences eight;- if (ParseVersionEight(serialized, &eight))- return PreferencesLoadResult{std::move(eight), PreferencesLoadStatus::kLoaded, std::string()};+ Preferences keyed;+ if (ParseKeyed(serialized, 9, &keyed) || ParseKeyed(serialized, 8, &keyed))+ return PreferencesLoadResult{std::move(keyed), PreferencesLoadStatus::kLoaded, std::string()};bool beta_updates = false;if (serialized.rfind("version=7\n", 0) == 0) {const auto suffix = serialized.rfind("beta_updates=");@@ -93,7 +97,7 @@ PreferencesLoadResult PreferencesStore::Load() const {// Version 1 holds only reduce_motion; version 2 adds title_store_suffix; version 3 cloud_saves_auto;// version 4 steam_sign_in_password; version 5 downloads_slow_network; version 6 steam_stay_signed_in// (on in files older than that). Version 7 appends beta_updates (off in older files); version 8 (above)- // adds the download server (Automatic in older files).+ // adds the download server (Automatic in older files), version 9 web access (on in older files).for (const int motion : {0, 1}) {if (serialized == std::string("version=1\nreduce_motion=") + char('0' + motion) + "\n") {Preferences preferences;@@ -178,14 +182,15 @@ Result<void> PreferencesStore::Save(const Preferences& preferences) const {if(!ready.ok()) return ready;// Never write a host that cannot be read back, including embedded newlines.const std::string server = ValidDownloadServer(preferences.download_server) ? preferences.download_server : std::string();- const std::string text = std::string("version=8\nreduce_motion=") + (preferences.reduce_motion ? "1" : "0") ++ const std::string text = std::string("version=9\nreduce_motion=") + (preferences.reduce_motion ? "1" : "0") +"\ntitle_store_suffix=" + (preferences.title_store_suffix ? "1" : "0") +"\ncloud_saves_auto=" + (preferences.cloud_saves_auto ? "1" : "0") +"\nsteam_sign_in_password=" + (preferences.steam_sign_in_password ? "1" : "0") +"\ndownloads_slow_network=" + (preferences.downloads_slow_network ? "1" : "0") +"\nsteam_stay_signed_in=" + (preferences.steam_stay_signed_in ? "1" : "0") +"\nbeta_updates=" + (preferences.beta_updates ? "1" : "0") +- "\ndownload_server=" + server + "\n";+ "\ndownload_server=" + server ++ "\nweb_access=" + (preferences.web_access ? "1" : "0") + "\n";return storage_.WriteAtomic(kPreferencesPath, Bytes(text.begin(), text.end()));}diff --git a/src/app/preferences.h b/src/app/preferences.hindex 2a94e7b..39b0de5 100644--- a/src/app/preferences.h+++ b/src/app/preferences.h@@ -25,6 +25,9 @@ struct Preferences {bool beta_updates = false;// The Steam CDN host to try first for new or resumed downloads. Empty uses Steam's server order (Automatic).std::string download_server;+ // Web access: Playden's logs, redacted, on the local network at port 7031 while Playden is open. On by default,+ // so a tester can send logs without first finding a switch; version 1 only reads.+ bool web_access = true;};enum class PreferencesLoadStatus {diff --git a/src/homebrew/controller.cpp b/src/homebrew/controller.cppindex 2abc21e..6824fb4 100644--- a/src/homebrew/controller.cpp+++ b/src/homebrew/controller.cpp@@ -130,6 +130,7 @@ void Controller::Shutdown() {};// The server source may inspect the install snapshot for its fallback payload.if(download_servers_) step("download-servers", [&] { download_servers_->Shutdown(); });+ if(web_) step("web", [&] { web_->Shutdown(); });if(library_) step("library", [&] { library_->Shutdown(); library_->Tick(); AdvanceClear(); });if(persistence_) step("persistence", [&] { persistence_->FlushAndShutdown(); AdvanceOrganizationClear(); });if(app_details_) step("details", [&] { app_details_->Shutdown(); });@@ -368,6 +369,7 @@ void Controller::Tick() {TickImports();TickInstalls();TickDownloadServers();+ TickWebAccess();TickSelfUpdate();lap(5);TickCloud();@@ -1825,6 +1827,28 @@ bool Controller::DownloadServerTestAllowed() const {}return true;}+void Controller::TickWebAccess() {+ if (!web_) return;+ // Not before the saved choice is known: a player who turned it off must not get an open port at each start.+ web_->SetEnabled(model_.state().web_access && (model_.PreferencesLoaded() || !persistence_));+ const auto snapshot = web_->Snapshot();+ LiveWebAccess live;+ switch (snapshot.state) {+ case web::ServiceSnapshot::State::kOff: live.state = "off"; break;+ case web::ServiceSnapshot::State::kStarting: live.state = "starting"; break;+ case web::ServiceSnapshot::State::kOn: live.state = "on"; break;+ case web::ServiceSnapshot::State::kFailed: live.state = "failed"; break;+ }+ live.url = snapshot.url;+ live.port = snapshot.port;+ live.error = snapshot.error;+ model_.ApplyLiveWebAccess(live);+ // The page's Quit Playden; it waits for a game being prepared.+ if (web_->TakeQuitRequest()) {+ if (shutdown_log_) shutdown_log_("quit requested from web access");+ model_.RequestQuit();+ }+}void Controller::TickDownloadServers() {const auto requests = model_.TakeDownloadServerRequests();if (!download_servers_) return;@@ -2139,6 +2163,7 @@ void Controller::Apply(const steam::SteamEvent& event) {model_.UpdateAccount(std::move(update));if(persistence_) persistence_->Activate(event.steam_id);if(runtime_) runtime_->SetSteamAccount(event.account_name, event.steam_id);+ if(web_) web_->SetAccount({event.account_name, event.steam_id});if(library_) library_->Activate(event.steam_id,offline);// Steam downloads that waited for a sign-in start now, not after their wait (up to a minute).if(installs_ && !offline) installs_->RetryWaiting(Store::kSteam);@@ -2150,6 +2175,7 @@ void Controller::Apply(const steam::SteamEvent& event) {if(library_) library_->Reset();if(persistence_) persistence_->Reset();if(runtime_) runtime_->SetSteamAccount({}, 0);+ if(web_) web_->SetAccount({});const bool begin = begin_after_clear_; begin_after_clear_ = false;Update(AuthState::SignedOut,{},true);if (begin) Begin(begin_password_after_clear_);diff --git a/src/homebrew/controller.hpp b/src/homebrew/controller.hppindex 985bfbc..282279b 100644--- a/src/homebrew/controller.hpp+++ b/src/homebrew/controller.hpp@@ -17,6 +17,7 @@#include "steam/download_rate.h"#include "steam/download_server_service.h"#include "update/update_service.h"+#include "web/service.h"#include <chrono>#include <map>#include <mutex>@@ -54,6 +55,9 @@ class Controller {void SetDownloadServers(steam::DownloadServerService* servers) { download_servers_ = servers; }// Playden's own update: the controller passes the player's requests on and shows its state.void SetSelfUpdate(update::UpdateService* self_update) { self_update_ = self_update; }+ // Settings › Web access turns it on and off (once the saved preferences are read); the signed-in account's+ // name and SteamID go to it for redaction. Shutdown stops it.+ void SetWebAccess(web::Service* web) { web_ = web; }// Receives one line per shutdown step with how long it took, so a quit that hangs names the step.void SetShutdownLog(std::function<void(const std::string&)> log) { shutdown_log_ = std::move(log); }// Preferences and organization load/save failures (app::PersistenceController::SetLog). The first loads@@ -113,6 +117,8 @@ class Controller {void TickDownloadServers();bool DownloadServerTestAllowed() const;steam::DownloadServerService* download_servers_ = nullptr;+ web::Service* web_ = nullptr;+ void TickWebAccess();std::string download_servers_account_;std::optional<LiveDownloadServers> shown_download_servers_;void TickSelfUpdate();diff --git a/src/homebrew/host.cpp b/src/homebrew/host.cppindex 74fb59f..2dc762e 100644--- a/src/homebrew/host.cpp+++ b/src/homebrew/host.cpp@@ -450,6 +450,7 @@ int main(int argc, char** argv) {std::unique_ptr<playden::LocalSessionRepository> servers_sessions;std::unique_ptr<playden::steam::CdnDownloadServerSource> servers_source;std::unique_ptr<playden::steam::DownloadServerService> servers;+ std::unique_ptr<playden::web::Service> web;std::unique_ptr<playden::steam::CmClient> cloud_cm;std::unique_ptr<playden::steam::HttpClient> cloud_http;std::unique_ptr<playden::steam::SteamCloudRunner> cloud_runner;@@ -667,6 +668,17 @@ int main(int argc, char** argv) {cloud.get(), nullptr, auth_log);services->SetLocalLibrary(local);services->SetDownloadServers(servers.get());+ {+ // Web access on the Mac: the same page over the host's logs folder, on 127.0.0.1's network too.+ playden::web::ServiceConfig web_config;+ web_config.paths = {log_directory, (options->data_directory / "homebrew").string(),+ (options->data_directory / "kits").string(), options->data_directory.string()};+ web_config.server.log = [log_directory](const std::string& line) {+ playden::app::AppendLogLine(log_directory, "web.log", line);+ };+ web = std::make_unique<playden::web::Service>(std::move(web_config));+ services->SetWebAccess(web.get());+ }services->SetStaySignedIn([repository = sessions.get(), log_directory](bool stay) {const auto moved = repository->SetPersist(stay);playden::app::AppendLogLine(log_directory, "auth.log", std::string("stay signed in ") + (stay ? "on" : "off") +@@ -821,6 +833,7 @@ int main(int argc, char** argv) {if (controller) SDL_GameControllerClose(controller);SDL_StopTextInput();if (services) services->Shutdown();+ if (web) web->Shutdown();// The install service stops before the Local store goes (`stores` is destroyed before// `installs`): its copy runner's change callback calls into the Local store. Explicit here, so// it doesn't rest on the controller's shutdown or on declaration order.diff --git a/src/homebrew/ps5.cpp b/src/homebrew/ps5.cppindex c0ffdb6..1c35392 100644--- a/src/homebrew/ps5.cpp+++ b/src/homebrew/ps5.cpp@@ -19,12 +19,16 @@#include "homebrew/runtime_host.hpp"#include "homebrew/title_icon.hpp"#include "platform/ps5/title_allow_list.h"+#include "platform/ps5/console_address.h"#include "platform/ps5/console_services.h"#include "platform/ps5/system_keyboard.h"#include "runtime/artifact_hash.h"#include "runtime/kit_admission.h"#include "runtime/kit_trust.h"#include "update/update_service.h"+#include "web/address.h"+#include "web/server.h"+#include "web/service.h"#include "homebrew/input_adapter.hpp"#include "homebrew/usb_keyboard.hpp"#include "core/input.hpp"@@ -746,8 +750,38 @@ int main() {copy_runner->SetChanged([local_library] { local_library->Reload(); });stores.Add(std::move(source));}+ // Web access, phase 0: with /data/playden/dev/web-probe present, a bare listener on 7031 answers every+ // request with "ok" and logs each socket call to web.log, to learn whether a title can listen at all.+ playden::web::Server web_probe;+ const bool web_probe_on = !paths.runtime_data_root.empty() &&+ access((paths.runtime_data_root + "/dev/web-probe").c_str(), F_OK) == 0;+ if (web_probe_on) {+ const auto web_log = [](const std::string& line) { playden::app::AppendLogLine(log_root, "web.log", "probe " + line); };+ std::string netctl;+ const auto netctl_address = playden::ps5::ConsoleAddress(&netctl);+ const auto udp_address = playden::web::LocalAddress();+ web_log("address udp=" + (udp_address.empty() ? std::string("unknown") : udp_address) + " netctl=" ++ (netctl_address.empty() ? std::string("unknown") : netctl_address) + " " + netctl);+ playden::web::ServerOptions probe;+ probe.first_port = probe.last_port = 7031;+ probe.verbose = true;+ probe.log = web_log;+ std::string error;+ if (web_probe.Start(probe, [](const playden::web::Request&, playden::web::Response& response) {+ response.Send(200, "text/plain", "ok\n");+ }, &error))+ web_log("listening port=" + std::to_string(web_probe.port()));+ }+ // Web access: the logs page on the local network (off while the probe holds port 7031).+ playden::web::ServiceConfig web_config;+ web_config.paths = {log_root, "/data/homebrew", paths.runtime_data_root.empty() ? std::string() : paths.runtime_data_root + "/kits",+ "/data/homebrew/" PLAYDEN_PS5_TITLE_ID};+ web_config.server.log = [](const std::string& line) { playden::app::AppendLogLine(log_root, "web.log", line); };+ web_config.address_fallback = [] { return playden::ps5::ConsoleAddress(); };+ playden::web::Service web(std::move(web_config));playden::homebrew::Controller services(simulation, stores, &persistence, &installs, &cloud, runtime_host.get(), auth_log);services.SetDownloadServers(&servers);+ if (!web_probe_on) services.SetWebAccess(&web);services.SetLocalLibrary(local_library);playden::steam::StoreDetailsService store_details(playden::homebrew::StoreFetch(paths.trust_store));services.SetStoreDetails(&store_details);@@ -953,7 +987,12 @@ int main() {}#if !PLAYDEN_UI_SIMULATIONplayden::app::AppendLogLine(log_root, "launch.log", "quit requested");+ if (web_probe.running()) {+ web_probe.Stop();+ playden::app::AppendLogLine(log_root, "web.log", "probe stopped");+ }services.Shutdown();+ web.Shutdown();// The install service stops before the Local store goes (`stores` is destroyed before// `installs`): its copy runner's change callback calls into the Local store. Explicit here,// so it doesn't rest on the controller's shutdown or on declaration order.diff --git a/src/homebrew/simulation.cpp b/src/homebrew/simulation.cppindex f13fa28..1b8b7bb 100644--- a/src/homebrew/simulation.cpp+++ b/src/homebrew/simulation.cpp@@ -2771,6 +2771,18 @@ void Simulation::refresh_download_servers(const std::string& focus) {}}+void Simulation::RequestQuit() {+ if (state_.quit_requested || state_.quit_waiting) return;+ quit_to_home();+ rebuild_view();+}++void Simulation::ApplyLiveWebAccess(const LiveWebAccess& snapshot) {+ if (web_access_ == snapshot) return;+ web_access_ = snapshot;+ rebuild_view();+}+void Simulation::ApplyLiveDownloadServers(const LiveDownloadServers& snapshot) {const bool finished = (download_servers_.phase == "testing" || download_server_test_requested_) && snapshot.phase == "tested" &&!download_server_cancel_pending_;@@ -2796,7 +2808,8 @@ void Simulation::ApplyLiveDownloadServers(const LiveDownloadServers& snapshot) {playden::Preferences Simulation::ExportPreferences() const {return {state_.reduced_motion, state_.title_store_suffix, state_.cloud_saves_auto, state_.sign_in_password,- state_.downloads_slow_network, state_.stay_signed_in, state_.beta_updates, state_.download_server};+ state_.downloads_slow_network, state_.stay_signed_in, state_.beta_updates, state_.download_server,+ state_.web_access};}void Simulation::apply_organization_snapshot(const playden::OrganizationSnapshot& snapshot) {@@ -3014,6 +3027,7 @@ bool Simulation::ApplyPreferences(PersistenceLoadToken token,const playden::PreferencesLoadResult& loaded) {if (!live() || !preferences_load_pending_ || !(token == preferences_load_token_)) return false;preferences_load_pending_ = false;+ preferences_loaded_ = true;preferences_load_failed_ = loaded.status == playden::PreferencesLoadStatus::kDefaultCorrupt ||loaded.status == playden::PreferencesLoadStatus::kDefaultReadError;if (preferences_load_may_apply_ && preferences_revision_ == token.baseline_revision) {@@ -3024,6 +3038,7 @@ bool Simulation::ApplyPreferences(PersistenceLoadToken token,state_.beta_updates = loaded.preferences.beta_updates;state_.downloads_slow_network = loaded.preferences.downloads_slow_network;state_.download_server = loaded.preferences.download_server;+ state_.web_access = loaded.preferences.web_access;state_.stay_signed_in = loaded.preferences.steam_stay_signed_in;captured_preferences_ = loaded.preferences;preferences_saved_revision_ = preferences_revision_;@@ -3104,6 +3119,7 @@ bool Simulation::record_live_persistence() {after_preferences.steam_sign_in_password != captured_preferences_.steam_sign_in_password ||after_preferences.downloads_slow_network != captured_preferences_.downloads_slow_network ||after_preferences.download_server != captured_preferences_.download_server ||+ after_preferences.web_access != captured_preferences_.web_access ||after_preferences.beta_updates != captured_preferences_.beta_updates ||after_preferences.steam_stay_signed_in != captured_preferences_.steam_stay_signed_in);@@ -3130,6 +3146,7 @@ bool Simulation::record_live_persistence() {state_.beta_updates = captured_preferences_.beta_updates;state_.downloads_slow_network = captured_preferences_.downloads_slow_network;state_.download_server = captured_preferences_.download_server;+ state_.web_access = captured_preferences_.web_access;state_.stay_signed_in = captured_preferences_.steam_stay_signed_in;organization_journal_full_ = true;force_organization_reset_ = false;@@ -3532,6 +3549,14 @@ bool Simulation::scenario(const std::string& name) {state_.leftover_titles = {{"FAKE78001", "A Short Hike", 12'000'000}, {"FAKE78002", "Portal", 8'000'000}};state_.leftover_deletions.clear();state_.jobs.clear();+ } else if (name == "web-access") {+ // Settings › Web access with its made-up address and QR code.+ state_.account().authentication = AuthState::SignedIn;+ state_.navigation.modals.clear();+ state_.navigation.route = Route::Settings;+ state_.navigation.focus_key = "settings-web-access";+ state_.web_access = true;+ state_.jobs.clear();} else if (name == "download-servers") {download_server_fixture_ = true;download_servers_ = {};@@ -5640,6 +5665,38 @@ void Simulation::rebuild_view() {auto& notes = add("settings-release-notes", RowKind::Action, "Release notes", "self-update-notes");notes.subtitle = "What changed in Playden " + version_label(state_.self_update.current);}+ section = "Web access";+ {+ auto& toggle = add("settings-web-access", RowKind::Toggle, "Web access", "toggle-web-access");+ toggle.selected = state_.web_access;+ // The simulation shows a made-up address; live, the controller reports the server's.+ LiveWebAccess shown = web_access_;+ if (!live()) shown = state_.web_access ? LiveWebAccess{"on", "http://192.168.1.50:7031/", 7031, {}} : LiveWebAccess{};+ if (!state_.web_access) {+ toggle.subtitle = "Off: Playden's logs can't be opened from a browser.";+ } else if (shown.state == "on" && !shown.url.empty()) {+ toggle.subtitle = "Playden's logs on the local network while Playden is open.";+ auto& address = add("settings-web-address", RowKind::Status, "Open on a phone or computer on the same network", "");+ address.value = shown.url.substr(0, shown.url.size() - 1); // without the trailing "/"+ address.subtitle = "Shows Playden's logs, with your Steam name removed. Nothing can be changed from there yet.";+ address.qr = shown.url;+ address.enabled = false; // nothing to do on it: focus stays on the switch+ } else if (shown.state == "on") {+ toggle.subtitle = "Playden's logs on the local network while Playden is open.";+ auto& address = add("settings-web-address", RowKind::Status, "Address unknown", "");+ address.value = "port " + std::to_string(shown.port);+ address.subtitle = "Open the console's IP address shown in the PS5's network settings, port " ++ std::to_string(shown.port) + ", on a phone or computer on the same network.";+ address.enabled = false; // nothing to do on it: focus stays on the switch+ } else if (shown.state == "failed") {+ toggle.subtitle = "Playden's logs on the local network while Playden is open.";+ auto& problem = add("settings-web-problem", RowKind::Status, "Web access is not open", "");+ problem.subtitle = "Web access could not start: " + shown.error + ". Turn it off and on to try again.";+ problem.enabled = false; // nothing to do on it: focus stays on the switch+ } else {+ toggle.subtitle = "Starting…";+ }+ }section = "About";add("settings-about", RowKind::Action, "About", "about").subtitle = "Playden for PlayStation 5";auto& logs = add("settings-logs", RowKind::Action, "Logs", live() ? "logs-pick" : "logs");@@ -7928,6 +7985,7 @@ void Simulation::activate() {else if (action_name == "toggle-motion") { state_.reduced_motion = !state_.reduced_motion; save_profile(); }else if (action_name == "toggle-title-store") { state_.title_store_suffix = !state_.title_store_suffix; save_profile(); }else if (action_name == "toggle-cloud-saves") { state_.cloud_saves_auto = !state_.cloud_saves_auto; save_profile(); }+ else if (action_name == "toggle-web-access") { state_.web_access = !state_.web_access; save_profile(); }else if (action_name == "toggle-downloads-slow") {state_.downloads_slow_network = !state_.downloads_slow_network;save_profile();diff --git a/src/homebrew/simulation.hpp b/src/homebrew/simulation.hppindex bb3c3c4..577b6b8 100644--- a/src/homebrew/simulation.hpp+++ b/src/homebrew/simulation.hpp@@ -57,6 +57,14 @@ struct LiveDownloadServers {std::string preferred_name; // the stored choice's display name, even when absent from this liststd::string message; // user-facing explanation, supplied by the controller};+// Web access as the controller reports it (web::Service): the page's address for the QR, or why it isn't open.+struct LiveWebAccess {+ std::string state = "off"; // off, starting, on, failed+ std::string url; // on: http://<address>:<port>/, empty when the address is unknown+ std::uint16_t port = 0;+ std::string error; // failed: why+ bool operator==(const LiveWebAccess&) const = default;+};enum class JobState { Queued, Downloading, Pausing, Paused, Verifying, Downloaded, Failed, Cancelled, Interrupted };enum class JobStage { Download, Verify, Install, Uninstall };enum class SessionState { Idle, Preparing, Launching, Running, Stopping, Failed, Crashed };@@ -678,6 +686,7 @@ struct State {// Empty: Steam default (Steam's order); kFastestDownloadServer: Fastest (raced at each download); otherwise// the chosen provider's stable identifier.std::string download_server;+ bool web_access = true; // Settings › Web access: the logs page on the local network (on by default)bool controller_connected = true;ControllerState controller;bool persistence_available = true;@@ -710,6 +719,7 @@ struct ViewRow {std::string tone; // Saves: the status colour (good, busy, attention, problem, quiet)std::string aside; // Saves: the right-hand note (size, last sync)bool rail_only = false; // Settings: the section's rail entry is the action (Quit Playden), no card+ std::string qr; // Settings: a link drawn as a QR code beside the row's text (Web access)};struct ViewData {@@ -857,6 +867,10 @@ public:void UpdateSelfUpdate(const LiveSelfUpdate& update);[[nodiscard]] std::vector<std::string> TakeSelfUpdateRequests();void ApplyLiveDownloadServers(const LiveDownloadServers& snapshot);+ void ApplyLiveWebAccess(const LiveWebAccess& snapshot);+ // Quit Playden from outside the UI (web access). A game being prepared or queued is waited for, with the+ // dialog the TV shows then, since nobody may be in front of the TV to see a half-made title.+ void RequestQuit();[[nodiscard]] std::vector<DownloadServerRequest> TakeDownloadServerRequests();// Live mode: the folder holding install.log, auth.log and launch.log for the log viewer.void SetLogDirectory(std::filesystem::path directory);@@ -889,6 +903,8 @@ public:[[nodiscard]] std::uint64_t PreferencesRevision() const noexcept { return preferences_revision_; }[[nodiscard]] bool OrganizationDirty() const noexcept;[[nodiscard]] bool PreferencesDirty() const noexcept;+ // The saved preferences have been read (or found missing), so a setting such as web access is the player's.+ [[nodiscard]] bool PreferencesLoaded() const noexcept { return preferences_loaded_; }[[nodiscard]] bool OrganizationReadyForSave() const noexcept;void OrganizationSaveResult(std::uint64_t account, std::uint64_t revision,playden::StorageError error);@@ -1094,6 +1110,8 @@ private:bool organization_journal_full_ = false;bool organization_save_suppressed_ = false;bool preferences_load_pending_ = false;+ bool preferences_loaded_ = false;+ LiveWebAccess web_access_;bool preferences_load_may_apply_ = false;bool preferences_load_failed_ = false;bool preferences_save_failed_ = false;diff --git a/src/homebrew/view.cpp b/src/homebrew/view.cppindex 86711ac..38a4b69 100644--- a/src/homebrew/view.cpp+++ b/src/homebrew/view.cpp@@ -2340,6 +2340,8 @@ class Render::Impl}const auto drive_row = [&](const ViewRow &row) { return usage != nullptr && row.key == "settings-storage"; };const auto height = [&](const ViewRow &row) {+ if (!row.qr.empty())+ return 300.0F;return drive_row(row) ? (usage->capacity_known ? 186.0F : 160.0F) : row.subtitle.empty() ? 92.0F : 118.0F;};float offset = 0.0F;@@ -2380,6 +2382,30 @@ class Render::Implscene_.rounded_rect(card, 8.0F, kText.with_alpha(row.dangerous ? 0.0F : 0.04F));if (row.dangerous)scene_.bordered_rect(card, 8.0F, kBackground.with_alpha(0.0F), 2.0F, kRed.with_alpha(0.35F));+ if (!row.qr.empty())+ {+ // The QR code, then what to do, the address and what the page shows (Web access).+ if (row.qr != row_qr_url_)+ {+ row_qr_url_ = row.qr;+ row_qr_ = encode_qr(row.qr);+ }+ constexpr int qr_side = 240;+ if (!draw_qr_matrix(scene_, row_qr_, card.x + 30.0F, card.y + 30.0F, qr_side))+ scene_.rounded_rect({card.x + 30.0F, card.y + 30.0F, static_cast<float>(qr_side), static_cast<float>(qr_side)},+ 8.0F, kMuted.with_alpha(0.25F));+ const float text_x = card.x + 30.0F + qr_side + 40.0F;+ const float text_w = card.w - (text_x - card.x) - 30.0F;+ ui::text(scene_, fonts_.regular, fit(fonts_.regular, row.title, 24.0F, text_w), text_x, card.y + 96.0F, 24.0F,+ kSecondary);+ ui::text(scene_, fonts_.semibold, fit(fonts_.semibold, row.value, 40.0F, text_w), text_x, card.y + 150.0F,+ 40.0F, kText);+ ui::paragraph(scene_, fonts_.regular, row.subtitle, text_x, card.y + 200.0F, 22.0F, text_w, 30.0F,+ kSecondary, 2);+ focus_ring(scene_, card, amount);+ y += h + 24.0F;+ continue;+ }const gfx::Color title_ink = !row.enabled ? kMuted : row.dangerous ? kRed : kText;const float title_y = row.subtitle.empty() ? head.cy() + 11.0F : card.y + 50.0F;ui::text(scene_, fonts_.display, fit(fonts_.display, row.title, 30.0F, 760.0F), card.x + 30.0F, title_y,@@ -4262,6 +4288,8 @@ class Render::Impl// The open dialog's link (release notes), drawn as a QR code.std::string link_qr_url_;QrMatrix link_qr_;+ std::string row_qr_url_; // Settings › Web access: the page's address+ QrMatrix row_qr_;std::vector<const Game *> visible_grid_games_;GameId grid_focused_game_;const State *current_state_ = nullptr;diff --git a/src/platform/ps5/console_address.cpp b/src/platform/ps5/console_address.cppnew file mode 100644index 0000000..36c9f71--- /dev/null+++ b/src/platform/ps5/console_address.cpp@@ -0,0 +1,39 @@+// SPDX-License-Identifier: GPL-3.0-or-later+#include "platform/ps5/console_address.h"++#include <cstdio>+#include <vector>++extern "C" {+int sceNetCtlInit(void);+int sceNetCtlGetInfo(int code, void* info);+}++namespace playden::ps5 {++std::string ConsoleAddress(std::string* diagnostic) {+ constexpr int kInfoIpAddress = 14; // SCE_NET_CTL_INFO_IP_ADDRESS: char[16] at the start of the info union+ // The union's largest member is well under this; on the heap, so a small worker stack is spared.+ std::vector<char> info(1024, '\0');+ const int init = sceNetCtlInit();+ const int result = sceNetCtlGetInfo(kInfoIpAddress, info.data());+ if (diagnostic) {+ char line[96];+ std::snprintf(line, sizeof line, "netctl init=0x%08x info=0x%08x", static_cast<unsigned>(init),+ static_cast<unsigned>(result));+ *diagnostic = line;+ }+ if (result != 0) return {};+ info[15] = '\0';+ std::string address(info.data());+ // Only a dotted IPv4 address; anything else is unknown rather than wrong.+ int dots = 0;+ for (const char c : address) {+ if (c == '.') ++dots;+ else if (c < '0' || c > '9') return {};+ }+ if (dots != 3 || address == "0.0.0.0") return {};+ return address;+}++} // namespace playden::ps5diff --git a/src/platform/ps5/console_address.h b/src/platform/ps5/console_address.hnew file mode 100644index 0000000..f1ba182--- /dev/null+++ b/src/platform/ps5/console_address.h@@ -0,0 +1,12 @@+// SPDX-License-Identifier: GPL-3.0-or-later+#pragma once++#include <string>++namespace playden::ps5 {++// The console's IPv4 address from the network control service (sceNetCtlGetInfo), or empty.+// diagnostic: the calls' results, for web.log.+std::string ConsoleAddress(std::string* diagnostic = nullptr);++} // namespace playden::ps5diff --git a/src/web/address.cpp b/src/web/address.cppnew file mode 100644index 0000000..930edfb--- /dev/null+++ b/src/web/address.cpp@@ -0,0 +1,38 @@+// SPDX-License-Identifier: GPL-3.0-or-later+#include "web/address.h"++#include <arpa/inet.h>+#include <netinet/in.h>+#include <sys/socket.h>+#include <unistd.h>++namespace playden::web {++std::string LocalAddress() {+ const int fd = ::socket(AF_INET, SOCK_DGRAM, 0);+ if (fd < 0) return {};+ sockaddr_in target{};+ target.sin_family = AF_INET;+ target.sin_port = htons(53);+ inet_pton(AF_INET, "1.1.1.1", &target.sin_addr);+ sockaddr_in own{};+ socklen_t size = sizeof own;+ std::string address;+ if (::connect(fd, reinterpret_cast<sockaddr*>(&target), sizeof target) == 0 &&+ ::getsockname(fd, reinterpret_cast<sockaddr*>(&own), &size) == 0 && own.sin_family == AF_INET) {+ const std::uint32_t host = ntohl(own.sin_addr.s_addr);+ char text[INET_ADDRSTRLEN] = {};+ // 0.0.0.0, loopback and link-local are not addresses a phone on the network can reach.+ if (host != 0 && (host >> 24) != 127 && (host >> 16) != 0xa9fe && inet_ntop(AF_INET, &own.sin_addr, text, sizeof text))+ address = text;+ }+ ::close(fd);+ return address;+}++std::string PageUrl(const std::string& address, std::uint16_t port) {+ if (address.empty()) return {};+ return "http://" + address + ":" + std::to_string(port) + "/";+}++} // namespace playden::webdiff --git a/src/web/address.h b/src/web/address.hnew file mode 100644index 0000000..0a38fc3--- /dev/null+++ b/src/web/address.h@@ -0,0 +1,17 @@+// SPDX-License-Identifier: GPL-3.0-or-later+#pragma once++#include <cstdint>+#include <string>++namespace playden::web {++// This device's address on the local network, as dotted IPv4 ("192.168.1.50"), or empty. A UDP+// socket is "connected" to a public address and asked for its own address: the system picks the+// interface it would route through, and no packet is sent.+std::string LocalAddress();++// The page's address for an IPv4 address and port: "http://192.168.1.50:7031/". Empty without an address.+std::string PageUrl(const std::string& address, std::uint16_t port);++} // namespace playden::webdiff --git a/src/web/assets.h b/src/web/assets.hnew file mode 100644index 0000000..7792a2f--- /dev/null+++ b/src/web/assets.h@@ -0,0 +1,27 @@+// SPDX-License-Identifier: GPL-3.0-or-later+#pragma once++#include <cstddef>+#include <string_view>++namespace playden::web {++// The page and its fonts, baked into the binary at build time (cmake/EmbedWebAssets.cmake), so the+// page works with no internet. Served only from this table.+struct EmbeddedAsset {+ const char* path; // "/", "/assets/barlow-regular.ttf", ...+ const char* content_type;+ const unsigned char* data;+ std::size_t size;+};++extern const EmbeddedAsset kEmbeddedAssets[];+extern const std::size_t kEmbeddedAssetCount;++inline const EmbeddedAsset* FindEmbeddedAsset(std::string_view path) {+ for (std::size_t i = 0; i < kEmbeddedAssetCount; ++i)+ if (path == kEmbeddedAssets[i].path) return &kEmbeddedAssets[i];+ return nullptr;+}++} // namespace playden::webdiff --git a/src/web/http.cpp b/src/web/http.cppnew file mode 100644index 0000000..80e2104--- /dev/null+++ b/src/web/http.cpp@@ -0,0 +1,175 @@+// SPDX-License-Identifier: GPL-3.0-or-later+#include "web/http.h"++#include <cstdio>++namespace playden::web {+namespace {++int HexDigit(char c) {+ if (c >= '0' && c <= '9') return c - '0';+ if (c >= 'a' && c <= 'f') return c - 'a' + 10;+ if (c >= 'A' && c <= 'F') return c - 'A' + 10;+ return -1;+}++bool TokenChar(unsigned char c) {+ if (c >= '0' && c <= '9') return true;+ if ((c | 0x20) >= 'a' && (c | 0x20) <= 'z') return true;+ for (const char allowed : std::string_view("!#$%&'*+-.^_`|~")) if (c == static_cast<unsigned char>(allowed)) return true;+ return false;+}++std::string_view TrimSpaces(std::string_view text) {+ while (!text.empty() && (text.front() == ' ' || text.front() == '\t')) text.remove_prefix(1);+ while (!text.empty() && (text.back() == ' ' || text.back() == '\t')) text.remove_suffix(1);+ return text;+}++} // namespace++std::optional<std::string> PercentDecode(std::string_view text, bool plus_is_space) {+ std::string out;+ out.reserve(text.size());+ for (std::size_t i = 0; i < text.size(); ++i) {+ char c = text[i];+ if (c == '%') {+ if (i + 2 >= text.size()) return std::nullopt;+ const int high = HexDigit(text[i + 1]), low = HexDigit(text[i + 2]);+ if (high < 0 || low < 0) return std::nullopt;+ c = static_cast<char>(high * 16 + low);+ i += 2;+ } else if (c == '+' && plus_is_space) {+ c = ' ';+ }+ if (c == '\0') return std::nullopt;+ out.push_back(c);+ }+ return out;+}++std::optional<std::string> QueryValue(std::string_view query, std::string_view key) {+ while (!query.empty()) {+ const auto amp = query.find('&');+ const auto pair = query.substr(0, amp);+ query = amp == std::string_view::npos ? std::string_view() : query.substr(amp + 1);+ const auto equals = pair.find('=');+ const auto name = PercentDecode(pair.substr(0, equals), true);+ if (!name || *name != key) continue;+ if (equals == std::string_view::npos) return std::string();+ return PercentDecode(pair.substr(equals + 1), true);+ }+ return std::nullopt;+}++ParseResult ParseRequestHead(std::string_view bytes, Request* out) {+ std::size_t end = bytes.find("\r\n\r\n");+ std::size_t terminator = 4;+ if (const auto bare = bytes.find("\n\n"); bare != std::string_view::npos && (end == std::string_view::npos || bare < end)) {+ end = bare;+ terminator = 2;+ }+ if (end == std::string_view::npos) return bytes.size() >= kMaxRequestHead ? ParseResult::kTooLarge : ParseResult::kIncomplete;+ if (end + terminator > kMaxRequestHead) return ParseResult::kTooLarge;+ std::string_view head = bytes.substr(0, end);++ Request request;+ const auto line_end = head.find('\n');+ std::string_view line = head.substr(0, line_end);+ if (!line.empty() && line.back() == '\r') line.remove_suffix(1);+ head = line_end == std::string_view::npos ? std::string_view() : head.substr(line_end + 1);++ const auto first_space = line.find(' ');+ const auto second_space = first_space == std::string_view::npos ? first_space : line.find(' ', first_space + 1);+ if (first_space == 0 || second_space == std::string_view::npos || line.find(' ', second_space + 1) != std::string_view::npos)+ return ParseResult::kBadRequest;+ const auto method = line.substr(0, first_space);+ const auto target = line.substr(first_space + 1, second_space - first_space - 1);+ const auto version = line.substr(second_space + 1);+ for (const unsigned char c : method) if (!TokenChar(c)) return ParseResult::kBadRequest;+ if (version != "HTTP/1.1" && version != "HTTP/1.0") return ParseResult::kBadRequest;+ // Origin form only: "/path?query". No absolute URLs, no "*".+ if (target.empty() || target.front() != '/') return ParseResult::kBadRequest;+ for (const unsigned char c : target) if (c <= 0x20 || c >= 0x7f) return ParseResult::kBadRequest;+ request.method_text = std::string(method);+ request.method = method == "GET" ? Method::kGet : method == "HEAD" ? Method::kHead : method == "POST" ? Method::kPost : Method::kOther;+ const auto question = target.find('?');+ auto path = PercentDecode(target.substr(0, question));+ if (!path) return ParseResult::kBadRequest;+ request.path = std::move(*path);+ if (question != std::string_view::npos) request.query = std::string(target.substr(question + 1));++ while (!head.empty()) {+ const auto next = head.find('\n');+ std::string_view header = head.substr(0, next);+ head = next == std::string_view::npos ? std::string_view() : head.substr(next + 1);+ if (!header.empty() && header.back() == '\r') header.remove_suffix(1);+ if (header.empty()) continue;+ const auto colon = header.find(':');+ if (colon == 0 || colon == std::string_view::npos) return ParseResult::kBadRequest;+ std::string name(header.substr(0, colon));+ for (auto& c : name) {+ if (!TokenChar(static_cast<unsigned char>(c))) return ParseResult::kBadRequest;+ if (c >= 'A' && c <= 'Z') c = static_cast<char>(c - 'A' + 'a');+ }+ const auto value = TrimSpaces(header.substr(colon + 1));+ for (const unsigned char c : value) if ((c < 0x20 && c != '\t') || c == 0x7f) return ParseResult::kBadRequest;+ request.headers.emplace_back(std::move(name), std::string(value));+ }+ *out = std::move(request);+ return ParseResult::kOk;+}++const char* StatusText(int status) {+ switch (status) {+ case 200: return "OK";+ case 202: return "Accepted";+ case 400: return "Bad Request";+ case 403: return "Forbidden";+ case 404: return "Not Found";+ case 405: return "Method Not Allowed";+ case 408: return "Request Timeout";+ case 431: return "Request Header Fields Too Large";+ case 500: return "Internal Server Error";+ case 503: return "Service Unavailable";+ default: return "Unknown";+ }+}++Response::Response(Write write, bool head_only) : write_(std::move(write)), head_only_(head_only) {}++bool Response::Start(int status, std::string_view content_type, std::optional<std::uint64_t> length,+ const std::vector<std::pair<std::string, std::string>>& extra) {+ if (started_) return !failed_;+ started_ = true;+ status_ = status;+ char line[64];+ std::snprintf(line, sizeof line, "HTTP/1.1 %d %s\r\n", status, StatusText(status));+ std::string head = line;+ head += "Content-Type: ";+ head += content_type;+ head += "\r\n";+ if (length) head += "Content-Length: " + std::to_string(*length) + "\r\n";+ for (const auto& [name, value] : extra) head += name + ": " + value + "\r\n";+ head += "X-Content-Type-Options: nosniff\r\nConnection: close\r\n\r\n";+ if (!write_(head.data(), head.size())) failed_ = true;+ return !failed_;+}++bool Response::Body(const char* data, std::size_t size) {+ if (!started_ || failed_) return false;+ if (head_only_ || size == 0) return true;+ if (!write_(data, size)) {+ failed_ = true;+ return false;+ }+ body_bytes_ += size;+ return true;+}++bool Response::Send(int status, std::string_view content_type, std::string_view body,+ const std::vector<std::pair<std::string, std::string>>& extra) {+ return Start(status, content_type, body.size(), extra) && Body(body);+}++} // namespace playden::webdiff --git a/src/web/http.h b/src/web/http.hnew file mode 100644index 0000000..df1fd76--- /dev/null+++ b/src/web/http.h@@ -0,0 +1,72 @@+// SPDX-License-Identifier: GPL-3.0-or-later+#pragma once++#include <cstddef>+#include <cstdint>+#include <functional>+#include <optional>+#include <string>+#include <string_view>+#include <utility>+#include <vector>++namespace playden::web {++// The request line and headers, up to the blank line; a longer head is refused with 431.+inline constexpr std::size_t kMaxRequestHead = 8 * 1024;++enum class Method { kGet, kHead, kPost, kOther };++struct Request {+ Method method = Method::kOther;+ std::string method_text; // as sent, for web.log+ std::string path; // percent-decoded, without the query+ std::string query; // raw, after '?'+ std::vector<std::pair<std::string, std::string>> headers; // names lower-cased+};++enum class ParseResult { kIncomplete, kOk, kBadRequest, kTooLarge };++// Parses an HTTP/1.x request head from the bytes received so far. kIncomplete: no blank line yet+// and still under kMaxRequestHead. The body, if any, is ignored.+ParseResult ParseRequestHead(std::string_view bytes, Request* out);++// The percent-decoded value of key in a query string ("title=FAKE78012&x=1"), or nothing.+std::optional<std::string> QueryValue(std::string_view query, std::string_view key);+// Decodes %XX and, in queries, '+'; nothing on a bad escape or a decoded NUL.+std::optional<std::string> PercentDecode(std::string_view text, bool plus_is_space = false);++const char* StatusText(int status);++// One response written through write(), which returns false once the client is gone. HEAD sends+// the headers only. Every response closes the connection.+class Response {+ public:+ using Write = std::function<bool(const char* data, std::size_t size)>;+ Response(Write write, bool head_only);++ // Sends the status line and headers. length: Content-Length, or none for a body that ends when+ // the connection closes (a streamed zip).+ bool Start(int status, std::string_view content_type, std::optional<std::uint64_t> length,+ const std::vector<std::pair<std::string, std::string>>& extra = {});+ bool Body(const char* data, std::size_t size);+ bool Body(std::string_view text) { return Body(text.data(), text.size()); }+ // A complete small response: Start with the body's length, then the body.+ bool Send(int status, std::string_view content_type, std::string_view body,+ const std::vector<std::pair<std::string, std::string>>& extra = {});++ bool started() const { return started_; }+ int status() const { return status_; }+ std::uint64_t body_bytes() const { return body_bytes_; }+ bool failed() const { return failed_; }++ private:+ Write write_;+ bool head_only_ = false;+ bool started_ = false;+ bool failed_ = false;+ int status_ = 0;+ std::uint64_t body_bytes_ = 0;+};++} // namespace playden::webdiff --git a/src/web/logs_source.cpp b/src/web/logs_source.cppnew file mode 100644index 0000000..d6bddc9--- /dev/null+++ b/src/web/logs_source.cpp@@ -0,0 +1,525 @@+// SPDX-License-Identifier: GPL-3.0-or-later+#include "web/logs_source.h"++#include "app/diagnostic_log.h"+#include "platform/directory_walk.h"+#include "steam/backend/json.h"+#include "web/zip.h"++#include <algorithm>+#include <cerrno>+#include <dirent.h>+#include <fcntl.h>+#include <limits>+#include <sys/stat.h>+#include <unistd.h>++namespace playden::web {+namespace {+namespace json = steam::json;++constexpr std::string_view kTitlePrefix = "title-";+constexpr std::string_view kSteamIdPrefix = "7656119";+constexpr std::string_view kKitId = "playden-kit";+// What Playden's "Store name in PS5 titles" setting adds to a title name; imported games get none.+constexpr std::string_view kStoreSuffixes[] = {" (Steam)", " (GOG)", " (Epic)"};++bool Digit(char c) { return c >= '0' && c <= '9'; }++// A regex word character for \b: ASCII letters, digits and '_'. Python also counts non-ASCII letters; treating+// every non-ASCII byte as a boundary instead redacts a SteamID in typographic quotes too, and at worst a little more.+bool WordChar(char c) {+ const auto u = static_cast<unsigned char>(c);+ return Digit(c) || ((u | 0x20) >= 'a' && (u | 0x20) <= 'z') || c == '_';+}++char Lower(char c) { return c >= 'A' && c <= 'Z' ? static_cast<char>(c - 'A' + 'a') : c; }++std::string LowerAscii(std::string_view text) {+ std::string out(text);+ for (auto& c : out) c = Lower(c);+ return out;+}++struct Entry {+ std::string name;+ std::uint64_t size = 0;+ std::int64_t changed = 0;+ bool directory = false;+};++// The plain files and folders of a directory, by absolute path: links and anything else are left out.+std::vector<Entry> ListDirectory(const std::string& path) {+ std::vector<Entry> entries;+ const int fd = platform::OpenDirectoryWalk(path);+ if (fd < 0) return entries;+ DIR* directory = ::fdopendir(fd);+ if (!directory) {+ ::close(fd);+ return entries;+ }+ while (entries.size() < 4096) {+ errno = 0;+ 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;+ entries.push_back({name, static_cast<std::uint64_t>(info.st_size > 0 ? info.st_size : 0),+ static_cast<std::int64_t>(info.st_mtime), S_ISDIR(info.st_mode)});+ }+ ::closedir(directory);+ return entries;+}++// A regular file's bytes, opened through its folder without following links. The strict walk checks the file is+// the one the held folder lists, so a folder swapped for a link after the walk (to the user data, say) is refused.+// A file over max_bytes gives its last max_bytes, after a line saying how much was left out.+std::optional<std::string> ReadFile(const std::string& directory, const std::string& name, std::size_t max_bytes) {+ const int parent = platform::OpenDirectoryWalk(directory);+ if (parent < 0) return std::nullopt;+ const int fd = platform::OpenWalkChild(parent, name.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK);+ ::close(parent);+ if (fd < 0) return std::nullopt;+ struct stat info{};+ if (::fstat(fd, &info) != 0 || !S_ISREG(info.st_mode)) {+ ::close(fd);+ return std::nullopt;+ }+ std::string note;+ if (info.st_size > 0 && static_cast<std::uint64_t>(info.st_size) > max_bytes) {+ const auto skipped = static_cast<std::uint64_t>(info.st_size) - max_bytes;+ if (::lseek(fd, static_cast<off_t>(skipped), SEEK_SET) < 0) {+ ::close(fd);+ return std::nullopt;+ }+ note = "[Playden: the first " + std::to_string(skipped) + " bytes of this file are left out]\n";+ }+ std::string bytes = note;+ bytes.reserve(std::min<std::size_t>(static_cast<std::size_t>(info.st_size > 0 ? info.st_size : 0), max_bytes));+ std::string chunk(64 * 1024, '\0');+ bool ok = true;+ while (bytes.size() < max_bytes + note.size()) {+ const auto count = ::read(fd, chunk.data(), std::min(chunk.size(), max_bytes + note.size() - bytes.size()));+ if (count < 0 && errno == EINTR) continue;+ if (count < 0) ok = false;+ if (count <= 0) break;+ bytes.append(chunk.data(), static_cast<std::size_t>(count));+ }+ ::close(fd);+ if (!ok) return std::nullopt;+ return bytes;+}++std::string Trimmed(std::string_view text) {+ while (!text.empty() && static_cast<unsigned char>(text.front()) <= ' ') text.remove_prefix(1);+ while (!text.empty() && static_cast<unsigned char>(text.back()) <= ' ') text.remove_suffix(1);+ return std::string(text);+}++void ReplaceAll(std::string& text, std::string_view from, std::string_view to) {+ if (from.empty()) return;+ std::string out;+ std::size_t start = 0;+ for (std::size_t at; (at = text.find(from, start)) != std::string::npos; start = at + from.size()) {+ out.append(text, start, at - start);+ out += to;+ }+ if (start == 0) return;+ out.append(text, start, std::string::npos);+ text = std::move(out);+}++} // namespace++bool LogsIndex::HasFile(std::string_view name) const {+ for (const auto& log : playden) if (log.name == name) return true;+ for (const auto& game : games)+ for (const auto& file : game.files) if (file == name) return true;+ return false;+}++const GameLog* LogsIndex::Game(std::string_view title) const {+ for (const auto& game : games) if (game.title == title) return &game;+ return nullptr;+}++std::optional<std::string> TitleLogId(std::string_view file) {+ // ^title-(FAKE\d{5})\.log$+ if (file.size() != 19 || file.substr(0, 10) != "title-FAKE" || file.substr(15) != ".log") return std::nullopt;+ for (const char c : file.substr(10, 5)) if (!Digit(c)) return std::nullopt;+ return std::string(file.substr(6, 9));+}++std::uint32_t TitleApp(std::string_view text) {+ constexpr std::string_view kProfile = "profile=playden-steam-";+ text = text.substr(0, 4096);+ for (std::size_t at = text.find(kProfile); at != std::string_view::npos; at = text.find(kProfile, at + 1)) {+ std::uint64_t value = 0;+ std::size_t i = at + kProfile.size(), digits = 0;+ for (; i < text.size() && Digit(text[i]) && digits < 11; ++i, ++digits) value = value * 10 + (text[i] - '0');+ if (digits == 0) continue;+ return digits <= 10 && value <= std::numeric_limits<std::uint32_t>::max() ? static_cast<std::uint32_t>(value) : 0;+ }+ return 0;+}++std::int64_t LastRun(std::string_view text) {+ constexpr std::string_view kReport = "PW_REPORT/1 ";+ std::int64_t newest = 0;+ std::size_t start = 0;+ while (start < text.size()) {+ const auto end = std::min(text.find('\n', start), text.size());+ const auto line = text.substr(start, end - start);+ start = end + 1;+ if (line.compare(0, kReport.size(), kReport) != 0) continue;+ for (std::size_t at = line.find("time=", kReport.size() - 1); at != std::string_view::npos; at = line.find("time=", at + 1)) {+ if (at > 0 && WordChar(line[at - 1])) continue;+ std::size_t i = at + 5;+ std::int64_t value = 0;+ bool overflow = false;+ for (; i < line.size() && Digit(line[i]); ++i) {+ if (value > (std::numeric_limits<std::int64_t>::max() - 9) / 10) overflow = true;+ else value = value * 10 + (line[i] - '0');+ }+ if (i == at + 5) continue;+ if (!overflow) newest = std::max(newest, value);+ break;+ }+ }+ return newest;+}++std::string WithoutStoreSuffix(const std::string& name) {+ for (const auto suffix : kStoreSuffixes)+ if (name.size() > suffix.size() && name.compare(name.size() - suffix.size(), suffix.size(), suffix) == 0)+ return name.substr(0, name.size() - suffix.size());+ return name;+}++std::string TitleNameFromParam(std::string_view text) {+ const auto parsed = json::Parse(text, {64 * 1024, 8, 4096, 4096});+ if (!parsed || !parsed->is_object()) return {};+ const auto* localized = parsed->Find("localizedParameters");+ if (!localized || !localized->is_object()) return {};+ const auto* language = localized->Find("defaultLanguage");+ const auto name_in = [&](std::string_view key) -> std::string {+ const auto* entry = localized->Find(key);+ const auto* name = entry && entry->is_object() ? entry->Find("titleName") : nullptr;+ if (!name || !name->is_string() || name->text().size() > 512) return {};+ for (const unsigned char c : name->text()) if (c < 0x20 || c == 0x7f) return {};+ return name->text();+ };+ std::string name = name_in(language && language->is_string() ? std::string_view(language->text()) : "en-US");+ if (name.empty()) name = name_in("en-US");+ return WithoutStoreSuffix(name);+}++void AddAccountNames(std::string_view text, std::set<std::string>* names) {+ for (const std::string_view key : {std::string_view("L\"SteamUser\" L\""), std::string_view("L\"SteamAppUser\" L\"")}) {+ for (std::size_t at = text.find(key); at != std::string_view::npos; at = text.find(key, at + 1)) {+ const auto start = at + key.size();+ const auto end = text.find('"', start);+ if (end == std::string_view::npos) break;+ if (end > start && end - start <= 256) names->insert(std::string(text.substr(start, end - start)));+ }+ }+}++std::string Redact(std::string_view text, const std::set<std::string>& found, const Redaction& account) {+ std::string out;+ out.reserve(text.size());+ // SteamIDs: \b7656119\d{10}\b.+ for (std::size_t i = 0; i < text.size();) {+ if (text.compare(i, kSteamIdPrefix.size(), kSteamIdPrefix) == 0 && (i == 0 || !WordChar(text[i - 1])) &&+ i + 17 <= text.size() && (i + 17 == text.size() || !WordChar(text[i + 17]))) {+ bool digits = true;+ for (std::size_t j = i + 7; j < i + 17; ++j) digits = digits && Digit(text[j]);+ if (digits) {+ out += "<steam-id>";+ i += 17;+ continue;+ }+ }+ out.push_back(text[i++]);+ }+ if (account.steam_id != 0) ReplaceAll(out, std::to_string(account.steam_id), "<steam-id>");+ std::vector<std::string> names(found.begin(), found.end());+ if (!account.account_name.empty()) names.push_back(account.account_name);+ std::sort(names.begin(), names.end(), [](const std::string& a, const std::string& b) { return a.size() > b.size(); });+ for (const auto& name : names) {+ if (name.empty()) continue;+ // ASCII case only: Python also folds other letters, which account names rarely have.+ const auto needle = LowerAscii(name);+ const auto lowered = LowerAscii(out);+ std::string replaced;+ std::size_t start = 0;+ for (std::size_t at; (at = lowered.find(needle, start)) != std::string::npos; start = at + needle.size()) {+ replaced.append(out, start, at - start);+ replaced += "<steam-user>";+ }+ if (start == 0) continue;+ replaced.append(out, start, std::string::npos);+ out = std::move(replaced);+ }+ return out;+}++std::string Firmware(const std::vector<std::string_view>& texts) {+ constexpr std::string_view kKey = "console_firmware=";+ std::string found;+ for (const auto text : texts)+ for (std::size_t at = text.find(kKey); at != std::string_view::npos; at = text.find(kKey, at + 1)) {+ auto end = at + kKey.size();+ while (end < text.size() && !(text[end] == ' ' || text[end] == '\t' || text[end] == '\n' || text[end] == '\r' ||+ text[end] == '\f' || text[end] == '\v')) ++end;+ if (end > at + kKey.size()) found = std::string(text.substr(at + kKey.size(), end - at - kKey.size()));+ }+ return found;+}++std::string Utf8Clean(std::string_view text) {+ std::string out;+ out.reserve(text.size());+ for (std::size_t i = 0; i < text.size();) {+ const auto c = static_cast<unsigned char>(text[i]);+ std::size_t length = c < 0x80 ? 1 : (c >> 5) == 0x6 ? 2 : (c >> 4) == 0xe ? 3 : (c >> 3) == 0x1e ? 4 : 0;+ bool valid = length > 0 && i + length <= text.size();+ for (std::size_t j = 1; valid && j < length; ++j) valid = (static_cast<unsigned char>(text[i + j]) & 0xc0) == 0x80;+ if (valid && length > 1) {+ // Overlong forms, surrogates and values past U+10FFFF are invalid too.+ std::uint32_t code = c & (0x7f >> length);+ for (std::size_t j = 1; j < length; ++j) code = (code << 6) | (static_cast<unsigned char>(text[i + j]) & 0x3f);+ const std::uint32_t least[] = {0, 0, 0x80, 0x800, 0x10000};+ valid = code >= least[length] && code <= 0x10ffff && (code < 0xd800 || code > 0xdfff);+ }+ if (!valid) {+ out += "\xef\xbf\xbd";+ ++i;+ continue;+ }+ out.append(text.data() + i, length);+ i += length;+ }+ return out;+}++std::string JsonString(std::string_view text) {+ const auto clean = Utf8Clean(text);+ std::string out = "\"";+ for (const char c : clean) {+ if (c == '"' || c == '\\') {+ out.push_back('\\');+ out.push_back(c);+ } else if (static_cast<unsigned char>(c) < 0x20 || c == 0x7f) {+ char escaped[8];+ std::snprintf(escaped, sizeof escaped, "\\u%04x", static_cast<unsigned>(static_cast<unsigned char>(c)));+ out += escaped;+ } else {+ out.push_back(c);+ }+ }+ return out + "\"";+}++std::string Summary(const std::vector<std::pair<std::string, std::string>>& fields) {+ std::string out = "| Field | Value |\n| --- | --- |";+ for (const auto& [key, value] : fields) out += "\n| " + key + " | " + (value.empty() ? std::string("unknown") : value) + " |";+ return out + "\n";+}++std::string CollectedTime(std::int64_t unix_seconds) {+ const auto stamp = app::FormatLogTimestamp(unix_seconds); // 2026-10-28T15:04:05Z+ return stamp.substr(0, 10) + " " + stamp.substr(11, 5) + " UTC";+}++std::string ReportFileName(std::int64_t unix_seconds) {+ const auto stamp = app::FormatLogTimestamp(unix_seconds);+ return "playden-logs-" + stamp.substr(0, 4) + stamp.substr(5, 2) + stamp.substr(8, 2) + "-" + stamp.substr(11, 2) ++ stamp.substr(14, 2) + stamp.substr(17, 2) + ".zip";+}++LogsSource::LogsSource(LogsPaths paths) : paths_(std::move(paths)) {}++std::optional<std::string> LogsSource::ReadLogFile(std::string_view name) const {+ auto bytes = ReadFile(paths_.logs, std::string(name), kMaxFileBytes);+ if (!bytes) return std::nullopt;+ return Utf8Clean(*bytes);+}++LogsIndex LogsSource::Index() const {+ LogsIndex index;+ const auto entries = ListDirectory(paths_.logs);+ for (const auto& entry : entries) {+ if (entry.directory || entry.name.size() >= 4 && entry.name.compare(entry.name.size() - 4, 4, ".ppm") == 0) continue;+ if (const auto title = TitleLogId(entry.name)) {+ GameLog game;+ game.title = *title;+ game.files.push_back(entry.name);+ game.size = entry.size;+ if (const auto text = ReadLogFile(entry.name)) {+ game.app = TitleApp(*text);+ game.last_run = LastRun(*text);+ }+ // Per-title extras such as registry dumps go with their title.+ const std::string prefix = "title-" + game.title + ".";+ for (const auto& extra : entries)+ if (!extra.directory && extra.name != entry.name && extra.name.compare(0, prefix.size(), prefix) == 0 &&+ !(extra.name.size() >= 4 && extra.name.compare(extra.name.size() - 4, 4, ".ppm") == 0)) {+ game.files.push_back(extra.name);+ game.size += extra.size;+ }+ std::sort(game.files.begin() + 1, game.files.end());+ if (const auto param = ReadFile(paths_.homebrew + "/" + game.title + "/sce_sys", "param.json", 64 * 1024))+ game.name = TitleNameFromParam(*param);+ index.games.push_back(std::move(game));+ } else if (entry.name.compare(0, kTitlePrefix.size(), kTitlePrefix) != 0) {+ index.playden.push_back({entry.name, entry.changed, entry.size});+ }+ }+ std::sort(index.games.begin(), index.games.end(), [](const GameLog& a, const GameLog& b) {+ return a.last_run != b.last_run ? a.last_run > b.last_run : a.title < b.title;+ });+ std::sort(index.playden.begin(), index.playden.end(), [](const PlaydenLog& a, const PlaydenLog& b) { return a.name < b.name; });+ return index;+}++std::vector<std::pair<std::string, std::string>> LogsSource::Facts(std::int64_t now) const {+ std::vector<std::pair<std::string, std::string>> facts;+ facts.emplace_back("collected", CollectedTime(now));+ std::string package;+ if (const auto identity = ReadFile(paths_.app, "playden-package.identity", 4096)) {+ // The identity's last word, shortened as the Python tool does.+ const auto text = Trimmed(*identity);+ const auto space = text.find_last_of(" \t\r\n");+ package = (space == std::string::npos ? text : text.substr(space + 1)).substr(0, 12);+ }+ facts.emplace_back("Playden package", Utf8Clean(package));+ const auto version = ReadFile(paths_.app, "playden-version", 256);+ facts.emplace_back("Playden version", version ? Utf8Clean(Trimmed(*version)) : std::string());+ const auto older = ReadLogFile("runtime.log.1"), current = ReadLogFile("runtime.log");+ facts.emplace_back("firmware", Firmware({older ? std::string_view(*older) : "", current ? std::string_view(*current) : ""}));++ // The current kit folder first: a console updated from an earlier Playden may still hold the kit under the+ // id it had before, until Playden retires it. Other folders are listed.+ std::vector<std::string> kits;+ for (const auto& entry : ListDirectory(paths_.kits))+ if (entry.directory && entry.name[0] != '.') kits.push_back(entry.name);+ std::sort(kits.begin(), kits.end(), [](const std::string& a, const std::string& b) {+ if ((a == kKitId) != (b == kKitId)) return a == kKitId;+ return a < b;+ });+ std::string others;+ for (std::size_t i = 1; i < kits.size(); ++i) others += (i > 1 ? ", " : "") + kits[i];+ bool found = false;+ for (const auto& kit : kits) {+ // A kit's manifest lists every file of the kit (about a megabyte and 20,000 values): the runtime's own limits.+ constexpr std::size_t kManifestBytes = 8 * 1024 * 1024, kManifestValues = 32768 * 8;+ const auto text = ReadFile(paths_.kits + "/" + kit, "manifest.json", kManifestBytes);+ const auto manifest = text ? json::Parse(*text, {kManifestBytes, 16, kManifestValues, 1024 * 1024}) : std::nullopt;+ if (!manifest || !manifest->is_object()) continue;+ // No kit_id: kit releases share it (the install folder), so it says nothing.+ std::string runtime, capabilities;+ if (const auto* section = manifest->Find("runtime"); section && section->is_object())+ if (const auto* revision = section->Find("artifact_revision"); revision && revision->is_string()) runtime = revision->text();+ if (const auto* list = manifest->Find("capabilities"); list && list->is_array())+ for (const auto& capability : list->array())+ if (capability.is_string()) capabilities += (capabilities.empty() ? "" : ", ") + capability.text();+ facts.emplace_back("kit runtime", Utf8Clean(runtime));+ facts.emplace_back("kit capabilities", Utf8Clean(capabilities));+ found = true;+ break;+ }+ if (!found) facts.emplace_back("kit runtime", "");+ if (!others.empty()) facts.emplace_back("other kit folders", Utf8Clean(others));+ return facts;+}++std::string LogsSource::StatusJson(std::int64_t now) const {+ const auto facts = Facts(now);+ const auto fact = [&](std::string_view key) {+ for (const auto& [name, value] : facts) if (name == key) return value.empty() ? std::string("null") : JsonString(value);+ return std::string("null");+ };+ return "{\"version\":" + fact("Playden version") + ",\"package\":" + fact("Playden package") ++ ",\"firmware\":" + fact("firmware") + ",\"kit_runtime\":" + fact("kit runtime") ++ ",\"kit_capabilities\":" + fact("kit capabilities") + ",\"other_kit_folders\":" + fact("other kit folders") ++ ",\"redacted\":\"Steam account name and SteamIDs\",\"collected\":" + fact("collected") + "}";+}++std::string LogsSource::IndexJson(const LogsIndex& index) const {+ std::string out = "{\"games\":[";+ for (std::size_t i = 0; i < index.games.size(); ++i) {+ const auto& game = index.games[i];+ out += (i ? "," : "") + std::string("{\"title\":") + JsonString(game.title) ++ ",\"app\":" + (game.app ? std::to_string(game.app) : "null") ++ ",\"name\":" + (game.name.empty() ? "null" : JsonString(game.name)) ++ ",\"last_run\":" + std::to_string(game.last_run) + ",\"size\":" + std::to_string(game.size) + ",\"files\":[";+ for (std::size_t j = 0; j < game.files.size(); ++j) out += (j ? "," : "") + JsonString(game.files[j]);+ out += "]}";+ }+ out += "],\"playden\":[";+ for (std::size_t i = 0; i < index.playden.size(); ++i) {+ const auto& log = index.playden[i];+ out += (i ? "," : "") + std::string("{\"name\":") + JsonString(log.name) + ",\"changed\":" + std::to_string(log.changed) ++ ",\"size\":" + std::to_string(log.size) + "}";+ }+ return out + "]}";+}++std::set<std::string> LogsSource::FoundNames(const LogsIndex& index) const {+ // Names come from every log, so a game that stopped before Wine named the user is still covered.+ std::set<std::string> names;+ const auto add = [&](const std::string& file) {+ if (const auto text = ReadLogFile(file)) AddAccountNames(*text, &names);+ };+ for (const auto& log : index.playden) add(log.name);+ for (const auto& game : index.games)+ for (const auto& file : game.files) add(file);+ return names;+}++std::optional<std::string> LogsSource::ReadLog(const LogsIndex& index, std::string_view name, const Redaction& account) const {+ if (name.empty() || name.find('/') != std::string_view::npos || name == "." || name == ".." || !index.HasFile(name))+ return std::nullopt;+ const auto text = ReadLogFile(name);+ if (!text) return std::nullopt;+ return Redact(*text, FoundNames(index), account);+}++bool LogsSource::WriteReport(const LogsIndex& index, std::string_view title, const Redaction& account, std::int64_t now,+ const Write& write) const {+ std::vector<const GameLog*> chosen;+ if (title == "all") {+ for (const auto& game : index.games) chosen.push_back(&game);+ std::sort(chosen.begin(), chosen.end(), [](const GameLog* a, const GameLog* b) { return a->title < b->title; });+ } else if (title.empty()) {+ if (!index.games.empty()) chosen.push_back(&index.games.front());+ } else if (const auto* game = index.Game(title)) {+ chosen.push_back(game);+ }+ auto fields = Facts(now);+ std::string titles;+ for (const auto* game : chosen)+ titles += (titles.empty() ? "" : ", ") + game->title + " (app " + (game->app ? std::to_string(game->app) : "?") + ")";+ fields.emplace_back("game titles", titles.empty() ? "none" : titles);+ fields.emplace_back("redacted", "Steam account name and SteamIDs");++ std::vector<std::string> files;+ for (const auto& log : index.playden) files.push_back(log.name);+ for (const auto* game : chosen) files.insert(files.end(), game->files.begin(), game->files.end());+ std::sort(files.begin(), files.end());+ const auto names = FoundNames(index);+ StoredZip zip(write, now);+ if (!zip.Add("summary.md", Summary(fields))) return false;+ for (const auto& file : files) {+ // A log that went away since the index was read is left out.+ const auto text = ReadLogFile(file);+ if (text && !zip.Add("logs/" + file, Redact(*text, names, account))) return false;+ }+ return zip.Finish();+}++} // namespace playden::webdiff --git a/src/web/logs_source.h b/src/web/logs_source.hnew file mode 100644index 0000000..2105280--- /dev/null+++ b/src/web/logs_source.h@@ -0,0 +1,107 @@+// SPDX-License-Identifier: GPL-3.0-or-later+#pragma once++#include <cstdint>+#include <functional>+#include <optional>+#include <set>+#include <string>+#include <string_view>+#include <utility>+#include <vector>++namespace playden::web {++// What the web page reads, all of it what tools/collect_logs.py reads over FTP: the logs folder,+// the kits' manifests, the app's version and package identity, and each listed title's param.json.+// Never the user data folder, a bottle or a game's files.+struct LogsPaths {+ std::string logs; // /data/playden/logs+ std::string homebrew; // /data/homebrew: <title>/sce_sys/param.json+ std::string kits; // /data/playden/kits+ std::string app; // /data/homebrew/FAKE77031: playden-version, playden-package.identity+};++// The signed-in Steam account, replaced in everything served. Not a credential.+struct Redaction {+ std::string account_name;+ std::uint64_t steam_id = 0;+};++struct GameLog {+ std::string title; // FAKE78012+ std::uint32_t app = 0; // 0: unknown+ std::string name; // from the title's param.json, without Playden's store suffix; empty: unknown+ std::int64_t last_run = 0;+ std::uint64_t size = 0; // the title log and its extras+ std::vector<std::string> files; // title-FAKE78012.log first, then its extras (title-FAKE78012.*)+};++struct PlaydenLog {+ std::string name;+ std::int64_t changed = 0;+ std::uint64_t size = 0;+};++struct LogsIndex {+ std::vector<GameLog> games; // most recently run first+ std::vector<PlaydenLog> playden; // by name+ bool HasFile(std::string_view name) const;+ const GameLog* Game(std::string_view title) const;+};++// Pure helpers, the same rules as collect_logs.py.+// "title-FAKE78012.log" -> "FAKE78012".+std::optional<std::string> TitleLogId(std::string_view file);+// The Steam app ID from "profile=playden-steam-<id>" in a title log's first 4 KB, or 0.+std::uint32_t TitleApp(std::string_view text);+// The newest "time=" of a "PW_REPORT/1 ..." line (seconds since 1970), or 0.+std::int64_t LastRun(std::string_view text);+// "Half-Life 2 (Steam)" -> "Half-Life 2"; one store suffix at most, and never the whole name.+std::string WithoutStoreSuffix(const std::string& name);+// The default language's titleName in a title's param.json, without the store suffix; empty if none.+std::string TitleNameFromParam(std::string_view json);+// Steam account names a log shows in Wine's L"SteamUser" L"<name>" and L"SteamAppUser" L"<name>".+void AddAccountNames(std::string_view text, std::set<std::string>* names);+// SteamIDs (7656119 and ten more digits) become <steam-id>, the signed-in account's ID too; every+// name (the signed-in one and the found ones, longest first, ignoring ASCII case) becomes <steam-user>.+std::string Redact(std::string_view text, const std::set<std::string>& names, const Redaction& account);+// The last console_firmware= value in the texts, in order; empty if none.+std::string Firmware(const std::vector<std::string_view>& texts);+// Invalid UTF-8 replaced with U+FFFD, as Python's decode(errors="replace").+std::string Utf8Clean(std::string_view text);+std::string JsonString(std::string_view text);+// summary.md: a two-column Markdown table; an empty value says "unknown".+std::string Summary(const std::vector<std::pair<std::string, std::string>>& fields);+// "2026-10-28 15:04 UTC" and "20261028-150405" for a Unix time.+std::string CollectedTime(std::int64_t unix_seconds);+std::string ReportFileName(std::int64_t unix_seconds);++class LogsSource {+ public:+ using Write = std::function<bool(const char* data, std::size_t size)>;+ explicit LogsSource(LogsPaths paths);++ LogsIndex Index() const;+ // The summary's facts, in its order, before the game titles: collected, Playden package, Playden+ // version, firmware, kit runtime, kit capabilities (and other kit folders when there are some).+ std::vector<std::pair<std::string, std::string>> Facts(std::int64_t now) const;+ std::string StatusJson(std::int64_t now) const;+ std::string IndexJson(const LogsIndex& index) const;+ // One log from the index, redacted. Nothing for a name the index doesn't list.+ std::optional<std::string> ReadLog(const LogsIndex& index, std::string_view name, const Redaction& account) const;+ // The report: summary.md, then logs/<name> for Playden's logs and the chosen games' logs, each+ // redacted and written one at a time. title: a title ID, "all", or empty for the most recent game.+ // A title with no log gives Playden's logs only, as collect_logs.py does.+ bool WriteReport(const LogsIndex& index, std::string_view title, const Redaction& account, std::int64_t now,+ const Write& write) const;++ static constexpr std::size_t kMaxFileBytes = 8 * 1024 * 1024;++ private:+ std::optional<std::string> ReadLogFile(std::string_view name) const;+ std::set<std::string> FoundNames(const LogsIndex& index) const;+ LogsPaths paths_;+};++} // namespace playden::webdiff --git a/src/web/page/index.html b/src/web/page/index.htmlnew file mode 100644index 0000000..d3f6678--- /dev/null+++ b/src/web/page/index.html@@ -0,0 +1,304 @@+<!doctype html>+<!-- SPDX-License-Identifier: GPL-3.0-or-later -->+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<meta name="robots" content="noindex, nofollow">+<meta name="color-scheme" content="dark">+<title>Playden on PS5</title>+<style>+/* The builds.playden.club look: same tokens, Barlow, tables and buttons, cards below 720 px. Nothing loads from the internet. */+@font-face { font-family: "Barlow"; font-weight: 400; font-style: normal; src: url("/assets/barlow-regular.ttf") format("truetype"); }+@font-face { font-family: "Barlow"; font-weight: 600; font-style: normal; src: url("/assets/barlow-semibold.ttf") format("truetype"); }+:root {+ --ground: #0e0d0c;+ --row: #17150f;+ --row-open: #1f1c17;+ --line: #2a2620;+ --ink: #f3efe9;+ --soft: #a8a29e;+ --accent: #f0863a;+ --on-accent: #0e0d0c;+ --ok: #8fbf7a;+ --warn: #e0b25c;+}+* { box-sizing: border-box; }+html, body { margin: 0; background: var(--ground); color: var(--ink); }+body { font: 400 16px/1.5 "Barlow", -apple-system, "Segoe UI", sans-serif; font-variant-numeric: tabular-nums;+ -webkit-font-smoothing: antialiased; }+a { color: var(--accent); }+:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }+main { max-width: 1080px; margin: 0 auto; padding: 32px max(16px, env(safe-area-inset-right, 0px)) 64px max(16px, env(safe-area-inset-left, 0px)); }+header { display: flex; justify-content: space-between; align-items: baseline; gap: 16px; flex-wrap: wrap; margin-bottom: 20px; }+h1 { margin: 0; font-size: 20px; font-weight: 600; white-space: nowrap; }+h1 small { color: var(--soft); font-weight: 400; font-size: 14px; margin-left: 8px; }+nav { display: flex; gap: 4px 20px; flex-wrap: wrap; font-size: 14px; }+nav span { color: var(--soft); white-space: nowrap; }+nav span.on { color: var(--ink); box-shadow: inset 0 -2px 0 var(--accent); padding-bottom: 2px; }+nav span.later { opacity: .55; }+nav span.later em { font-style: normal; font-size: 11px; letter-spacing: .06em; text-transform: uppercase; margin-left: 4px; }++.facts { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 1px; background: var(--line);+ border: 1px solid var(--line); border-radius: 6px; overflow: hidden; margin: 0 0 24px; }+.facts div { background: var(--row); padding: 10px 12px; min-width: 0; }+.facts dt { color: var(--soft); font-size: 12px; }+.facts dd { margin: 0; font-weight: 600; overflow-wrap: anywhere; }+.facts dd.ok { color: var(--ok); }+.actions-row { display: flex; gap: 10px; flex-wrap: wrap; align-items: center; margin-bottom: 8px; }+.download { display: inline-block; background: var(--accent); color: var(--on-accent); font-weight: 600; text-decoration: none;+ padding: 6px 12px; border-radius: 4px; white-space: nowrap; }+.download:hover { background: #f59a57; }+.download:active { transform: translateY(1px); }+.download[aria-disabled="true"] { pointer-events: none; opacity: .5; }+.ghost { font: 600 14px/1.5 "Barlow", sans-serif; color: var(--ink); background: var(--line); border: 0; border-radius: 4px;+ padding: 4px 10px; cursor: pointer; white-space: nowrap; text-decoration: none; display: inline-block; }+.ghost:hover { background: #38332b; }+.ghost:disabled { cursor: progress; color: var(--soft); }+.quit { margin-left: auto; }+.hint { color: var(--soft); font-size: 13px; margin: 0; }+.note { color: var(--soft); font-size: 14px; margin: 8px 0 0; max-width: 72ch; }+.sub { font-size: 13px; font-weight: 600; letter-spacing: .06em; text-transform: uppercase; color: var(--soft); margin: 28px 0 8px; }+.problem { background: var(--row); border: 1px solid var(--line); border-left: 3px solid var(--warn); border-radius: 6px;+ padding: 14px 16px; margin: 0 0 24px; }+.problem p { margin: 0 0 10px; }+.problem[hidden], [hidden] { display: none !important; }++table { width: 100%; border-collapse: collapse; }+th { text-align: left; font-weight: 500; color: var(--soft); font-size: 13px; padding: 0 12px 8px; white-space: nowrap; }+td { padding: 11px 12px; border-top: 1px solid var(--line); vertical-align: middle; }+th.num, td.num { text-align: right; }+tbody tr:hover td { background: var(--row); }+tr.sel td { background: var(--row-open); }+tr.pick { cursor: pointer; }+td.name { font-weight: 600; overflow-wrap: anywhere; }+td.name span { display: block; color: var(--soft); font-size: 13px; font-weight: 400; }+td.soft { color: var(--soft); white-space: nowrap; }+td.radio { width: 1%; }+input[type=radio] { accent-color: var(--accent); margin: 0; }+td.empty { color: var(--soft); }++@media (max-width: 720px) {+ .facts .wide { display: none; }+ thead, td.title, td.when-wide { display: none; }+ table, tbody { display: block; }+ tbody tr { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; gap: 2px 10px; align-items: center;+ padding: 12px 4px; border-top: 1px solid var(--line); }+ tbody tr:last-child { border-bottom: 1px solid var(--line); }+ tbody tr:hover td { background: none; }+ tr.sel { background: var(--row-open); }+ tr.sel td { background: none; }+ td { border: 0; padding: 0; }+ td.radio { grid-row: 1; }+ td.name { grid-row: 1; }+ td.size { grid-row: 1; color: var(--soft); font-size: 13px; }+ td.card-line { display: block !important; grid-column: 2 / -1; color: var(--soft); font-size: 13px; white-space: normal; }+ td.view { grid-column: 2 / -1; text-align: left; padding-top: 6px; }+ #playden-logs tr { grid-template-columns: minmax(0, 1fr) auto; }+ #playden-logs td.name, #playden-logs td.size { grid-row: 1; }+ #playden-logs td.card-line, #playden-logs td.view { grid-column: 1 / -1; }+ td.empty { grid-column: 1 / -1; }+}+@media (min-width: 721px) { td.card-line { display: none; } }+</style>+</head>+<body>+<main>+ <header>+ <h1>Playden<small id="where">on PS5</small></h1>+ <nav aria-label="Sections"><span class="on">Logs</span><span class="later">Recipes<em>later</em></span><span class="later">Files<em>later</em></span></nav>+ </header>++ <div class="problem" id="problem" role="alert" hidden>+ <p id="problem-text">Playden isn't answering. Is it open on the PS5?</p>+ <button class="ghost" type="button" id="retry">Try again</button>+ </div>++ <dl class="facts" id="facts">+ <div><dt>Playden</dt><dd id="fact-version">…</dd></div>+ <div class="wide"><dt>Package</dt><dd id="fact-package">…</dd></div>+ <div class="wide"><dt>Firmware</dt><dd id="fact-firmware">…</dd></div>+ <div><dt>Runtime kit</dt><dd id="fact-kit">…</dd></div>+ <div class="wide"><dt>Redacted</dt><dd class="ok">Steam name, SteamIDs</dd></div>+ </dl>++ <div class="actions-row">+ <a class="download" id="download" href="/api/report.zip" aria-disabled="true">Download report (.zip)</a>+ <span class="hint" id="download-hint"></span>+ <button class="ghost quit" type="button" id="quit">Quit Playden</button>+ </div>+ <p class="note">Logs can still name your games and file paths. Look through them before you share.</p>++ <div class="sub">Game logs · most recent first</div>+ <table id="game-logs">+ <thead><tr><th></th><th>Game</th><th>Title</th><th>Last run</th><th class="num">Size</th><th class="num"></th></tr></thead>+ <tbody></tbody>+ </table>+ <p class="note">Playden answers only while it is open. A game's log appears here once Playden starts again after the game.</p>++ <div class="sub">Playden logs</div>+ <table id="playden-logs">+ <thead><tr><th>File</th><th>Changed</th><th class="num">Size</th><th class="num"></th></tr></thead>+ <tbody></tbody>+ </table>+</main>+<script>+(() => {+ const $ = (id) => document.getElementById(id);+ const state = { games: [], playden: [], picked: null };++ const element = (tag, attributes = {}, ...children) => {+ const node = document.createElement(tag);+ for (const [key, value] of Object.entries(attributes)) {+ if (key === "class") node.className = value;+ else if (key === "text") node.textContent = value;+ else node.setAttribute(key, value);+ }+ for (const child of children) if (child) node.append(child);+ return node;+ };++ const size = (bytes) => {+ if (bytes < 1024) return `${bytes} B`;+ if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`;+ };+ const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];+ const when = (seconds) => {+ if (!seconds) return "never";+ const date = new Date(seconds * 1000), now = new Date();+ const time = `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;+ const day = (d) => new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();+ const days = Math.round((day(now) - day(date)) / 86400000);+ if (days === 0) return `Today ${time}`;+ if (days === 1) return `Yesterday ${time}`;+ return `${months[date.getMonth()]} ${date.getDate()}${date.getFullYear() !== now.getFullYear() ? " " + date.getFullYear() : ""} ${time}`;+ };+ const view = (name) => element("a", { class: "ghost", href: `/api/logs/${encodeURIComponent(name)}`, target: "_blank", rel: "noopener", text: "View" });++ const fail = (message) => {+ $("problem-text").textContent = message;+ $("problem").hidden = false;+ };++ const updateDownload = () => {+ const link = $("download");+ const picked = state.picked;+ link.href = picked ? `/api/report.zip?title=${encodeURIComponent(picked)}` : "/api/report.zip";+ link.removeAttribute("aria-disabled");+ const ownBytes = state.playden.reduce((sum, log) => sum + log.size, 0);+ let gameBytes = 0, what = "Playden's logs";+ if (picked === "all") { gameBytes = state.games.reduce((sum, game) => sum + game.size, 0); what += " + every game's log"; }+ else if (picked) {+ const game = state.games.find((g) => g.title === picked);+ if (game) { gameBytes = game.size; what += " + the game picked below"; }+ }+ $("download-hint").textContent = `${what} · ${size(ownBytes + gameBytes)}`;+ for (const row of document.querySelectorAll("#game-logs tbody tr[data-title]"))+ row.classList.toggle("sel", row.dataset.title === picked);+ };++ const pick = (title) => {+ state.picked = title;+ const radio = document.querySelector(`#game-logs input[value="${CSS.escape(title)}"]`);+ if (radio) radio.checked = true;+ updateDownload();+ };++ const gameRow = (game) => {+ const label = game.name || "Unknown game";+ const radio = element("input", { type: "radio", name: "game", value: game.title, "aria-label": `Pick ${label}` });+ const row = element("tr", { class: "pick", "data-title": game.title },+ element("td", { class: "radio" }, radio),+ element("td", { class: "name" }, label, element("span", { text: game.app ? `app ${game.app}` : "app unknown" })),+ element("td", { class: "soft title", text: game.title }),+ element("td", { class: "soft when-wide", text: when(game.last_run) }),+ element("td", { class: "num soft size", text: size(game.size) }),+ element("td", { class: "soft card-line", text: `${game.title} · ${when(game.last_run).toLowerCase()}` }),+ element("td", { class: "num view" }, view(`title-${game.title}.log`)));+ row.addEventListener("click", (event) => { if (!event.target.closest("a")) pick(game.title); });+ return row;+ };++ const render = () => {+ const games = $("game-logs").tBodies[0];+ games.replaceChildren();+ if (!state.games.length) {+ games.append(element("tr", {}, element("td", { class: "empty", colspan: "6",+ text: "No game logs yet. Start Playden once after running a game: it copies the game's log when it starts." })));+ } else {+ for (const game of state.games) games.append(gameRow(game));+ const total = state.games.reduce((sum, game) => sum + game.size, 0);+ const all = element("tr", { class: "pick", "data-title": "all" },+ element("td", { class: "radio" }, element("input", { type: "radio", name: "game", value: "all", "aria-label": "Pick all games" })),+ element("td", { class: "name" }, "All games", element("span", { text: "every title log" })),+ element("td", { class: "soft title", text: "—" }),+ element("td", { class: "soft when-wide", text: "—" }),+ element("td", { class: "num soft size", text: size(total) }),+ element("td", { class: "soft card-line", text: `${state.games.length} ${state.games.length === 1 ? "game" : "games"}` }),+ element("td", { class: "num view" }));+ all.addEventListener("click", () => pick("all"));+ games.append(all);+ }+ const own = $("playden-logs").tBodies[0];+ own.replaceChildren();+ if (!state.playden.length) own.append(element("tr", {}, element("td", { class: "empty", colspan: "4", text: "No Playden logs yet." })));+ for (const log of state.playden)+ own.append(element("tr", {},+ element("td", { class: "name", text: log.name }),+ element("td", { class: "soft when-wide", text: when(log.changed) }),+ element("td", { class: "num soft size", text: size(log.size) }),+ element("td", { class: "soft card-line", text: `changed ${when(log.changed).toLowerCase()}` }),+ element("td", { class: "num view" }, view(log.name))));+ const keep = state.picked === "all" || state.games.some((game) => game.title === state.picked);+ pick(keep ? state.picked : state.games.length ? state.games[0].title : null);+ };++ const json = async (path) => {+ const response = await fetch(path, { cache: "no-store" });+ if (!response.ok) throw new Error(`${path} answered ${response.status}`);+ return response.json();+ };++ const load = async () => {+ $("problem").hidden = true;+ $("where").textContent = `on PS5 · ${location.hostname}`;+ try {+ const [status, logs] = await Promise.all([json("/api/status"), json("/api/logs")]);+ $("fact-version").textContent = status.version || "unknown";+ $("fact-package").textContent = status.package || "unknown";+ $("fact-firmware").textContent = status.firmware || "unknown";+ $("fact-kit").textContent = status.kit_runtime || "unknown";+ state.games = logs.games || [];+ state.playden = logs.playden || [];+ render();+ } catch (error) {+ fail(error instanceof TypeError+ ? "Playden isn't answering. Is it open on the PS5? It stops answering while a game is in front."+ : `Playden answered with an error (${error.message}). Try again, or restart Playden.`);+ }+ };++ $("game-logs").addEventListener("change", (event) => { if (event.target.name === "game") pick(event.target.value); });+ $("retry").addEventListener("click", load);+ // Quit Playden on the PS5. The custom header keeps other web pages from doing it (they'd need a CORS+ // preflight, which Playden never answers).+ $("quit").addEventListener("click", async () => {+ if (!confirm("Quit Playden on the PS5? It waits for a game being prepared first.")) return;+ const button = $("quit");+ button.disabled = true;+ try {+ const response = await fetch("/api/quit", { method: "POST", headers: { "X-Playden-Action": "quit" } });+ if (!response.ok) throw new Error(`answered ${response.status}`);+ button.textContent = "Quitting…";+ fail("Playden is quitting. Open it again on the PS5 to see its logs here.");+ } catch (error) {+ button.disabled = false;+ fail(error instanceof TypeError ? "Playden isn't answering. Is it open on the PS5?" : `Playden didn't quit (${error.message}).`);+ }+ });+ load();+})();+</script>+</body>+</html>diff --git a/src/web/router.cpp b/src/web/router.cppnew file mode 100644index 0000000..3b01f77--- /dev/null+++ b/src/web/router.cpp@@ -0,0 +1,44 @@+// SPDX-License-Identifier: GPL-3.0-or-later+#include "web/router.h"++namespace playden::web {++void Router::Exact(std::string path, Handler handler) { routes_.push_back({std::move(path), false, false, std::move(handler)}); }++void Router::Prefix(std::string prefix, Handler handler) { routes_.push_back({std::move(prefix), true, false, std::move(handler)}); }++void Router::Post(std::string path, Handler handler) { routes_.push_back({std::move(path), false, true, std::move(handler)}); }++void SendError(Response& response, int status, std::string_view message) {+ std::string body(message);+ body += "\n";+ response.Send(status, "text/plain; charset=utf-8", body, {{"Cache-Control", "no-store"}});+}++void Router::Handle(const Request& request, Response& response) const {+ for (const auto& route : routes_) {+ if (!route.post || request.path != route.path) continue;+ if (request.method == Method::kPost) return route.handler(request, {}, response);+ response.Send(405, "text/plain; charset=utf-8", "Only POST is allowed.\n", {{"Allow", "POST"}, {"Cache-Control", "no-store"}});+ return;+ }+ if (request.method != Method::kGet && request.method != Method::kHead) {+ response.Send(405, "text/plain; charset=utf-8", "Only GET and HEAD are allowed.\n",+ {{"Allow", "GET, HEAD"}, {"Cache-Control", "no-store"}});+ return;+ }+ for (const auto& route : routes_) {+ if (route.post) continue;+ if (!route.prefix && request.path == route.path) {+ route.handler(request, {}, response);+ return;+ }+ if (route.prefix && request.path.size() > route.path.size() && request.path.compare(0, route.path.size(), route.path) == 0) {+ route.handler(request, request.path.substr(route.path.size()), response);+ return;+ }+ }+ SendError(response, 404, "Not found.");+}++} // namespace playden::webdiff --git a/src/web/router.h b/src/web/router.hnew file mode 100644index 0000000..438e8e2--- /dev/null+++ b/src/web/router.h@@ -0,0 +1,37 @@+// SPDX-License-Identifier: GPL-3.0-or-later+#pragma once++#include "web/http.h"++#include <functional>+#include <string>+#include <vector>++namespace playden::web {++// Routes GET and HEAD requests by exact path or by a "/prefix/", and POST only to the few exact paths+// registered with Post; every other method or path gets 405, and an unknown path 404. A prefix handler+// receives the rest of the path after the prefix.+class Router {+ public:+ using Handler = std::function<void(const Request& request, const std::string& rest, Response& response)>;+ void Exact(std::string path, Handler handler);+ void Prefix(std::string prefix, Handler handler);+ // An action (POST only): GET and HEAD on it get 405.+ void Post(std::string path, Handler handler);+ void Handle(const Request& request, Response& response) const;++ private:+ struct Route {+ std::string path;+ bool prefix = false;+ bool post = false;+ Handler handler;+ };+ std::vector<Route> routes_;+};++// A plain-text error answer, as every route sends it.+void SendError(Response& response, int status, std::string_view message);++} // namespace playden::webdiff --git a/src/web/server.cpp b/src/web/server.cppnew file mode 100644index 0000000..498f5ce--- /dev/null+++ b/src/web/server.cpp@@ -0,0 +1,212 @@+// SPDX-License-Identifier: GPL-3.0-or-later+#include "web/server.h"++#include "web/router.h"++#include <arpa/inet.h>+#include <cerrno>+#include <chrono>+#include <cstring>+#include <netinet/in.h>+#include <poll.h>+#include <sys/socket.h>+#include <sys/time.h>+#include <unistd.h>+#include <vector>++namespace playden::web {+namespace {++#if defined(MSG_NOSIGNAL)+constexpr int kSendFlags = MSG_NOSIGNAL;+#else+constexpr int kSendFlags = 0;+#endif++// A browser that closes the tab mid-download must not raise SIGPIPE in the title.+void NoSigpipe(int fd) {+#if defined(SO_NOSIGPIPE)+ int on = 1;+ setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &on, sizeof on);+#else+ (void)fd;+#endif+}++void SetTimeout(int fd, int option, int milliseconds) {+ timeval timeout{};+ timeout.tv_sec = milliseconds / 1000;+ timeout.tv_usec = (milliseconds % 1000) * 1000;+ setsockopt(fd, SOL_SOCKET, option, &timeout, sizeof timeout);+}++std::string ErrorText(int error) { return std::string(std::strerror(error)) + " (errno " + std::to_string(error) + ")"; }++// The path as web.log shows it: no query, except the title a report was asked for.+std::string LoggedTarget(const Request& request) {+ std::string target;+ for (const char c : request.path) target += (static_cast<unsigned char>(c) < 0x20 || c == 0x7f || c == ' ') ? '?' : c;+ if (target.size() > 120) target = target.substr(0, 120) + "...";+ if (const auto title = QueryValue(request.query, "title")) {+ std::string clean;+ for (const char c : *title) if (((c | 0x20) >= 'a' && (c | 0x20) <= 'z') || (c >= '0' && c <= '9')) clean += c;+ target += "?title=" + clean.substr(0, 16);+ }+ return target;+}++} // namespace++Server::~Server() { Stop(); }++void Server::Log(const std::string& line) const {+ if (options_.log) options_.log(line);+}++bool Server::Start(const ServerOptions& options, Handler handler, std::string* error) {+ Stop();+ options_ = options;+ handler_ = std::move(handler);+ stop_.store(false);+ const auto fail = [&](const std::string& why) {+ if (listener_ >= 0) ::close(listener_);+ listener_ = -1;+ if (error) *error = why;+ Log("start failed: " + why);+ return false;+ };+ int last_error = 0;+ std::uint16_t tried = options.first_port;+ for (std::uint32_t port = options.first_port; port <= options.last_port; ++port) {+ tried = static_cast<std::uint16_t>(port);+ listener_ = ::socket(AF_INET, SOCK_STREAM, 0);+ if (options_.verbose) Log("socket fd=" + std::to_string(listener_) + (listener_ < 0 ? " " + ErrorText(errno) : ""));+ if (listener_ < 0) return fail("socket: " + ErrorText(errno));+ int on = 1;+ setsockopt(listener_, SOL_SOCKET, SO_REUSEADDR, &on, sizeof on);+ NoSigpipe(listener_);+ sockaddr_in address{};+ address.sin_family = AF_INET;+ address.sin_port = htons(static_cast<std::uint16_t>(port));+ address.sin_addr.s_addr = htonl(options.loopback_only ? INADDR_LOOPBACK : INADDR_ANY);+ const int bound = ::bind(listener_, reinterpret_cast<sockaddr*>(&address), sizeof address);+ last_error = bound == 0 ? 0 : errno;+ if (options_.verbose)+ Log("bind port=" + std::to_string(port) + " result=" + std::to_string(bound) + (bound ? " " + ErrorText(last_error) : ""));+ if (bound == 0) break;+ ::close(listener_);+ listener_ = -1;+ if (last_error != EADDRINUSE) return fail("port " + std::to_string(port) + ": " + ErrorText(last_error));+ if (port == 0xffff) break;+ }+ if (listener_ < 0) return fail("port " + std::to_string(tried) + ": " + ErrorText(last_error));+ const int listening = ::listen(listener_, options.backlog);+ const int listen_error = listening == 0 ? 0 : errno;+ if (options_.verbose) Log("listen result=" + std::to_string(listening) + (listening ? " " + ErrorText(listen_error) : ""));+ if (listening != 0) return fail("listen: " + ErrorText(listen_error));+ sockaddr_in bound{};+ socklen_t size = sizeof bound;+ if (::getsockname(listener_, reinterpret_cast<sockaddr*>(&bound), &size) != 0) return fail("getsockname: " + ErrorText(errno));+ port_ = ntohs(bound.sin_port);+ worker_ = std::thread([this] { Run(); });+ return true;+}++void Server::Stop() {+ stop_.store(true);+ {+ // Wakes a send or recv blocked on the client; the worker still owns and closes the descriptor.+ std::lock_guard<std::mutex> lock(client_mutex_);+ if (client_ >= 0) ::shutdown(client_, SHUT_RDWR);+ }+ if (worker_.joinable()) worker_.join();+ if (listener_ >= 0) ::close(listener_);+ listener_ = -1;+}++void Server::Run() {+ while (!stop_.load()) {+ pollfd waiting{};+ waiting.fd = listener_;+ waiting.events = POLLIN;+ const int ready = ::poll(&waiting, 1, options_.poll_interval_ms);+ if (ready < 0) {+ if (errno == EINTR) continue;+ Log("poll failed: " + ErrorText(errno));+ // Not a spin: wait as long as one poll would have.+ std::this_thread::sleep_for(std::chrono::milliseconds(options_.poll_interval_ms));+ continue;+ }+ if (ready == 0 || stop_.load()) continue;+ sockaddr_in peer{};+ socklen_t size = sizeof peer;+ const int client = ::accept(listener_, reinterpret_cast<sockaddr*>(&peer), &size);+ const int accept_error = client < 0 ? errno : 0;+ char ip[INET_ADDRSTRLEN] = "?";+ if (client >= 0) inet_ntop(AF_INET, &peer.sin_addr, ip, sizeof ip);+ if (options_.verbose)+ Log("accept fd=" + std::to_string(client) + (client < 0 ? " " + ErrorText(accept_error) : std::string(" client=") + ip));+ if (client < 0) continue;+ NoSigpipe(client);+ SetTimeout(client, SO_RCVTIMEO, options_.read_timeout_ms);+ SetTimeout(client, SO_SNDTIMEO, options_.write_timeout_ms);+ {+ std::lock_guard<std::mutex> lock(client_mutex_);+ client_ = client;+ }+ if (!stop_.load()) Serve(client, ip);+ {+ std::lock_guard<std::mutex> lock(client_mutex_);+ client_ = -1;+ }+ ::shutdown(client, SHUT_RDWR);+ ::close(client);+ }+}++void Server::Serve(int client, const std::string& client_ip) {+ const auto write = [this, client](const char* data, std::size_t size) {+ while (size > 0) {+ if (stop_.load()) return false;+ const auto sent = ::send(client, data, size, kSendFlags);+ if (sent < 0 && errno == EINTR) continue;+ if (sent <= 0) return false;+ data += sent;+ size -= static_cast<std::size_t>(sent);+ }+ return true;+ };+ const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(options_.read_timeout_ms);+ std::string received;+ std::vector<char> buffer(2048);+ Request request;+ ParseResult parsed = ParseResult::kIncomplete;+ while (parsed == ParseResult::kIncomplete) {+ if (std::chrono::steady_clock::now() > deadline || stop_.load()) break;+ const auto count = ::recv(client, buffer.data(), buffer.size(), 0);+ if (count < 0 && errno == EINTR) continue;+ if (count <= 0) break;+ received.append(buffer.data(), static_cast<std::size_t>(count));+ parsed = ParseRequestHead(received, &request);+ }+ Response response(write, request.method == Method::kHead);+ std::string target = "-";+ if (parsed == ParseResult::kOk) {+ target = LoggedTarget(request);+ handler_(request, response);+ if (!response.started()) SendError(response, 500, "No answer.");+ } else if (parsed == ParseResult::kTooLarge) {+ SendError(response, 431, "The request is too large.");+ } else if (parsed == ParseResult::kBadRequest) {+ SendError(response, 400, "Bad request.");+ } else if (!received.empty()) {+ SendError(response, 408, "The request took too long.");+ } else {+ return; // connected and sent nothing: a browser's spare connection+ }+ Log((parsed == ParseResult::kOk ? request.method_text : std::string("-")) + " " + target + " " ++ std::to_string(response.status()) + " " + std::to_string(response.body_bytes()) + " " + client_ip ++ (response.failed() ? " cut" : ""));+}++} // namespace playden::webdiff --git a/src/web/server.h b/src/web/server.hnew file mode 100644index 0000000..eaa1786--- /dev/null+++ b/src/web/server.h@@ -0,0 +1,64 @@+// SPDX-License-Identifier: GPL-3.0-or-later+#pragma once++#include "web/http.h"++#include <atomic>+#include <cstdint>+#include <functional>+#include <mutex>+#include <string>+#include <thread>++namespace playden::web {++struct ServerOptions {+ // Ports tried in turn while bind says the address is in use. 0 asks for any free port (tests).+ std::uint16_t first_port = 7031;+ std::uint16_t last_port = 7039;+ bool loopback_only = false; // 127.0.0.1 instead of every address (tests)+ int backlog = 4; // connections waiting while one is served+ int read_timeout_ms = 10'000;+ int write_timeout_ms = 10'000;+ // How often the accept wait looks at Stop. Closing a listening socket does not reliably wake a+ // blocked accept, so the worker never blocks longer than this.+ int poll_interval_ms = 250;+ // Logs every socket, bind, listen and accept result (the console listener probe).+ bool verbose = false;+ // One line per request and each start and stop, for web.log.+ std::function<void(const std::string&)> log;+};++// A small HTTP/1.1 server: one worker accepts and serves one connection at a time, reading the+// request, routing it and writing the answer, then closing. No keep-alive.+class Server {+ public:+ using Handler = std::function<void(const Request& request, Response& response)>;+ Server() = default;+ ~Server();+ Server(const Server&) = delete;+ Server& operator=(const Server&) = delete;++ // Binds and listens on the caller's thread, then starts the worker. On failure, error says why+ // and which port was tried last.+ bool Start(const ServerOptions& options, Handler handler, std::string* error);+ // Stops accepting, cuts the connection being served (a slow download included), and closes the socket.+ void Stop();+ bool running() const { return worker_.joinable(); }+ std::uint16_t port() const { return port_; }++ private:+ void Run();+ void Serve(int client, const std::string& client_ip);+ void Log(const std::string& line) const;+ ServerOptions options_;+ Handler handler_;+ int listener_ = -1;+ std::uint16_t port_ = 0;+ std::atomic<bool> stop_{false};+ std::mutex client_mutex_;+ int client_ = -1; // the connection being served, so Stop can cut it+ std::thread worker_;+};++} // namespace playden::webdiff --git a/src/web/service.cpp b/src/web/service.cppnew file mode 100644index 0000000..07f5848--- /dev/null+++ b/src/web/service.cpp@@ -0,0 +1,191 @@+// SPDX-License-Identifier: GPL-3.0-or-later+#include "web/service.h"++#include "web/address.h"+#include "web/assets.h"++namespace playden::web {+namespace {+const std::vector<std::pair<std::string, std::string>> kNoStore = {{"Cache-Control", "no-store"}};+} // namespace++Service::Service(ServiceConfig config) : config_(std::move(config)), logs_(config_.paths) {+ router_.Exact("/", [](const Request&, const std::string&, Response& response) {+ const auto* page = FindEmbeddedAsset("/");+ if (!page) return SendError(response, 404, "Not found.");+ response.Send(200, page->content_type, std::string_view(reinterpret_cast<const char*>(page->data), page->size),+ {{"Cache-Control", "no-cache"}});+ });+ router_.Prefix("/assets/", [](const Request& request, const std::string&, Response& response) {+ const auto* asset = FindEmbeddedAsset(request.path);+ if (!asset) return SendError(response, 404, "Not found.");+ response.Send(200, asset->content_type, std::string_view(reinterpret_cast<const char*>(asset->data), asset->size),+ {{"Cache-Control", "max-age=86400"}});+ });+ router_.Exact("/api/status", [this](const Request&, const std::string&, Response& response) {+ response.Send(200, "application/json", logs_.StatusJson(Now()), kNoStore);+ });+ router_.Exact("/api/logs", [this](const Request&, const std::string&, Response& response) {+ response.Send(200, "application/json", logs_.IndexJson(logs_.Index()), kNoStore);+ });+ router_.Prefix("/api/logs/", [this](const Request&, const std::string& name, Response& response) {+ Redaction account;+ {+ std::lock_guard<std::mutex> lock(mutex_);+ account = account_;+ }+ // The name must be one the index lists: no path from the request reaches the file system.+ const auto text = logs_.ReadLog(logs_.Index(), name, account);+ if (!text) return SendError(response, 404, "No such log.");+ response.Send(200, "text/plain; charset=utf-8", *text, kNoStore);+ });+ router_.Exact("/api/report.zip", [this](const Request& request, const std::string&, Response& response) {+ Redaction account;+ {+ std::lock_guard<std::mutex> lock(mutex_);+ account = account_;+ }+ const auto now = Now();+ const auto title = QueryValue(request.query, "title").value_or(std::string());+ const auto index = logs_.Index();+ // Streamed, so no length: the end of the connection ends the zip.+ if (!response.Start(200, "application/zip", std::nullopt,+ {{"Content-Disposition", "attachment; filename=\"" + ReportFileName(now) + "\""},+ {"Cache-Control", "no-store"}}) ||+ request.method == Method::kHead)+ return;+ logs_.WriteReport(index, title, account, now, [&response](const char* data, std::size_t size) { return response.Body(data, size); });+ });+ // The only action. It must carry X-Playden-Action: a custom header makes a browser ask first (a CORS+ // preflight, never answered), so another web page can't quit Playden from the player's browser.+ router_.Post("/api/quit", [this](const Request& request, const std::string&, Response& response) {+ bool asked = false;+ for (const auto& [name, value] : request.headers) asked = asked || (name == "x-playden-action" && value == "quit");+ if (!asked) return SendError(response, 403, "Send X-Playden-Action: quit to quit Playden.");+ {+ std::lock_guard<std::mutex> lock(mutex_);+ quit_requested_ = true;+ }+ response.Send(202, "application/json", "{\"quitting\":true}", kNoStore);+ });+ worker_ = std::thread([this] { Run(); });+}++bool Service::TakeQuitRequest() {+ std::lock_guard<std::mutex> lock(mutex_);+ const bool asked = quit_requested_;+ quit_requested_ = false;+ return asked;+}++Service::~Service() { Shutdown(); }++void Service::Log(const std::string& line) const {+ if (config_.server.log) config_.server.log(line);+}++std::int64_t Service::Now() const {+ if (config_.now) return config_.now();+ return std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count();+}++std::string Service::LookUpAddress() const {+ auto address = LocalAddress();+ if (address.empty() && config_.address_fallback) address = config_.address_fallback();+ return address;+}++void Service::SetEnabled(bool enabled) {+ {+ std::lock_guard<std::mutex> lock(mutex_);+ if (enabled_ == enabled) return;+ enabled_ = enabled;+ ++requests_;+ }+ wake_.notify_all();+}++void Service::SetAccount(Redaction account) {+ std::lock_guard<std::mutex> lock(mutex_);+ account_ = std::move(account);+}++ServiceSnapshot Service::Snapshot() const {+ std::lock_guard<std::mutex> lock(mutex_);+ return snapshot_;+}++void Service::Shutdown() {+ {+ std::lock_guard<std::mutex> lock(mutex_);+ stopping_ = true;+ }+ wake_.notify_all();+ if (worker_.joinable()) worker_.join();+}++void Service::Handle(const Request& request, Response& response) { router_.Handle(request, response); }++void Service::Run() {+ using Clock = std::chrono::steady_clock;+ std::unique_lock<std::mutex> lock(mutex_);+ std::uint64_t tried = 0; // the change a failed start answered; another change tries again+ auto next_lookup = Clock::time_point::max();+ while (!stopping_) {+ if (enabled_ && !server_.running() && (snapshot_.state != ServiceSnapshot::State::kFailed || tried != requests_)) {+ tried = requests_;+ snapshot_ = {};+ snapshot_.state = ServiceSnapshot::State::kStarting;+ lock.unlock();+ std::string error;+ const bool started = server_.Start(config_.server, [this](const Request& request, Response& response) {+ Handle(request, response);+ }, &error);+ const auto address = started ? LookUpAddress() : std::string();+ lock.lock();+ snapshot_ = {};+ if (started) {+ snapshot_.state = ServiceSnapshot::State::kOn;+ snapshot_.port = server_.port();+ snapshot_.address = address;+ snapshot_.url = PageUrl(address, server_.port());+ Log("started port=" + std::to_string(server_.port()) + " address=" + (address.empty() ? "unknown" : address));+ next_lookup = Clock::now() + config_.address_refresh;+ } else {+ snapshot_.state = ServiceSnapshot::State::kFailed;+ snapshot_.error = error;+ }+ continue;+ }+ if (!enabled_ && server_.running()) {+ lock.unlock();+ server_.Stop();+ Log("stopped");+ lock.lock();+ snapshot_ = {};+ next_lookup = Clock::time_point::max();+ continue;+ }+ if (!enabled_) snapshot_ = {};+ if (server_.running() && Clock::now() >= next_lookup) {+ lock.unlock();+ const auto address = LookUpAddress();+ lock.lock();+ if (address != snapshot_.address && server_.running()) {+ Log("address=" + (address.empty() ? std::string("unknown") : address));+ snapshot_.address = address;+ snapshot_.url = PageUrl(address, snapshot_.port);+ }+ next_lookup = Clock::now() + config_.address_refresh;+ continue;+ }+ if (next_lookup == Clock::time_point::max()) wake_.wait(lock);+ else wake_.wait_until(lock, next_lookup);+ }+ const bool was_running = server_.running();+ lock.unlock();+ server_.Stop();+ if (was_running) Log("stopped");+}++} // namespace playden::webdiff --git a/src/web/service.h b/src/web/service.hnew file mode 100644index 0000000..f3c02d7--- /dev/null+++ b/src/web/service.h@@ -0,0 +1,81 @@+// SPDX-License-Identifier: GPL-3.0-or-later+#pragma once++#include "web/logs_source.h"+#include "web/router.h"+#include "web/server.h"++#include <chrono>+#include <condition_variable>+#include <cstdint>+#include <functional>+#include <mutex>+#include <string>+#include <thread>++namespace playden::web {++struct ServiceConfig {+ LogsPaths paths;+ ServerOptions server; // ports 7031-7039 by default; its log is web.log+ // Asked when the UDP route lookup finds no address (the console's network control service).+ std::function<std::string()> address_fallback;+ // Seconds since 1970; the system clock when empty (tests pin it).+ 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};+};++struct ServiceSnapshot {+ enum class State { kOff, kStarting, kOn, kFailed };+ State state = State::kOff;+ std::uint16_t port = 0; // kOn: the port in use; kFailed: the last port tried+ std::string address; // empty: unknown+ std::string url; // http://<address>:<port>/ or empty+ std::string error; // kFailed: why+};++// 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.+class Service {+ public:+ explicit Service(ServiceConfig config);+ ~Service();+ Service(const Service&) = delete;+ Service& operator=(const Service&) = delete;++ // Turns the server on or off; it happens on the worker.+ void SetEnabled(bool enabled);+ // The signed-in account to redact exactly; empty when signed out (the patterns still apply).+ void SetAccount(Redaction account);+ ServiceSnapshot Snapshot() const;+ // True once after the page asked Playden to quit; the caller quits.+ bool TakeQuitRequest();+ // Stops the server and the worker. Safe to call twice.+ void Shutdown();++ // Routes one request, as the server's worker does (tests call it directly).+ void Handle(const Request& request, Response& response);++ private:+ void Run();+ void Log(const std::string& line) const;+ std::int64_t Now() const;+ std::string LookUpAddress() const;+ ServiceConfig config_;+ LogsSource logs_;+ Router router_;+ Server server_;+ mutable std::mutex mutex_;+ std::condition_variable wake_;+ bool enabled_ = false;+ bool stopping_ = false;+ std::uint64_t requests_ = 0; // enable/disable changes, so a quick off-on restarts+ Redaction account_;+ bool quit_requested_ = false;+ ServiceSnapshot snapshot_;+ std::thread worker_;+};++} // namespace playden::webdiff --git a/src/web/zip.cpp b/src/web/zip.cppnew file mode 100644index 0000000..4487248--- /dev/null+++ b/src/web/zip.cpp@@ -0,0 +1,146 @@+// SPDX-License-Identifier: GPL-3.0-or-later+#include "web/zip.h"++#include <array>++namespace playden::web {+namespace {++constexpr std::uint64_t kMaxArchiveBytes = 0x7fffffffu;++const std::array<std::uint32_t, 256>& CrcTable() {+ static const auto table = [] {+ std::array<std::uint32_t, 256> values{};+ for (std::uint32_t n = 0; n < 256; ++n) {+ std::uint32_t c = n;+ for (int k = 0; k < 8; ++k) c = (c & 1) ? 0xedb88320u ^ (c >> 1) : c >> 1;+ values[n] = c;+ }+ return values;+ }();+ return table;+}++void Put16(std::string& out, std::uint32_t value) {+ out.push_back(static_cast<char>(value & 0xff));+ out.push_back(static_cast<char>((value >> 8) & 0xff));+}++void Put32(std::string& out, std::uint32_t value) {+ Put16(out, value & 0xffff);+ Put16(out, value >> 16);+}++// MS-DOS date and time for a Unix time, without the platform's time zone support (zip readers+// show it as local time; the archive says UTC in its summary).+void DosTime(std::int64_t unix_seconds, std::uint16_t* time, std::uint16_t* date) {+ if (unix_seconds < 315532800) unix_seconds = 315532800; // 1980-01-01, the earliest DOS date+ std::int64_t days = unix_seconds / 86400;+ const std::int64_t seconds = unix_seconds % 86400;+ // Civil from days (Howard Hinnant's algorithm).+ days += 719468;+ const std::int64_t era = days / 146097;+ const std::int64_t doe = days - era * 146097;+ const std::int64_t yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;+ std::int64_t year = yoe + era * 400;+ const std::int64_t doy = doe - (365 * yoe + yoe / 4 - yoe / 100);+ const std::int64_t mp = (5 * doy + 2) / 153;+ const std::int64_t day = doy - (153 * mp + 2) / 5 + 1;+ const std::int64_t month = mp < 10 ? mp + 3 : mp - 9;+ if (month <= 2) ++year;+ if (year > 2107) year = 2107;+ *date = static_cast<std::uint16_t>(((year - 1980) << 9) | (month << 5) | day);+ *time = static_cast<std::uint16_t>(((seconds / 3600) << 11) | (((seconds / 60) % 60) << 5) | ((seconds % 60) / 2));+}++} // namespace++std::uint32_t Crc32(std::uint32_t crc, const void* data, std::size_t size) {+ const auto& table = CrcTable();+ const auto* bytes = static_cast<const unsigned char*>(data);+ crc = ~crc;+ for (std::size_t i = 0; i < size; ++i) crc = table[(crc ^ bytes[i]) & 0xff] ^ (crc >> 8);+ return ~crc;+}++StoredZip::StoredZip(Write write, std::int64_t modified) : write_(std::move(write)) {+ DosTime(modified, &dos_time_, &dos_date_);+}++bool StoredZip::Put(const std::string& bytes) {+ if (failed_) return false;+ if (!write_(bytes.data(), bytes.size())) failed_ = true;+ offset_ += bytes.size();+ return !failed_;+}++bool StoredZip::Add(std::string_view name, std::string_view data) {+ if (failed_ || finished_ || name.empty() || name.size() > 0xffff || entries_.size() >= 0xffff) 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) {+ failed_ = true;+ return false;+ }+ Entry entry{std::string(name), Crc32(0, data.data(), data.size()), static_cast<std::uint32_t>(data.size()),+ static_cast<std::uint32_t>(offset_)};+ std::string header;+ Put32(header, 0x04034b50);+ Put16(header, 20); // version needed: 2.0+ Put16(header, 1u << 11); // names are UTF-8+ Put16(header, 0); // stored+ Put16(header, dos_time_);+ Put16(header, dos_date_);+ Put32(header, entry.crc);+ Put32(header, entry.size);+ Put32(header, entry.size);+ Put16(header, static_cast<std::uint32_t>(name.size()));+ Put16(header, 0);+ header.append(name.data(), name.size());+ if (!Put(header)) return false;+ if (!data.empty()) {+ if (!write_(data.data(), data.size())) failed_ = true;+ offset_ += data.size();+ }+ if (failed_) return false;+ entries_.push_back(std::move(entry));+ return true;+}++bool StoredZip::Finish() {+ if (failed_ || finished_) return false;+ finished_ = true;+ const auto directory_offset = static_cast<std::uint32_t>(offset_);+ std::string directory;+ for (const auto& entry : entries_) {+ Put32(directory, 0x02014b50);+ Put16(directory, 20); // made by: 2.0, MS-DOS attributes+ Put16(directory, 20);+ Put16(directory, 1u << 11);+ Put16(directory, 0);+ Put16(directory, dos_time_);+ Put16(directory, dos_date_);+ Put32(directory, entry.crc);+ Put32(directory, entry.size);+ Put32(directory, entry.size);+ Put16(directory, static_cast<std::uint32_t>(entry.name.size()));+ Put16(directory, 0); // extra+ Put16(directory, 0); // comment+ Put16(directory, 0); // disk+ Put16(directory, 0); // internal attributes+ Put32(directory, 0); // external attributes+ Put32(directory, entry.offset);+ directory += entry.name;+ }+ const auto directory_size = static_cast<std::uint32_t>(directory.size());+ Put32(directory, 0x06054b50);+ Put16(directory, 0);+ Put16(directory, 0);+ Put16(directory, static_cast<std::uint32_t>(entries_.size()));+ Put16(directory, static_cast<std::uint32_t>(entries_.size()));+ Put32(directory, directory_size);+ Put32(directory, directory_offset);+ Put16(directory, 0);+ return Put(directory);+}++} // namespace playden::webdiff --git a/src/web/zip.h b/src/web/zip.hnew file mode 100644index 0000000..0233b04--- /dev/null+++ b/src/web/zip.h@@ -0,0 +1,44 @@+// SPDX-License-Identifier: GPL-3.0-or-later+#pragma once++#include <cstddef>+#include <cstdint>+#include <functional>+#include <string>+#include <string_view>+#include <vector>++namespace playden::web {++std::uint32_t Crc32(std::uint32_t crc, const void* data, std::size_t size);++// A zip archive written with the store method (no compression, CRC-32 only), so no zlib is needed.+// Each entry goes out whole as it is added; the central directory follows in Finish. Zip64 is not+// written: an archive that would pass 2 GB, or 65535 entries, is refused.+class StoredZip {+ public:+ using Write = std::function<bool(const char* data, std::size_t size)>;+ // 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);+ bool Finish();+ std::uint64_t bytes() const { return offset_; }++ private:+ struct Entry {+ std::string name;+ std::uint32_t crc = 0;+ std::uint32_t size = 0;+ std::uint32_t offset = 0;+ };+ bool Put(const std::string& bytes);+ Write write_;+ std::uint16_t dos_time_ = 0;+ std::uint16_t dos_date_ = 0;+ std::uint64_t offset_ = 0;+ std::vector<Entry> entries_;+ bool failed_ = false;+ bool finished_ = false;+};++} // namespace playden::webdiff --git a/tests/homebrew_library_model_test.cpp b/tests/homebrew_library_model_test.cppindex 3923a8b..ea8b51f 100644--- a/tests/homebrew_library_model_test.cpp+++ b/tests/homebrew_library_model_test.cpp@@ -1265,9 +1265,37 @@ void live_storage_section_and_installed_games() {std::vector<std::string> sections;for (const auto& row : model.view().rows)if (sections.empty() || sections.back() != row.section) sections.push_back(row.section);- check(sections == std::vector<std::string>{"Account", "Library", "Storage", "Downloads", "Display", "Updates", "About",- "Quit Playden"},- "the rail order is Account, Library, Storage, Downloads, Display, Updates, About, Quit");+ check(sections == std::vector<std::string>{"Account", "Library", "Storage", "Downloads", "Display", "Updates", "Web access",+ "About", "Quit Playden"},+ "the rail order is Account, Library, Storage, Downloads, Display, Updates, Web access, About, Quit");+ // Web access: on by default; the address and its QR once the server reports them; the reason when it can't open.+ check(find_row(model, "settings-web-access")->selected && model.ExportPreferences().web_access, "web access is on by default");+ check(!find_row(model, "settings-web-address"), "no address before the server reports one");+ model.ApplyLiveWebAccess({"on", "http://192.168.1.50:7031/", 7031, {}});+ const auto* address = find_row(model, "settings-web-address");+ check(address && address->qr == "http://192.168.1.50:7031/" && address->value == "http://192.168.1.50:7031" &&+ address->section == "Web access" && address->subtitle.find("your Steam name removed") != std::string::npos &&+ !address->enabled,+ "the page's address shows with its QR code");+ model.ApplyLiveWebAccess({"on", "", 7032, {}});+ check(find_row(model, "settings-web-address") && find_row(model, "settings-web-address")->qr.empty() &&+ find_row(model, "settings-web-address")->title == "Address unknown" &&+ find_row(model, "settings-web-address")->value == "port 7032",+ "an unknown address is said, never guessed");+ model.ApplyLiveWebAccess({"failed", "", 0, "port 7039: Address already in use (errno 48)"});+ check(find_row(model, "settings-web-problem") &&+ find_row(model, "settings-web-problem")->subtitle.rfind(+ "Web access could not start: port 7039: Address already in use (errno 48).", 0) == 0,+ "a port that could not be opened says why");+ activate(model, "settings-web-access");+ check(!find_row(model, "settings-web-access")->selected && !model.ExportPreferences().web_access &&+ !find_row(model, "settings-web-problem") && !find_row(model, "settings-web-address"),+ "the toggle turns web access off");+ activate(model, "settings-web-access");+ check(model.ExportPreferences().web_access, "and on again");+ check(!model.state().quit_requested, "not quitting yet");+ model.RequestQuit();+ check(model.state().quit_requested, "the page's Quit Playden quits when nothing is being prepared");const auto* empty = find_row(model, "settings-installed");check(empty && !empty->enabled && empty->value == "None", "nothing installed says None");check(find_row(model, "settings-kept")->value == "None" && !has_row(model, "settings-runtime-cleanup"),diff --git a/tests/homebrew_simulation_test.cpp b/tests/homebrew_simulation_test.cppindex c045347..8f35633 100644--- a/tests/homebrew_simulation_test.cpp+++ b/tests/homebrew_simulation_test.cpp@@ -1448,6 +1448,15 @@ void leftover_titles_simulation_uses_controller_navigation(const std::filesystemconst std::filesystem::path& profile) {using namespace playden::homebrew;Simulation simulation(fixtures, profile);+ check(simulation.scenario("web-access"), "web access scenario exists");+ check(simulation.view().focused_row >= 0 &&+ simulation.view().rows[static_cast<std::size_t>(simulation.view().focused_row)].key == "settings-web-access",+ "the web access scenario opens Settings on Web access");+ {+ bool qr = false;+ for (const auto& row : simulation.view().rows) qr = qr || row.qr == "http://192.168.1.50:7031/";+ check(qr, "the simulation shows a made-up address with its QR code");+ }check(simulation.scenario("leftover-titles"), "leftover title scenario exists");check(simulation.state().leftover_titles.size() == 2 &&simulation.state().navigation.focus_key == "settings-leftovers", "the Leftover PS5 titles row starts focused");diff --git a/tests/preferences_test.cpp b/tests/preferences_test.cppindex 3d7a2bc..9e8e722 100644--- a/tests/preferences_test.cpp+++ b/tests/preferences_test.cpp@@ -186,9 +186,9 @@ void SignInMethodPersistsAndVersionThreeOpensQr() {Check(store.Save(preferences).ok(), "sign-in method preference saves");const auto saved = storage.Read("preferences.conf");Check(saved.ok() && std::string(saved.value().begin(), saved.value().end()) ==- "version=8\nreduce_motion=0\ntitle_store_suffix=0\ncloud_saves_auto=1\nsteam_sign_in_password=1\n"- "downloads_slow_network=0\nsteam_stay_signed_in=1\nbeta_updates=0\ndownload_server=\n",- "version 8 format includes Automatic download server");+ "version=9\nreduce_motion=0\ntitle_store_suffix=0\ncloud_saves_auto=1\nsteam_sign_in_password=1\n"+ "downloads_slow_network=0\nsteam_stay_signed_in=1\nbeta_updates=0\ndownload_server=\nweb_access=1\n",+ "version 9 format includes Automatic download server and web access");const auto loaded = store.Load();Check(loaded.status == playden::PreferencesLoadStatus::kLoaded && loaded.preferences.steam_sign_in_password &&loaded.preferences.cloud_saves_auto,@@ -289,6 +289,35 @@ void VersionEightLoadsDownloadServerWithoutResettingOtherFields() {"version 8 restores the chosen download server");}+void VersionNineKeepsWebAccessAndVersionEightTurnsItOn() {+ TemporaryDirectory directory;+ playden::Storage storage(directory.path());+ playden::PreferencesStore store(storage);+ playden::Preferences preferences;+ preferences.web_access = false;+ preferences.beta_updates = true;+ preferences.download_server = "fastest";+ Check(store.Save(preferences).ok(), "web access off saves");+ auto loaded = store.Load();+ Check(loaded.status == playden::PreferencesLoadStatus::kLoaded && !loaded.preferences.web_access &&+ loaded.preferences.beta_updates && loaded.preferences.download_server == "fastest",+ "web access off survives restart with the other fields");+ const std::string eight =+ "version=8\nreduce_motion=1\ntitle_store_suffix=0\ncloud_saves_auto=0\nsteam_sign_in_password=0\n"+ "downloads_slow_network=0\nsteam_stay_signed_in=1\nbeta_updates=0\ndownload_server=cache.example\n";+ Check(storage.WriteAtomic("preferences.conf", playden::Bytes(eight.begin(), eight.end())).ok(), "version 8 fixture is written");+ loaded = store.Load();+ Check(loaded.status == playden::PreferencesLoadStatus::kLoaded && loaded.preferences.web_access &&+ loaded.preferences.reduce_motion && loaded.preferences.download_server == "cache.example",+ "a version 8 file loads with web access on");+ const std::string malformed[] = {eight + "web_access=1\n", "version=9" + eight.substr(9) + "web_access=2\n",+ "version=9" + eight.substr(9), "version=9" + eight.substr(9) + "web_access=1\nx=1\n"};+ for (const auto& text : malformed) {+ Check(storage.WriteAtomic("preferences.conf", playden::Bytes(text.begin(), text.end())).ok(), "malformed fixture is written");+ Check(store.Load().status == playden::PreferencesLoadStatus::kDefaultCorrupt, "a malformed version 8 or 9 file is corrupt");+ }+}+void OlderPreferencesUseAutomaticDownloadServer() {TemporaryDirectory directory;playden::Storage storage(directory.path());@@ -315,8 +344,9 @@ void OlderPreferencesUseAutomaticDownloadServer() {"migration retains old fields and defaults later fields");Check(store.Save(loaded.preferences).ok(), "migrated preferences save");const auto saved = storage.Read("preferences.conf");- Check(saved.ok() && std::string(saved.value().begin(), saved.value().end()).rfind("version=8\n", 0) == 0,- "saving a migrated file writes version 8");+ Check(saved.ok() && std::string(saved.value().begin(), saved.value().end()).rfind("version=9\n", 0) == 0,+ "saving a migrated file writes version 9");+ Check(loaded.preferences.web_access, "every older preference version has web access on");}}@@ -432,6 +462,7 @@ int main() {SignInMethodPersistsAndVersionThreeOpensQr();StaySignedInDefaultsOnAndPersistsOff();VersionEightLoadsDownloadServerWithoutResettingOtherFields();+ VersionNineKeepsWebAccessAndVersionEightTurnsItOn();OlderPreferencesUseAutomaticDownloadServer();DownloadServerRoundTripsAndInvalidHostsUseAutomatic();VersionEightRejectsTruncatedOrMalformedFiles();diff --git a/tests/test_collect_logs.py b/tests/test_collect_logs.pyindex 6841d23..9d69d0c 100644--- a/tests/test_collect_logs.py+++ b/tests/test_collect_logs.py@@ -1,7 +1,13 @@+import http.server+import ioimport jsonfrom pathlib import Path+import subprocessimport sys+import tempfile+import threadingimport unittest+import zipfileROOT = Path(__file__).resolve().parents[1]sys.path.insert(0, str(ROOT / 'tools'))@@ -92,6 +98,91 @@ class CollectLogsTests(unittest.TestCase):collect_logs.folders, collect_logs.fetch = folders, fetch+class StubPlayden(http.server.BaseHTTPRequestHandler):+ """Playden's web access as the --http path sees it: the log index and a report zip."""+ index = {'games': [{'title': 'FAKE78002', 'app': 40800, 'name': None, 'last_run': 300, 'size': 10, 'files': []},+ {'title': 'FAKE78001', 'app': 220, 'name': 'Half-Life 2', 'last_run': 100, 'size': 10, 'files': []}],+ 'playden': [{'name': 'runtime.log', 'changed': 1, 'size': 5}]}+ requests = []++ def do_GET(self):+ StubPlayden.requests.append(self.path)+ if self.path == '/api/logs':+ body, kind = json.dumps(self.index).encode(), 'application/json'+ elif self.path.startswith('/api/report.zip'):+ buffer = io.BytesIO()+ with zipfile.ZipFile(buffer, 'w', zipfile.ZIP_STORED) as archive:+ archive.writestr('summary.md', '| Field | Value |\n| --- | --- |\n| asked | ' + self.path + ' |\n')+ archive.writestr('logs/runtime.log', 'console_firmware=4.03\n')+ body, kind = buffer.getvalue(), 'application/zip'+ else:+ self.send_error(404)+ return+ self.send_response(200)+ self.send_header('Content-Type', kind)+ self.end_headers()+ self.wfile.write(body)++ def log_message(self, *args):+ pass+++class CollectLogsHttpTests(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.server = http.server.ThreadingHTTPServer(('127.0.0.1', 0), StubPlayden)+ threading.Thread(target=cls.server.serve_forever, daemon=True).start()++ @classmethod+ def tearDownClass(cls):+ cls.server.shutdown()+ cls.server.server_close()++ def run_tool(self, *extra):+ StubPlayden.requests = []+ return subprocess.run([sys.executable, '-I', str(ROOT / 'tools' / 'collect_logs.py'), '--http', '--host', '127.0.0.1',+ '--port', str(self.server.server_address[1]), *extra],+ capture_output=True, text=True, stdin=subprocess.DEVNULL, timeout=60)++ def report(self, *extra):+ with tempfile.TemporaryDirectory() as directory:+ out = Path(directory) / 'report.zip'+ result = self.run_tool('--out', str(out), *extra)+ self.assertEqual(result.returncode, 0, result.stderr)+ with zipfile.ZipFile(out) as archive:+ self.assertEqual(archive.namelist(), ['summary.md', 'logs/runtime.log'])+ return result, StubPlayden.requests++ def test_lists_the_games_from_the_index(self):+ result = self.run_tool('--list')+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertIn('1. unknown game (FAKE78002, app 40800', result.stdout)+ self.assertIn('Half-Life 2 (FAKE78001, app 220', result.stdout)+ self.assertEqual(StubPlayden.requests, ['/api/logs'])++ def test_downloads_the_newest_game_without_a_terminal(self):+ result, requests = self.report()+ self.assertEqual(requests, ['/api/logs', '/api/report.zip?title=FAKE78002'])+ self.assertIn('| asked | /api/report.zip?title=FAKE78002 |', result.stdout)+ self.assertIn('Wrote ', result.stdout)++ def test_picks_by_title_app_or_all(self):+ self.assertEqual(self.report('--title', 'FAKE78001')[1][-1], '/api/report.zip?title=FAKE78001')+ self.assertEqual(self.report('--app', '220')[1][-1], '/api/report.zip?title=FAKE78001')+ self.assertEqual(self.report('--all-titles')[1][-1], '/api/report.zip?title=all')+ result, requests = self.report('--app', '1')+ self.assertEqual(requests[-1], '/api/report.zip?title=none')+ self.assertIn('no game log found for app 1', result.stderr)++ def test_refuses_no_redact_and_says_when_playden_is_closed(self):+ result = self.run_tool('--no-redact')+ self.assertNotEqual(result.returncode, 0)+ self.assertIn('always redacted', result.stderr)+ closed = subprocess.run([sys.executable, '-I', str(ROOT / 'tools' / 'collect_logs.py'), '--http', '--host',+ '127.0.0.1', '--port', '9', '--list'], capture_output=True, text=True, timeout=60)+ self.assertNotEqual(closed.returncode, 0)+ self.assertIn('Is Playden open on the PS5', closed.stderr)+if __name__ == '__main__':unittest.main()diff --git a/tests/web_logs_source_test.cpp b/tests/web_logs_source_test.cppnew file mode 100644index 0000000..55584f9--- /dev/null+++ b/tests/web_logs_source_test.cpp@@ -0,0 +1,222 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Also built as web_logs_source_native_policy with PLAYDEN_PLATFORM_PS5=1: the console's walk by path.+#include "web/logs_source.h"++#include <cstdio>+#include <cstdlib>+#include <filesystem>+#include <string>+#include <unistd.h>++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 {+std::string TitleLog(std::uint32_t app, const std::string& account = "Alice", std::int64_t time = 1791601941) {+ return "== session-1.log\nPW_REPORT/1 build=abc profile=playden-steam-" + std::to_string(app) ++ " cycle=0 pid=5 time=" + std::to_string(time) ++ "\nREC seq=561 WINE trace:process:SetEnvironmentVariableW (L\"SteamAppUser\" L\"" + account ++ "\")\nREC seq=562 WINE trace:process:SetEnvironmentVariableW (L\"SteamUser\" L\"" + account + "\")\n";+}++void Put(const fs::path& path, const std::string& text) {+ fs::create_directories(path.parent_path());+ FILE* file = std::fopen(path.c_str(), "wb");+ CHECK(file != nullptr);+ CHECK(std::fwrite(text.data(), 1, text.size(), file) == text.size());+ std::fclose(file);+}++std::string Param(const std::string& name) {+ return R"({"localizedParameters":{"defaultLanguage":"en-US","en-US":{"titleName":")" + name + R"("}},"titleId":"x"})";+}+} // namespace++int main() {+ // Pure rules, as tests/test_collect_logs.py has them.+ CHECK(TitleLogId("title-FAKE78012.log") == std::optional<std::string>("FAKE78012"));+ CHECK(!TitleLogId("title-FAKE7801.log") && !TitleLogId("title-FAKE78012.reg") && !TitleLogId("title-PPSA12345.log"));+ CHECK(TitleApp(TitleLog(220)) == 220 && TitleApp("no profile") == 0);+ CHECK(TitleApp(std::string(5000, 'x') + "profile=playden-steam-1") == 0); // first 4 KB only+ CHECK(LastRun(TitleLog(40800, "A", 300) + "PW_REPORT/1 build=abc profile=x time=50\n") == 300);+ CHECK(LastRun("no report yet\n") == 0);+ CHECK(LastRun("x PW_REPORT/1 time=9\n") == 0); // the line must start with it+ CHECK(LastRun("PW_REPORT/1 runtime=5 time=7\n") == 7); // \btime=, not runtime=+ CHECK(WithoutStoreSuffix("Half-Life 2 (Steam)") == "Half-Life 2");+ CHECK(WithoutStoreSuffix("Delores (Epic)") == "Delores" && WithoutStoreSuffix("Gothic (GOG)") == "Gothic");+ CHECK(WithoutStoreSuffix("Imported") == "Imported");+ CHECK(WithoutStoreSuffix("Game (Steam) (GOG)") == "Game (Steam)");+ CHECK(WithoutStoreSuffix(" (Steam)") == " (Steam)" && WithoutStoreSuffix("").empty());+ CHECK(TitleNameFromParam(Param("Half-Life 2 (Steam)")) == "Half-Life 2");+ CHECK(TitleNameFromParam(R"({"localizedParameters":{"defaultLanguage":"ja-JP","ja-JP":{"titleName":"Game"}}})") == "Game");+ CHECK(TitleNameFromParam("not json").empty() && TitleNameFromParam("{}").empty());++ std::set<std::string> names;+ const std::string text = TitleLog(220) + "cloud user=alice id=76561198000000001 path=C:/users/Alice/saves\n";+ AddAccountNames(text, &names);+ CHECK(names == std::set<std::string>{"Alice"});+ auto redacted = Redact(text, names, {});+ CHECK(redacted.find("lice") == std::string::npos && redacted.find("76561198000000001") == std::string::npos);+ CHECK(redacted.find("<steam-user>") != std::string::npos && redacted.find("<steam-id>") != std::string::npos);+ // Word boundaries around SteamIDs, as \b in the Python regex.+ CHECK(Redact("x76561198000000001 765611980000000012 76561198000000001_", {}, {}) ==+ "x76561198000000001 765611980000000012 76561198000000001_");+ CHECK(Redact("(76561198000000001)", {}, {}) == "(<steam-id>)");+ // Non-ASCII punctuation is a boundary too, as in Python ("“76561198000000001”").+ CHECK(Redact("\xe2\x80\x9c" "76561198000000001\xe2\x80\x9d", {}, {}) == "\xe2\x80\x9c<steam-id>\xe2\x80\x9d");+ // The signed-in account, exactly, even where no Wine line names it; the longest name first.+ CHECK(Redact("steam user Bob 123 bobby", {"Bobby"}, {"bob", 123}) == "steam user <steam-user> <steam-id> <steam-user>");+ // A game that stopped before Wine named the user is still covered by another log's name.+ names.clear();+ const std::string stopped = "== session-1.log\nPW_REPORT/1 profile=playden-steam-220\nopen C:/users/Alice failed\n";+ AddAccountNames(stopped, &names);+ AddAccountNames(TitleLog(40800), &names);+ CHECK(Redact(stopped, names, {}).find("lice") == std::string::npos);+ CHECK(Firmware({"console_firmware=13.40 x", "a\nconsole_firmware=13.60 y"}) == "13.60" && Firmware({"nothing"}).empty());+ CHECK(Utf8Clean("ok \xff\xc3\xa9") == "ok \xef\xbf\xbd\xc3\xa9" && Utf8Clean("\xed\xa0\x80") == "\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd");+ CHECK(JsonString("a\"b\\c\n") == "\"a\\\"b\\\\c\\u000a\"");+ CHECK(Summary({{"collected", "x"}, {"firmware", ""}}) == "| Field | Value |\n| --- | --- |\n| collected | x |\n| firmware | unknown |\n");+ CHECK(CollectedTime(1791601941) == "2026-10-10 03:12 UTC" && ReportFileName(1791601941) == "playden-logs-20261010-031221.zip");++ // A console's folders under a temporary root (no links in the path: the walk refuses them).+ const fs::path root = fs::canonical(fs::temp_directory_path()) / ("playden-web-logs-" + std::to_string(::getpid()));+ fs::remove_all(root);+ const fs::path logs = root / "playden/logs", homebrew = root / "homebrew", kits = root / "playden/kits";+ const fs::path app = homebrew / "FAKE77031";+ Put(logs / "runtime.log.1", "console_firmware=4.00 kit=x\n");+ Put(logs / "runtime.log", "console_firmware=4.03 kit=x\n");+ Put(logs / "install.log", "user alice id=76561198000000001\n");+ Put(logs / "steam.log", "signed in as Bob (76561198000000002)\n");+ Put(logs / "title-FAKE78001.log", TitleLog(220, "Alice", 100));+ Put(logs / "title-FAKE78002.log", TitleLog(40800, "Alice", 300));+ Put(logs / "title-FAKE78002.registry.txt", "[Software\\Valve\\Steam] \"LastGameNameUsed\"=\"Alice\"\n");+ Put(logs / "title-FAKE78002.ppm", "P6");+ Put(logs / "title-FAKE78003.log", "no report yet\n");+ Put(logs / "screen.ppm", "P6");+ fs::create_directories(logs / "folder");+ Put(root / "playden/user/session.v1", "secret token");+ fs::create_symlink(root / "playden/user/session.v1", logs / "session-link.log");+ Put(homebrew / "FAKE78001/sce_sys/param.json", Param("Half-Life 2 (Steam)"));+ Put(kits / "old-kit/manifest.json", R"({"kit_id":"old-kit","runtime":{"artifact_revision":"f729534-kit-0.12"},"capabilities":["dxvk"]})");+ {+ // A real kit's manifest lists every file: tens of thousands of JSON values, about a megabyte.+ std::string files;+ for (int i = 0; i < 20000; ++i) files += std::string(i ? "," : "") + "{\"path\":\"runtime/file" + std::to_string(i) + "\",\"size\":1}";+ Put(kits / "playden-kit/manifest.json",+ R"({"kit_id":"playden-kit","runtime":{"artifact_revision":"ce28942-kit-0.13"},"capabilities":["dxvk","wine-mono"],"files":[)" ++ files + "]}");+ }+ fs::create_directories(kits / ".previous-x");+ Put(app / "playden-version", "0.9.0-nightly.20261028.4\n");+ Put(app / "playden-package.identity", "sha256 917f7b2a81c4d5e6f7a8b9c0d1e2f3a4\n");++ LogsSource source({logs.string(), homebrew.string(), kits.string(), app.string()});+ const auto index = source.Index();+ // Games: newest run first, then by title; names from param.json without the store suffix.+ CHECK(index.games.size() == 3);+ CHECK(index.games[0].title == "FAKE78002" && index.games[0].app == 40800 && index.games[0].last_run == 300);+ CHECK(index.games[0].name.empty());+ CHECK((index.games[0].files == std::vector<std::string>{"title-FAKE78002.log", "title-FAKE78002.registry.txt"}));+ CHECK(index.games[0].size == fs::file_size(logs / "title-FAKE78002.log") + fs::file_size(logs / "title-FAKE78002.registry.txt"));+ CHECK(index.games[1].title == "FAKE78001" && index.games[1].name == "Half-Life 2" && index.games[1].app == 220);+ CHECK(index.games[2].title == "FAKE78003" && index.games[2].last_run == 0 && index.games[2].app == 0);+ // Playden's logs by name: no screenshots, folders, links or title files.+ CHECK(index.playden.size() == 4);+ CHECK(index.playden[0].name == "install.log" && index.playden[1].name == "runtime.log" &&+ index.playden[2].name == "runtime.log.1" && index.playden[3].name == "steam.log");+ CHECK(index.playden[1].size == fs::file_size(logs / "runtime.log") && index.playden[1].changed > 0);+ CHECK(!index.HasFile("session-link.log") && !index.HasFile("screen.ppm") && index.HasFile("title-FAKE78002.registry.txt"));+ const auto json = source.IndexJson(index);+ CHECK(json.find("{\"title\":\"FAKE78002\",\"app\":40800,\"name\":null,\"last_run\":300,") != std::string::npos);+ CHECK(json.find("\"name\":\"Half-Life 2\"") != std::string::npos && json.find("\"app\":null") != std::string::npos);++ // The facts: the latest firmware, the current kit folder first and the others named.+ const auto facts = source.Facts(1791601941);+ const auto fact = [&](const std::string& key) {+ for (const auto& [name, value] : facts) if (name == key) return value;+ return std::string("<missing>");+ };+ CHECK(fact("collected") == "2026-10-10 03:12 UTC" && fact("Playden package") == "917f7b2a81c4");+ CHECK(fact("Playden version") == "0.9.0-nightly.20261028.4" && fact("firmware") == "4.03");+ CHECK(fact("kit runtime") == "ce28942-kit-0.13" && fact("kit capabilities") == "dxvk, wine-mono");+ CHECK(fact("other kit folders") == "old-kit");+ const auto status = source.StatusJson(1791601941);+ CHECK(status.find("\"version\":\"0.9.0-nightly.20261028.4\"") != std::string::npos);+ CHECK(status.find("\"other_kit_folders\":\"old-kit\"") != std::string::npos && status.find("\"firmware\":\"4.03\"") != std::string::npos);++ // One log: only names the index lists, always redacted (the found name and the signed-in account).+ const Redaction account{"Bob", 76561198000000002ull};+ const auto install = source.ReadLog(index, "install.log", account);+ CHECK(install && *install == "user <steam-user> id=<steam-id>\n");+ const auto steam = source.ReadLog(index, "steam.log", account);+ CHECK(steam && *steam == "signed in as <steam-user> (<steam-id>)\n");+ CHECK(!source.ReadLog(index, "session-link.log", account) && !source.ReadLog(index, "../user/session.v1", account));+ CHECK(!source.ReadLog(index, "screen.ppm", account) && !source.ReadLog(index, "", account) && !source.ReadLog(index, "..", account));++ // Reports: summary.md + logs/, as collect_logs.py writes them.+ const auto report = [&](const std::string& title, const fs::path& path) {+ std::string bytes;+ CHECK(source.WriteReport(index, title, account, 1791601941,+ [&bytes](const char* data, std::size_t size) { bytes.append(data, size); return true; }));+ Put(path, bytes);+ };+ report("", root / "newest.zip");+ report("all", root / "all.zip");+ report("FAKE78001", root / "one.zip");+ report("FAKE79999", root / "none.zip");+ const std::string check = R"(+import sys, zipfile+def names(path):+ z = zipfile.ZipFile(path); assert z.testzip() is None+ for name in z.namelist():+ text = z.read(name).decode()+ assert 'alice' not in text.lower() and 'bob' not in text.lower(), name+ assert '76561198000000001' not in text and '76561198000000002' not in text, name+ return z.namelist(), z.read('summary.md').decode()+playden = ['logs/install.log', 'logs/runtime.log', 'logs/runtime.log.1', 'logs/steam.log']+listed, summary = names(sys.argv[1] + '/newest.zip')+assert listed == ['summary.md'] + sorted(playden + ['logs/title-FAKE78002.log', 'logs/title-FAKE78002.registry.txt']), listed+assert '| game titles | FAKE78002 (app 40800) |' in summary and '| redacted | Steam account name and SteamIDs |' in summary+assert summary.startswith('| Field | Value |\n| --- | --- |\n| collected | 2026-10-10 03:12 UTC |\n| Playden package | 917f7b2a81c4 |')+listed, summary = names(sys.argv[1] + '/all.zip')+assert '| game titles | FAKE78001 (app 220), FAKE78002 (app 40800), FAKE78003 (app ?) |' in summary, summary+assert 'logs/title-FAKE78003.log' in listed and 'logs/title-FAKE78002.ppm' not in listed+listed, summary = names(sys.argv[1] + '/one.zip')+assert listed == ['summary.md'] + sorted(playden + ['logs/title-FAKE78001.log']), listed+listed, summary = names(sys.argv[1] + '/none.zip')+assert listed == ['summary.md'] + playden and '| game titles | none |' in summary+)";+ Put(root / "check.py", check);+ CHECK(std::system(("python3 -I '" + (root / "check.py").string() + "' '" + root.string() + "'").c_str()) == 0);++ // A log over the read limit: its newest part, after a line saying how much was left out.+ {+ const std::string last = "last line alice 76561198000000001\n";+ std::string big(LogsSource::kMaxFileBytes + 1000 - last.size(), 'x');+ big += last;+ Put(logs / "huge.log", big);+ const auto index_big = source.Index();+ const auto huge = source.ReadLog(index_big, "huge.log", {});+ CHECK(huge && huge->rfind("[Playden: the first 1000 bytes of this file are left out]\n", 0) == 0);+ CHECK(huge->find("last line <steam-user> <steam-id>") != std::string::npos);+ fs::remove(logs / "huge.log");+ }++ // A logs folder that isn't there: an empty index, not an error.+ LogsSource missing({(root / "nowhere").string(), homebrew.string(), (root / "nokits").string(), app.string()});+ const auto empty = missing.Index();+ CHECK(empty.games.empty() && empty.playden.empty());+ std::string bytes;+ CHECK(missing.WriteReport(empty, "", {}, 0, [&bytes](const char* data, std::size_t size) { bytes.append(data, size); return true; }));+ CHECK(bytes.size() > 22);+ fs::remove_all(root);+ std::puts("web_logs_source: ok");+}diff --git a/tests/web_request_test.cpp b/tests/web_request_test.cppnew file mode 100644index 0000000..cf779b2--- /dev/null+++ b/tests/web_request_test.cpp@@ -0,0 +1,83 @@+// SPDX-License-Identifier: GPL-3.0-or-later+#include "web/http.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() {+ Request request;+ CHECK(ParseRequestHead("GET / HTTP/1.1\r\nHost: x\r\n", &request) == ParseResult::kIncomplete);+ CHECK(ParseRequestHead("GET /api/logs HTTP/1.1\r\nHost: 10.0.1.68:7031\r\nUser-Agent: curl\r\n\r\n", &request) ==+ ParseResult::kOk);+ CHECK(request.method == Method::kGet && request.method_text == "GET" && request.path == "/api/logs");+ CHECK(request.headers.size() == 2 && request.headers[0].first == "host" && request.headers[0].second == "10.0.1.68:7031");+ // A body after the head is ignored.+ CHECK(ParseRequestHead("HEAD /x?title=FAKE78012 HTTP/1.0\n\nbody", &request) == ParseResult::kOk);+ CHECK(request.method == Method::kHead && request.path == "/x" && request.query == "title=FAKE78012");+ CHECK(ParseRequestHead("POST / HTTP/1.1\r\n\r\n", &request) == ParseResult::kOk && request.method == Method::kPost);+ CHECK(ParseRequestHead("DELETE /api/logs/runtime.log HTTP/1.1\r\n\r\n", &request) == ParseResult::kOk &&+ request.method == Method::kOther && request.method_text == "DELETE");++ // Percent escapes decode in the path; a bad escape or a NUL is refused.+ CHECK(ParseRequestHead("GET /api/logs/title-FAKE78012%2Elog HTTP/1.1\r\n\r\n", &request) == ParseResult::kOk);+ CHECK(request.path == "/api/logs/title-FAKE78012.log");+ CHECK(ParseRequestHead("GET /a%2 HTTP/1.1\r\n\r\n", &request) == ParseResult::kBadRequest);+ CHECK(ParseRequestHead("GET /a%zz HTTP/1.1\r\n\r\n", &request) == ParseResult::kBadRequest);+ CHECK(ParseRequestHead("GET /a%00b HTTP/1.1\r\n\r\n", &request) == ParseResult::kBadRequest);++ // Bad request lines.+ CHECK(ParseRequestHead("GET\r\n\r\n", &request) == ParseResult::kBadRequest);+ CHECK(ParseRequestHead("GET / HTTP/2\r\n\r\n", &request) == ParseResult::kBadRequest);+ CHECK(ParseRequestHead("GET http://evil/ HTTP/1.1\r\n\r\n", &request) == ParseResult::kBadRequest);+ CHECK(ParseRequestHead("GET * HTTP/1.1\r\n\r\n", &request) == ParseResult::kBadRequest);+ CHECK(ParseRequestHead("GET / HTTP/1.1\r\n\r\n", &request) == ParseResult::kBadRequest);+ CHECK(ParseRequestHead("G(T / HTTP/1.1\r\n\r\n", &request) == ParseResult::kBadRequest);+ CHECK(ParseRequestHead(std::string("GET /\x7f HTTP/1.1\r\n\r\n"), &request) == ParseResult::kBadRequest);+ CHECK(ParseRequestHead("GET / HTTP/1.1\r\nNo colon\r\n\r\n", &request) == ParseResult::kBadRequest);+ CHECK(ParseRequestHead("GET / HTTP/1.1\r\n: empty\r\n\r\n", &request) == ParseResult::kBadRequest);+ CHECK(ParseRequestHead(std::string("GET / HTTP/1.1\r\nX: a\x01" "b\r\n\r\n"), &request) == ParseResult::kBadRequest);++ // The head limit: 8 KB, with or without the blank line seen.+ const std::string big_header = "X-Big: " + std::string(kMaxRequestHead, 'a');+ CHECK(ParseRequestHead("GET / HTTP/1.1\r\n" + big_header, &request) == ParseResult::kTooLarge);+ CHECK(ParseRequestHead("GET / HTTP/1.1\r\n" + big_header + "\r\n\r\n", &request) == ParseResult::kTooLarge);+ const std::string fits = "GET / HTTP/1.1\r\nX: " + std::string(kMaxRequestHead - 25, 'a') + "\r\n\r\n";+ CHECK(fits.size() <= kMaxRequestHead && ParseRequestHead(fits, &request) == ParseResult::kOk);++ // Query values.+ CHECK(QueryValue("title=FAKE78012", "title") == std::optional<std::string>("FAKE78012"));+ CHECK(QueryValue("a=1&title=all&b", "title") == std::optional<std::string>("all"));+ CHECK(QueryValue("a=1&b", "b") == std::optional<std::string>(""));+ CHECK(!QueryValue("a=1", "title"));+ CHECK(QueryValue("t%69tle=x+y%21", "title") == std::optional<std::string>("x y!"));+ CHECK(!QueryValue("title=%zz", "title"));++ // Responses: status line, headers, Connection: close; HEAD sends no body.+ std::string sent;+ const auto into = [&sent](const char* data, std::size_t size) { sent.append(data, size); return true; };+ Response get(into, false);+ CHECK(get.Send(200, "text/plain", "hi", {{"Cache-Control", "no-store"}}));+ CHECK(sent.rfind("HTTP/1.1 200 OK\r\n", 0) == 0);+ CHECK(sent.find("Content-Length: 2\r\n") != std::string::npos && sent.find("Cache-Control: no-store\r\n") != std::string::npos);+ CHECK(sent.find("Connection: close\r\n\r\nhi") != std::string::npos && get.body_bytes() == 2 && get.status() == 200);+ sent.clear();+ Response head(into, true);+ CHECK(head.Send(404, "text/plain", "missing"));+ CHECK(sent.rfind("HTTP/1.1 404 Not Found\r\n", 0) == 0 && sent.find("Content-Length: 7\r\n") != std::string::npos);+ CHECK(sent.size() >= 4 && sent.compare(sent.size() - 4, 4, "\r\n\r\n") == 0 && head.body_bytes() == 0);+ // A client gone mid-answer: the response says so and writes nothing more.+ Response gone([](const char*, std::size_t) { return false; }, false);+ CHECK(!gone.Start(200, "text/plain", std::nullopt) && gone.failed() && !gone.Body("x"));+ std::puts("web_request: ok");+}diff --git a/tests/web_router_test.cpp b/tests/web_router_test.cppnew file mode 100644index 0000000..2df13fc--- /dev/null+++ b/tests/web_router_test.cpp@@ -0,0 +1,94 @@+// SPDX-License-Identifier: GPL-3.0-or-later+#include "web/router.h"++#include <cstdio>+#include <cstdlib>+#include <set>+#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)++namespace {+struct Answer {+ std::string bytes;+ int status = 0;+};++Answer Ask(const Router& router, const std::string& head) {+ Request request;+ Answer answer;+ if (ParseRequestHead(head + "\r\n\r\n", &request) != ParseResult::kOk) return answer;+ Response response([&answer](const char* data, std::size_t size) { answer.bytes.append(data, size); return true; },+ request.method == Method::kHead);+ router.Handle(request, response);+ answer.status = response.status();+ return answer;+}++std::string Body(const Answer& answer) {+ const auto end = answer.bytes.find("\r\n\r\n");+ return end == std::string::npos ? std::string() : answer.bytes.substr(end + 4);+}+} // namespace++int main() {+ // The log route as the web layer registers it: the name must be one the index lists.+ const std::set<std::string> index = {"runtime.log", "title-FAKE78012.log"};+ Router router;+ router.Exact("/", [](const Request&, const std::string&, Response& response) { response.Send(200, "text/html", "page"); });+ router.Exact("/api/logs", [](const Request&, const std::string&, Response& response) { response.Send(200, "application/json", "{}"); });+ router.Prefix("/api/logs/", [&index](const Request&, const std::string& name, Response& response) {+ if (!index.count(name)) return SendError(response, 404, "No such log.");+ response.Send(200, "text/plain; charset=utf-8", name);+ });++ CHECK(Ask(router, "GET / HTTP/1.1").status == 200);+ CHECK(Body(Ask(router, "GET / HTTP/1.1")) == "page");+ CHECK(Ask(router, "GET /index.html HTTP/1.1").status == 404);+ CHECK(Ask(router, "GET /api/logs HTTP/1.1").status == 200);+ CHECK(Ask(router, "GET /api/logs/ HTTP/1.1").status == 404);+ CHECK(Body(Ask(router, "GET /api/logs/runtime.log HTTP/1.1")) == "runtime.log");+ CHECK(Ask(router, "GET /api/logs/title-FAKE78012.log HTTP/1.1").status == 200);+ // HEAD answers like GET without the body.+ const auto head = Ask(router, "HEAD /api/logs/runtime.log HTTP/1.1");+ CHECK(head.status == 200 && Body(head).empty() && head.bytes.find("Content-Length: 11\r\n") != std::string::npos);++ // Names not in the index, paths and escapes: never a file outside it.+ CHECK(Ask(router, "GET /api/logs/missing.log HTTP/1.1").status == 404);+ CHECK(Ask(router, "GET /api/logs/../user/session.v1 HTTP/1.1").status == 404);+ CHECK(Ask(router, "GET /api/logs/..%2Fuser%2Fsession.v1 HTTP/1.1").status == 404);+ CHECK(Ask(router, "GET /api/logs/%2E%2E HTTP/1.1").status == 404);+ CHECK(Ask(router, "GET /api/logs//etc/passwd HTTP/1.1").status == 404);+ CHECK(Ask(router, "GET /api/logs/sub/runtime.log HTTP/1.1").status == 404);+ CHECK(Ask(router, "GET /API/LOGS HTTP/1.1").status == 404);++ // Only GET and HEAD.+ for (const char* method : {"POST", "PUT", "DELETE", "OPTIONS", "PATCH", "TRACE"}) {+ const auto answer = Ask(router, std::string(method) + " /api/logs HTTP/1.1");+ CHECK(answer.status == 405 && answer.bytes.find("Allow: GET, HEAD\r\n") != std::string::npos);+ }+ CHECK(Ask(router, "POST /nowhere HTTP/1.1").status == 405);++ // An action takes POST only; it is not reachable by GET, HEAD or a prefix.+ int actions = 0;+ router.Post("/api/quit", [&actions](const Request&, const std::string&, Response& response) {+ ++actions;+ response.Send(202, "application/json", "{}");+ });+ CHECK(Ask(router, "POST /api/quit HTTP/1.1").status == 202 && actions == 1);+ for (const char* method : {"GET", "HEAD", "PUT", "DELETE"}) {+ const auto answer = Ask(router, std::string(method) + " /api/quit HTTP/1.1");+ CHECK(answer.status == 405 && answer.bytes.find("Allow: POST\r\n") != std::string::npos);+ }+ CHECK(Ask(router, "POST /api/quit/now HTTP/1.1").status == 405 && Ask(router, "POST /api/logs HTTP/1.1").status == 405);+ CHECK(actions == 1);+ std::puts("web_router: ok");+}diff --git a/tests/web_server_test.cpp b/tests/web_server_test.cppnew file mode 100644index 0000000..22837e5--- /dev/null+++ b/tests/web_server_test.cpp@@ -0,0 +1,195 @@+// SPDX-License-Identifier: GPL-3.0-or-later+#include "web/router.h"+#include "web/server.h"++#include <arpa/inet.h>+#include <chrono>+#include <cstdio>+#include <cstdlib>+#include <mutex>+#include <netinet/in.h>+#include <string>+#include <sys/socket.h>+#include <thread>+#include <unistd.h>+#include <vector>++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)++namespace {+int Connect(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& request) {+ const int fd = Connect(port);+ CHECK(::send(fd, request.data(), request.size(), 0) == static_cast<ssize_t>(request.size()));+ std::string answer;+ char buffer[4096];+ 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;+}++// A listener on a free loopback port, held so the server must move to the next one.+int Hold(std::uint16_t* port) {+ const int fd = ::socket(AF_INET, SOCK_STREAM, 0);+ sockaddr_in address{};+ address.sin_family = AF_INET;+ address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);+ socklen_t size = sizeof address;+ CHECK(::bind(fd, reinterpret_cast<sockaddr*>(&address), sizeof address) == 0 && ::listen(fd, 1) == 0);+ CHECK(::getsockname(fd, reinterpret_cast<sockaddr*>(&address), &size) == 0);+ *port = ntohs(address.sin_port);+ return fd;+}+} // namespace++int main() {+ Router router;+ router.Exact("/", [](const Request&, const std::string&, Response& response) { response.Send(200, "text/plain", "hello\n"); });+ router.Exact("/big", [](const Request&, const std::string&, Response& response) {+ response.Start(200, "application/octet-stream", std::nullopt);+ const std::string chunk(64 * 1024, 'z');+ for (int i = 0; i < 64 && response.Body(chunk); ++i) {}+ });+ std::mutex lines_mutex;+ std::vector<std::string> lines;+ ServerOptions options;+ options.first_port = options.last_port = 0;+ options.loopback_only = true;+ options.read_timeout_ms = 500;+ options.write_timeout_ms = 500;+ options.poll_interval_ms = 50;+ options.log = [&](const std::string& line) { std::lock_guard<std::mutex> lock(lines_mutex); lines.push_back(line); };+ Server server;+ std::string error;+ CHECK(server.Start(options, [&router](const Request& request, Response& response) { router.Handle(request, response); }, &error));+ CHECK(server.running() && server.port() != 0);++ auto answer = Exchange(server.port(), "GET / HTTP/1.1\r\nHost: x\r\n\r\n");+ CHECK(answer.rfind("HTTP/1.1 200 OK\r\n", 0) == 0 && answer.size() > 6 && answer.compare(answer.size() - 6, 6, "hello\n") == 0);+ CHECK(answer.find("Connection: close\r\n") != std::string::npos);+ answer = Exchange(server.port(), "HEAD / HTTP/1.1\r\n\r\n");+ CHECK(answer.rfind("HTTP/1.1 200 OK\r\n", 0) == 0 && answer.find("hello") == std::string::npos);+ CHECK(Exchange(server.port(), "POST / HTTP/1.1\r\nContent-Length: 3\r\n\r\nabc").rfind("HTTP/1.1 405", 0) == 0);+ CHECK(Exchange(server.port(), "GET /nope HTTP/1.1\r\n\r\n").rfind("HTTP/1.1 404", 0) == 0);+ CHECK(Exchange(server.port(), "GARBAGE\r\n\r\n").rfind("HTTP/1.1 400", 0) == 0);+ CHECK(Exchange(server.port(), "GET / HTTP/1.1\r\nX: " + std::string(9000, 'a') + "\r\n\r\n").rfind("HTTP/1.1 431", 0) == 0);+ // Half a request, then silence: answered with 408 once the read time is up.+ {+ const auto started = std::chrono::steady_clock::now();+ CHECK(Exchange(server.port(), "GET / HTTP/1.1\r\n").rfind("HTTP/1.1 408", 0) == 0);+ CHECK(std::chrono::steady_clock::now() - started < std::chrono::seconds(3));+ }+ // A client that goes away in the middle of a 4 MB answer: the server carries on.+ {+ const int fd = Connect(server.port());+ const std::string request = "GET /big HTTP/1.1\r\n\r\n";+ CHECK(::send(fd, request.data(), request.size(), 0) > 0);+ char buffer[1024];+ CHECK(::recv(fd, buffer, sizeof buffer, 0) > 0);+ ::close(fd);+ }+ CHECK(Exchange(server.port(), "GET / HTTP/1.1\r\n\r\n").rfind("HTTP/1.1 200", 0) == 0);+ // A connection that sends nothing is closed without an answer or a log line.+ {+ const int fd = Connect(server.port());+ ::shutdown(fd, SHUT_WR);+ char byte;+ CHECK(::recv(fd, &byte, 1, 0) == 0);+ ::close(fd);+ }++ // Stop returns promptly and the port is closed.+ const auto port = server.port();+ const auto stopping = std::chrono::steady_clock::now();+ server.Stop();+ CHECK(!server.running());+ CHECK(std::chrono::steady_clock::now() - stopping < std::chrono::seconds(2));+ {+ 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(::connect(fd, reinterpret_cast<sockaddr*>(&address), sizeof address) != 0);+ ::close(fd);+ }+ {+ std::lock_guard<std::mutex> lock(lines_mutex);+ bool logged = false;+ for (const auto& line : lines) logged = logged || line == "GET / 200 6 127.0.0.1";+ CHECK(logged);+ }++ // A port in use: the next one in the range is taken; when all are taken, the error names the last.+ std::uint16_t held_port = 0;+ const int held = Hold(&held_port);+ options.first_port = held_port;+ options.last_port = static_cast<std::uint16_t>(held_port + 1);+ Server next;+ if (next.Start(options, [](const Request&, Response& response) { response.Send(200, "text/plain", "next"); }, &error)) {+ CHECK(next.port() == held_port + 1);+ next.Stop();+ }+ options.last_port = held_port;+ Server refused;+ CHECK(!refused.Start(options, [](const Request&, Response&) {}, &error) && !refused.running());+ CHECK(error.find("port " + std::to_string(held_port)) == 0);+ ::close(held);++ // A client that asks for a big answer and never reads it: Stop cuts it at once, not after the write time limit.+ {+ ServerOptions slow = options;+ slow.first_port = slow.last_port = 0;+ slow.write_timeout_ms = 30'000;+ Server stalled;+ CHECK(stalled.Start(slow, [&router](const Request& request, Response& response) { router.Handle(request, response); }, &error));+ const int fd = Connect(stalled.port());+ const std::string request = "GET /big HTTP/1.1\r\n\r\n";+ CHECK(::send(fd, request.data(), request.size(), 0) > 0);+ std::this_thread::sleep_for(std::chrono::milliseconds(300)); // the worker is now blocked in send+ const auto cut = std::chrono::steady_clock::now();+ stalled.Stop();+ CHECK(std::chrono::steady_clock::now() - cut < std::chrono::seconds(3));+ ::close(fd);+ }+ // A client that sends half a request and waits: Stop doesn't wait for the read time limit either.+ {+ ServerOptions slow = options;+ slow.first_port = slow.last_port = 0;+ slow.read_timeout_ms = 30'000;+ Server waiting;+ CHECK(waiting.Start(slow, [](const Request&, Response& response) { response.Send(200, "text/plain", "x"); }, &error));+ const int fd = Connect(waiting.port());+ CHECK(::send(fd, "GET / HTTP/1.1\r\n", 16, 0) == 16);+ std::this_thread::sleep_for(std::chrono::milliseconds(300));+ const auto cut = std::chrono::steady_clock::now();+ waiting.Stop();+ CHECK(std::chrono::steady_clock::now() - cut < std::chrono::seconds(3));+ ::close(fd);+ }++ // Started again after a stop.+ options.first_port = options.last_port = 0;+ CHECK(server.Start(options, [&router](const Request& request, Response& response) { router.Handle(request, response); }, &error));+ CHECK(Exchange(server.port(), "GET / HTTP/1.1\r\n\r\n").rfind("HTTP/1.1 200", 0) == 0);+ server.Stop();+ std::puts("web_server: ok");+}diff --git a/tests/web_service_test.cpp b/tests/web_service_test.cppnew file mode 100644index 0000000..cb48413--- /dev/null+++ b/tests/web_service_test.cpp@@ -0,0 +1,204 @@+// 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 <mutex>+#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 {+std::string Get(std::uint16_t port, const std::string& head) {+ 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);+ if (fd < 0 || ::connect(fd, reinterpret_cast<sockaddr*>(&address), sizeof address) != 0) {+ if (fd >= 0) ::close(fd);+ return {};+ }+ const std::string request = head + " HTTP/1.1\r\nHost: x\r\n\r\n";+ CHECK(::send(fd, request.data(), request.size(), 0) == static_cast<ssize_t>(request.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;+}++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);+}++void Put(const fs::path& path, const std::string& text) {+ fs::create_directories(path.parent_path());+ FILE* file = std::fopen(path.c_str(), "wb");+ CHECK(file != nullptr);+ std::fwrite(text.data(), 1, text.size(), file);+ std::fclose(file);+}++ServiceSnapshot WaitFor(const Service& service, ServiceSnapshot::State state) {+ for (int i = 0; i < 400; ++i) {+ const auto snapshot = service.Snapshot();+ if (snapshot.state == state) return snapshot;+ std::this_thread::sleep_for(std::chrono::milliseconds(10));+ }+ CHECK(!"the service did not reach the state");+ return {};+}+} // namespace++int main() {+ const fs::path root = fs::canonical(fs::temp_directory_path()) / ("playden-web-service-" + std::to_string(::getpid()));+ fs::remove_all(root);+ Put(root / "logs/steam.log", "signed in as Bob (76561198000000002)\n");+ Put(root / "logs/title-FAKE78012.log",+ "PW_REPORT/1 profile=playden-steam-1332010 time=300\n(L\"SteamUser\" L\"Alice\") C:/users/Alice\n");+ Put(root / "homebrew/FAKE78012/sce_sys/param.json",+ R"json({"localizedParameters":{"defaultLanguage":"en-US","en-US":{"titleName":"Stray (Steam)"}}})json");+ Put(root / "homebrew/FAKE77031/playden-version", "0.9.0\n");++ std::mutex lines_mutex;+ std::vector<std::string> lines;+ ServiceConfig config;+ config.paths = {(root / "logs").string(), (root / "homebrew").string(), (root / "kits").string(),+ (root / "homebrew/FAKE77031").string()};+ config.server.first_port = config.server.last_port = 0;+ config.server.loopback_only = true;+ config.server.poll_interval_ms = 20;+ config.server.read_timeout_ms = 1000;+ config.server.log = [&](const std::string& line) { std::lock_guard<std::mutex> lock(lines_mutex); lines.push_back(line); };+ config.now = [] { return std::int64_t{1791601941}; };+ Service service(config);+ CHECK(service.Snapshot().state == ServiceSnapshot::State::kOff);+ service.SetAccount({"Bob", 76561198000000002ull});+ service.SetEnabled(true);+ const auto on = WaitFor(service, ServiceSnapshot::State::kOn);+ CHECK(on.port != 0 && on.error.empty());+ CHECK(on.url.empty() == on.address.empty());+ if (!on.address.empty()) CHECK(on.url == "http://" + on.address + ":" + std::to_string(on.port) + "/");++ // The page and its fonts come from the binary; nothing else under /assets/.+ auto answer = Get(on.port, "GET /");+ CHECK(answer.rfind("HTTP/1.1 200 OK\r\n", 0) == 0 && answer.find("Content-Type: text/html; charset=utf-8\r\n") != std::string::npos);+ CHECK(Body(answer).find("Download report (.zip)") != std::string::npos);+ CHECK(Body(answer).find("https://") == std::string::npos); // works with no internet+ answer = Get(on.port, "GET /assets/barlow-regular.ttf");+ CHECK(answer.find("Content-Type: font/ttf\r\n") != std::string::npos && Body(answer).size() == 104068);+ CHECK(Get(on.port, "GET /assets/barlow-semibold.ttf").rfind("HTTP/1.1 200", 0) == 0);+ CHECK(Get(on.port, "GET /assets/../logs/steam.log").rfind("HTTP/1.1 404", 0) == 0);+ CHECK(Get(on.port, "GET /assets/index.html").rfind("HTTP/1.1 404", 0) == 0);++ // JSON routes, never cached.+ answer = Get(on.port, "GET /api/status");+ CHECK(answer.find("Cache-Control: no-store\r\n") != std::string::npos);+ CHECK(Body(answer).find("\"version\":\"0.9.0\"") != std::string::npos);+ CHECK(Body(answer).find("\"collected\":\"2026-10-10 03:12 UTC\"") != std::string::npos);+ answer = Get(on.port, "GET /api/logs");+ CHECK(Body(answer).find("{\"title\":\"FAKE78012\",\"app\":1332010,\"name\":\"Stray\",\"last_run\":300,") != std::string::npos);+ CHECK(Body(answer).find("{\"name\":\"steam.log\",") != std::string::npos);++ // One log, redacted with the account Playden is signed in with.+ answer = Get(on.port, "GET /api/logs/steam.log");+ CHECK(answer.find("Content-Type: text/plain; charset=utf-8\r\n") != std::string::npos);+ CHECK(Body(answer) == "signed in as <steam-user> (<steam-id>)\n");+ CHECK(Body(Get(on.port, "GET /api/logs/title-FAKE78012.log")).find("Alice") == std::string::npos);+ CHECK(Get(on.port, "GET /api/logs/..%2Fhomebrew%2FFAKE77031%2Fplayden-version").rfind("HTTP/1.1 404", 0) == 0);+ CHECK(Get(on.port, "POST /api/logs").rfind("HTTP/1.1 405", 0) == 0);++ // The report: a download with its name; HEAD has no body.+ answer = Get(on.port, "HEAD /api/report.zip?title=FAKE78012");+ CHECK(answer.find("Content-Disposition: attachment; filename=\"playden-logs-20261010-031221.zip\"\r\n") != std::string::npos);+ CHECK(Body(answer).empty());+ answer = Get(on.port, "GET /api/report.zip?title=FAKE78012");+ CHECK(answer.find("Content-Type: application/zip\r\n") != std::string::npos);+ CHECK(answer.find("Content-Length:") == std::string::npos);+ const auto zip = Body(answer);+ CHECK(zip.rfind("PK\x03\x04", 0) == 0 && zip.find("logs/title-FAKE78012.log") != std::string::npos);+ CHECK(zip.find("Alice") == std::string::npos && zip.find("Bob") == std::string::npos);+ {+ std::lock_guard<std::mutex> lock(lines_mutex);+ bool logged = false;+ for (const auto& line : lines) logged = logged || line == "GET /api/report.zip?title=FAKE78012 200 " + std::to_string(zip.size()) + " 127.0.0.1";+ CHECK(logged);+ }++ // Quit: POST with the header only; the caller takes the request once.+ CHECK(Get(on.port, "GET /api/quit").rfind("HTTP/1.1 405", 0) == 0);+ CHECK(Get(on.port, "POST /api/quit").rfind("HTTP/1.1 403", 0) == 0 && !service.TakeQuitRequest());+ {+ const int fd = ::socket(AF_INET, SOCK_STREAM, 0);+ sockaddr_in address{};+ address.sin_family = AF_INET;+ address.sin_port = htons(on.port);+ address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);+ CHECK(::connect(fd, reinterpret_cast<sockaddr*>(&address), sizeof address) == 0);+ const std::string request = "POST /api/quit HTTP/1.1\r\nX-Playden-Action: quit\r\nContent-Length: 0\r\n\r\n";+ CHECK(::send(fd, request.data(), request.size(), 0) == static_cast<ssize_t>(request.size()));+ std::string answer;+ char buffer[1024];+ ssize_t count;+ while ((count = ::recv(fd, buffer, sizeof buffer, 0)) > 0) answer.append(buffer, static_cast<std::size_t>(count));+ ::close(fd);+ CHECK(answer.rfind("HTTP/1.1 202 Accepted\r\n", 0) == 0 && Body(answer) == "{\"quitting\":true}");+ }+ CHECK(service.TakeQuitRequest() && !service.TakeQuitRequest());++ // Off closes the port; on again opens it.+ service.SetEnabled(false);+ WaitFor(service, ServiceSnapshot::State::kOff);+ CHECK(Get(on.port, "GET /").empty());+ service.SetEnabled(true);+ const auto again = WaitFor(service, ServiceSnapshot::State::kOn);+ CHECK(Get(again.port, "GET /api/status").rfind("HTTP/1.1 200", 0) == 0);++ // A port another program holds: the service says why, and tries again only when turned off and on.+ {+ Server holder;+ std::string error;+ ServerOptions hold;+ hold.first_port = hold.last_port = 0;+ hold.loopback_only = true;+ CHECK(holder.Start(hold, [](const Request&, Response& response) { response.Send(200, "text/plain", "x"); }, &error));+ ServiceConfig busy = config;+ busy.server.first_port = busy.server.last_port = holder.port();+ Service refused(busy);+ refused.SetEnabled(true);+ const auto failed = WaitFor(refused, ServiceSnapshot::State::kFailed);+ CHECK(failed.error.find("port " + std::to_string(holder.port())) == 0 && failed.url.empty());+ holder.Stop();+ refused.SetEnabled(false);+ WaitFor(refused, ServiceSnapshot::State::kOff);+ refused.SetEnabled(true);+ WaitFor(refused, ServiceSnapshot::State::kOn);+ refused.Shutdown();+ }++ service.Shutdown();+ service.Shutdown();+ CHECK(Get(again.port, "GET /").empty());+ fs::remove_all(root);+ std::puts("web_service: ok");+}diff --git a/tests/web_zip_test.cpp b/tests/web_zip_test.cppnew file mode 100644index 0000000..4946ea4--- /dev/null+++ b/tests/web_zip_test.cpp@@ -0,0 +1,89 @@+// SPDX-License-Identifier: GPL-3.0-or-later+#include "web/zip.h"++#include <cstdint>+#include <cstdio>+#include <cstdlib>+#include <filesystem>+#include <string>+#include <unistd.h>++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)++namespace {+std::uint32_t Read32(const std::string& bytes, std::size_t at) {+ return static_cast<std::uint32_t>(static_cast<unsigned char>(bytes[at])) |+ static_cast<std::uint32_t>(static_cast<unsigned char>(bytes[at + 1])) << 8 |+ static_cast<std::uint32_t>(static_cast<unsigned char>(bytes[at + 2])) << 16 |+ static_cast<std::uint32_t>(static_cast<unsigned char>(bytes[at + 3])) << 24;+}+std::uint16_t Read16(const std::string& bytes, std::size_t at) {+ return static_cast<std::uint16_t>(static_cast<unsigned char>(bytes[at]) | static_cast<unsigned char>(bytes[at + 1]) << 8);+}+} // namespace++int main() {+ // Known CRC-32 values.+ CHECK(Crc32(0, "", 0) == 0);+ CHECK(Crc32(0, "123456789", 9) == 0xcbf43926u);+ CHECK(Crc32(Crc32(0, "1234", 4), "56789", 5) == 0xcbf43926u);++ std::string archive;+ std::size_t writes = 0;+ StoredZip zip([&](const char* data, std::size_t size) { archive.append(data, size); ++writes; return true; },+ 1'791'601'941); // 2026-10-10 03:12:21 UTC+ const std::string summary = "| Field | Value |\n| --- | --- |\n| collected | 2026-10-28 15:00 UTC |\n";+ std::string big(300 * 1024, 'x');+ for (std::size_t i = 0; i < big.size(); i += 97) big[i] = static_cast<char>('a' + i % 26);+ CHECK(zip.Add("summary.md", summary));+ CHECK(zip.Add("logs/runtime.log", big));+ CHECK(zip.Add("logs/empty.log", ""));+ CHECK(zip.Finish());+ CHECK(!zip.Add("late.txt", "x") && !zip.Finish());+ CHECK(zip.bytes() == archive.size());++ // Local header of the first entry: stored, UTF-8 names, the CRC and sizes in place.+ CHECK(Read32(archive, 0) == 0x04034b50u && Read16(archive, 8) == 0 && Read16(archive, 6) == (1u << 11));+ CHECK(Read32(archive, 14) == Crc32(0, summary.data(), summary.size()));+ CHECK(Read32(archive, 18) == summary.size() && Read32(archive, 22) == summary.size());+ CHECK(archive.compare(30, 10, "summary.md") == 0 && archive.compare(40, summary.size(), summary) == 0);+ // DOS date and time: 2026-10-10, 03:12:20 (two-second steps).+ CHECK(Read16(archive, 12) == ((46u << 9) | (10u << 5) | 10u));+ CHECK(Read16(archive, 10) == ((3u << 11) | (12u << 5) | 10u));+ // End of central directory: three entries, the directory right after the data.+ const std::size_t end = archive.size() - 22;+ CHECK(Read32(archive, end) == 0x06054b50u && Read16(archive, end + 10) == 3);+ const std::uint32_t directory_size = Read32(archive, end + 12), directory_offset = Read32(archive, end + 16);+ CHECK(directory_offset + directory_size == end);+ CHECK(Read32(archive, directory_offset) == 0x02014b50u);++ // The archive opens in a real unzip and every CRC matches.+ const std::string path =+ (std::filesystem::temp_directory_path() / ("playden-web-zip-" + std::to_string(::getpid()) + ".zip")).string();+ if (FILE* file = std::fopen(path.c_str(), "wb")) {+ CHECK(std::fwrite(archive.data(), 1, archive.size(), file) == archive.size());+ std::fclose(file);+ }+ const std::string unzip = "/usr/bin/unzip";+ if (::access(unzip.c_str(), X_OK) == 0) CHECK(std::system((unzip + " -tq '" + path + "' >/dev/null").c_str()) == 0);+ const std::string python = "python3 -I -c \"import sys, zipfile; z = zipfile.ZipFile(sys.argv[1]); "+ "sys.exit(0 if z.testzip() is None and z.namelist() == ['summary.md', 'logs/runtime.log', "+ "'logs/empty.log'] and len(z.read('logs/runtime.log')) == 307200 else 1)\" '" + path + "'";+ CHECK(std::system(python.c_str()) == 0);+ std::remove(path.c_str());++ // A client gone: nothing more is written.+ std::size_t attempts = 0;+ StoredZip cut([&](const char*, std::size_t) { ++attempts; return false; }, 0);+ CHECK(!cut.Add("a", "b") && !cut.Add("c", "d") && !cut.Finish() && attempts == 1);+ CHECK(!StoredZip([](const char*, std::size_t) { return true; }, 0).Add("", "x"));+ std::puts("web_zip: ok");+}diff --git a/tools/collect_logs.py b/tools/collect_logs.pyindex c2a64a1..17befb1 100644--- a/tools/collect_logs.py+++ b/tools/collect_logs.py@@ -10,6 +10,11 @@ replaced in every file unless --no-redact is given.It lists the games that have a log, the most recently run first, and asks which one tocollect (the newest when there is no terminal to ask on). --app, --title or --all-titlespick without asking; --list only prints the games.++With --http it asks Playden's web access (Settings > Web access, port 7031) instead of FTP:+Playden builds the same zip itself, always redacted. Playden must be open on the PS5.++ python3 tools/collect_logs.py --host 192.168.1.50 --http"""import argparsefrom datetime import datetime, timezone@@ -20,6 +25,9 @@ import osfrom pathlib import Pathimport reimport sys+import urllib.error+import urllib.parse+import urllib.requestimport zipfileLOGS = "/data/playden/logs"@@ -198,11 +206,79 @@ def active_kit(ftp):return {"kit runtime": None, **others}+WEB_PORT = 7031+++def http_get(base, path, timeout=30):+ with urllib.request.urlopen(base + path, timeout=timeout) as response:+ return response.read()+++def http_games(index):+ """The rows game_table prints, from the web page's /api/logs."""+ return [{"title": game["title"], "app": game.get("app"), "name": game.get("name"),+ "last_run": game.get("last_run") or 0} for game in index.get("games", [])]+++def collect_over_http(args):+ """The report from Playden's web access: the same zip, made and redacted by Playden."""+ base = f"http://{args.host}:{args.port or WEB_PORT}"+ try:+ index = json.loads(http_get(base, "/api/logs"))+ except (OSError, ValueError) as error:+ sys.exit(f"could not reach Playden at {base}: {error}\n"+ "Is Playden open on the PS5, with Settings > Web access on?")+ rows = http_games(index)+ if args.list or not (args.all_titles or args.app is not None or args.title):+ if not rows:+ print("No game logs yet. Start Playden once after running a game: it copies the game's log when it "+ "starts.", file=sys.stderr)+ else:+ print(game_table(rows))+ if args.list:+ return+ if rows:+ args.title = ask(rows)["title"]+ if args.all_titles:+ title = "all"+ else:+ title = None+ if args.title:+ title = args.title if any(row["title"] == args.title for row in rows) else None+ elif args.app is not None:+ title = next((row["title"] for row in rows if row["app"] == args.app), None)+ elif rows:+ title = rows[0]["title"]+ if title is None and (args.app is not None or args.title):+ asked = args.title or f"app {args.app}"+ print(f"warning: no game log found for {asked}; collecting Playden's logs only.\n"+ "Start Playden once after the failed run: it copies the game's log when it starts.",+ file=sys.stderr)+ title = "none" # names no game: Playden's logs only+ query = "?" + urllib.parse.urlencode({"title": title}) if title else ""+ try:+ report = http_get(base, "/api/report.zip" + query, timeout=120)+ except OSError as error:+ sys.exit(f"could not download the report from {base}: {error}")+ out = args.out or Path(f"playden-logs-{datetime.now().strftime('%Y%m%d-%H%M%S')}.zip")+ out.write_bytes(report)+ try:+ with zipfile.ZipFile(out) as archive:+ names = [name for name in archive.namelist() if name.startswith("logs/")]+ print(archive.read("summary.md").decode("utf-8", "replace"))+ except (zipfile.BadZipFile, KeyError) as error:+ sys.exit(f"Playden sent a report that isn't a valid zip ({error}); it is in {out}")+ print(f"Wrote {out} ({len(names)} logs). Attach it to your test report.")+ print("Logs can still name your games and file paths. Look through them before you share.")++def main():parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)parser.add_argument("--host", default=os.environ.get("PLAYDEN_PS5_HOST"),help="the PS5's IP address (or set PLAYDEN_PS5_HOST)")- parser.add_argument("--port", type=int, default=2120, help="FTP port (default 2120, zftpd)")+ parser.add_argument("--port", type=int, help="FTP port (default 2120, zftpd), or with --http the web port (7031)")+ parser.add_argument("--http", action="store_true",+ help="ask Playden's web access instead of FTP (Playden must be open; always redacted)")which = parser.add_mutually_exclusive_group()which.add_argument("--app", type=int, help="Steam app ID of the game (from its store page URL)")which.add_argument("--title", help="PS5 title ID of the game, for example FAKE78003")@@ -213,6 +289,12 @@ def main():args = parser.parse_args()if not args.host:parser.error("give the PS5's address with --host or PLAYDEN_PS5_HOST")+ if args.http:+ if args.no_redact:+ parser.error("--http reports are always redacted; use FTP (without --http) for --no-redact")+ collect_over_http(args)+ return+ args.port = args.port or 2120ftp = ftplib.FTP()try: