Play your Steam library's Windows games on a jailbroken PS5.
C++
List games shared by a Steam family member
Leonardo Lobatoc0a945e98920
diff --git a/cmake/SteamBackend.cmake b/cmake/SteamBackend.cmakeindex 3e846e3..2407a31 100644--- a/cmake/SteamBackend.cmake+++ b/cmake/SteamBackend.cmake@@ -148,6 +148,7 @@ endif()add_library(playden_steam_cm STATIC"${CMAKE_SOURCE_DIR}/src/steam/backend/cm_client.cpp""${CMAKE_SOURCE_DIR}/src/steam/backend/entitled_library.cpp"+ "${CMAKE_SOURCE_DIR}/src/steam/backend/family_groups.cpp""${CMAKE_SOURCE_DIR}/src/steam/backend/cm_app_details.cpp""${CMAKE_SOURCE_DIR}/src/steam/backend/cdn_client.cpp""${CMAKE_SOURCE_DIR}/src/steam/backend/download_server_source.cpp"@@ -303,6 +304,9 @@ function(playden_register_steam_backend_tests)add_executable(entitled_library_test "${CMAKE_SOURCE_DIR}/tests/entitled_library_test.cpp")target_link_libraries(entitled_library_test PRIVATE playden_steam_cm)add_test(NAME entitled_library COMMAND entitled_library_test)+ add_executable(family_groups_test "${CMAKE_SOURCE_DIR}/tests/family_groups_test.cpp")+ target_link_libraries(family_groups_test PRIVATE playden_steam_cm)+ add_test(NAME family_groups COMMAND family_groups_test)add_executable(library_client_test "${CMAKE_SOURCE_DIR}/tests/library_client_test.cpp")target_link_libraries(library_client_test PRIVATE playden_steam_library)diff --git a/src/homebrew/browse.cpp b/src/homebrew/browse.cppindex 83b021f..5495ff2 100644--- a/src/homebrew/browse.cpp+++ b/src/homebrew/browse.cpp@@ -140,6 +140,8 @@ std::vector<const Game*> filtered_games(const State& state)// Demos show unless the player hides them, so the stored filter is the hiding one.if (state.library.filters.contains("hide-demos") && game.demo)continue;+ if (state.library.filters.contains("hide-family") && game.family_shared)+ continue;if (state.library.filters.contains("genre-adventure") &&std::find(game.genres.begin(), game.genres.end(), "Adventure") == game.genres.end())continue;diff --git a/src/homebrew/host.cpp b/src/homebrew/host.cppindex 62cf8c5..b86c534 100644--- a/src/homebrew/host.cpp+++ b/src/homebrew/host.cpp@@ -537,6 +537,10 @@ int main(int argc, char** argv) {cm_client->SetSharedSession(steam_cm);library_backend = std::make_unique<playden::steam::EntitledLibraryBackend>(*owned_library, *cm_client);library_backend->SetLicensedDepots(&licensed_depots);+ // Family sharing diagnostics.+ library_backend->SetFamilyDiagnostics(PLAYDEN_HOMEBREW_CA_BUNDLE, [log_directory](const std::string& line) {+ playden::app::AppendLogLine(log_directory, "steam-cm.log", line);+ });library_cache = std::make_unique<playden::LibraryCache>(*library_storage);library_service = std::make_unique<playden::LibraryService>(*library_backend,*library_sessions,library_cache.get());preferences=std::make_unique<playden::PreferencesStore>(*library_storage);diff --git a/src/homebrew/ps5.cpp b/src/homebrew/ps5.cppindex 781cfa7..9fec7db 100644--- a/src/homebrew/ps5.cpp+++ b/src/homebrew/ps5.cpp@@ -339,6 +339,10 @@ int main() {playden::steam::EntitledLibraryBackend library_backend(owned_library, cm_client);playden::steam::LicensedDepots licensed_depots;library_backend.SetLicensedDepots(&licensed_depots);+ // Family sharing diagnostics, with the CM license lines.+ library_backend.SetFamilyDiagnostics(paths.trust_store, [](const std::string& line) {+ playden::app::AppendLogLine(log_root, "steam-cm.log", line);+ });playden::LibraryCache library_cache(library_storage);playden::LibraryService library_service(library_backend,library_sessions,&library_cache);playden::PreferencesStore preferences(library_storage);diff --git a/src/homebrew/simulation.cpp b/src/homebrew/simulation.cppindex 9d9e9f7..c73bbd8 100644--- a/src/homebrew/simulation.cpp+++ b/src/homebrew/simulation.cpp@@ -497,7 +497,7 @@ std::string action_label(const std::string& key) {{"sort-name", "Name"}, {"sort-recent-played", "Recently played"}, {"sort-recent-added", "Recently added"},{"sort-playtime", "Playtime"}, {"sort-install-size", "Install size"}, {"filter-installed", "Installed"},{"filter-genre-adventure", "Adventure"}, {"filter-controller-full", "Full controller support"},- {"filter-compat-playable", "Playable"}, {"filter-hide-demos", "Demos"}, {"filters-reset", "Reset filters"}, {"refresh-library", "Refresh library"}, {"advance-clock", "Advance fixture clock"},+ {"filter-compat-playable", "Playable"}, {"filter-hide-demos", "Demos"}, {"filter-hide-family", "Family sharing"}, {"filters-reset", "Reset filters"}, {"refresh-library", "Refresh library"}, {"advance-clock", "Advance fixture clock"},{"inject-download-failed", "Inject download failure"}, {"inject-verification-failed", "Inject verification failure"},{"inject-uninstall-failed", "Inject uninstall failure"},{"inject-storage-disconnect", "Disconnect storage"}, {"inject-controller-disconnect", "Disconnect controller"},@@ -2552,6 +2552,7 @@ bool Simulation::UpdateLibrary(LibraryUpdate update) {if (summary.added_at_unix_seconds)game.added_at = static_cast<std::int64_t>(*summary.added_at_unix_seconds);game.demo = summary.demo;+ game.family_shared = summary.family_shared;if (const auto facts = store_facts_.find(game.id); facts != store_facts_.end()) {if (!facts->second.description.empty()) game.description = facts->second.description;game.genres = facts->second.genres;@@ -3177,6 +3178,7 @@ void Simulation::load_fixtures() {if (const auto played = optional_uint(item.get("last_played"))) game.last_played = static_cast<std::int64_t>(*played);game.playtime_minutes = optional_uint(item.get("playtime_minutes"));game.demo = bool_value(item.get("demo"));+ game.family_shared = bool_value(item.get("family_shared"));state_.games.push_back(std::move(game));}}@@ -3794,6 +3796,24 @@ bool Simulation::scenario(const std::string& name) {}if (!find_game(state_, demo.id)) state_.games.push_back(std::move(demo));reconcile_library_selection(state_);+ } else if (name == "family-sharing") {+ // Games a Steam family member shares. The external drive is disconnected and a download is+ // interrupted, so status badges have to fit beside "Family".+ state_.navigation.route = Route::Library;+ if (auto* volume = find_volume(state_, "external")) volume->available = false;+ // The demos fixture's demo, when loaded first, shows both corner badges.+ std::vector<GameId> shared{GameId::Steam(900014), GameId::Steam(900011), GameId::Steam(900025)};+ if (auto* job = find_job(state_, "job-1")) {+ job->state = JobState::Interrupted;+ job->failure = "Storage disconnected";+ shared.push_back(job->game_id);+ }+ const auto external = std::find_if(state_.installations.begin(), state_.installations.end(),+ [](const Installation& item) { return item.volume_id == "external"; });+ if (external != state_.installations.end()) shared.push_back(external->game_id);+ for (const auto id : shared)+ if (auto* game = const_cast<Game*>(find_game(state_, id))) game->family_shared = true;+ reconcile_library_selection(state_);} else if (name == "stress") {const auto source = read_file(fixture_directory_.parent_path() / "library.json");const auto root = json::parse(source);@@ -4161,10 +4181,10 @@ void Simulation::rebuild_view() {}continue;}- // Demos is on unless the player hid them.- if (action_key == "filter-hide-demos") {+ // Demos and Family sharing are on unless the player hid them.+ if (action_key == "filter-hide-demos" || action_key == "filter-hide-family") {item.kind = RowKind::Toggle;- item.selected = !state_.library.filters.contains("hide-demos");+ item.selected = !state_.library.filters.contains(action_key.substr(7));item.value = item.selected ? "On" : "Off";}// The menu's Favorite says what it will do for this game.@@ -8369,8 +8389,13 @@ bool Simulation::action(const std::string& logical_action) {: std::vector<std::string>{"sort-name", "sort-recent-played", "sort-recent-added", "sort-playtime", "sort-install-size","filter-installed", "filter-genre-adventure", "filter-controller-full", "filter-compat-playable","filters-reset", "refresh-library", "cancel"};+ // Family sharing likewise, for games a Steam family member shares.+ const bool family = state_.library.filters.contains("hide-family") ||+ std::any_of(state_.games.begin(), state_.games.end(), [](const Game& game) { return game.family_shared; });if (demos)actions.insert(std::find(actions.begin(), actions.end(), "filters-reset"), "filter-hide-demos");+ if (family)+ actions.insert(std::find(actions.begin(), actions.end(), "filters-reset"), "filter-hide-family");open_modal({"filters", "Sort and filters", state_.navigation.focus_key, std::move(actions), 0, false});}}diff --git a/src/homebrew/simulation.hpp b/src/homebrew/simulation.hppindex fac0316..d91aeb9 100644--- a/src/homebrew/simulation.hpp+++ b/src/homebrew/simulation.hpp@@ -451,6 +451,7 @@ struct Game {std::optional<std::uint64_t> playtime_minutes;std::optional<bool> windows_installable; // from Steam app info; absent until fetchedbool demo = false; // a Steam demo; Sort and filters › Demos hides it+ bool family_shared = false; // shared by a Steam family member; the tile says "Family"bool art_pending = false;bool art_failed = false;};diff --git a/src/homebrew/view.cpp b/src/homebrew/view.cppindex 1f6e47b..8bbc35e 100644--- a/src/homebrew/view.cpp+++ b/src/homebrew/view.cpp@@ -1682,7 +1682,7 @@ class Render::Implreturn game.download_bytes ? "Not installed · " + short_size(*game.download_bytes) : "Not installed";}- // reserve: room kept free at the right for the demo badge.+ // reserve: room kept free at the right for the corner badges.void tile_badge(const gfx::Rect &rect, std::string_view text, gfx::Color dot, float reserve = 0.0F){constexpr float size = 16.0F;@@ -1693,18 +1693,31 @@ class Render::Implrect.y + 32.0F, size, kText);}- // A Steam demo says so in the tile's top-right corner; returns the width it takes, gap included.- float demo_badge(const gfx::Rect &rect)+ // A word in the tile's top-right corner, `right` px in from the corner's usual spot; returns the+ // width it takes, gap included.+ float corner_badge(const gfx::Rect &rect, std::string_view text, float right = 0.0F){constexpr float size = 16.0F;- const float width = fonts_.semibold.measure("Demo", size) + 20.0F;- scene_.rounded_rect({rect.x + rect.w - 10.0F - width, rect.y + 10.0F, width, 32.0F}, 6.0F,+ const float width = fonts_.semibold.measure(text, size) + 20.0F;+ scene_.rounded_rect({rect.x + rect.w - 10.0F - right - width, rect.y + 10.0F, width, 32.0F}, 6.0F,kBackground.with_alpha(0.85F));- ui::text(scene_, fonts_.semibold, "Demo", rect.x + rect.w - 20.0F, rect.y + 32.0F, size, kAccent,+ ui::text(scene_, fonts_.semibold, text, rect.x + rect.w - 20.0F - right, rect.y + 32.0F, size, kAccent,gfx::Align::right);return width + 8.0F;}+ // A Steam demo says "Demo" and a game a Steam family member shares says "Family", right to left;+ // returns the width they take. Beside a status badge a tile has room for one: Demo.+ float corner_badges(const Game &game, const gfx::Rect &rect, bool status_badge)+ {+ float taken = 0.0F;+ if (game.demo)+ taken += corner_badge(rect, "Demo", taken);+ if (game.family_shared && !(game.demo && status_badge))+ taken += corner_badge(rect, "Family", taken);+ return taken;+ }+void download_mark(float cx, float cy, float opacity){scene_.circle(cx, cy, 15.0F, kBackground.with_alpha(0.8F * opacity));@@ -1784,12 +1797,13 @@ class Render::Implscene_.pop_transform();return;}- const float demo = game.demo ? demo_badge(rect) : 0.0F;- if (status.job != nullptr && !downloading)+ const bool job_badge = status.job != nullptr && !downloading;+ const float corner = corner_badges(game, rect, job_badge || status.disconnected);+ if (job_badge)tile_badge(rect, JobStateText(*status.job),- status.job->state == JobState::Failed ? kAmber : kSecondary, demo);+ status.job->state == JobState::Failed ? kAmber : kSecondary, corner);else if (status.disconnected)- tile_badge(rect, "Drive disconnected", kAmber, demo);+ tile_badge(rect, "Drive disconnected", kAmber, corner);if (show_download_mark)download_mark(rect.x + rect.w - 25.0F, rect.y + rect.h - 25.0F, 1.0F);else if (status.installed && status.installation != nullptr && status.installation->installed_bytes > 0 && amount < 1.0F && title_overlay)@@ -3100,8 +3114,11 @@ class Render::Implconst float facts_top = setup == view.rows.end() ? 754.0F : setup_detail.empty() ? 694.0F : 662.0F;detail_cell("Playtime", playtime, left, facts_top, 240.0F);detail_cell("Size", size, right, facts_top, 240.0F);- detail_cell("Store", game->id.store == Store::kLocal ? std::string("Imported") : game->source.empty() ? "Steam" : game->source,- left, facts_top + 76.0F, 240.0F);+ // A game a Steam family member shares comes from Steam Families, not the account's own library.+ const std::string store = game->id.store == Store::kLocal ? std::string("Imported") :+ game->family_shared ? std::string("Steam Family") :+ game->source.empty() ? std::string("Steam") : game->source;+ detail_cell("Store", store, left, facts_top + 76.0F, 240.0F);detail_cell("Location", location, right, facts_top + 76.0F, 240.0F);detail_cell("Compatibility", compat, left, facts_top + 152.0F, 240.0F);if (game->last_played && setup == view.rows.end())diff --git a/src/library/cache.cpp b/src/library/cache.cppindex 842e16d..64faa8f 100644--- a/src/library/cache.cpp+++ b/src/library/cache.cpp@@ -8,7 +8,7 @@ namespace {constexpr std::size_t kMaximumCacheBytes = 16 * 1024 * 1024;constexpr std::size_t kMaximumGames = 100000;// Schema 5 names each game by store and value; 4 and older hold Steam app IDs only. 6 marks demos.-constexpr unsigned kLatestSchema = 6;+constexpr unsigned kLatestSchema = 7;constexpr std::size_t kMaximumGameValue = 48;const Bytes kMagic = {'P','D','L','I','B',0,1,0};bool ValidAccount(const std::string& account) {@@ -70,11 +70,12 @@ Result<void> LibraryCache::Save(const std::string& account,const LibrarySnapshotif(snapshot.schema_version==1 && (game.playtime_minutes || game.last_played_unix_seconds))return Invalid("Cache schema cannot preserve game history.");if(snapshot.schema_version<4 && game.added_at_unix_seconds)return Invalid("Cache schema cannot preserve acquisition dates.");if(snapshot.schema_version<6 && game.demo)return Invalid("Cache schema cannot preserve demos.");+ if(snapshot.schema_version<7 && game.family_shared)return Invalid("Cache schema cannot preserve family sharing.");if(snapshot.schema_version>=5){Number(encoded,static_cast<std::uint8_t>(game.id.store),1);String(encoded,game.id.value);}else Number(encoded,*game.id.steam_app(),4);String(encoded,game.title);String(encoded,game.artwork_source);String(encoded,game.description);String(encoded,game.developer);if(snapshot.schema_version>=2){- Number(encoded,(game.playtime_minutes?1u:0u)|(game.last_played_unix_seconds?2u:0u)|(game.added_at_unix_seconds?4u:0u)|(game.demo?8u:0u),1);+ Number(encoded,(game.playtime_minutes?1u:0u)|(game.last_played_unix_seconds?2u:0u)|(game.added_at_unix_seconds?4u:0u)|(game.demo?8u:0u)|(game.family_shared?16u:0u),1);if(game.playtime_minutes)Number(encoded,*game.playtime_minutes,8);if(game.last_played_unix_seconds)Number(encoded,*game.last_played_unix_seconds,8);if(game.added_at_unix_seconds)Number(encoded,*game.added_at_unix_seconds,8);@@ -116,11 +117,12 @@ Result<LibrarySnapshot> LibraryCache::Load(const std::string& account) const {game.artwork_source=reader.String(8192);game.description=reader.String(65536);game.developer=reader.String(4096);if(snapshot.schema_version>=2){const auto flags=reader.Number(1);- if(flags>(snapshot.schema_version>=6?15u:snapshot.schema_version>=4?7u:3u))return invalid();+ if(flags>(snapshot.schema_version>=7?31u:snapshot.schema_version>=6?15u:snapshot.schema_version>=4?7u:3u))return invalid();if(flags&1)game.playtime_minutes=reader.Number(8);if(flags&2)game.last_played_unix_seconds=reader.Number(8);if(flags&4)game.added_at_unix_seconds=reader.Number(8);game.demo=(flags&8)!=0;+ game.family_shared=(flags&16)!=0;}if(!reader.okay||!ValidGame(game,snapshot.schema_version)||!seen.insert(game.id).second)return invalid();snapshot.games.push_back(std::move(game));diff --git a/src/library/model.h b/src/library/model.hindex 1136ac0..13b7c76 100644--- a/src/library/model.h+++ b/src/library/model.h@@ -18,5 +18,7 @@ struct GameSummary {std::optional<std::uint64_t> added_at_unix_seconds;// A Steam demo (PICS type "demo"), which the Library can hide.bool demo = false;+ // Shared by another member of the account's Steam family, not owned; the Library marks it.+ bool family_shared = false;};} // namespace playdendiff --git a/src/library/organization.cpp b/src/library/organization.cppindex 50c0f64..a74eaaa 100644--- a/src/library/organization.cpp+++ b/src/library/organization.cpp@@ -112,9 +112,9 @@ bool ValidSort(const std::string& value) {value == "playtime";}-// Version 1 knows only Playable; version 2 also keeps demos hidden (they show by default).+// Version 1 knows only Playable; version 2 also keeps demos and family-shared games hidden (they show by default).bool ValidFilter(const std::string& value, std::uint16_t version) {- return value == "compat-playable" || (version != kVersion1 && value == "hide-demos");+ return value == "compat-playable" || (version != kVersion1 && (value == "hide-demos" || value == "hide-family"));}// Version 1 stores Steam app IDs only; version 2 any valid game.@@ -175,7 +175,7 @@ bool Validate(const OrganizationSnapshot& snapshot, std::uint16_t version) {return false;}}- if (snapshot.filters.size() > (version == kVersion1 ? 1u : 2u)) return false;+ if (snapshot.filters.size() > (version == kVersion1 ? 1u : 3u)) return false;for (const auto& filter : snapshot.filters) {if (!ValidText(filter, kMaximumFilterBytes, false) || !ValidFilter(filter, version)) return false;}@@ -504,7 +504,7 @@ Loaded DecodeV2(const Bytes& bytes) {if (!reader.String(snapshot.query, kMaximumQueryBytes) ||!reader.String(snapshot.scope, kMaximumScopeBytes) ||!reader.String(snapshot.sort, kMaximumSortBytes) ||- !reader.U32(filter_count) || filter_count > 2) {+ !reader.U32(filter_count) || filter_count > 3) {return InvalidLoad("view state");}for (std::uint32_t index = 0; index < filter_count; ++index) {diff --git a/src/library/service.cpp b/src/library/service.cppindex a849ea7..43451bb 100644--- a/src/library/service.cpp+++ b/src/library/service.cpp@@ -294,9 +294,13 @@ void LibraryService::ExecuteRefresh(const Job& job) {if (previous != previous_added_at.end()) game.added_at_unix_seconds = previous->second;}snapshot.metadata_partial = result.metadata_partial;- // Only a library with demos needs schema 6; one without stays readable by older versions.+ // Only a library with demos needs schema 6, and one with family-shared games schema 7; one without stays+ // readable by older versions.if (std::any_of(snapshot.games.begin(), snapshot.games.end(), [](const GameSummary& game) { return game.demo; }))snapshot.schema_version = 6;+ if (std::any_of(snapshot.games.begin(), snapshot.games.end(),+ [](const GameSummary& game) { return game.family_shared; }))+ snapshot.schema_version = 7;if (cache_) {const auto saved = cache_->Save(job.account, snapshot);if (!Current(job)) return;diff --git a/src/steam/backend/cm_client.cpp b/src/steam/backend/cm_client.cppindex ed2ffbe..77c24dd 100644--- a/src/steam/backend/cm_client.cpp+++ b/src/steam/backend/cm_client.cpp@@ -12,6 +12,7 @@#include <algorithm>#include <chrono>#include <condition_variable>+#include <cstdio>#include <functional>#include <map>#include <mutex>@@ -30,9 +31,16 @@ constexpr std::size_t kMaxJobBytes = 16 * 1024 * 1024;constexpr std::size_t kDirectoryBodyLimit = 256 * 1024;constexpr const char* kDeviceSeedFile = "steam-device-id";// ELicenseFlags that make a license unavailable: renewal failed, pending, expired, cancelled,-// fraud, not activated, pending refund, borrowed, cancelled by partner.+// fraud, not activated, pending refund, cancelled by partner. Borrowed (0x4000) is not among them: a+// license another Steam family member shares is usable here.constexpr std::uint32_t kUnavailableLicense =- 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x400 | 0x800 | 0x2000 | 0x4000 | 0x40000;+ 0x02 | 0x04 | 0x08 | 0x10 | 0x20 | 0x400 | 0x800 | 0x2000 | 0x40000;+constexpr std::uint32_t kRenewLicense = 0x1;+constexpr std::uint32_t kBorrowedLicense = 0x4000;+// At most this many per-license family lines per dump, so a huge account cannot rotate the log away.+constexpr std::size_t kMaxFamilyLicenseLines = 300;+// At most this many package IDs on one family PICS line.+constexpr std::size_t kMaxFamilyIds = 100;std::string Hex(const unsigned char* data, std::size_t size) {static constexpr char kDigits[] = "0123456789abcdef";@@ -63,10 +71,132 @@ bool ValidEndpoint(const std::string& endpoint) {// Package 0 counts: older accounts hold Valve's games there (Team Fortress 2's content, issue #58), and the// reference reads every package in the license list.-bool OwnedActiveLicense(const cm::License& license, std::uint32_t account_id) {- return (license.flags & kUnavailableLicense) == 0 &&- (license.owner_id == 0 || license.owner_id == account_id) &&- (license.minute_limit <= 0 || license.minutes_used < license.minute_limit);+bool OwnLicense(const cm::License& license, std::uint32_t account_id) {+ return (license.owner_id == 0 || license.owner_id == account_id) && (license.flags & kBorrowedLicense) == 0;+}++// Why an unusable license is left out, or nullptr when it is usable: own or borrowed from a family member.+const char* UnusableLicense(const cm::License& license) {+ if (license.flags & kUnavailableLicense) return "flags";+ if (license.minute_limit > 0 && license.minutes_used >= license.minute_limit) return "minutes";+ return nullptr;+}++std::string HexFlags(std::uint32_t flags) {+ char text[16];+ std::snprintf(text, sizeof(text), "0x%x", flags);+ return text;+}++// Comma-separated IDs, at most kMaxFamilyIds of them, then how many more there were.+std::string IdList(const std::vector<std::uint32_t>& ids) {+ std::string text;+ for (std::size_t index = 0; index < ids.size() && index < kMaxFamilyIds; ++index)+ text += (index ? "," : "") + std::to_string(ids[index]);+ if (ids.size() > kMaxFamilyIds) text += ",+" + std::to_string(ids.size() - kMaxFamilyIds);+ return text.empty() ? "none" : text;+}++// FNV-1a over what the per-license family lines show, to dump them only when the list changed.+std::uint64_t LicenseListHash(const std::vector<cm::License>& licenses, std::uint32_t account_id) {+ std::uint64_t hash = 0xcbf29ce484222325ull;+ auto mix = [&hash](std::uint64_t value) {+ for (int shift = 0; shift < 64; shift += 8) {+ hash ^= (value >> shift) & 0xff;+ hash *= 0x100000001b3ull;+ }+ };+ mix(account_id);+ for (const auto& license : licenses) {+ mix(license.package_id);+ mix(license.owner_id);+ mix(license.flags);+ mix(license.license_type);+ mix(license.time_created);+ mix(static_cast<std::uint32_t>(license.minute_limit) ^+ (static_cast<std::uint64_t>(static_cast<std::uint32_t>(license.minutes_used)) << 32));+ mix(license.access_token != 0);+ }+ return hash;+}++// The license list whose per-license family lines were last written, process-wide: a library refresh+// with the same list writes only the summary.+std::mutex g_family_mutex;+std::uint64_t g_family_dumped = 0;++bool ShouldDumpLicenses(std::uint64_t hash) {+ std::lock_guard<std::mutex> lock(g_family_mutex);+ if (hash == g_family_dumped) return false;+ g_family_dumped = hash;+ return true;+}++// The family summary of one license-list load and, when the list changed, a line per license that isn't+// plainly the account's own.+void LogLicenses(const std::function<void(const std::string&)>& log, const std::vector<cm::License>& licenses,+ const std::map<std::uint32_t, const cm::License*>& chosen, std::uint32_t account_id) {+ std::size_t own = 0, borrowed = 0, dropped = 0;+ std::map<std::uint32_t, std::size_t> owners; // other account IDs+ std::size_t bits[32] = {};+ for (const auto& license : licenses) {+ if (UnusableLicense(license)) ++dropped;+ else if (OwnLicense(license, account_id)) ++own;+ else ++borrowed;+ if (license.owner_id != 0 && license.owner_id != account_id) ++owners[license.owner_id];+ for (int bit = 0; bit < 32; ++bit) bits[bit] += (license.flags >> bit) & 1;+ }+ const auto hash = LicenseListHash(licenses, account_id);+ const bool dump = ShouldDumpLicenses(hash);+ std::string owner_text, flag_text;+ std::size_t listed = 0;+ for (const auto& [owner, count] : owners) {+ if (listed++ == 16) {+ owner_text += ",+" + std::to_string(owners.size() - 16);+ break;+ }+ owner_text += (owner_text.empty() ? "" : ",") + std::to_string(owner) + ":" + std::to_string(count);+ }+ for (int bit = 0; bit < 32; ++bit)+ if (bits[bit])+ flag_text += (flag_text.empty() ? "" : ",") + HexFlags(1u << bit) + ":" + std::to_string(bits[bit]);+ log("family step=licenses total=" + std::to_string(licenses.size()) + " own=" + std::to_string(own) ++ " borrowed=" + std::to_string(borrowed) + " dropped=" + std::to_string(dropped) ++ " owners=" + (owner_text.empty() ? "none" : owner_text) + " flags=" + (flag_text.empty() ? "none" : flag_text) ++ " changed=" + (dump ? "y" : "n"));+ if (!dump) return;+ // Another owner, any flag but Renew, or left out. Licenses from another account or marked Borrowed come+ // first, so the cap never hides them behind an old account's flagged licenses.+ std::size_t lines = 0, left_out = 0;+ auto detail = [&](const cm::License& license) {+ if (lines == kMaxFamilyLicenseLines) {+ ++left_out;+ return;+ }+ ++lines;+ std::string verdict;+ if (const auto* reason = UnusableLicense(license)) {+ verdict = std::string("result=dropped reason=") + reason;+ if (license.flags & kUnavailableLicense) verdict += ":" + HexFlags(license.flags & kUnavailableLicense);+ } else if (chosen.at(license.package_id) != &license) {+ verdict = "result=superseded reason=" ++ std::string(OwnLicense(*chosen.at(license.package_id), account_id) ? "own" : "duplicate");+ } else {+ verdict = std::string("result=kept reason=") + (OwnLicense(license, account_id) ? "own" : "borrowed");+ }+ log("family step=license package=" + std::to_string(license.package_id) ++ " owner=" + std::to_string(license.owner_id) + " flags=" + HexFlags(license.flags) ++ " type=" + std::to_string(license.license_type) + " created=" + std::to_string(license.time_created) ++ " token=" + (license.access_token ? "y" : "n") + " " + verdict);+ };+ auto family = [account_id](const cm::License& license) {+ return (license.owner_id != 0 && license.owner_id != account_id) || (license.flags & kBorrowedLicense);+ };+ for (const auto& license : licenses)+ if (family(license)) detail(license);+ for (const auto& license : licenses)+ if (!family(license) && ((license.flags & ~kRenewLicense) != 0 || UnusableLicense(license))) detail(license);+ if (left_out) log("family step=license truncated=" + std::to_string(left_out));}std::uint32_t RemainingMs(Clock::time_point deadline) {@@ -840,6 +970,11 @@ DepotAccessResult CmClient::FetchDepotAccess(const StoredSession& stored, std::uif (const auto open = Acquire(stored, cancel, deadline, &lease); open != CmError::kNone)return finish(open);auto& session = lease.session;+ // Each depot's key and manifest request code result, with Steam's EResult, for every install.+ auto note = [this, app_id](const char* step, std::uint32_t depot_id, const std::string& outcome) {+ Log(std::string("step=") + step + " app=" + std::to_string(app_id) + " depot=" + std::to_string(depot_id) + " " ++ outcome);+ };for (const auto& depot : depots) {DepotGrant grant;grant.depot_id = depot.depot_id;@@ -848,31 +983,53 @@ DepotAccessResult CmClient::FetchDepotAccess(const StoredSession& stored, std::uif (const auto call = session->Call(cm::kEMsgClientGetDepotDecryptionKey, {},cm::EncodeDepotKeyRequest(depot.depot_id, app_id),cm::kEMsgClientGetDepotDecryptionKeyResponse, &reply);- call != CmError::kNone)+ call != CmError::kNone) {+ // Steam's EResult rides only on a refusal; other failures never reached it.+ note("depot_key", depot.depot_id,+ std::string("error=") + CmErrorName(call) ++ (call == CmError::kRejected ? " eresult=" + std::to_string(session->last_eresult()) : ""));return finish(call);+ }cm::DepotKeyResponse key;- if (!cm::DecodeDepotKeyResponse(reply, &key)) return finish(CmError::kProtocol);+ if (!cm::DecodeDepotKeyResponse(reply, &key)) {+ note("depot_key", depot.depot_id, "error=protocol");+ return finish(CmError::kProtocol);+ }if (key.eresult == cm::kEResultAccessDenied && depot.optional) {+ note("depot_key", depot.depot_id, "result=skipped eresult=" + std::to_string(key.eresult));result.skipped.push_back(depot.depot_id);continue;}if (key.eresult != cm::kEResultOk) {+ note("depot_key", depot.depot_id, "result=refused eresult=" + std::to_string(key.eresult));result.detail = "depot key refused eresult=" + std::to_string(key.eresult);return finish(CmError::kRejected);}- if (key.depot_id != depot.depot_id || key.key.size() != grant.key.size()) return finish(CmError::kProtocol);+ if (key.depot_id != depot.depot_id || key.key.size() != grant.key.size()) {+ note("depot_key", depot.depot_id, "error=protocol");+ return finish(CmError::kProtocol);+ }+ note("depot_key", depot.depot_id, "result=ok");std::copy(key.key.begin(), key.key.end(), grant.key.begin());reply.clear();if (const auto call = session->ServiceMethod("ContentServerDirectory.GetManifestRequestCode#1",cm::EncodeManifestRequestCodeRequest(app_id, depot.depot_id, depot.manifest_gid), &reply);- call != CmError::kNone)+ call != CmError::kNone) {+ const auto eresult = std::to_string(session->last_eresult());+ const bool refused = call == CmError::kRejected;+ note("manifest_code", depot.depot_id,+ std::string("error=") + CmErrorName(call) + (refused ? " eresult=" + eresult : ""));+ if (refused) result.detail = "manifest request code refused eresult=" + eresult;return finish(call);+ }if (!cm::DecodeManifestRequestCodeResponse(reply, &grant.manifest_request_code) ||grant.manifest_request_code == 0) {+ note("manifest_code", depot.depot_id, "result=refused code=0");result.detail = "manifest request code refused";return finish(CmError::kRejected);}+ note("manifest_code", depot.depot_id, "result=ok");result.grants.push_back(grant);}return finish(CmError::kNone);@@ -968,6 +1125,7 @@ AcquisitionResult CmClient::FetchAcquisitionDates(const StoredSession& stored,result.owned_depots.clear();result.package_apps.clear();result.package_depots.clear();+ result.shared_apps.clear();}return result;};@@ -981,17 +1139,27 @@ AcquisitionResult CmClient::FetchAcquisitionDates(const StoredSession& stored,const auto adopted = session.steam_id();const auto account_id = static_cast<std::uint32_t>(adopted != cm::kAnonymousSteamId ? adopted : stored.steam_id);- std::map<std::uint32_t, std::uint64_t> tokens;- std::vector<const cm::License*> active;+ // One license per package: the account's own wins over one borrowed from a family member, whatever+ // the list order, so its token and date are used.+ std::map<std::uint32_t, const cm::License*> chosen;for (const auto& license : licenses) {- if (!OwnedActiveLicense(license, account_id)) continue;- active.push_back(&license);- tokens[license.package_id] = license.access_token;+ if (UnusableLicense(license)) continue;+ auto [entry, inserted] = chosen.emplace(license.package_id, &license);+ if (!inserted && !OwnLicense(*entry->second, account_id) && OwnLicense(license, account_id))+ entry->second = &license;}+ LogLicenses([this](const std::string& line) { Log(line); }, licenses, chosen, account_id);std::vector<cm::PackageRequest> packages;- for (const auto& [id, token] : tokens) packages.push_back({id, token});+ std::set<std::uint32_t> borrowed_packages;+ for (const auto& [id, license] : chosen) {+ packages.push_back({id, license->access_token});+ if (!OwnLicense(*license, account_id)) borrowed_packages.insert(id);+ }std::map<std::uint32_t, std::vector<std::uint32_t>> package_apps;+ // What the borrowed packages did in PICS, for the family log.+ std::vector<std::uint32_t> borrowed_missing_token, borrowed_unparsable, borrowed_absent;+ std::set<std::uint32_t> borrowed_apps, borrowed_depots;for (std::size_t start = 0; start < packages.size(); start += kPicsBatch) {// Each batch gets its own deadline: an account with thousands of licenses needs hundreds of// batches, more than one deadline covers (issue #47). A stalled batch still times out.@@ -1003,27 +1171,59 @@ AcquisitionResult CmClient::FetchAcquisitionDates(const StoredSession& stored,if (const auto pics = session.Pics(batch, &parts); pics != CmError::kNone) return finish(pics);std::set<std::uint32_t> wanted;for (const auto& package : batch) wanted.insert(package.package_id);- std::set<std::uint32_t> received;+ std::set<std::uint32_t> received, answered;for (const auto& part : parts) {for (const auto& package : part.packages) {if (!wanted.count(package.package_id)) continue;+ const bool borrowed = borrowed_packages.count(package.package_id) > 0;+ // A borrowed package's first answer, for the family log.+ const bool first_answer = borrowed && answered.insert(package.package_id).second;+ if (first_answer && package.missing_token) borrowed_missing_token.push_back(package.package_id);+ if (package.missing_token) continue;PackageContents contents;// One odd license must not block every install (issue #1): skip it, its apps stay unowned.- if (package.missing_token ||- !ParsePackageBuffer(package.buffer.data(), package.buffer.size(), package.package_id,- &contents))+ if (!ParsePackageBuffer(package.buffer.data(), package.buffer.size(), package.package_id, &contents)) {+ if (first_answer) borrowed_unparsable.push_back(package.package_id);continue;+ }auto& apps = package_apps[package.package_id];apps.insert(apps.end(), contents.app_ids.begin(), contents.app_ids.end());auto& depots = result.package_depots[package.package_id];depots.insert(depots.end(), contents.depot_ids.begin(), contents.depot_ids.end());result.owned_apps.insert(contents.app_ids.begin(), contents.app_ids.end());result.owned_depots.insert(contents.depot_ids.begin(), contents.depot_ids.end());+ if (borrowed) {+ borrowed_apps.insert(contents.app_ids.begin(), contents.app_ids.end());+ borrowed_depots.insert(contents.depot_ids.begin(), contents.depot_ids.end());+ }received.insert(package.package_id);}}+ for (const auto id : wanted)+ if (borrowed_packages.count(id) && !answered.count(id)) borrowed_absent.push_back(id);result.skipped_packages += static_cast<std::uint32_t>(wanted.size() - received.size());}++ // Apps any of the account's own packages grant are its own, even when a family member shares them too.+ std::set<std::uint32_t> own_apps;+ for (const auto& [id, apps] : package_apps)+ if (!borrowed_packages.count(id)) own_apps.insert(apps.begin(), apps.end());+ for (const auto app : borrowed_apps)+ if (!own_apps.count(app)) result.shared_apps.insert(app);+ {+ std::uint32_t borrowed_received = 0;+ for (const auto& entry : package_apps) borrowed_received += borrowed_packages.count(entry.first) ? 1 : 0;+ Log("family step=pics borrowed_packages=" + std::to_string(borrowed_packages.size()) ++ " received=" + std::to_string(borrowed_received) ++ " missing_token=" + std::to_string(borrowed_missing_token.size()) ++ " unparsable=" + std::to_string(borrowed_unparsable.size()) ++ " absent=" + std::to_string(borrowed_absent.size()) + " apps=" + std::to_string(borrowed_apps.size()) ++ " depots=" + std::to_string(borrowed_depots.size()) + " shared_apps=" ++ std::to_string(result.shared_apps.size()));+ if (!borrowed_missing_token.empty()) Log("family step=pics missing_token_packages=" + IdList(borrowed_missing_token));+ if (!borrowed_unparsable.empty()) Log("family step=pics unparsable_packages=" + IdList(borrowed_unparsable));+ if (!borrowed_absent.empty()) Log("family step=pics absent_packages=" + IdList(borrowed_absent));+ }// Nothing usable at all is a reply this client does not understand, not a few odd licenses.if (!packages.empty() && result.skipped_packages == packages.size()) return finish(CmError::kProtocol);@@ -1031,11 +1231,14 @@ AcquisitionResult CmClient::FetchAcquisitionDates(const StoredSession& stored,? hooks_.unix_now(): static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count());- for (const auto* license : active) {+ for (const auto& [id, license] : chosen) {if (license->time_created == 0 || license->time_created > now) continue;- const auto found = package_apps.find(license->package_id);+ const auto found = package_apps.find(id);if (found == package_apps.end()) continue;+ const bool borrowed = borrowed_packages.count(id) > 0;for (const auto app : found->second) {+ // A borrowed license dates only an app the account doesn't own itself.+ if (borrowed && own_apps.count(app)) continue;auto [entry, inserted] = result.acquired_at.emplace(app, license->time_created);if (!inserted) entry->second = std::min(entry->second, license->time_created);}diff --git a/src/steam/backend/cm_client.h b/src/steam/backend/cm_client.hindex 5887654..9477f41 100644--- a/src/steam/backend/cm_client.h+++ b/src/steam/backend/cm_client.h@@ -35,7 +35,8 @@ enum class CmError {const char* CmErrorName(CmError error);// Receives one line per CM logon and per refusal, for steam-cm.log: the owner, the step, the error-// and Steam's result code. Never a token, account name, SteamID or endpoint. Process-wide.+// and Steam's result code. Never a token, account name, the account's SteamID or an endpoint. Family+// sharing lines name the owning family member's account ID, so a shared game can be traced. Process-wide.void SetCmLog(std::function<void(const std::string& line)> log);// After Steam refuses a logon for a reason other than the credentials (busy, rate limited), or the@@ -55,6 +56,9 @@ struct AcquisitionResult {// The apps of each active licensed package, for games the owned list leaves out.std::map<std::uint32_t, std::vector<std::uint32_t>> package_apps;std::map<std::uint32_t, std::vector<std::uint32_t>> package_depots;+ // Apps reached only through licenses borrowed from another Steam family member, not through one of the+ // account's own. They are also in owned_apps and package_apps.+ std::set<std::uint32_t> shared_apps;// Licensed packages Steam left out, sent without a token, or sent unreadable; their apps are not owned here.std::uint32_t skipped_packages = 0;bool ok() const { return error == CmError::kNone; }diff --git a/src/steam/backend/cm_messages.cpp b/src/steam/backend/cm_messages.cppindex 333b19c..ab60035 100644--- a/src/steam/backend/cm_messages.cpp+++ b/src/steam/backend/cm_messages.cpp@@ -224,6 +224,7 @@ bool DecodeLicenseList(const std::vector<std::uint8_t>& body, LicenseList* list)case 4: if (!IsVarint(entry)) return false; license.minute_limit = AsInt32(entry.value); break;case 5: if (!IsVarint(entry)) return false; license.minutes_used = AsInt32(entry.value); break;case 7: if (!IsVarint(entry)) return false; license.flags = static_cast<std::uint32_t>(entry.value); break;+ case 9: if (!IsVarint(entry)) return false; license.license_type = static_cast<std::uint32_t>(entry.value); break;case 12: if (!IsVarint(entry)) return false; license.owner_id = static_cast<std::uint32_t>(entry.value); break;case 17: if (!IsVarint(entry)) return false; license.access_token = entry.value; break;default: break;diff --git a/src/steam/backend/cm_messages.h b/src/steam/backend/cm_messages.hindex 76c9184..958a6c0 100644--- a/src/steam/backend/cm_messages.h+++ b/src/steam/backend/cm_messages.h@@ -112,6 +112,7 @@ struct License {std::int32_t minute_limit = 0;std::int32_t minutes_used = 0;std::uint32_t flags = 0;+ std::uint32_t license_type = 0; // ELicenseType, for diagnostics onlystd::uint32_t owner_id = 0;std::uint64_t access_token = 0;};diff --git a/src/steam/backend/entitled_library.cpp b/src/steam/backend/entitled_library.cppindex aa27cf6..744b8d8 100644--- a/src/steam/backend/entitled_library.cpp+++ b/src/steam/backend/entitled_library.cpp@@ -5,10 +5,118 @@#include <algorithm>#include <cctype>#include <chrono>+#include <condition_variable>+#include <memory>#include <set>#include <thread>+#include <utility>namespace playden::steam {+namespace {++constexpr std::size_t kFamilyAppLineLimit = 100;++// The probe thread and the library load both write family lines; one at a time.+FamilyLog Serialized(FamilyLog log) {+ if (!log) return log;+ auto mutex = std::make_shared<std::mutex>();+ return [log = std::move(log), mutex](const std::string& line) {+ std::lock_guard<std::mutex> lock(*mutex);+ log(line);+ };+}++} // namespace++EntitledLibraryBackend::~EntitledLibraryBackend() { StopFamilyProbe(); }++void EntitledLibraryBackend::StopFamilyProbe() {+ std::lock_guard<std::mutex> guard(family_start_mutex_);+ {+ std::lock_guard<std::mutex> lock(family_mutex_);+ family_stop_.store(true);+ }+ family_cv_.notify_all();+ if (family_thread_.joinable()) family_thread_.join();+ family_stop_.store(false);+}++void EntitledLibraryBackend::SetFamilyDiagnostics(std::string ca_bundle, FamilyLog log) {+ StopFamilyProbe();+ family_answered_.store(false);+ family_ca_bundle_ = std::move(ca_bundle);+ family_perform_ = nullptr;+ family_log_ = Serialized(std::move(log));+}++void EntitledLibraryBackend::SetFamilyDiagnostics(FamilyPerform perform, FamilyLog log) {+ StopFamilyProbe();+ family_answered_.store(false);+ family_ca_bundle_.clear();+ family_perform_ = std::move(perform);+ family_log_ = Serialized(std::move(log));+}++// Once per run Steam's family service is asked what the family shares. The probe never decides or holds up+// a load: it runs on its own copies, one at a time, and a failed one is tried again by the next load.+bool EntitledLibraryBackend::StartFamilyProbe(const StoredSession& session) {+ if (!family_log_ || (!family_perform_ && family_ca_bundle_.empty())) return false;+ std::lock_guard<std::mutex> guard(family_start_mutex_);+ if (family_running_.load() || family_answered_.load()) return false;+ if (family_thread_.joinable()) family_thread_.join(); // finished+ {+ std::lock_guard<std::mutex> lock(family_mutex_);+ family_licenses_published_ = false;+ }+ family_running_.store(true);+ family_thread_ = std::thread([this, session, perform = family_perform_, ca_bundle = family_ca_bundle_,+ log = family_log_] {+ std::unique_ptr<HttpClient> http;+ FamilyPerform request = perform;+ if (!request) {+ http = std::make_unique<HttpClient>(ca_bundle);+ request = [&http](const HttpRequest& r, const std::atomic<bool>& stop) { return http->Perform(r, stop); };+ }+ const auto start = std::chrono::steady_clock::now();+ const FamilyProbe probe = ProbeFamily(session, request, log, family_stop_);+ const auto elapsed_ms = static_cast<std::uint64_t>(+ std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start).count());+ // Only Steam's answer ends the probing for this run: no family, or a family compared with known+ // licenses. A failure, or a family whose load had no licenses, is tried again by the next load.+ if (probe.outcome == FamilyProbe::Outcome::kNoGroup) family_answered_.store(true);+ if (probe.outcome == FamilyProbe::Outcome::kGroup && probe.library) {+ // Compared with the licenses of the load that started the probe, once that load has them.+ AcquisitionResult licenses;+ bool known = false;+ {+ std::unique_lock<std::mutex> lock(family_mutex_);+ family_cv_.wait_for(lock, std::chrono::seconds(30),+ [&] { return family_stop_.load() || family_licenses_published_; });+ if (family_licenses_published_ && family_licenses_ok_) {+ known = true;+ licenses.error = CmError::kNone;+ licenses.shared_apps = family_shared_apps_;+ licenses.owned_apps = family_owned_apps_;+ }+ }+ if (!family_stop_.load()) LogFamilySharedApps(probe, known ? &licenses : nullptr, elapsed_ms, log);+ if (known) family_answered_.store(true);+ }+ family_running_.store(false);+ });+ return true;+}++void EntitledLibraryBackend::PublishFamilyLicenses(const AcquisitionResult* licenses) {+ {+ std::lock_guard<std::mutex> lock(family_mutex_);+ family_licenses_published_ = true;+ family_licenses_ok_ = licenses && licenses->ok();+ family_shared_apps_ = family_licenses_ok_ ? licenses->shared_apps : std::set<std::uint32_t>{};+ family_owned_apps_ = family_licenses_ok_ ? licenses->owned_apps : std::set<std::uint32_t>{};+ }+ family_cv_.notify_all();+}LibraryResult EntitledLibraryBackend::Fetch(const StoredSession& session,const std::atomic<bool>& cancel) {@@ -20,6 +128,7 @@ LibraryResult EntitledLibraryBackend::Fetch(const StoredSession& session,acquisitions = acquisitions_.FetchAcquisitionDates(session, stop);done.store(true, std::memory_order_release);});+ const bool probing = StartFamilyProbe(session);LibraryResult result = owned_.Fetch(session, cancel);if (result.error != LibraryError::kNone) stop.store(true, std::memory_order_release);@@ -30,12 +139,18 @@ LibraryResult EntitledLibraryBackend::Fetch(const StoredSession& session,worker.join();last_error_.store(acquisitions.error);- if (result.error != LibraryError::kNone || !acquisitions.ok()) return result;+ if (result.error != LibraryError::kNone || !acquisitions.ok()) {+ if (family_log_ && result.error == LibraryError::kNone)+ family_log_(std::string("family library licenses=unavailable cm_error=") + CmErrorName(acquisitions.error));+ if (probing) PublishFamilyLicenses(nullptr);+ return result;+ }if (licensed_) licensed_->Set(acquisitions);for (auto& game : result.games) {const auto found = acquisitions.acquired_at.find(*game.id.steam_app());if (found != acquisitions.acquired_at.end()) game.added_at_unix_seconds = found->second;}+ if (probing) PublishFamilyLicenses(&acquisitions);AddLicensedGames(session, acquisitions, cancel, &result);return result;}@@ -43,16 +158,21 @@ LibraryResult EntitledLibraryBackend::Fetch(const StoredSession& session,void EntitledLibraryBackend::AddLicensedGames(const StoredSession& session,const AcquisitionResult& acquisitions,const std::atomic<bool>& cancel, LibraryResult* result) {+ const auto& shared = acquisitions.shared_apps;std::set<std::uint32_t> listed;for (const auto& game : result->games) listed.insert(*game.id.steam_app());// A package with a listed app is a bought game (with its DLC) the owned list already covers.- // Package 0 is Steam's basic free package, which GetOwnedGames leaves out on purpose.+ // Package 0 is Steam's basic free package, which GetOwnedGames leaves out on purpose. A package borrowed+ // from a family member can hold an app the account also owns next to ones only the lender has, so only+ // its listed apps are passed over.std::set<std::uint32_t> candidates;for (const auto& [package, apps] : acquisitions.package_apps) {- if (package == 0 || std::any_of(apps.begin(), apps.end(), [&](auto app) { return listed.count(app); })) continue;- candidates.insert(apps.begin(), apps.end());+ if (package == 0) continue;+ const bool borrowed = std::any_of(apps.begin(), apps.end(), [&](auto app) { return shared.count(app); });+ if (!borrowed && std::any_of(apps.begin(), apps.end(), [&](auto app) { return listed.count(app); })) continue;+ for (const auto app : apps)+ if (!listed.count(app)) candidates.insert(app);}- if (candidates.empty()) return;std::lock_guard<std::mutex> lock(looked_up_mutex_);std::vector<std::uint32_t> unknown;@@ -67,30 +187,87 @@ void EntitledLibraryBackend::AddLicensedGames(const StoredSession& session,if (!fetched.ok()) break;for (const auto app : batch) {std::string name;+ std::string type;const auto found = fetched.buffers.find(app);- if (found != fetched.buffers.end()) {- const auto info = ParseAppInfo(app, found->second);- std::string type = info ? info->type : std::string();+ const auto info = found != fetched.buffers.end() ? ParseAppInfo(app, found->second) : std::nullopt;+ if (info) {+ type = info->type;std::transform(type.begin(), type.end(), type.begin(), [](unsigned char c) { return std::tolower(c); });- if (info && (type == "game" || type == "demo") && info->name != "app_" + std::to_string(app)) name = info->name;+ if ((type == "game" || type == "demo") && info->name != "app_" + std::to_string(app)) name = info->name;if (!name.empty() && type == "demo") demos_.insert(app);- if (!name.empty() && info && !info->icon.empty())+ if (!name.empty() && !info->icon.empty())icons_[app] = "https://media.steampowered.com/steamcommunity/public/images/apps/" + std::to_string(app) +"/" + info->icon + ".jpg";}+ if (name.empty() && shared.count(app)) {+ // Why a shared app stays out of the Library, for the family log.+ std::string reason = found == fetched.buffers.end() ? "no_app_info"+ : !info ? "app_info_unreadable"+ : type != "game" && type != "demo"+ ? "type=" + (type.empty() ? std::string("none") : type.substr(0, 32))+ : "no_name";+ family_left_out_[app] = std::move(reason);+ }looked_up_[app] = name;}}+ std::size_t added = 0;+ std::size_t left_out = 0;+ std::size_t pending = 0;+ // Per-app lines are capped per load so a big family library can't rotate the license dump out of the+ // log. An app's line counts as logged only once written, so the rest follow on later loads.+ std::size_t written = 0;+ std::size_t truncated = 0;+ const auto detail = [&](std::set<std::uint32_t>& logged, std::uint32_t app, const std::string& line) {+ if (logged.count(app)) return;+ if (written == kFamilyAppLineLimit) {+ ++truncated;+ return;+ }+ ++written;+ logged.insert(app);+ family_log_(line);+ };for (const auto app : candidates) {const auto found = looked_up_.find(app);- if (found == looked_up_.end() || found->second.empty()) continue;+ const bool is_shared = shared.count(app) != 0;+ if (found == looked_up_.end() || found->second.empty()) {+ if (!is_shared || !family_log_) continue;+ if (found == looked_up_.end()) {+ // PICS did not answer (or the load was canceled): asked again on the next refresh. Logged once per+ // app; a repeated failure only counts as pending.+ ++pending;+ if (!cancel.load())+ detail(family_failed_logged_, app, "family library left_out app=" + std::to_string(app) + " reason=app_info_failed");+ continue;+ }+ ++left_out;+ const auto reason = family_left_out_.find(app);+ detail(family_logged_, app, "family library left_out app=" + std::to_string(app) ++ " reason=" + (reason != family_left_out_.end() ? reason->second : std::string("no_name")));+ continue;+ }GameSummary game{GameId::Steam(app), found->second, {}, {}, {}};game.demo = demos_.count(app) != 0;+ game.family_shared = is_shared;if (const auto icon = icons_.find(app); icon != icons_.end()) game.artwork_source = icon->second;- if (const auto added = acquisitions.acquired_at.find(app); added != acquisitions.acquired_at.end())- game.added_at_unix_seconds = added->second;+ if (const auto added_at = acquisitions.acquired_at.find(app); added_at != acquisitions.acquired_at.end())+ game.added_at_unix_seconds = added_at->second;+ if (is_shared) {+ ++added;+ if (family_log_)+ detail(family_logged_, app, "family library added app=" + std::to_string(app) + " demo=" + (game.demo ? "1" : "0"));+ }result->games.push_back(std::move(game));}+ if (family_log_) {+ if (truncated) family_log_("family library truncated=" + std::to_string(truncated));+ std::size_t in_owned_list = 0;+ for (const auto app : shared) in_owned_list += listed.count(app);+ family_log_("family library shared=" + std::to_string(shared.size()) + " added=" + std::to_string(added) ++ " left_out=" + std::to_string(left_out) + " pending=" + std::to_string(pending) ++ " in_owned_list=" + std::to_string(in_owned_list));+ }}} // namespace playden::steamdiff --git a/src/steam/backend/entitled_library.h b/src/steam/backend/entitled_library.hindex 7dcdcd0..90c780a 100644--- a/src/steam/backend/entitled_library.h+++ b/src/steam/backend/entitled_library.h@@ -1,9 +1,16 @@#pragma once#include "steam/backend/cm_client.h"+#include "steam/backend/family_groups.h"#include "steam/library_backend.h"+#include <atomic>+#include <condition_variable>+#include <memory>#include <mutex>+#include <set>+#include <string>+#include <thread>#include <unordered_map>#include <unordered_set>@@ -15,20 +22,35 @@ namespace playden::steam {// GetOwnedGames leaves out free-to-play games added to the library but never played. Licensed// packages none of whose apps are listed are looked up in PICS, and their games and demos (marked)// are added. Each app is looked up once per run, so after the first load a refresh only asks about-// new licenses.+// new licenses. Apps only a Steam family member's licenses grant are marked family_shared.class EntitledLibraryBackend final : public LibraryBackend {public:EntitledLibraryBackend(LibraryBackend& owned, AcquisitionSource& acquisitions): owned_(owned), acquisitions_(acquisitions) {}+ // Stops a running family probe and waits for it.+ ~EntitledLibraryBackend() override;LibraryResult Fetch(const StoredSession& session, const std::atomic<bool>& cancel) override;// Receives each successful license read, for size estimates.void SetLicensedDepots(LicensedDepots* licensed) { licensed_ = licensed; }+ // Writes "family" lines: which family-shared apps the Library got or left out, and what Steam's family+ // service lists, asked over HTTPS (with this CA bundle) on a thread of its own until it answers once this+ // run. A load starts it when none runs and never waits for it. Purely diagnostic: its failures are log+ // lines. Off until set; set it before the first Fetch, as it is not synchronized with a running one.+ void SetFamilyDiagnostics(std::string ca_bundle, FamilyLog log);+ // For tests: the family service requests go to `perform`.+ void SetFamilyDiagnostics(FamilyPerform perform, FamilyLog log);+// Category of the most recent CM attempt, for diagnostics without identifiers.CmError last_acquisition_error() const { return last_error_.load(); }private:+ // True when this load started the probe; it then owes the probe its licenses.+ bool StartFamilyProbe(const StoredSession& session);+ void StopFamilyProbe();+ // Hands the license sets of the load that started the probe (or that it had none) to the probe.+ void PublishFamilyLicenses(const AcquisitionResult* licenses);void AddLicensedGames(const StoredSession& session, const AcquisitionResult& acquisitions,const std::atomic<bool>& cancel, LibraryResult* result);@@ -42,6 +64,29 @@ class EntitledLibraryBackend final : public LibraryBackend {std::unordered_map<std::uint32_t, std::string> looked_up_;std::unordered_map<std::uint32_t, std::string> icons_;std::unordered_set<std::uint32_t> demos_;+ // Shared apps PICS left out -> why, and the shared apps whose outcome is already logged this run.+ std::unordered_map<std::uint32_t, std::string> family_left_out_;+ std::set<std::uint32_t> family_logged_;+ // Shared apps whose failed PICS lookup is already logged; later failures only count as pending.+ std::set<std::uint32_t> family_failed_logged_;++ FamilyLog family_log_;+ FamilyPerform family_perform_;+ std::string family_ca_bundle_;+ // The probe works on copies; these outlive it because the destructor joins it. Starting and stopping it+ // take family_start_mutex_.+ std::mutex family_start_mutex_;+ std::thread family_thread_;+ std::atomic<bool> family_running_{false};+ std::atomic<bool> family_answered_{false};+ std::atomic<bool> family_stop_{false};+ // The license sets of the load that started the probe, for the comparison, once it published them.+ std::mutex family_mutex_;+ std::condition_variable family_cv_;+ bool family_licenses_published_ = false;+ bool family_licenses_ok_ = false;+ std::set<std::uint32_t> family_shared_apps_;+ std::set<std::uint32_t> family_owned_apps_;};} // namespace playden::steamdiff --git a/src/steam/backend/family_groups.cpp b/src/steam/backend/family_groups.cppnew file mode 100644index 0000000..387bb9d--- /dev/null+++ b/src/steam/backend/family_groups.cpp@@ -0,0 +1,269 @@+// SPDX-License-Identifier: GPL-3.0-or-later+#include "steam/backend/family_groups.h"++#include "steam/backend/json.h"++#include <algorithm>+#include <chrono>+#include <limits>+#include <set>+#include <utility>++namespace playden::steam {+namespace {++constexpr std::size_t kBodyLimit = 8 * 1024 * 1024;+constexpr std::uint32_t kRequestTimeoutMs = 6000;+constexpr std::size_t kMemberLimit = 32;+constexpr std::size_t kAppLimit = 20000;+constexpr std::size_t kOwnerLimit = 32;+constexpr std::size_t kAppLineLimit = 200;++bool Unreserved(unsigned char byte) {+ return (byte >= 'a' && byte <= 'z') || (byte >= 'A' && byte <= 'Z') || (byte >= '0' && byte <= '9') ||+ byte == '-' || byte == '.' || byte == '_' || byte == '~';+}++std::string PercentEncode(std::string_view value) {+ constexpr char hex[] = "0123456789ABCDEF";+ std::string encoded;+ encoded.reserve(value.size());+ for (const unsigned char byte : value) {+ if (Unreserved(byte)) {+ encoded.push_back(static_cast<char>(byte));+ } else {+ encoded.push_back('%');+ encoded.push_back(hex[byte >> 4]);+ encoded.push_back(hex[byte & 0x0f]);+ }+ }+ return encoded;+}++// Steam's WebAPI sends 64-bit IDs as strings and small numbers as numbers; take either.+std::optional<std::uint64_t> Id(const json::Value* value) {+ if (!value) return std::nullopt;+ if (value->is_number()) return value->AsUint64();+ if (!value->is_string() || value->text().empty() || value->text().size() > 20) return std::nullopt;+ std::uint64_t parsed = 0;+ for (const unsigned char byte : value->text()) {+ if (byte < '0' || byte > '9') return std::nullopt;+ const std::uint64_t digit = byte - '0';+ if (parsed > (std::numeric_limits<std::uint64_t>::max() - digit) / 10) return std::nullopt;+ parsed = parsed * 10 + digit;+ }+ return parsed;+}++const json::Value* Payload(std::string_view body, std::optional<json::Value>* root) {+ json::Limits limits;+ limits.max_bytes = kBodyLimit;+ limits.max_depth = 16;+ limits.max_values = 400000;+ limits.max_string_bytes = 65536;+ *root = json::Parse(body, limits);+ if (!*root || !(*root)->is_object()) return nullptr;+ const auto* payload = (*root)->Find("response");+ return payload && payload->is_object() ? payload : nullptr;+}++std::string_view Body(const HttpResponse& response) {+ if (response.body.empty()) return {};+ return {reinterpret_cast<const char*>(response.body.data()), response.body.size()};+}++// One request: the response on success, else a logged failure and nothing.+std::optional<HttpResponse> Get(const std::string& url, const char* step, const FamilyPerform& perform,+ const FamilyLog& log, const std::atomic<bool>& cancel) {+ HttpRequest request;+ request.method = HttpMethod::kGet;+ request.url = url;+ request.headers = {{"User-Agent", "Playden/1.0"}};+ request.timeout_ms = kRequestTimeoutMs;+ request.max_response_bytes = kBodyLimit;+ auto response = perform(request, cancel);+ if (cancel.load()) return std::nullopt;+ if (!response.ok()) {+ log(std::string("family webapi step=") + step + " error=" + HttpFailureName(response));+ return std::nullopt;+ }+ if (response.status_code != 200) {+ std::string line = std::string("family webapi step=") + step + " http=" + std::to_string(response.status_code);+ for (const auto& [name, value] : response.headers) {+ std::string lower = name;+ for (auto& c : lower) c = static_cast<char>(c >= 'A' && c <= 'Z' ? c - 'A' + 'a' : c);+ if (lower == "x-eresult" && value.size() <= 8) line += " eresult=" + value;+ }+ log(line);+ return std::nullopt;+ }+ return response;+}++} // namespace++std::optional<FamilyGroup> ParseFamilyGroup(std::string_view body) {+ std::optional<json::Value> root;+ const auto* payload = Payload(body, &root);+ if (!payload) return std::nullopt;+ FamilyGroup group;+ group.family_groupid = Id(payload->Find("family_groupid")).value_or(0);+ if (const auto* flag = payload->Find("is_not_member_of_any_group"); flag && flag->is_bool())+ group.not_member = flag->boolean();+ group.role = Id(payload->Find("role"));+ const auto* family = payload->Find("family_group");+ const auto* members = family && family->is_object() ? family->Find("members") : nullptr;+ if (members && members->is_array()) {+ for (const auto& item : members->array()) {+ if (group.members.size() >= kMemberLimit) break;+ if (!item.is_object()) continue;+ FamilyMember member;+ member.steamid = Id(item.Find("steamid")).value_or(0);+ member.role = Id(item.Find("role"));+ group.members.push_back(member);+ }+ }+ return group;+}++std::optional<SharedLibrary> ParseSharedLibraryApps(std::string_view body) {+ std::optional<json::Value> root;+ const auto* payload = Payload(body, &root);+ if (!payload) return std::nullopt;+ SharedLibrary library;+ const auto* apps = payload->Find("apps");+ if (!apps || !apps->is_array()) return library;+ library.apps.reserve(std::min(apps->array().size(), kAppLimit));+ for (const auto& item : apps->array()) {+ if (library.apps.size() >= kAppLimit) break;+ if (!item.is_object()) continue;+ const auto appid = Id(item.Find("appid"));+ if (!appid || !*appid || *appid > std::numeric_limits<std::uint32_t>::max()) continue;+ SharedLibraryApp app;+ app.appid = static_cast<std::uint32_t>(*appid);+ if (const auto* owners = item.Find("owner_steamids"); owners && owners->is_array()) {+ for (const auto& owner : owners->array()) {+ if (app.owners.size() >= kOwnerLimit) break;+ if (const auto id = Id(&owner)) app.owners.push_back(*id);+ }+ }+ app.exclude_reason = Id(item.Find("exclude_reason")).value_or(0);+ library.apps.push_back(std::move(app));+ }+ return library;+}++FamilyProbe ProbeFamily(const StoredSession& session, const FamilyPerform& perform, const FamilyLog& log,+ const std::atomic<bool>& cancel) {+ FamilyProbe probe;+ if (cancel.load()) {+ probe.outcome = FamilyProbe::Outcome::kCanceled;+ return probe;+ }+ if (!session.steam_id || session.access_token.empty()) {+ log("family webapi step=group error=no_session");+ return probe;+ }+ const std::string token = PercentEncode(session.access_token);+ const std::string steamid = std::to_string(session.steam_id);+ const auto group_response =+ Get("https://api.steampowered.com/IFamilyGroupsService/GetFamilyGroupForUser/v1/?access_token=" + token ++ "&steamid=" + steamid + "&include_family_group_response=true",+ "group", perform, log, cancel);+ if (cancel.load()) {+ probe.outcome = FamilyProbe::Outcome::kCanceled;+ return probe;+ }+ if (!group_response) return probe;+ const auto group = ParseFamilyGroup(Body(*group_response));+ if (!group) {+ log("family webapi step=group error=unreadable bytes=" + std::to_string(group_response->body.size()));+ return probe;+ }+ probe.group = *group;+ if (!group->family_groupid) {+ probe.outcome = FamilyProbe::Outcome::kNoGroup;+ log(std::string("family webapi group=n not_member=") + (group->not_member ? "1" : "0"));+ return probe;+ }+ std::string line = "family webapi group=y family_groupid=" + std::to_string(group->family_groupid) ++ " role=" + (group->role ? std::to_string(*group->role) : std::string("?")) ++ " members=" + std::to_string(group->members.size());+ for (const auto& member : group->members)+ line += " member=" + std::to_string(member.steamid) + ":" ++ (member.role ? std::to_string(*member.role) : std::string("?"));+ log(line);+ probe.outcome = FamilyProbe::Outcome::kGroup;++ const auto apps_response =+ Get("https://api.steampowered.com/IFamilyGroupsService/GetSharedLibraryApps/v1/?access_token=" + token ++ "&family_groupid=" + std::to_string(group->family_groupid) + "&steamid=" + steamid ++ "&include_own=false&include_excluded=true&include_free=false&include_non_games=false",+ "apps", perform, log, cancel);+ if (cancel.load()) {+ probe.outcome = FamilyProbe::Outcome::kCanceled;+ return probe;+ }+ // Without the app list the probe failed, and is tried again.+ if (!apps_response) {+ probe.outcome = FamilyProbe::Outcome::kFailed;+ return probe;+ }+ probe.library = ParseSharedLibraryApps(Body(*apps_response));+ if (!probe.library) {+ probe.outcome = FamilyProbe::Outcome::kFailed;+ log("family webapi step=apps error=unreadable bytes=" + std::to_string(apps_response->body.size()));+ }+ return probe;+}++void LogFamilySharedApps(const FamilyProbe& probe, const AcquisitionResult* acquisitions, std::uint64_t elapsed_ms,+ const FamilyLog& log) {+ if (probe.outcome != FamilyProbe::Outcome::kGroup || !probe.library) return;+ const bool known = acquisitions && acquisitions->ok();+ std::size_t excluded = 0;+ std::size_t unlicensed = 0;+ std::set<std::uint64_t> owners;+ for (const auto& app : probe.library->apps) {+ owners.insert(app.owners.begin(), app.owners.end());+ if (app.exclude_reason) {+ ++excluded;+ } else if (known && !acquisitions->shared_apps.count(app.appid) && !acquisitions->owned_apps.count(app.appid)) {+ ++unlicensed;+ }+ }+ log("family webapi shared_apps=" + std::to_string(probe.library->apps.size()) ++ " excluded=" + std::to_string(excluded) + " owners=" + std::to_string(owners.size()) ++ " unlicensed=" + (known ? std::to_string(unlicensed) : std::string("?")) ++ " licenses=" + (known ? "known" : "unknown") ++ (known ? " license_shared_apps=" + std::to_string(acquisitions->shared_apps.size()) : std::string()) ++ " elapsed_ms=" + std::to_string(elapsed_ms));+ std::size_t written = 0;+ for (const auto& app : probe.library->apps) {+ if (written == kAppLineLimit) {+ log("family webapi truncated=" + std::to_string(probe.library->apps.size() - written));+ break;+ }+ std::string line = "family webapi app=" + std::to_string(app.appid) + " owners=";+ for (std::size_t i = 0; i < app.owners.size(); ++i) line += (i ? "," : "") + std::to_string(app.owners[i]);+ if (app.owners.empty()) line += "-";+ line += " exclude_reason=" + std::to_string(app.exclude_reason) + " licensed=";+ if (!known) line += "?";+ else if (acquisitions->shared_apps.count(app.appid)) line += "shared";+ else if (acquisitions->owned_apps.count(app.appid)) line += "own";+ else line += "n";+ log(line);+ ++written;+ }+}++void RunFamilyDiagnostics(const StoredSession& session, const AcquisitionResult* acquisitions,+ const FamilyPerform& perform, const FamilyLog& log, const std::atomic<bool>& cancel) {+ const auto start = std::chrono::steady_clock::now();+ const auto probe = ProbeFamily(session, perform, log, cancel);+ const auto elapsed =+ std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start).count();+ LogFamilySharedApps(probe, acquisitions, static_cast<std::uint64_t>(elapsed), log);+}++} // namespace playden::steamdiff --git a/src/steam/backend/family_groups.h b/src/steam/backend/family_groups.hnew file mode 100644index 0000000..35b3e4c--- /dev/null+++ b/src/steam/backend/family_groups.h@@ -0,0 +1,74 @@+// SPDX-License-Identifier: GPL-3.0-or-later+#pragma once++#include "steam/backend/cm_client.h"+#include "steam/backend/http_client.h"+#include "steam/session_store.h"++#include <atomic>+#include <cstdint>+#include <functional>+#include <optional>+#include <string>+#include <string_view>+#include <vector>++namespace playden::steam {++// Diagnostics only: what IFamilyGroupsService says about the account's Steam family, to compare with the+// licenses the CM sent. Nothing here adds games or affects a library load.++using FamilyPerform = std::function<HttpResponse(const HttpRequest&, const std::atomic<bool>&)>;+using FamilyLog = std::function<void(const std::string& line)>;++struct FamilyMember {+ std::uint64_t steamid = 0;+ std::optional<std::uint64_t> role;+};++// GetFamilyGroupForUser. family_groupid 0 means the account is in no family.+struct FamilyGroup {+ std::uint64_t family_groupid = 0;+ bool not_member = false;+ std::optional<std::uint64_t> role;+ std::vector<FamilyMember> members;+};++struct SharedLibraryApp {+ std::uint32_t appid = 0;+ std::vector<std::uint64_t> owners;+ std::uint64_t exclude_reason = 0; // 0: shared; anything else is Steam's reason it is not+};++// GetSharedLibraryApps.+struct SharedLibrary {+ std::vector<SharedLibraryApp> apps;+};++// Lenient: unknown fields are ignored, IDs may be JSON numbers or strings, missing fields stay at their+// defaults. Empty when the body is not a JSON object with a "response" object.+std::optional<FamilyGroup> ParseFamilyGroup(std::string_view body);+std::optional<SharedLibrary> ParseSharedLibraryApps(std::string_view body);++// Asks Steam about the account's family and its shared library and writes "family webapi ..." lines.+// `acquisitions` (when ok) tells which shared apps have a license here. Every failure becomes a log line.+// The URL, the token and response bodies are never logged.+void RunFamilyDiagnostics(const StoredSession& session, const AcquisitionResult* acquisitions,+ const FamilyPerform& perform, const FamilyLog& log, const std::atomic<bool>& cancel);++// What the probe found, kept so the comparison with licenses can run after both finish.+struct FamilyProbe {+ enum class Outcome { kCanceled, kFailed, kNoGroup, kGroup };+ Outcome outcome = Outcome::kFailed;+ FamilyGroup group;+ std::optional<SharedLibrary> library;+};++// The two requests of RunFamilyDiagnostics, logging the group and any failure. Split so a caller can run+// the requests while the license list loads and compare afterwards with LogFamilySharedApps.+FamilyProbe ProbeFamily(const StoredSession& session, const FamilyPerform& perform, const FamilyLog& log,+ const std::atomic<bool>& cancel);+void LogFamilySharedApps(const FamilyProbe& probe, const AcquisitionResult* acquisitions, std::uint64_t elapsed_ms,+ const FamilyLog& log);++} // namespace playden::steamdiff --git a/src/steam/backend/steam_install_runner.cpp b/src/steam/backend/steam_install_runner.cppindex 5a5ca4c..24bb3d0 100644--- a/src/steam/backend/steam_install_runner.cpp+++ b/src/steam/backend/steam_install_runner.cpp@@ -106,6 +106,30 @@ const char* InstallFailureText(InstallError error) {return "Install failed.";}+namespace {++// Comma-separated items after a key, split so each line fits the native log buffer with room for the+// timestamp, app and step.+std::vector<std::string> FamilyLines(const char* key, const std::vector<std::string>& items) {+ std::vector<std::string> lines;+ std::string line = key;+ bool first = true;+ for (const auto& item : items) {+ if (!first && line.size() + 1 + item.size() > 360) {+ lines.push_back(std::move(line));+ line = key;+ first = true;+ }+ line += (first ? "" : ",") + item;+ first = false;+ }+ if (first) line += "none";+ lines.push_back(std::move(line));+ return lines;+}++} // namespace+InstallRunner::Result SteamInstallRunner::InstallApp(const StoredSession& session, std::uint32_t id, const std::string& root,const std::atomic<bool>& cancel,const std::function<void(std::uint64_t, std::uint64_t, std::uint64_t)>& progress,@@ -154,6 +178,15 @@ InstallRunner::Result SteamInstallRunner::InstallApp(const StoredSession& sessio}if (entitlements.skipped_packages)log("entitlements", "partial", ("skipped_packages=" + std::to_string(entitlements.skipped_packages)).c_str());+ // A game a Steam family member shares: which borrowed packages carry it. steam-cm.log names each+ // package's owner (family step=license).+ const bool family_shared = entitlements.shared_apps.count(id) > 0;+ if (family_shared) {+ std::vector<std::string> packages;+ for (const auto& [package, apps] : entitlements.package_apps)+ if (std::find(apps.begin(), apps.end(), id) != apps.end()) packages.push_back(std::to_string(package));+ for (const auto& line : FamilyLines("packages=", packages)) log("family", "shared", line.c_str());+ }std::set<std::uint32_t> owned_apps = entitlements.owned_apps;owned_apps.insert(id);if (!SelectDepots(*app, owned_apps, entitlements.owned_depots, &target.depots, &reason)) {@@ -194,6 +227,19 @@ InstallRunner::Result SteamInstallRunner::InstallApp(const StoredSession& sessiostd::string selected_ids;for (const auto& depot : target.depots) selected_ids += (selected_ids.empty() ? "" : " ") + std::to_string(depot.id);log("depots", "selected", selected_ids.c_str());+ if (family_shared) {+ // Which packages grant each selected depot, as depot:package/package.+ std::vector<std::string> grants;+ for (const auto& depot : target.depots) {+ std::string grant = std::to_string(depot.id) + ":";+ std::size_t found = 0;+ for (const auto& [package, depots] : entitlements.package_depots)+ if (std::find(depots.begin(), depots.end(), depot.id) != depots.end())+ grant += (found++ ? "/" : "") + std::to_string(package);+ grants.push_back(found ? grant : grant + "none");+ }+ for (const auto& line : FamilyLines("depots=", grants)) log("family", "depots", line.c_str());+ }if (step) step(InstallStep::kDownloading);const auto outcome = installer_.Run(session, target, cancel, [&](const InstallProgress& state) {if (progress) progress(state.download_done, state.download_total, state.held_bytes);diff --git a/tests/cm_client_test.cpp b/tests/cm_client_test.cppindex 5b881e5..73e778f 100644--- a/tests/cm_client_test.cpp+++ b/tests/cm_client_test.cpp@@ -177,8 +177,9 @@ void AcquisitionDatesFromGzipMultiLicensesAndMultipartPics() {const auto result = client.FetchAcquisitionDates(Session(), cancel);assert(result.ok());// Package 100 (1600000000) holds apps 10, 20; package 200 (1500000000) holds 20, 30. Packages- // 300 (expired), 400 (another owner) and 500 (minutes used up) are not this account's.- assert(result.acquired_at.size() == 3);+ // 300 (expired) and 500 (minutes used up) are left out. Package 400 is another owner's, shared with+ // this account, but Steam doesn't describe it.+ assert(result.acquired_at.size() == 3 && result.skipped_packages == 1 && result.shared_apps.empty());assert(result.acquired_at.at(10) == 1600000000u);assert(result.acquired_at.at(20) == 1500000000u);assert(result.acquired_at.at(30) == 1500000000u);@@ -193,7 +194,7 @@ void AcquisitionDatesFromGzipMultiLicensesAndMultipartPics() {assert(script->sent[1].header.session_id == 0);// After logon the frame header carries the adopted session identity and the job ID.assert(script->sent[2].emsg == cm::kEMsgClientPICSProductInfoRequest);- assert(script->sent[2].body == Fixture("pics_request.pb"));+ assert(script->sent[2].body == cm::EncodePicsPackagesRequest({{100, 7001}, {200, 0}, {400, 0}}));assert(script->sent[2].header.steam_id == kAccountSteamId);assert(script->sent[2].header.session_id == 77);assert(script->sent[2].header.jobid_source == 1u);@@ -229,7 +230,7 @@ void PackagesSteamCannotDescribeAreSkipped() {left_out->on_pics = {ServerFrame(cm::kEMsgClientPICSProductInfoResponse, Fixture("pics_response_part2.pb"), std::nullopt, 1)};auto client = MakeClient(left_out);const auto partial = client.FetchAcquisitionDates(Session(), cancel);- assert(partial.ok() && partial.skipped_packages == 1);+ assert(partial.ok() && partial.skipped_packages == 2); // and the shared package 400assert(partial.owned_apps == (std::set<std::uint32_t>{20, 30}));assert(partial.acquired_at.size() == 2 && partial.acquired_at.at(20) == 1500000000u);@@ -245,7 +246,7 @@ void PackagesSteamCannotDescribeAreSkipped() {tokenless->on_pics = {ServerFrame(cm::kEMsgClientPICSProductInfoResponse, body, std::nullopt, 1)};auto other = MakeClient(tokenless);const auto skipped = other.FetchAcquisitionDates(Session(), cancel);- assert(skipped.ok() && skipped.skipped_packages == 1 && skipped.owned_apps == (std::set<std::uint32_t>{20, 30}));+ assert(skipped.ok() && skipped.skipped_packages == 2 && skipped.owned_apps == (std::set<std::uint32_t>{20, 30}));// A reply with none of the packages is still a protocol error.auto empty = HappyScript();@@ -370,6 +371,227 @@ void PackageZeroCounts() {assert(result.acquired_at.at(440) == 1240000000u && result.acquired_at.at(220) == 1240000000u);}+// A license in a synthetic list; owner 4242 is the signed-in account.+struct TestLicense {+ std::uint32_t package_id = 0;+ std::uint32_t created = 0;+ std::uint32_t flags = 0;+ std::uint32_t owner_id = 4242;+ std::uint64_t token = 0;+ std::int32_t minute_limit = 0;+ std::int32_t minutes_used = 0;+};++using PackageContentsMap = std::map<std::uint32_t, std::pair<std::vector<std::uint32_t>, std::vector<std::uint32_t>>>;++// A script whose logon pushes `licenses` and whose PICS answers every package in `contents` it was asked for.+std::shared_ptr<Script> LicenseScript(const std::vector<TestLicense>& licenses, PackageContentsMap contents) {+ auto script = std::make_shared<Script>();+ proto::Writer list;+ list.AddVarint(1, 1);+ for (const auto& entry : licenses) {+ proto::Writer license;+ license.AddVarint(1, entry.package_id);+ if (entry.created) license.AddFixed32(2, entry.created);+ if (entry.minute_limit) license.AddVarint(4, static_cast<std::uint32_t>(entry.minute_limit));+ if (entry.minutes_used) license.AddVarint(5, static_cast<std::uint32_t>(entry.minutes_used));+ if (entry.flags) license.AddVarint(7, entry.flags);+ license.AddVarint(12, entry.owner_id);+ if (entry.token) license.AddVarint(17, entry.token);+ list.AddMessage(2, license);+ }+ script->on_logon = {ServerFrame(cm::kEMsgClientLogOnResponse, LogonResponseBody(1, 9)),+ ServerFrame(cm::kEMsgClientLicenseList, list.bytes())};+ script->pics_reply = [contents](const cm::Frame& request) {+ proto::Writer body;+ for (const auto& [id, granted] : contents) {+ proto::Writer package;+ package.AddVarint(1, id);+ package.AddBytes(5, PackageBuffer(id, granted.first, granted.second));+ body.AddMessage(3, package);+ }+ return ServerFrame(cm::kEMsgClientPICSProductInfoResponse, body.bytes(), std::nullopt, request.header.jobid_source);+ };+ return script;+}++std::vector<std::uint8_t> PicsRequestSent(Script& script) {+ std::lock_guard<std::mutex> lock(script.mutex);+ for (const auto& frame : script.sent)+ if (frame.emsg == cm::kEMsgClientPICSProductInfoRequest) return frame.body;+ return {};+}++struct LogCapture {+ std::mutex mutex;+ std::vector<std::string> lines;+ LogCapture() {+ SetCmLog([this](const std::string& line) {+ std::lock_guard<std::mutex> lock(mutex);+ lines.push_back(line);+ });+ }+ ~LogCapture() { SetCmLog(nullptr); }+ std::vector<std::string> Take() {+ std::lock_guard<std::mutex> lock(mutex);+ auto taken = std::move(lines);+ lines.clear();+ return taken;+ }+};++bool HasLine(const std::vector<std::string>& lines, const std::string& line) {+ return std::find(lines.begin(), lines.end(), line) != lines.end();+}++std::size_t CountPrefix(const std::vector<std::string>& lines, const std::string& prefix) {+ return static_cast<std::size_t>(std::count_if(lines.begin(), lines.end(), [&](const std::string& line) {+ return line.rfind(prefix, 0) == 0;+ }));+}++// Steam Families: a license another member shares (another owner, the Borrowed flag) counts, and its apps+// that no own license grants are shared. Every other unavailable flag and used-up minutes still drop it.+void BorrowedLicensesAreShared() {+ LogCapture log;+ auto script = LicenseScript(+ {{100, 1600000000, 0, 4242, 7001},+ {600, 1550000000, 0x4000, 9999, 6601},+ {700, 1500000000, 0x4000 | 0x8, 9999, 7701}, // expired+ {800, 1500000000, 0x4000, 8888, 8801, 60, 60}, // minutes used up+ {900, 1450000000, 0x2000, 4242}}, // pending refund+ {{100, {{10, 20}, {101}}}, {600, {{20, 40}, {201, 401}}}});+ auto client = MakeClient(script);+ std::atomic<bool> cancel{false};+ const auto result = client.FetchAcquisitionDates(Session(), cancel);+ assert(result.ok() && result.skipped_packages == 0);+ assert(PicsRequestSent(*script) == cm::EncodePicsPackagesRequest({{100, 7001}, {600, 6601}}));+ assert(result.owned_apps == (std::set<std::uint32_t>{10, 20, 40}));+ assert(result.owned_depots == (std::set<std::uint32_t>{101, 201, 401}));+ assert(result.shared_apps == (std::set<std::uint32_t>{40}));+ // App 20 is the account's own: the borrowed license's earlier date doesn't apply to it.+ assert(result.acquired_at.at(10) == 1600000000u && result.acquired_at.at(20) == 1600000000u);+ assert(result.acquired_at.at(40) == 1550000000u);+ assert(result.package_apps.at(600) == (std::vector<std::uint32_t>{20, 40}));++ const auto lines = log.Take();+ assert(HasLine(lines, "owner=cm family step=licenses total=5 own=1 borrowed=1 dropped=3 owners=8888:1,9999:2 "+ "flags=0x8:1,0x2000:1,0x4000:3 changed=y"));+ assert(HasLine(lines, "owner=cm family step=license package=600 owner=9999 flags=0x4000 type=0 created=1550000000 "+ "token=y result=kept reason=borrowed"));+ assert(HasLine(lines, "owner=cm family step=license package=700 owner=9999 flags=0x4008 type=0 created=1500000000 "+ "token=y result=dropped reason=flags:0x8"));+ assert(HasLine(lines, "owner=cm family step=license package=800 owner=8888 flags=0x4000 type=0 created=1500000000 "+ "token=y result=dropped reason=minutes"));+ assert(HasLine(lines, "owner=cm family step=license package=900 owner=4242 flags=0x2000 type=0 created=1450000000 "+ "token=n result=dropped reason=flags:0x2000"));+ assert(CountPrefix(lines, "owner=cm family step=license ") == 4); // package 100 is plainly the account's own+ assert(HasLine(lines, "owner=cm family step=pics borrowed_packages=1 received=1 missing_token=0 unparsable=0 "+ "absent=0 apps=2 depots=2 shared_apps=1"));+}++// The same package through the account's own license and a borrowed one: the own license's token and date+// count, and its apps are not shared, whichever comes first in the list.+void OwnLicenseWinsOverBorrowedInEitherOrder() {+ const TestLicense own{100, 1600000000, 0, 4242, 7001};+ for (const bool borrowed_first : {false, true}) {+ LogCapture log;+ const TestLicense borrowed{100, 1400000000 + (borrowed_first ? 1u : 0u), 0x4000, 9999, 8001};+ auto script = LicenseScript(borrowed_first ? std::vector<TestLicense>{borrowed, own}+ : std::vector<TestLicense>{own, borrowed},+ {{100, {{10}, {101}}}});+ auto client = MakeClient(script);+ std::atomic<bool> cancel{false};+ const auto result = client.FetchAcquisitionDates(Session(), cancel);+ assert(result.ok());+ assert(PicsRequestSent(*script) == cm::EncodePicsPackagesRequest({{100, 7001}}));+ assert(result.owned_apps == (std::set<std::uint32_t>{10}) && result.shared_apps.empty());+ assert(result.acquired_at.at(10) == 1600000000u);+ const auto lines = log.Take();+ assert(HasLine(lines, "owner=cm family step=license package=100 owner=9999 flags=0x4000 type=0 created=" ++ std::to_string(borrowed.created) + " token=y result=superseded reason=own"));+ assert(HasLine(lines, "owner=cm family step=pics borrowed_packages=0 received=0 missing_token=0 unparsable=0 "+ "absent=0 apps=0 depots=0 shared_apps=0"));+ }+}++// Borrowed packages PICS doesn't describe are named, and their apps stay unowned.+void BorrowedPackagesPicsSkipsAreLogged() {+ LogCapture log;+ auto script = LicenseScript({{100, 1600000000, 0, 4242, 7001},+ {610, 1550000000, 0x4000, 9999, 0},+ {620, 1550000000, 0x4000, 9999, 0},+ {630, 1550000000, 0x4000, 9999, 0}},+ {{100, {{10}, {101}}}});+ script->pics_reply = [](const cm::Frame& request) {+ proto::Writer body;+ proto::Writer own;+ own.AddVarint(1, 100);+ own.AddBytes(5, PackageBuffer(100, {10}, {101}));+ body.AddMessage(3, own);+ proto::Writer tokenless; // 610: missing its token+ tokenless.AddVarint(1, 610);+ tokenless.AddVarint(3, 1);+ body.AddMessage(3, tokenless);+ proto::Writer garbled; // 620: unreadable buffer; 630 left out+ garbled.AddVarint(1, 620);+ garbled.AddBytes(5, std::vector<std::uint8_t>{1, 2, 3});+ body.AddMessage(3, garbled);+ return ServerFrame(cm::kEMsgClientPICSProductInfoResponse, body.bytes(), std::nullopt, request.header.jobid_source);+ };+ auto client = MakeClient(script);+ std::atomic<bool> cancel{false};+ const auto result = client.FetchAcquisitionDates(Session(), cancel);+ assert(result.ok() && result.skipped_packages == 3 && result.shared_apps.empty());+ assert(result.owned_apps == (std::set<std::uint32_t>{10}));+ const auto lines = log.Take();+ assert(HasLine(lines, "owner=cm family step=pics borrowed_packages=3 received=0 missing_token=1 unparsable=1 "+ "absent=1 apps=0 depots=0 shared_apps=0"));+ assert(HasLine(lines, "owner=cm family step=pics missing_token_packages=610"));+ assert(HasLine(lines, "owner=cm family step=pics unparsable_packages=620"));+ assert(HasLine(lines, "owner=cm family step=pics absent_packages=630"));+}++// The per-license lines are written once per distinct list, so library refreshes don't rotate the log away,+// and at most 300 at a time.+void FamilyLicenseLinesAreCappedAndOnlyOnChange() {+ std::vector<TestLicense> licenses;+ for (std::uint32_t id = 5000; id < 5305; ++id) licenses.push_back({id, 1500000000, 0x80, 0});+ auto script = LicenseScript(licenses, {{5000, {{50}, {51}}}});+ std::atomic<bool> cancel{false};+ LogCapture log;+ {+ auto client = MakeClient(script);+ assert(client.FetchAcquisitionDates(Session(), cancel).ok());+ }+ auto lines = log.Take();+ assert(HasLine(lines, "owner=cm family step=licenses total=305 own=305 borrowed=0 dropped=0 owners=none "+ "flags=0x80:305 changed=y"));+ assert(CountPrefix(lines, "owner=cm family step=license package=") == 300);+ assert(HasLine(lines, "owner=cm family step=license truncated=5"));+ // The same list again: only the summary.+ {+ auto client = MakeClient(script);+ assert(client.FetchAcquisitionDates(Session(), cancel).ok());+ }+ lines = log.Take();+ assert(HasLine(lines, "owner=cm family step=licenses total=305 own=305 borrowed=0 dropped=0 owners=none "+ "flags=0x80:305 changed=n"));+ assert(CountPrefix(lines, "owner=cm family step=license ") == 0);+ // A changed list is written again, a shared license first even past the cap.+ licenses.push_back({5400, 1500000000, 0x4000, 9999, 1});+ auto changed = LicenseScript(licenses, {{5000, {{50}, {51}}}});+ {+ auto client = MakeClient(changed);+ assert(client.FetchAcquisitionDates(Session(), cancel).ok());+ }+ lines = log.Take();+ assert(CountPrefix(lines, "owner=cm family step=license package=") == 300);+ assert(HasLine(lines, "owner=cm family step=license package=5400 owner=9999 flags=0x4000 type=0 created=1500000000 "+ "token=y result=kept reason=borrowed"));+ assert(HasLine(lines, "owner=cm family step=license truncated=6"));+}+void CancelStopsWaiting() {auto script = std::make_shared<Script>();auto client = MakeClient(script, 5000);@@ -771,6 +993,7 @@ std::shared_ptr<Script> DepotScript(std::int32_t key_result, std::uint64_t code)}void DepotAccessReturnsKeysAndManifestCodes() {+ LogCapture log;auto script = DepotScript(cm::kEResultOk, 987654321);auto client = MakeClient(script);std::atomic<bool> cancel{false};@@ -793,6 +1016,28 @@ void DepotAccessReturnsKeysAndManifestCodes() {assert(skipped.ok() && skipped.grants.empty() && skipped.skipped == std::vector<std::uint32_t>{441});auto no_code = MakeClient(DepotScript(cm::kEResultOk, 0));assert(no_code.FetchDepotAccess(Session(), 440, {{441, 11}}, cancel).error == CmError::kRejected);+ // Steam refusing the manifest request code: its EResult is in the detail.+ auto code_refused_script = DepotScript(cm::kEResultOk, 1);+ code_refused_script->on_service = {+ ServerFrame(cm::kEMsgServiceMethodResponse, {}, cm::kEResultAccessDenied, 2)};+ auto code_refused = MakeClient(code_refused_script);+ const auto denied = code_refused.FetchDepotAccess(Session(), 440, {{441, 11}}, cancel);+ assert(denied.error == CmError::kRejected && denied.detail == "manifest request code refused eresult=15");+ // Every depot's key and request code result is logged, with Steam's EResult when refused.+ std::vector<std::string> lines;+ for (auto& line : log.Take())+ if (line.find("step=depot_key") != std::string::npos || line.find("step=manifest_code") != std::string::npos)+ lines.push_back(std::move(line));+ assert(lines == (std::vector<std::string>{+ "owner=cm step=depot_key app=440 depot=441 result=ok",+ "owner=cm step=manifest_code app=440 depot=441 result=ok",+ "owner=cm step=depot_key app=440 depot=441 result=refused eresult=15",+ "owner=cm step=depot_key app=440 depot=441 result=skipped eresult=15",+ "owner=cm step=depot_key app=440 depot=441 result=ok",+ "owner=cm step=manifest_code app=440 depot=441 result=refused code=0",+ "owner=cm step=depot_key app=440 depot=441 result=ok",+ "owner=cm step=manifest_code app=440 depot=441 error=rejected eresult=15",+ }));}void DeviceSeedPersistsPerInstall() {@@ -823,6 +1068,14 @@ int main(int argc, char** argv) {AcquisitionDatesFromGzipMultiLicensesAndMultipartPics();PackageZeroCounts();ResetCmBackoff();+ BorrowedLicensesAreShared();+ ResetCmBackoff();+ OwnLicenseWinsOverBorrowedInEitherOrder();+ ResetCmBackoff();+ BorrowedPackagesPicsSkipsAreLogged();+ ResetCmBackoff();+ FamilyLicenseLinesAreCappedAndOnlyOnChange();+ ResetCmBackoff();RejectedLogonIsReportedWithoutDates();ResetCmBackoff();FailedLicenseListIsRejected();diff --git a/tests/cm_messages_test.cpp b/tests/cm_messages_test.cppindex d1e0f30..886e5d8 100644--- a/tests/cm_messages_test.cpp+++ b/tests/cm_messages_test.cpp@@ -1,6 +1,7 @@#include "steam/backend/binary_kv.h"#include "steam/backend/cm_client.h"#include "steam/backend/cm_messages.h"+#include "steam/backend/proto_wire.h"#include <cassert>#include <fstream>@@ -94,6 +95,32 @@ void FramesRoundTripAndRejectMalformedInput() {assert(decoded.header.steam_id == 76561197960269970ull && decoded.header.session_id == 77);}+// A borrowed license carries the lender's account ID, the Borrowed flag and a license type.+void LicenseOwnerFlagsAndTypeDecode() {+ proto::Writer license;+ license.AddVarint(1, 77);+ license.AddFixed32(2, 1700000000);+ license.AddVarint(7, 0x4000);+ license.AddVarint(9, 10);+ license.AddVarint(12, 9999);+ license.AddVarint(17, 31337);+ proto::Writer body;+ body.AddVarint(1, cm::kEResultOk);+ body.AddMessage(2, license);+ cm::LicenseList list;+ assert(cm::DecodeLicenseList(body.bytes(), &list) && list.licenses.size() == 1);+ const auto& decoded = list.licenses[0];+ assert(decoded.package_id == 77 && decoded.time_created == 1700000000 && decoded.flags == 0x4000);+ assert(decoded.license_type == 10 && decoded.owner_id == 9999 && decoded.access_token == 31337);+ // A license type that is not a varint is malformed.+ proto::Writer bad_entry;+ bad_entry.AddVarint(1, 77);+ bad_entry.AddFixed32(9, 10);+ proto::Writer bad;+ bad.AddMessage(2, bad_entry);+ assert(!cm::DecodeLicenseList(bad.bytes(), &list));+}+void TruncatedMessagesFail() {auto licenses = Fixture("license_list.pb");licenses.resize(licenses.size() - 3);@@ -115,5 +142,6 @@ int main(int argc, char** argv) {ResponsesDecode();LogonResponseFallsBackToLegacyAndDefaultHeartbeat();FramesRoundTripAndRejectMalformedInput();+ LicenseOwnerFlagsAndTypeDecode();TruncatedMessagesFail();}diff --git a/tests/entitled_library_test.cpp b/tests/entitled_library_test.cppindex 11b9b1a..46041f6 100644--- a/tests/entitled_library_test.cpp+++ b/tests/entitled_library_test.cpp@@ -4,7 +4,10 @@#include <atomic>#include <cassert>#include <chrono>+#include <cstdio>#include <map>+#include <memory>+#include <mutex>#include <string>#include <vector>#include <thread>@@ -27,9 +30,11 @@ struct Acquisitions final : AcquisitionSource {std::atomic<bool> saw_stop{false};std::map<std::uint32_t, std::string> app_info;std::vector<std::vector<std::uint32_t>> app_info_requests;+ bool fail_app_info = false;AppInfoBuffers FetchAppInfo(const StoredSession&, const std::vector<std::uint32_t>& ids,const std::atomic<bool>&) override {app_info_requests.push_back(ids);+ if (fail_app_info) return {CmError::kNetwork, {}};AppInfoBuffers result{CmError::kNone, {}};for (const auto id : ids)if (const auto found = app_info.find(id); found != app_info.end()) result.buffers[id] = found->second;@@ -73,6 +78,7 @@ void CmFailureIsNeverFatal() {assert(backend.last_acquisition_error() == CmError::kRejected);}+void OwnedFailureStopsTheCmSession() {Owned owned;owned.result = {LibraryError::kCredentialsRevoked, {}, false};@@ -165,9 +171,375 @@ void LicensedDemosAreAddedAndMarked() {assert(acquisitions.app_info_requests.size() == 1);}+// Declared before the backend in each test: the family probe thread may still log while the backend stops it.+struct Lines {+ std::mutex mutex;+ std::vector<std::string> lines;+ FamilyLog Log() {+ return [this](const std::string& line) {+ std::lock_guard<std::mutex> lock(mutex);+ std::printf("%s\n", line.c_str());+ lines.push_back(line);+ };+ }+ std::size_t Count(const std::string& text) {+ std::lock_guard<std::mutex> lock(mutex);+ return static_cast<std::size_t>(std::count_if(lines.begin(), lines.end(), [&](const auto& line) {+ return line.find(text) != std::string::npos;+ }));+ }+};++// Waits for a line written by the family probe thread.+bool WaitFor(Lines& lines, const std::string& text, std::size_t count = 1) {+ const auto deadline = std::chrono::steady_clock::now() + 5s;+ while (lines.Count(text) < count) {+ if (std::chrono::steady_clock::now() > deadline) return false;+ std::this_thread::sleep_for(1ms);+ }+ return true;+}++const GameSummary* Find(const LibraryResult& result, std::uint32_t app) {+ const auto found = std::find_if(result.games.begin(), result.games.end(),+ [&](const auto& game) { return game.id == SteamId(app); });+ return found == result.games.end() ? nullptr : &*found;+}++// The family probe is off in these: no requests are answered.+FamilyPerform NoFamilyService() {+ return [](const HttpRequest&, const std::atomic<bool>&) {+ HttpResponse response;+ response.error = HttpError::kConnectionFailed;+ return response;+ };+}++// Apps only a family member's licenses grant are added and marked; owned games never are.+void FamilySharedAppsAreMarked() {+ Owned owned;+ Acquisitions acquisitions;+ acquisitions.result.package_apps = {{100, {10, 11}}, // the account's own game and its DLC+ {800, {80}}, // a game borrowed from a family member+ {900, {20, 90}}, // a borrowed bundle with a game the account also owns+ {950, {95}}}; // a free game of the account's own+ acquisitions.result.shared_apps = {80, 90};+ acquisitions.app_info = {{11, AppInfoText(11, "Synthetic DLC", "DLC")},+ {80, AppInfoText(80, "Synthetic Shared", "Game")},+ {90, AppInfoText(90, "Synthetic Bundled", "game")},+ {95, AppInfoText(95, "Synthetic Free", "game")}};+ Lines lines;+ EntitledLibraryBackend backend(owned, acquisitions);+ backend.SetFamilyDiagnostics(NoFamilyService(), lines.Log());+ std::atomic<bool> cancel{false};+ for (int pass = 0; pass < 2; ++pass) {+ const auto result = backend.Fetch(Session(), cancel);+ assert(result.error == LibraryError::kNone && result.games.size() == 5);+ assert(Find(result, 80) && Find(result, 80)->family_shared && Find(result, 80)->title == "Synthetic Shared");+ assert(Find(result, 90) && Find(result, 90)->family_shared);+ assert(Find(result, 95) && !Find(result, 95)->family_shared);+ assert(!Find(result, 10)->family_shared && !Find(result, 20)->family_shared && !Find(result, 11));+ }+ // The package with an owned game is passed over; the borrowed bundle only skips the owned game.+ assert((acquisitions.app_info_requests == std::vector<std::vector<std::uint32_t>>{{80, 90, 95}}));+ // Each shared app is logged once per run; the summary once per load.+ assert(lines.Count("family library added app=80 demo=0") == 1);+ assert(lines.Count("family library added app=90 demo=0") == 1);+ assert(lines.Count("family library shared=2 added=2 left_out=0 pending=0 in_owned_list=0") == 2);+}++// An app the account owns stays unmarked even when a family member's license also grants it.+void OwnedAndBorrowedIsNotShared() {+ Owned owned;+ Acquisitions acquisitions;+ acquisitions.result.package_apps = {{800, {20}}};+ acquisitions.result.shared_apps = {20};+ Lines lines;+ EntitledLibraryBackend backend(owned, acquisitions);+ backend.SetFamilyDiagnostics(NoFamilyService(), lines.Log());+ std::atomic<bool> cancel{false};+ const auto result = backend.Fetch(Session(), cancel);+ assert(result.games.size() == 2 && !Find(result, 20)->family_shared);+ assert(acquisitions.app_info_requests.empty());+ assert(lines.Count("family library shared=1 added=0 left_out=0 pending=0 in_owned_list=1") == 1);+}++// Shared apps PICS doesn't call a named game or demo stay out, with the reason logged.+void SharedAppsLeftOutAreLogged() {+ Owned owned;+ Acquisitions acquisitions;+ acquisitions.result.package_apps = {{810, {81}}, {820, {82}}, {830, {83}}, {840, {84}}};+ acquisitions.result.shared_apps = {81, 82, 83, 84};+ acquisitions.app_info = {{81, AppInfoText(81, "Synthetic DLC", "DLC")},+ {83, AppInfoText(83, "app_83", "game")},+ {84, "not app info"}};+ Lines lines;+ EntitledLibraryBackend backend(owned, acquisitions);+ backend.SetFamilyDiagnostics(NoFamilyService(), lines.Log());+ std::atomic<bool> cancel{false};+ const auto result = backend.Fetch(Session(), cancel);+ assert(result.games.size() == 2);+ assert(lines.Count("family library left_out app=81 reason=type=dlc") == 1);+ assert(lines.Count("family library left_out app=82 reason=no_app_info") == 1);+ assert(lines.Count("family library left_out app=83 reason=no_name") == 1);+ assert(lines.Count("family library left_out app=84 reason=app_info_unreadable") == 1);+ assert(lines.Count("family library shared=4 added=0 left_out=4 pending=0") == 1);+}++// When PICS fails the shared apps are logged as pending and asked again on the next load.+void SharedAppInfoFailureIsRetried() {+ Owned owned;+ Acquisitions acquisitions;+ acquisitions.result.package_apps = {{800, {80}}};+ acquisitions.result.shared_apps = {80};+ acquisitions.app_info = {{80, AppInfoText(80, "Synthetic Shared", "game")}};+ acquisitions.fail_app_info = true;+ Lines lines;+ EntitledLibraryBackend backend(owned, acquisitions);+ backend.SetFamilyDiagnostics(NoFamilyService(), lines.Log());+ std::atomic<bool> cancel{false};+ auto result = backend.Fetch(Session(), cancel);+ assert(result.games.size() == 2 && !Find(result, 80));+ assert(lines.Count("family library left_out app=80 reason=app_info_failed") == 1);+ assert(lines.Count("family library shared=1 added=0 left_out=0 pending=1") == 1);+ acquisitions.fail_app_info = false;+ result = backend.Fetch(Session(), cancel);+ assert(Find(result, 80) && Find(result, 80)->family_shared);+ assert(lines.Count("family library added app=80") == 1);+}++HttpResponse Json(const std::string& body, long status = 200) {+ HttpResponse response;+ response.status_code = status;+ response.body.assign(body.begin(), body.end());+ return response;+}++// Without licenses the family log says so, and the probe still reports without comparing.+void CmFailureIsLoggedForFamily() {+ Owned owned;+ Acquisitions acquisitions;+ acquisitions.result = {CmError::kRejected, {}};+ Lines lines;+ EntitledLibraryBackend backend(owned, acquisitions);+ backend.SetFamilyDiagnostics(+ [](const HttpRequest& request, const std::atomic<bool>&) {+ if (request.url.find("GetFamilyGroupForUser") != std::string::npos)+ return Json(R"({"response":{"family_groupid":"42"}})");+ return Json(R"({"response":{"apps":[{"appid":80,"owner_steamids":["5"]}]}})");+ },+ lines.Log());+ std::atomic<bool> cancel{false};+ const auto result = backend.Fetch(Session(), cancel);+ assert(result.error == LibraryError::kNone && result.games.size() == 2);+ assert(lines.Count("family library licenses=unavailable cm_error=rejected") == 1);+ assert(WaitFor(lines, "family webapi app=80 owners=5 exclude_reason=0 licensed=?"));+ assert(lines.Count("family webapi shared_apps=1 excluded=0 owners=1 unlicensed=? licenses=unknown") == 1);+ assert(lines.Count("family webapi app=80 owners=5 exclude_reason=0 licensed=?") == 1);+}++// The family service is asked once per run while the library loads; what it says only reaches the log.+void FamilyServiceIsAskedOncePerRun() {+ Owned owned;+ Acquisitions acquisitions;+ acquisitions.result.package_apps = {{800, {80}}};+ acquisitions.result.owned_apps = {10, 80};+ acquisitions.result.shared_apps = {80};+ acquisitions.app_info = {{80, AppInfoText(80, "Synthetic Shared", "game")}};+ Lines lines;+ std::atomic<int> requests{0};+ EntitledLibraryBackend backend(owned, acquisitions);+ backend.SetFamilyDiagnostics(+ [&requests](const HttpRequest& request, const std::atomic<bool>&) {+ ++requests;+ if (request.url.find("GetFamilyGroupForUser") != std::string::npos)+ return Json(R"({"response":{"family_groupid":"42","role":2,"family_group":{"members":[{"steamid":"5","role":1}]}}})");+ return Json(R"({"response":{"apps":[{"appid":80,"owner_steamids":["5"]},{"appid":81,"owner_steamids":["5"]}]}})");+ },+ lines.Log());+ std::atomic<bool> cancel{false};+ auto result = backend.Fetch(Session(), cancel);+ assert(result.error == LibraryError::kNone && result.games.size() == 3);+ assert(WaitFor(lines, "family webapi app=81 "));+ result = backend.Fetch(Session(), cancel);+ assert(result.games.size() == 3 && requests == 2);+ assert(lines.Count("family webapi group=y family_groupid=42 role=2 members=1 member=5:1") == 1);+ assert(lines.Count("family webapi shared_apps=2 excluded=0 owners=1 unlicensed=1 licenses=known") == 1);+ assert(lines.Count("family webapi app=80 owners=5 exclude_reason=0 licensed=shared") == 1);+ assert(lines.Count("family webapi app=81 owners=5 exclude_reason=0 licensed=n") == 1);+ assert(lines.Count("access") == 0);+}++// A family compared with no licenses (the load that started the probe had none) is asked again by the next+// load, which compares it with that load's own licenses.+void FamilyWithoutLicensesIsAskedAgain() {+ Owned owned;+ Acquisitions acquisitions;+ acquisitions.result = {CmError::kNetwork, {}};+ Lines lines;+ std::atomic<int> requests{0};+ EntitledLibraryBackend backend(owned, acquisitions);+ backend.SetFamilyDiagnostics(+ [&requests](const HttpRequest& request, const std::atomic<bool>&) {+ ++requests;+ if (request.url.find("GetFamilyGroupForUser") != std::string::npos)+ return Json(R"({"response":{"family_groupid":"42","role":2}})");+ return Json(R"({"response":{"apps":[{"appid":80,"owner_steamids":["5"]}]}})");+ },+ lines.Log());+ std::atomic<bool> cancel{false};+ backend.Fetch(Session(), cancel);+ assert(WaitFor(lines, "licenses=unknown"));+ while (requests < 2) std::this_thread::sleep_for(1ms);+ std::this_thread::sleep_for(100ms); // the probe thread finishes after its last line+ acquisitions.result = AcquisitionResult{CmError::kNone, {}};+ acquisitions.result.package_apps = {{800, {80}}};+ acquisitions.result.owned_apps = {80};+ acquisitions.result.shared_apps = {80};+ acquisitions.app_info = {{80, AppInfoText(80, "Synthetic Shared", "game")}};+ backend.Fetch(Session(), cancel);+ assert(WaitFor(lines, "family webapi app=80 owners=5 exclude_reason=0 licensed=shared"));+ assert(requests == 4 && lines.Count("licenses=known") == 1);+}++// A failing family service never fails a load and is tried again by a later one, one probe at a time.+void FamilyServiceNeverFailsTheLoad() {+ Owned owned;+ Acquisitions acquisitions;+ Lines lines;+ std::atomic<int> requests{0};+ EntitledLibraryBackend backend(owned, acquisitions);+ backend.SetFamilyDiagnostics(+ [&](const HttpRequest&, const std::atomic<bool>&) {+ ++requests;+ HttpResponse response;+ response.error = HttpError::kTimeout;+ return response;+ },+ lines.Log());+ std::atomic<bool> cancel{false};+ auto result = backend.Fetch(Session(), cancel);+ assert(result.error == LibraryError::kNone && result.games.size() == 2);+ assert(WaitFor(lines, "family webapi step=group error=timeout"));+ // A failure is tried again by a later load, never twice by one.+ const auto deadline = std::chrono::steady_clock::now() + 5s;+ int loads = 1;+ while (requests < 2 && std::chrono::steady_clock::now() < deadline) {+ result = backend.Fetch(Session(), cancel);+ ++loads;+ assert(result.error == LibraryError::kNone && requests <= loads);+ }+ assert(WaitFor(lines, "family webapi step=group error=timeout", 2));+}++// A stalled family service holds up neither a load (not even an uncanceled one) nor the backend's+// destruction, and a second probe never starts beside it.+void StalledFamilyServiceHoldsNothingUp() {+ Owned owned;+ Acquisitions acquisitions;+ Lines lines;+ std::atomic<int> requests{0};+ auto backend = std::make_unique<EntitledLibraryBackend>(owned, acquisitions);+ backend->SetFamilyDiagnostics(+ [&](const HttpRequest&, const std::atomic<bool>& stop) {+ ++requests;+ while (!stop) std::this_thread::sleep_for(1ms);+ HttpResponse response;+ response.error = HttpError::kCanceled;+ return response;+ },+ lines.Log());+ std::atomic<bool> cancel{false};+ auto start = std::chrono::steady_clock::now();+ auto result = backend->Fetch(Session(), cancel);+ assert(std::chrono::steady_clock::now() - start < 1s);+ assert(result.error == LibraryError::kNone && result.games.size() == 2);+ while (requests == 0) std::this_thread::sleep_for(1ms);+ result = backend->Fetch(Session(), cancel);+ assert(result.error == LibraryError::kNone && requests == 1);+ start = std::chrono::steady_clock::now();+ backend.reset();+ assert(std::chrono::steady_clock::now() - start < 1s);+ assert(requests == 1 && lines.Count("family webapi") == 0);+}++// A family service that answers after the load returned is still logged and compared with its licenses.+void LateFamilyAnswerIsLogged() {+ Owned owned;+ Acquisitions acquisitions;+ acquisitions.result.owned_apps = {10, 80};+ acquisitions.result.shared_apps = {80};+ Lines lines;+ std::atomic<bool> release{false};+ EntitledLibraryBackend backend(owned, acquisitions);+ backend.SetFamilyDiagnostics(+ [&release](const HttpRequest& request, const std::atomic<bool>& stop) {+ if (request.url.find("GetFamilyGroupForUser") != std::string::npos) {+ while (!release && !stop) std::this_thread::sleep_for(1ms);+ return Json(R"({"response":{"family_groupid":"42"}})");+ }+ return Json(R"({"response":{"apps":[{"appid":80,"owner_steamids":["5"]},{"appid":81,"owner_steamids":["5"]}]}})");+ },+ lines.Log());+ std::atomic<bool> cancel{false};+ const auto result = backend.Fetch(Session(), cancel);+ assert(result.error == LibraryError::kNone && lines.Count("family webapi") == 0);+ release = true;+ // The last line the probe writes.+ assert(WaitFor(lines, "family webapi app=81 owners=5 exclude_reason=0 licensed=n"));+ assert(lines.Count("family webapi shared_apps=2 excluded=0 owners=1 unlicensed=1 licenses=known") == 1);+ assert(lines.Count("family webapi app=80 owners=5 exclude_reason=0 licensed=shared") == 1);+}++// Per-app family lines stay bounded per load, and a lookup that keeps failing is logged once per app.+void FamilyAppLinesAreCapped() {+ Owned owned;+ Acquisitions acquisitions;+ for (std::uint32_t app = 1000; app < 1300; ++app) {+ acquisitions.result.package_apps[app] = {app};+ acquisitions.result.shared_apps.insert(app);+ acquisitions.app_info[app] = AppInfoText(app, "Synthetic " + std::to_string(app), "game");+ }+ acquisitions.fail_app_info = true;+ Lines lines;+ EntitledLibraryBackend backend(owned, acquisitions);+ backend.SetFamilyDiagnostics(NoFamilyService(), lines.Log());+ std::atomic<bool> cancel{false};+ const auto load = [&] {+ const auto before = lines.Count("family library ");+ backend.Fetch(Session(), cancel);+ return lines.Count("family library ") - before;+ };+ // Each load writes at most 100 per-app lines, a truncated line and the summary; no app repeats.+ assert(load() == 102 && lines.Count("reason=app_info_failed") == 100);+ assert(lines.Count("family library truncated=200") == 1);+ assert(lines.Count("family library shared=300 added=0 left_out=0 pending=300") == 1);+ assert(load() == 102 && lines.Count("reason=app_info_failed") == 200 &&+ lines.Count("family library truncated=100") == 1);+ assert(load() == 101 && lines.Count("reason=app_info_failed") == 300);+ assert(load() == 1 && lines.Count("reason=app_info_failed") == 300);+ for (std::uint32_t app = 1000; app < 1300; ++app)+ assert(lines.Count("family library left_out app=" + std::to_string(app) + " reason=app_info_failed") == 1);+ assert(lines.Count("family library shared=300 added=0 left_out=0 pending=300") == 4);+ acquisitions.fail_app_info = false;+ assert(load() == 102 && lines.Count("family library added app=") == 100);+ assert(lines.Count("family library shared=300 added=300 left_out=0 pending=0") == 1);+}+} // namespaceint main() {+ FamilySharedAppsAreMarked();+ OwnedAndBorrowedIsNotShared();+ SharedAppsLeftOutAreLogged();+ SharedAppInfoFailureIsRetried();+ FamilyServiceIsAskedOncePerRun();+ FamilyServiceNeverFailsTheLoad();+ FamilyWithoutLicensesIsAskedAgain();+ StalledFamilyServiceHoldsNothingUp();+ LateFamilyAnswerIsLogged();+ FamilyAppLinesAreCapped();+ CmFailureIsLoggedForFamily();LicensedFreeGamesAreAdded();LicensedDemosAreAddedAndMarked();DatesMergeIntoOwnedGames();diff --git a/tests/family_groups_test.cpp b/tests/family_groups_test.cppnew file mode 100644index 0000000..1485e37--- /dev/null+++ b/tests/family_groups_test.cpp@@ -0,0 +1,202 @@+// SPDX-License-Identifier: GPL-3.0-or-later+#include "steam/backend/family_groups.h"++#include <algorithm>+#include <atomic>+#include <cassert>+#include <cstdio>+#include <string>+#include <vector>++using namespace playden;+using namespace playden::steam;++namespace {++const char* kGroup = R"({"response":{"family_groupid":"9876543210","is_not_member_of_any_group":false,+ "latest_time_joined":1700000000,"role":1,"cooldown_seconds_remaining":0,"pending_group_invites":[],+ "family_group":{"name":"Synthetic Family","members":[+ {"steamid":"76561198000000001","role":1,"time_joined":1700000000,"cooldown_seconds_remaining":0},+ {"steamid":76561198000000002,"role":2,"time_joined":1700000001}],+ "free_spots":4,"country":"BR","slot_cooldown_remaining_seconds":0},+ "can_undelete_last_joined_family":false}})";++const char* kApps = R"({"response":{"apps":[+ {"appid":620,"owner_steamids":["76561198000000002"],"name":"Synthetic Shared","capsule_filename":"c.jpg",+ "img_icon_hash":"abc","exclude_reason":0,"rt_time_acquired":1600000000,"app_type":1,"content_descriptors":[]},+ {"appid":"730","owner_steamids":["76561198000000002","76561198000000003"],"exclude_reason":0},+ {"appid":440,"owner_steamids":["76561198000000003"],"exclude_reason":3},+ {"appid":"not a number"},+ {"appid":0},+ "unexpected"],+ "owner_steamid":"76561198000000001"}})";++HttpResponse Json(const std::string& body, long status = 200) {+ HttpResponse response;+ response.status_code = status;+ response.body.assign(body.begin(), body.end());+ return response;+}++StoredSession Session() { return {76561198000000001ULL, "synthetic", "refresh", "secret token/+", 7}; }++struct Fake {+ std::vector<HttpRequest> requests;+ std::vector<HttpResponse> responses;+ std::vector<std::string> lines;+ FamilyPerform Perform() {+ return [this](const HttpRequest& request, const std::atomic<bool>&) {+ requests.push_back(request);+ if (responses.empty()) return Json("", 500);+ auto response = responses.front();+ responses.erase(responses.begin());+ return response;+ };+ }+ FamilyLog Log() {+ return [this](const std::string& line) {+ std::printf("%s\n", line.c_str());+ lines.push_back(line);+ };+ }+ bool Has(const std::string& text) const {+ return std::any_of(lines.begin(), lines.end(), [&](const auto& line) { return line.find(text) != std::string::npos; });+ }+ bool Leaks() const {+ return std::any_of(lines.begin(), lines.end(), [](const auto& line) {+ return line.find("secret") != std::string::npos || line.find("access_token") != std::string::npos ||+ line.find("api.steampowered") != std::string::npos;+ });+ }+};++void ParsesAGroup() {+ const auto group = ParseFamilyGroup(kGroup);+ assert(group && group->family_groupid == 9876543210ULL && !group->not_member && group->role == 1u);+ assert(group->members.size() == 2 && group->members[0].steamid == 76561198000000001ULL &&+ group->members[1].steamid == 76561198000000002ULL && group->members[1].role == 2u);+}++void ParsesNoGroup() {+ auto group = ParseFamilyGroup(R"({"response":{}})");+ assert(group && !group->family_groupid && group->members.empty() && !group->role);+ group = ParseFamilyGroup(R"({"response":{"is_not_member_of_any_group":true,"family_groupid":"0"}})");+ assert(group && !group->family_groupid && group->not_member);+ assert(!ParseFamilyGroup(""));+ assert(!ParseFamilyGroup("<html>"));+ assert(!ParseFamilyGroup(R"({"response":[]})"));+ assert(!ParseFamilyGroup(R"({})"));+}++void ParsesSharedApps() {+ const auto library = ParseSharedLibraryApps(kApps);+ assert(library && library->apps.size() == 3);+ assert(library->apps[0].appid == 620 && library->apps[0].owners == std::vector<std::uint64_t>{76561198000000002ULL});+ assert(library->apps[1].appid == 730 && library->apps[1].owners.size() == 2 && !library->apps[1].exclude_reason);+ assert(library->apps[2].appid == 440 && library->apps[2].exclude_reason == 3);+ const auto empty = ParseSharedLibraryApps(R"({"response":{}})");+ assert(empty && empty->apps.empty());+ assert(!ParseSharedLibraryApps("not json"));+}++// The family lists 620 (licensed here through the family), 730 (no license arrived) and 440 (excluded).+void LogsTheGroupAndTheUnlicensedApps() {+ Fake fake;+ fake.responses = {Json(kGroup), Json(kApps)};+ AcquisitionResult licenses;+ licenses.error = CmError::kNone;+ licenses.owned_apps = {620, 10};+ licenses.shared_apps = {620};+ std::atomic<bool> cancel{false};+ RunFamilyDiagnostics(Session(), &licenses, fake.Perform(), fake.Log(), cancel);+ assert(fake.requests.size() == 2);+ assert(fake.requests[0].url.find("/IFamilyGroupsService/GetFamilyGroupForUser/v1/") != std::string::npos);+ assert(fake.requests[0].url.find("access_token=secret%20token%2F%2B") != std::string::npos);+ assert(fake.requests[0].url.find("steamid=76561198000000001") != std::string::npos);+ assert(fake.requests[1].url.find("/IFamilyGroupsService/GetSharedLibraryApps/v1/") != std::string::npos);+ assert(fake.requests[1].url.find("family_groupid=9876543210") != std::string::npos);+ assert(fake.requests[1].url.find("include_own=false") != std::string::npos);+ assert(fake.requests[1].url.find("include_excluded=true") != std::string::npos);+ assert(fake.requests[0].timeout_ms <= 10000 && fake.requests[1].timeout_ms <= 10000);+ assert(fake.Has("family webapi group=y family_groupid=9876543210 role=1 members=2 member=76561198000000001:1 "+ "member=76561198000000002:2"));+ assert(fake.Has("family webapi shared_apps=3 excluded=1 owners=2 unlicensed=1 licenses=known license_shared_apps=1"));+ assert(fake.Has("family webapi app=620 owners=76561198000000002 exclude_reason=0 licensed=shared"));+ assert(fake.Has("family webapi app=730 owners=76561198000000002,76561198000000003 exclude_reason=0 licensed=n"));+ assert(fake.Has("family webapi app=440 owners=76561198000000003 exclude_reason=3 licensed=n"));+ assert(!fake.Leaks());+}++void LogsNoGroupWithoutAskingForApps() {+ for (const char* body : {R"({"response":{}})", R"({"response":{"is_not_member_of_any_group":true}})"}) {+ Fake fake;+ fake.responses = {Json(body)};+ std::atomic<bool> cancel{false};+ RunFamilyDiagnostics(Session(), nullptr, fake.Perform(), fake.Log(), cancel);+ assert(fake.requests.size() == 1 && fake.lines.size() == 1);+ assert(fake.Has("family webapi group=n not_member="));+ }+}++void FailuresAreLogLines() {+ {+ Fake fake;+ auto refused = Json("", 403);+ refused.headers = {{"X-eresult", "15"}};+ fake.responses = {refused};+ std::atomic<bool> cancel{false};+ RunFamilyDiagnostics(Session(), nullptr, fake.Perform(), fake.Log(), cancel);+ assert(fake.lines.size() == 1 && fake.Has("family webapi step=group http=403 eresult=15"));+ }+ {+ Fake fake;+ HttpResponse timeout;+ timeout.error = HttpError::kTimeout;+ fake.responses = {timeout};+ std::atomic<bool> cancel{false};+ RunFamilyDiagnostics(Session(), nullptr, fake.Perform(), fake.Log(), cancel);+ assert(fake.lines.size() == 1 && fake.Has("family webapi step=group error=timeout"));+ }+ {+ Fake fake;+ fake.responses = {Json(kGroup), Json("garbage")};+ std::atomic<bool> cancel{false};+ RunFamilyDiagnostics(Session(), nullptr, fake.Perform(), fake.Log(), cancel);+ assert(fake.Has("family webapi step=apps error=unreadable bytes=7") && !fake.Has("shared_apps="));+ assert(!fake.Leaks());+ }+ {+ Fake fake;+ std::atomic<bool> cancel{true};+ RunFamilyDiagnostics(Session(), nullptr, fake.Perform(), fake.Log(), cancel);+ assert(fake.requests.empty() && fake.lines.empty());+ }+}++void AppLinesAreCapped() {+ std::string apps = R"({"response":{"apps":[)";+ for (int i = 1; i <= 250; ++i) apps += (i > 1 ? "," : "") + std::string(R"({"appid":)") + std::to_string(i) + "}";+ apps += "]}}";+ Fake fake;+ fake.responses = {Json(kGroup), Json(apps)};+ std::atomic<bool> cancel{false};+ RunFamilyDiagnostics(Session(), nullptr, fake.Perform(), fake.Log(), cancel);+ const auto app_lines = std::count_if(fake.lines.begin(), fake.lines.end(),+ [](const auto& line) { return line.find("family webapi app=") == 0; });+ assert(app_lines == 200 && fake.Has("family webapi truncated=50"));+ assert(fake.Has("family webapi shared_apps=250 excluded=0 owners=0 unlicensed=? licenses=unknown"));+ assert(fake.Has("family webapi app=1 owners=- exclude_reason=0 licensed=?"));+}++} // namespace++int main() {+ ParsesAGroup();+ ParsesNoGroup();+ ParsesSharedApps();+ LogsTheGroupAndTheUnlicensedApps();+ LogsNoGroupWithoutAskingForApps();+ FailuresAreLogLines();+ AppLinesAreCapped();+ std::puts("family_groups_test passed");+}diff --git a/tests/homebrew_browse_test.cpp b/tests/homebrew_browse_test.cppindex e300199..7994764 100644--- a/tests/homebrew_browse_test.cpp+++ b/tests/homebrew_browse_test.cpp@@ -90,6 +90,15 @@ void filtering_uses_real_fixture(const std::filesystem::path& fixtures)state.library.ratings.erase(SteamId(900010));state.library.filters.clear();demo.demo = false;+ demo.family_shared = true;+ check(filtered_games(state).size() == every_game, "family-shared games show with no filter");+ state.library.filters = {"hide-family"};+ const auto owned = filtered_games(state);+ check(owned.size() == every_game - 1 &&+ std::none_of(owned.begin(), owned.end(), [](const Game* game) { return game->family_shared; }),+ "hiding family sharing leaves the owned games");+ state.library.filters.clear();+ demo.family_shared = false;state.account().authentication = AuthState::SignedOut;state.account().cache_available = false;check(filtered_games(state).empty(), "signed out without cache has no browsable catalog");diff --git a/tests/homebrew_library_model_test.cpp b/tests/homebrew_library_model_test.cppindex 4a12684..687374b 100644--- a/tests/homebrew_library_model_test.cpp+++ b/tests/homebrew_library_model_test.cpp@@ -923,6 +923,47 @@ void live_demos_filter_defaults_on() {check(row!=nullptr && !row->selected,"Demos stays listed while demos are hidden");}+// A game a Steam family member shares keeps that mark in the Library; the rest of the library does not.+void live_family_shared_projected() {+ auto model=make_live();+ model.UpdateAccount({AuthState::SignedIn,"123","Synthetic",{},{},true});+ auto shared=game(SteamId(43),"Synthetic Shared");shared.family_shared=true;+ check(model.UpdateLibrary({{game(SteamId(42),"Synthetic"),shared},false,{},false,false,{}}),"library with a shared game loaded");+ check(model.state().games.back().family_shared && !model.state().games.front().family_shared,"family mark projected");+ check(model.action("r1") && model.visible_games().size()==2,"shared games show with the rest");+}++// Family sharing works like Demos: on by default, turning it off hides shared games and is saved, and the+// row is listed only while the library has a shared game or they are hidden.+void live_family_filter_defaults_on() {+ auto model=make_live();+ model.UpdateAccount({AuthState::SignedIn,"123","Synthetic",{},{},true});+ check(model.UpdateLibrary({{game(SteamId(42),"Synthetic")},false,{},false,false,{}}),"library without shared games loaded");+ check(model.action("r1") && model.action("triangle"),"live filter modal opens");+ check(find_row(model,"filter-hide-family")==nullptr,"a library without shared games has no Family sharing row");+ model.action("circle");++ auto shared=game(SteamId(43),"Synthetic Shared");shared.family_shared=true;auto demo=game(SteamId(44),"Synthetic Demo");demo.demo=true;+ check(model.UpdateLibrary({{game(SteamId(42),"Synthetic"),shared,demo},false,{},false,false,{}}),"library with a shared game loaded");+ check(model.action("triangle"),"filter modal opens");+ const auto* row=find_row(model,"filter-hide-family");+ check(row!=nullptr && row->title=="Family sharing" && row->kind==RowKind::Toggle && row->selected && row->value=="On",+ "Family sharing is a toggle, on");+ activate(model,"filter-hide-family");+ check(model.visible_games().size()==2 && model.ExportOrganization().filters==std::set<std::string>{"hide-family"},+ "turning Family sharing off hides the shared game and is saved");+ check(model.action("triangle"),"filter modal opens again");+ activate(model,"filter-hide-demos");+ check(model.visible_games().size()==1 && model.visible_games().front()->id==SteamId(42),"both filters compose");+ check(model.ExportOrganization().filters==std::set<std::string>{"hide-demos","hide-family"},"both hidden kinds are saved");+ check(model.action("triangle"),"filter modal opens again");+ row=find_row(model,"filter-hide-family");+ check(row!=nullptr && !row->selected && row->value=="Off","Family sharing shows off");+ activate(model,"filter-hide-family");+ check(model.visible_games().size()==2 && model.ExportOrganization().filters==std::set<std::string>{"hide-demos"},+ "turning Family sharing on shows it again");+}+// Sort and filters offers Refresh library: it asks the controller for Steam's current list and the// Library stays on screen. While a refresh runs, the row waits.void live_sort_sheet_refreshes_the_library() {@@ -3356,6 +3397,8 @@ int main() {live_store_without_cloud_never_asks_the_cloud();live_filters_only_use_available_facts();live_demos_filter_defaults_on();+ live_family_shared_projected();+ live_family_filter_defaults_on();live_sort_sheet_refreshes_the_library();continue_playing_more_keeps_the_chosen_sort();live_empty_filter_keeps_the_signed_in_account();diff --git a/tests/homebrew_simulation_test.cpp b/tests/homebrew_simulation_test.cppindex 2b9ed01..50218c3 100644--- a/tests/homebrew_simulation_test.cpp+++ b/tests/homebrew_simulation_test.cpp@@ -704,6 +704,19 @@ void t11_preferences_failure_and_controller_modal_recovery(const std::filesystem}}+// The family-sharing fixture marks a few games shared by a Steam family member and leaves the rest owned.+void family_sharing_scenario_marks_shared_games(const std::filesystem::path& fixtures,+ const std::filesystem::path& profile) {+ playden::homebrew::Simulation simulation(fixtures, profile);+ const auto count = simulation.state().games.size();+ check(simulation.scenario("family-sharing"), "family-sharing scenario loads");+ const auto& games = simulation.state().games;+ const auto shared = std::count_if(games.begin(), games.end(), [](const playden::homebrew::Game& game) { return game.family_shared; });+ check(games.size() == count && shared > 0 && static_cast<std::size_t>(shared) < count,+ "family-sharing marks some fixture games shared without adding games");+ check(simulation.snapshot().find("\"route\":\"library\"") != std::string::npos, "family-sharing opens the Library");+}+void t12_stress_dataset_keeps_logical_focus(const std::filesystem::path& fixtures,const std::filesystem::path& profile) {playden::homebrew::Simulation simulation(fixtures, profile);@@ -1489,6 +1502,8 @@ int main(int argc, char** argv) {clean();t12_stress_dataset_keeps_logical_focus(fixtures, profile);clean();+ family_sharing_scenario_marks_shared_games(fixtures, profile);+ clean();t13_settings_sections_rail(fixtures, profile);clean();t14_tab_bar_from_the_top_of_a_page(fixtures, profile);diff --git a/tests/library_cache_test.cpp b/tests/library_cache_test.cppindex 80641db..6464dc9 100644--- a/tests/library_cache_test.cpp+++ b/tests/library_cache_test.cpp@@ -74,6 +74,18 @@ int main(){auto lossy_demos=demos;lossy_demos.schema_version=5;Check(!cache.Save("76561198000000006",lossy_demos).ok(),"schema five cannot silently discard demos");Check(!dated_restored.value().games[0].demo,"older schemas hold no demos");+ LibrarySnapshot shared{7,123462,{{SteamId(70),"Synthetic Shared","","",""},{SteamId(71),"Owned Game","","",""},{SteamId(72),"Shared Demo","","",""}}};+ shared.games[0].family_shared=true;shared.games[0].added_at_unix_seconds=1650000000;+ shared.games[2].family_shared=true;shared.games[2].demo=true;+ Check(cache.Save("76561198000000007",shared).ok(),"save schema seven family-shared games");+ auto shared_restored=cache.Load("76561198000000007");+ Check(shared_restored.ok()&&shared_restored.value().schema_version==7,"load schema seven");+ Check(shared_restored.value().games[0].family_shared&&shared_restored.value().games[0].added_at_unix_seconds==1650000000u&&+ !shared_restored.value().games[0].demo&&!shared_restored.value().games[1].family_shared&&+ shared_restored.value().games[2].family_shared&&shared_restored.value().games[2].demo,"family mark roundtrip next to demos; owned games stay unmarked");+ auto lossy_shared=shared;lossy_shared.schema_version=6;+ Check(!cache.Save("76561198000000007",lossy_shared).ok(),"schema six cannot silently discard family sharing");+ Check(!demos_restored.value().games[0].family_shared&&!dated_restored.value().games[0].family_shared,"older schemas hold no family sharing");auto zero_dated=dated;zero_dated.games[0].added_at_unix_seconds=0;Check(!cache.Save("76561198000000005",zero_dated).ok(),"zero acquisition date rejected");auto future=partial;future.retrieved_at_unix_seconds=std::uint64_t{1}<<63;diff --git a/tests/library_organization_test.cpp b/tests/library_organization_test.cppindex 40aac75..dd5d367 100644--- a/tests/library_organization_test.cpp+++ b/tests/library_organization_test.cpp@@ -353,6 +353,7 @@ void V2RoundTripsEveryStore() {expected.notes[kLocalGame] = "Imported";expected.selected_game_id = kLocalGame;expected.filters.insert("hide-demos");+ expected.filters.insert("hide-family");Check(playden::OrganizationSnapshotIsValid(expected), "a Local game is valid organization");Check(store.Save(kDevice, expected).ok(), "device organization saves");const auto restored = store.Load(kDevice);@@ -364,7 +365,11 @@ void V2RoundTripsEveryStore() {Check(!store.SaveV1(kFirstAccount, v1_demos).ok(), "version 1 cannot hold hidden demos");auto three_filters = expected;three_filters.filters.insert("controller-full");- Check(!store.Save(kDevice, three_filters).ok(), "version 2 holds at most Playable and hidden demos");+ Check(!store.Save(kDevice, three_filters).ok(), "version 2 holds at most Playable, hidden demos and hidden family games");+ auto v1_family = Example();+ v1_family.schema_version = 1;+ v1_family.filters = {"hide-family"};+ Check(!store.SaveV1(kFirstAccount, v1_family).ok(), "version 1 cannot hold hidden family games");playden::OrganizationSnapshot unselected;Check(store.Save(kDevice, unselected).ok(), "no selection saves");const auto empty = store.Load(kDevice);diff --git a/tests/library_sync_test.cpp b/tests/library_sync_test.cppindex 5d1b091..2004456 100644--- a/tests/library_sync_test.cpp+++ b/tests/library_sync_test.cpp@@ -43,4 +43,6 @@ void GenerationsAndNoCache(){Sessions s;Backend b;LibraryService service(b,s);se// A library with demos is saved as schema 6, the first that can mark them; one without keeps the older schema.void DemosChooseTheCacheSchema(){Sessions s;Backend b;Cache c;LibraryService service(b,s,&c,[]{return std::uint64_t{2000};});service.Refresh(123,1);Until(service,LibraryEventKind::kComplete);{std::lock_guard<std::mutex>l(c.mutex);assert(c.snapshots[123].schema_version==4);}b.result.games[0].demo=true;service.Refresh(123,1);auto e=Until(service,LibraryEventKind::kComplete);assert(e.back().games[0].demo);std::lock_guard<std::mutex>l(c.mutex);assert(c.snapshots[123].schema_version==6&&c.snapshots[123].games[0].demo);}void AcquisitionDatesCarryForward(){Sessions s;Backend b;Cache c;auto cached=Snapshot(1);cached.games[0].added_at_unix_seconds=900;c.snapshots[123]=cached;LibraryService service(b,s,&c,[]{return std::uint64_t{2000};});service.Refresh(123,1);auto e=Until(service,LibraryEventKind::kComplete);assert(e.back().games[0].added_at_unix_seconds==900u);{std::lock_guard<std::mutex>l(c.mutex);assert(c.snapshots[123].games[0].added_at_unix_seconds==900u);}b.result.games[0].added_at_unix_seconds=1000;service.Refresh(123,1);e=Until(service,LibraryEventKind::kComplete);assert(e.back().games[0].added_at_unix_seconds==1000u);}-int main(){AcquisitionDatesCarryForward();DemosChooseTheCacheSchema();CachedThenNetworkAndSave();OfflineCacheOnly();FailureAndSaveError();AccountSwitchDuringLoad();SessionIdentityPrecedesCache();ClearWaitsForSave();ClearFailureAndShutdown();ShutdownCancelsNetwork();GenerationsAndNoCache();}+// Only a library with a family-shared game needs schema 7; demos alone stay at 6 and plain libraries at 4.+void FamilySharedGamesChooseTheCacheSchema(){Sessions s;Backend b;Cache c;LibraryService service(b,s,&c,[]{return std::uint64_t{2000};});b.result.games[0].demo=true;service.Refresh(123,1);Until(service,LibraryEventKind::kComplete);{std::lock_guard<std::mutex>l(c.mutex);assert(c.snapshots[123].schema_version==6);}b.result.games[0].demo=false;b.result.games[0].family_shared=true;service.Refresh(123,1);auto e=Until(service,LibraryEventKind::kComplete);assert(e.back().games[0].family_shared);{std::lock_guard<std::mutex>l(c.mutex);assert(c.snapshots[123].schema_version==7&&c.snapshots[123].games[0].family_shared);}b.result.games[0].family_shared=false;service.Refresh(123,1);Until(service,LibraryEventKind::kComplete);std::lock_guard<std::mutex>l(c.mutex);assert(c.snapshots[123].schema_version==4&&!c.snapshots[123].games[0].family_shared);}+int main(){AcquisitionDatesCarryForward();DemosChooseTheCacheSchema();FamilySharedGamesChooseTheCacheSchema();CachedThenNetworkAndSave();OfflineCacheOnly();FailureAndSaveError();AccountSwitchDuringLoad();SessionIdentityPrecedesCache();ClearWaitsForSave();ClearFailureAndShutdown();ShutdownCancelsNetwork();GenerationsAndNoCache();}