Play your Steam library's Windows games on a jailbroken PS5.
C++
Fix the license check notice and shared session waits
Leonardo Lobatoc93d9028fc2c
diff --git a/src/homebrew/controller.cpp b/src/homebrew/controller.cppindex 9e24e8f..025e687 100644--- a/src/homebrew/controller.cpp+++ b/src/homebrew/controller.cpp@@ -1120,7 +1120,7 @@ void Controller::TickInstalls() {model_.UpdateVolumes(volumes, snapshot.default_volume_id);volume_refreshed_at_ = now;}- if (snapshot.revision == install_revision_ && !account_changed) return;+ if (snapshot.revision == install_revision_ && !account_changed && !licenses_due) return;install_revision_ = snapshot.revision;install_generation_ = model_.state().account_generation;std::vector<LiveInstallJob> jobs;diff --git a/src/homebrew/simulation.cpp b/src/homebrew/simulation.cppindex f2f8149..34cbc3b 100644--- a/src/homebrew/simulation.cpp+++ b/src/homebrew/simulation.cpp@@ -5396,6 +5396,7 @@ void Simulation::advance_jobs() {if (active->state == JobState::Downloading) {const auto* volume = find_volume(state_, active->volume_id);if (!volume || !volume->available) { active->state = JobState::Interrupted; active->failure = "Storage disconnected"; return; }+ if (active->checking_licenses) return; // an injected license check holds the transferactive->completed_bytes = std::min(active->total_bytes, active->completed_bytes + kTransferPerTick);if (active->completed_bytes >= active->total_bytes) { active->stage = JobStage::Verify; active->state = JobState::Verifying; active->stage_ticks = 0; }} else if (active->state == JobState::Verifying) {diff --git a/src/homebrew/view.cpp b/src/homebrew/view.cppindex 94239ed..c792d4d 100644--- a/src/homebrew/view.cpp+++ b/src/homebrew/view.cpp@@ -1551,7 +1551,7 @@ class Render::Impl{if (status.job != nullptr){- if (status.job->checking_licenses)+ if (status.job->state == JobState::Downloading && status.job->checking_licenses)return "Checking licenses";if (status.job->state == JobState::Downloading && status.job->total_bytes > 0)return std::to_string(static_cast<int>(100.0 * status.job->completed_bytes / status.job->total_bytes)) +@@ -1804,7 +1804,7 @@ class Render::Implbar.set_bounds({282.0F, 302.0F, 756.0F, 12.0F});bar.set_value(std::clamp(progress, 0.0F, 1.0F), true);bar.draw(canvas);- if (primary->checking_licenses)+ if (primary->state == JobState::Downloading && primary->checking_licenses){// Large accounts take a minute here, before Steam gives the download size (issue #47).spinner(292.0F, 345.0F, 9.0F, kBlue);diff --git a/src/steam/backend/cm_client.cpp b/src/steam/backend/cm_client.cppindex a8bb676..9140131 100644--- a/src/steam/backend/cm_client.cpp+++ b/src/steam/backend/cm_client.cpp@@ -590,7 +590,16 @@ CmError CmClient::Acquire(const StoredSession& stored, const std::atomic<bool>&if (opened != CmError::kNone) CloseSession(lease);return opened;}- lease->hold = std::unique_lock<std::mutex>(shared_->mutex_);+ // Another call (a library license scan can take a minute) may hold the session: waiting for it+ // stays cancelable, and this call's deadline starts once it has the session.+ const auto wait_start = Clock::now();+ lease->hold = std::unique_lock<std::mutex>(shared_->mutex_, std::try_to_lock);+ while (!lease->hold.owns_lock()) {+ if (cancel.load(std::memory_order_acquire)) return CmError::kCanceled;+ std::this_thread::sleep_for(std::chrono::milliseconds(5));+ lease->hold.try_lock();+ }+ deadline += Clock::now() - wait_start;const std::string key = std::to_string(stored.steam_id) + ":" + stored.refresh_token;if (shared_->session_ && key == shared_->key_ && shared_->session_->usable()) {shared_->session_->Rebind(deadline, cancel);diff --git a/tests/cm_client_test.cpp b/tests/cm_client_test.cppindex 05f36db..d10e0cd 100644--- a/tests/cm_client_test.cpp+++ b/tests/cm_client_test.cpp@@ -456,6 +456,47 @@ void SharedSessionLogsOnAgainForNewCredentials() {assert(CountSent(script, cm::kEMsgClientLogon) == 2 && CountSent(script, cm::kEMsgClientLogOff) == 0);}+// A call waiting while another holds the shared session (a long library license scan, issue #47)+// can be canceled, and its deadline starts only once it has the session.+void WaitingForTheSharedSessionIsCancelableAndUntimed() {+ auto script = std::make_shared<Script>();+ script->on_logon = {ServerFrame(cm::kEMsgClientLogOnResponse, LogonResponseBody(1, 9))};+ script->on_service = {ServerFrame(cm::kEMsgServiceMethodResponse, {}, std::nullopt, 1)};+ auto shared = MakeCmSharedSession();+ auto holder = MakeClient(script);+ auto waiter = MakeClient(script);+ holder.SetSharedSession(shared);+ waiter.SetSharedSession(shared);+ std::atomic<bool> held{false};+ std::atomic<bool> no_cancel{false};+ std::thread scan([&] {+ assert(holder.WithServiceSession(Session(), 3000, no_cancel, [&](const CmClient::ServiceCall&, std::uint64_t) {+ held = true;+ std::this_thread::sleep_for(600ms);+ return CmError::kNone;+ }) == CmError::kNone);+ });+ while (!held) std::this_thread::sleep_for(1ms);++ std::atomic<bool> cancel{false};+ std::thread canceler([&cancel] {+ std::this_thread::sleep_for(50ms);+ cancel = true;+ });+ const auto start = std::chrono::steady_clock::now();+ assert(Ping(waiter, cancel) == CmError::kCanceled);+ assert(std::chrono::steady_clock::now() - start < 300ms);+ canceler.join();++ // Waits out the rest of the scan, longer than its own 200 ms deadline, then still gets its answer.+ const auto result = waiter.WithServiceSession(Session(), 200, no_cancel, [](const CmClient::ServiceCall& call, std::uint64_t) {+ std::vector<std::uint8_t> reply;+ return call("Cloud.Ping#1", {}, &reply, nullptr);+ });+ assert(result == CmError::kNone);+ scan.join();+}+void WithoutKeepAliveEachCallLogsOnAgain() {auto script = std::make_shared<Script>();script->on_logon = {ServerFrame(cm::kEMsgClientLogOnResponse, LogonResponseBody(1, 9))};@@ -681,6 +722,8 @@ int main(int argc, char** argv) {ResetCmBackoff();SharedSessionLogsOnAgainForNewCredentials();ResetCmBackoff();+ WaitingForTheSharedSessionIsCancelableAndUntimed();+ ResetCmBackoff();WithoutKeepAliveEachCallLogsOnAgain();ResetCmBackoff();RefusedTokenIsNotTriedAgain();diff --git a/tests/homebrew_account_test.cpp b/tests/homebrew_account_test.cppindex 96aa8ae..ac832f7 100644--- a/tests/homebrew_account_test.cpp+++ b/tests/homebrew_account_test.cpp@@ -3,7 +3,9 @@#include <cassert>#include <chrono>#include <condition_variable>+#include <filesystem>#include <functional>+#include <unistd.h>#include <mutex>#include <thread>@@ -75,6 +77,19 @@ class CacheFixture final : public LibraryRepository {value.reset();return Result<void>::Success();}};+// Holds an install in its license check until released.+class LicenseCheckRunner final : public InstallRunner {+ public:+ std::atomic<bool> release{false};+ Result Install(const StoredSession&,GameId,const std::string&,const std::atomic<bool>& cancel,+ const std::function<void(std::uint64_t,std::uint64_t,std::uint64_t)>&,+ const std::function<void(InstallStep)>& step) override {+ step(InstallStep::kCheckingLicenses);+ while (!release && !cancel) std::this_thread::sleep_for(1ms);+ return {false,true,{},0};+ }+ bool Remove(const std::string&) override { return true; }+};void Wait(Controller& controller,const std::function<bool()>& predicate) {const auto deadline = std::chrono::steady_clock::now()+4s;do { controller.Tick(); if (predicate()) return; std::this_thread::sleep_for(1ms); } while (std::chrono::steady_clock::now()<deadline);@@ -324,4 +339,31 @@ void ShutdownClearsLibraryBeforeSession() {assert(!repo.Load().value() && !cache.value);}}-int main() { CanceledStorageRetryKeepsSavedSessionIntent(); RevokedSessionCleanupRetriesAfterStorageRecovery(); StorageFailureKeepsVisibleAccount(); StorageFailureRetriesSavedSession(); ChallengeAndCancel(); AuthenticationRestoreAndSignOut(); FailedClearDoesNotSwitch(); SignInAgainKeepsTheAccount(); ExitHonorsClearWithoutStartingNewQr(); StorageFailureAndRevocation(); ConnectedLibraryAndOfflineRestart(); ShutdownClearsLibraryBeforeSession(); RepeatedClearPreservesFirstIntent(); }+// A license check shows only once it has run for a few seconds, even with no other install change (issue #47).+void SlowLicenseCheckShowsAfterAFewSeconds() {+ const auto root=std::filesystem::temp_directory_path()/("playden-license-check-"+std::to_string(::getpid()));+ std::filesystem::remove_all(root);+ std::filesystem::create_directories(root);+ {+ Simulation model({}, {},ModelMode::Live); Repository repo; repo.value=Session(); Backend backend;+ LicenseCheckRunner runner;+ InstallService installs(runner,repo,root.string());+ Controller controller(model,backend,repo,nullptr,nullptr,nullptr,&installs);+ const auto job=[&]() -> const Job* {+ for (const auto& value : model.state().jobs) if (value.game_id==70) return &value;+ return nullptr;+ };+ const auto start=std::chrono::steady_clock::now();+ installs.Install(70);+ Wait(controller,[&]{return job() && job()->state==JobState::Downloading;});+ assert(!job()->checking_licenses);+ const auto checking=[&]{ return job() && job()->checking_licenses; };+ for (auto deadline=start+6s; !checking() && std::chrono::steady_clock::now()<deadline; std::this_thread::sleep_for(5ms))+ controller.Tick();+ assert(checking() && std::chrono::steady_clock::now()-start>=3s);+ runner.release=true;+ controller.Shutdown();+ }+ std::filesystem::remove_all(root);+}+int main() { SlowLicenseCheckShowsAfterAFewSeconds(); CanceledStorageRetryKeepsSavedSessionIntent(); RevokedSessionCleanupRetriesAfterStorageRecovery(); StorageFailureKeepsVisibleAccount(); StorageFailureRetriesSavedSession(); ChallengeAndCancel(); AuthenticationRestoreAndSignOut(); FailedClearDoesNotSwitch(); SignInAgainKeepsTheAccount(); ExitHonorsClearWithoutStartingNewQr(); StorageFailureAndRevocation(); ConnectedLibraryAndOfflineRestart(); ShutdownClearsLibraryBeforeSession(); RepeatedClearPreservesFirstIntent(); }