From 85253dff87346afcd9c978aa977f925bef6df905 Mon Sep 17 00:00:00 2001 From: Satish Ramteare Date: Mon, 16 Nov 2026 09:05:23 -0500 Subject: [PATCH] fix(linux): clear stale portal restore token when Start returns no streams (#6112) --- src/platform/linux/misc.h | 12 ++ src/platform/linux/portalgrab.cpp | 189 +++++++++++++----- tests/unit/platform/linux/test_portalgrab.cpp | 167 ++++++++++++++-- 3 files changed, 301 insertions(+), 67 deletions(-) diff --git a/src/platform/linux/misc.h b/src/platform/linux/misc.h index 8ae9b70b4..f7b143e2e 100644 --- a/src/platform/linux/misc.h +++ b/src/platform/linux/misc.h @@ -96,6 +96,18 @@ namespace portal { * @return Path of the selected test token. */ std::filesystem::path get_saved_token_path_for_testing(const std::filesystem::path &directory, const std::string &desktop); + + /** + * @brief Override the token path used by portal persistence in unit tests. + * + * @param path Token path used by load, save, clear and existence checks. + */ + void set_saved_token_path_for_testing(const std::filesystem::path &path); + + /** + * @brief Restore the production token path after a unit test. + */ + void reset_saved_token_path_for_testing(); #endif /** diff --git a/src/platform/linux/portalgrab.cpp b/src/platform/linux/portalgrab.cpp index 2b0edac59..9245f58b3 100644 --- a/src/platform/linux/portalgrab.cpp +++ b/src/platform/linux/portalgrab.cpp @@ -80,7 +80,7 @@ namespace portal { * @brief Load persisted state from its backing store. */ static void load() { - std::ifstream file(get_file_path()); + std::ifstream file(active_file_path()); if (file.is_open()) { std::getline(file, *token_); if (!token_->empty()) { @@ -96,7 +96,7 @@ namespace portal { */ static bool exists() { std::error_code ec; - return std::filesystem::exists(get_file_path(), ec); + return std::filesystem::exists(active_file_path(), ec); } /** @@ -105,7 +105,7 @@ namespace portal { static void clear() { std::error_code ec; token_->clear(); - std::filesystem::remove(get_file_path(), ec); + std::filesystem::remove(active_file_path(), ec); } /** @@ -115,7 +115,7 @@ namespace portal { if (token_->empty()) { return; } - std::ofstream file(get_file_path()); + std::ofstream file(active_file_path()); if (file.is_open()) { file << *token_; BOOST_LOG(info) << "[portalgrab] Saved portal restore token to disk"sv; @@ -173,8 +173,43 @@ namespace portal { return suffixed_path; } +#ifdef SUNSHINE_TESTS + /** + * @brief Override the token path used by persistence operations in unit tests. + * + * @param path Token path, or an empty path to restore the production path. + */ + static void set_file_path_for_testing(const std::filesystem::path &path) { + test_file_path_ = path; + } + + /** + * @brief Restore the production token path after a unit test. + */ + static void reset_file_path_for_testing() { + test_file_path_.clear(); + } +#endif + private: + /** + * @brief Get the path used by persistence operations. + * + * @return Test override path when set, otherwise the production session token path. + */ + static std::filesystem::path active_file_path() { +#ifdef SUNSHINE_TESTS + if (!test_file_path_.empty()) { + return test_file_path_; + } +#endif + return get_file_path(); + } + static inline const std::unique_ptr token_ = std::make_unique(); +#ifdef SUNSHINE_TESTS + static inline std::filesystem::path test_file_path_; +#endif }; /** @@ -270,6 +305,14 @@ namespace portal { std::filesystem::path get_saved_token_path_for_testing(const std::filesystem::path &directory, const std::string &desktop) { return restore_token_t::get_file_path(directory, desktop); } + + void set_saved_token_path_for_testing(const std::filesystem::path &path) { + restore_token_t::set_file_path_for_testing(path); + } + + void reset_saved_token_path_for_testing() { + restore_token_t::reset_file_path_for_testing(); + } #endif /** @@ -308,6 +351,15 @@ namespace portal { } }; + /** + * @brief Result of asking the portal to start a screencast session. + */ + enum class portal_start_e { + success, ///< The portal returned at least one stream. + no_streams, ///< The portal accepted the request but returned no streams. + failure, ///< The request failed, was cancelled, or timed out. + }; + /** * @brief DBus connection and portal request helpers for screencast setup. */ @@ -319,29 +371,7 @@ namespace portal { ~dbus_t() noexcept { try { - if (conn && !session_handle.empty()) { - g_autoptr(GError) err = nullptr; - // This is a blocking C call; it won't throw, but we wrap for safety - g_dbus_connection_call_sync( - conn, - "org.freedesktop.portal.Desktop", - session_handle.c_str(), - "org.freedesktop.portal.Session", - "Close", - nullptr, - nullptr, - G_DBUS_CALL_FLAGS_NONE, - dbus_timeout * 1000, - nullptr, - &err - ); - - if (err) { - BOOST_LOG(warning) << "[portalgrab] Failed to explicitly close portal session: "sv << err->message; - } else { - BOOST_LOG(debug) << "[portalgrab] Explicitly closed portal session: "sv << session_handle; - } - } + close_session(); } catch (const std::exception &e) { BOOST_LOG(error) << "[portalgrab] Standard exception caught in ~dbus_t: "sv << e.what(); } catch (...) { @@ -421,33 +451,51 @@ namespace portal { /** * @brief Connect to xdg-desktop-portal and restore or create a screencast session. * + * A saved restore token that no longer matches the current monitor setup is discarded and the + * connection is retried once without it. + * * @param allow_start_timeout True if "Start" DBus call is allowed to time out. * @return 0 when a portal session is ready; nonzero when D-Bus or portal setup fails. */ int connect_to_portal(bool allow_start_timeout) { g_autoptr(GMainContext) context = g_main_context_new(); g_autoptr(GMainLoop) loop = g_main_loop_new(context, false); - g_autofree gchar *session_path = nullptr; - g_autofree gchar *session_token = nullptr; - create_session_path(conn, nullptr, &session_token); - // Try combined RemoteDesktop + ScreenCast session first - bool use_screencast_only = !try_remote_desktop_session(loop, &session_path, session_token); + for (int attempt = 0; attempt < 2; ++attempt) { + const bool used_restore_token = !restore_token_t::empty(); + pipewire_streams.clear(); - // Fall back to ScreenCast-only if RemoteDesktop failed - if (use_screencast_only && try_screencast_only_session(loop, &session_path) < 0) { - return -1; + g_autofree gchar *session_path = nullptr; + g_autofree gchar *session_token = nullptr; + create_session_path(conn, nullptr, &session_token); + + // Try combined RemoteDesktop + ScreenCast session first + bool use_screencast_only = !try_remote_desktop_session(loop, &session_path, session_token); + + // Fall back to ScreenCast-only if RemoteDesktop failed + if (use_screencast_only && try_screencast_only_session(loop, &session_path) < 0) { + return -1; + } + + const auto start_result = start_portal_session(loop, session_path, pipewire_streams, use_screencast_only, allow_start_timeout); + if (start_result != portal_start_e::success) { + if (start_result == portal_start_e::no_streams && used_restore_token && attempt == 0) { + BOOST_LOG(warning) << "[portalgrab] Portal returned no streams for the saved restore token; discarding the stale token and retrying without it"sv; + restore_token_t::clear(); + close_session(); + continue; + } + return -1; + } + + if (open_pipewire_remote(session_path, pipewire_fd) < 0) { + return -1; + } + + return 0; } - if (start_portal_session(loop, session_path, pipewire_streams, use_screencast_only, allow_start_timeout) < 0) { - return -1; - } - - if (open_pipewire_remote(session_path, pipewire_fd) < 0) { - return -1; - } - - return 0; + return -1; } // Try to create a combined RemoteDesktop + ScreenCast session @@ -537,14 +585,45 @@ namespace portal { } std::vector pipewire_streams; ///< Pipewire streams. - int pipewire_fd; ///< Pipewire fd. + int pipewire_fd = -1; ///< Pipewire fd. private: - GDBusConnection *conn; - GDBusProxy *screencast_proxy; - GDBusProxy *remote_desktop_proxy; + GDBusConnection *conn = nullptr; + GDBusProxy *screencast_proxy = nullptr; + GDBusProxy *remote_desktop_proxy = nullptr; std::string session_handle; + /** + * @brief Close the portal session created for the current connection. + */ + void close_session() { + if (!conn || session_handle.empty()) { + return; + } + + g_autoptr(GError) err = nullptr; + g_dbus_connection_call_sync( + conn, + PORTAL_NAME, + session_handle.c_str(), + "org.freedesktop.portal.Session", + "Close", + nullptr, + nullptr, + G_DBUS_CALL_FLAGS_NONE, + dbus_timeout * 1000, + nullptr, + &err + ); + + if (err) { + BOOST_LOG(warning) << "[portalgrab] Failed to explicitly close portal session: "sv << err->message; + } else { + BOOST_LOG(debug) << "[portalgrab] Explicitly closed portal session: "sv << session_handle; + } + session_handle.clear(); + } + int create_portal_session(GMainLoop *loop, gchar **session_path_out, const gchar *session_token, bool use_screencast) { GDBusProxy *proxy = use_screencast ? screencast_proxy : remote_desktop_proxy; const char *session_type = use_screencast ? "ScreenCast" : "RemoteDesktop"; @@ -702,7 +781,7 @@ namespace portal { return 0; } - int start_portal_session(GMainLoop *loop, const gchar *session_path, std::vector &out_pipewire_streams, bool use_screencast, bool allow_start_timeout) { + portal_start_e start_portal_session(GMainLoop *loop, const gchar *session_path, std::vector &out_pipewire_streams, bool use_screencast, bool allow_start_timeout) { GDBusProxy *proxy = use_screencast ? screencast_proxy : remote_desktop_proxy; const char *session_type = use_screencast ? "ScreenCast" : "RemoteDesktop"; @@ -722,7 +801,7 @@ namespace portal { g_autoptr(GVariant) reply = g_dbus_proxy_call_sync(proxy, "Start", g_variant_builder_end(&builder), G_DBUS_CALL_FLAGS_NONE, dbus_timeout * 1000, nullptr, &err); if (err) { BOOST_LOG(error) << "[portalgrab] Could not start "sv << session_type << " session: "sv << err->message; - return -1; + return portal_start_e::failure; } dbus_response_follow_handle(&response, reply); @@ -731,7 +810,7 @@ namespace portal { if (!start_response) { BOOST_LOG(error) << "[portalgrab] " << session_type << " Start: no response received"sv; - return -1; + return portal_start_e::failure; } guint32 response_code; @@ -743,13 +822,13 @@ namespace portal { if (response_code != 0) { BOOST_LOG(error) << "[portalgrab] " << session_type << " Start failed with response code: "sv << response_code; - return -1; + return portal_start_e::failure; } streams = g_variant_lookup_value(dict, "streams", G_VARIANT_TYPE("a(ua{sv})")); - if (!streams) { + if (!streams || g_variant_n_children(streams) == 0) { BOOST_LOG(error) << "[portalgrab] " << session_type << " Start: no streams in response"sv; - return -1; + return portal_start_e::no_streams; } if (const gchar *new_token = nullptr; g_variant_lookup(dict, "restore_token", "s", &new_token) && new_token && new_token[0] != '\0' && restore_token_t::get() != new_token) { @@ -813,7 +892,7 @@ namespace portal { return a.pos_x < b.pos_x || a.pos_y < b.pos_y; }); - return 0; + return portal_start_e::success; } int open_pipewire_remote(const gchar *session_path, int &fd) { diff --git a/tests/unit/platform/linux/test_portalgrab.cpp b/tests/unit/platform/linux/test_portalgrab.cpp index fbc831a26..fb5a3f9f2 100644 --- a/tests/unit/platform/linux/test_portalgrab.cpp +++ b/tests/unit/platform/linux/test_portalgrab.cpp @@ -8,6 +8,7 @@ // standard includes #include + #include #include #include #include @@ -33,6 +34,7 @@ // local includes #include "src/logging.h" + #include "src/platform/linux/misc.h" namespace platf { std::vector portal_display_names(bool allow_start_timeout); @@ -146,6 +148,33 @@ namespace { stop(); } + /** + * @brief Configure whether restored sessions return no streams. + * + * @param reject True to make Start return no streams when the session used a restore token. + */ + void set_reject_restored_sessions(bool reject) { + reject_restored_sessions_.store(reject); + } + + /** + * @brief Configure whether rejected restored sessions emit an empty streams array instead of omitting it. + * + * @param emit_empty True to emit `@a(ua{sv}) []`; false to omit the `streams` entry. + */ + void set_emit_empty_streams_array(bool emit_empty) { + emit_empty_streams_array_.store(emit_empty); + } + + /** + * @brief Check whether any request carried a restore token. + * + * @return True when a restore token was seen. + */ + bool saw_restore_token() const { + return saw_restore_token_.load(); + } + private: /** * @brief Connect to the bus, claim the portal name and export the portal object. @@ -187,7 +216,7 @@ namespace { g_autoptr(GDBusNodeInfo) node = g_dbus_node_info_new_for_xml(PORTAL_XML, nullptr); static const GDBusInterfaceVTable vtable {handle_method_call, nullptr, nullptr, {}}; for (auto **iface = node->interfaces; *iface; ++iface) { - const auto id = g_dbus_connection_register_object(conn_, PORTAL_PATH, *iface, &vtable, nullptr, nullptr, nullptr); + const auto id = g_dbus_connection_register_object(conn_, PORTAL_PATH, *iface, &vtable, this, nullptr, nullptr); if (id == 0) { return false; } @@ -199,7 +228,8 @@ namespace { /** * @brief Answer a portal method call, emitting the request's Response first. */ - static void handle_method_call(GDBusConnection *conn, const gchar *sender, [[maybe_unused]] const gchar *object_path, [[maybe_unused]] const gchar *interface_name, const gchar *method_name, GVariant *parameters, GDBusMethodInvocation *invocation, [[maybe_unused]] gpointer user_data) { // NOSONAR(cpp:S107): GDBusInterfaceMethodCallFunc signature. + static void handle_method_call(GDBusConnection *conn, const gchar *sender, [[maybe_unused]] const gchar *object_path, [[maybe_unused]] const gchar *interface_name, const gchar *method_name, GVariant *parameters, GDBusMethodInvocation *invocation, gpointer user_data) { // NOSONAR(cpp:S107): GDBusInterfaceMethodCallFunc signature. + auto *portal = static_cast(user_data); if (g_str_equal(method_name, "OpenPipeWireRemote")) { g_autoptr(GUnixFDList) fd_list = g_unix_fd_list_new(); const int fd = open("/dev/null", O_RDONLY | O_CLOEXEC); @@ -217,6 +247,9 @@ namespace { return; } + const gchar *restore_token = nullptr; + const bool has_restore_token = g_variant_lookup(options, "restore_token", "&s", &restore_token) && restore_token && restore_token[0] != '\0'; + g_autofree gchar *sender_id = g_strdelimit(g_strdup(sender + 1), ".", '_'); g_autofree gchar *request_path = g_strdup_printf("%s/request/%s/%s", PORTAL_PATH, sender_id, handle_token); @@ -226,17 +259,38 @@ namespace { const gchar *session_token = nullptr; g_variant_lookup(options, "session_handle_token", "&s", &session_token); g_autofree gchar *session_path = g_strdup_printf("%s/session/%s/%s", PORTAL_PATH, sender_id, session_token); + portal->session_restore_tokens_[session_path] = false; g_variant_builder_add(&results, "{sv}", "session_handle", g_variant_new_string(session_path)); - } else if (g_str_equal(method_name, "Start")) { - // A geometry no real monitor has, so the stream is named by position and resolution - GVariantBuilder properties; - g_variant_builder_init(&properties, G_VARIANT_TYPE_VARDICT); - g_variant_builder_add(&properties, "{sv}", "size", g_variant_new("(ii)", 1234, 567)); - g_variant_builder_add(&properties, "{sv}", "position", g_variant_new("(ii)", 7, 9)); - GVariantBuilder streams; - g_variant_builder_init(&streams, G_VARIANT_TYPE("a(ua{sv})")); - g_variant_builder_add(&streams, "(ua{sv})", 42u, &properties); - g_variant_builder_add(&results, "{sv}", "streams", g_variant_builder_end(&streams)); + } else { + g_autoptr(GVariant) session_value = g_variant_get_child_value(parameters, 0); + const gchar *session_path = g_variant_get_string(session_value, nullptr); + if (g_str_equal(method_name, "SelectDevices") || g_str_equal(method_name, "SelectSources")) { + if (has_restore_token) { + portal->session_restore_tokens_[session_path] = true; + portal->saw_restore_token_.store(true); + } + } else if (g_str_equal(method_name, "Start")) { + const auto session = portal->session_restore_tokens_.find(session_path); + const bool restored_session = session != portal->session_restore_tokens_.end() && session->second; + if (!restored_session || !portal->reject_restored_sessions_.load()) { + // A geometry no real monitor has, so the stream is named by position and resolution + GVariantBuilder properties; + g_variant_builder_init(&properties, G_VARIANT_TYPE_VARDICT); + g_variant_builder_add(&properties, "{sv}", "size", g_variant_new("(ii)", 1234, 567)); + g_variant_builder_add(&properties, "{sv}", "position", g_variant_new("(ii)", 7, 9)); + GVariantBuilder streams; + g_variant_builder_init(&streams, G_VARIANT_TYPE("a(ua{sv})")); + g_variant_builder_add(&streams, "(ua{sv})", 42u, &properties); + g_variant_builder_add(&results, "{sv}", "streams", g_variant_builder_end(&streams)); + } else if (portal->emit_empty_streams_array_.load()) { + GVariantBuilder streams; + g_variant_builder_init(&streams, G_VARIANT_TYPE("a(ua{sv})")); + g_variant_builder_add(&results, "{sv}", "streams", g_variant_builder_end(&streams)); + } + if (!restored_session) { + g_variant_builder_add(&results, "{sv}", "restore_token", g_variant_new_string("fresh-token")); + } + } } g_dbus_connection_emit_signal(conn, sender, request_path, "org.freedesktop.portal.Request", "Response", g_variant_new("(ua{sv})", 0u, &results), nullptr); @@ -247,6 +301,10 @@ namespace { GMainLoop *loop_ = nullptr; GDBusConnection *conn_ = nullptr; std::vector registrations_; + std::map session_restore_tokens_; + std::atomic saw_restore_token_ {false}; + std::atomic reject_restored_sessions_ {true}; + std::atomic emit_empty_streams_array_ {false}; std::jthread thread_; }; @@ -289,6 +347,10 @@ namespace { auto directory_template = (std::filesystem::temp_directory_path() / "sunshine-portal-bus-XXXXXX").string(); // NOSONAR(cpp:S5443): mkdtemp creates a private unique directory. ASSERT_NE(mkdtemp(directory_template.data()), nullptr); bus_directory_ = directory_template; + token_path_ = bus_directory_ / "portal_token.test"; + portal::set_saved_token_path_for_testing(token_path_); + portal::clear_saved_token(); + const auto config_path = bus_directory_ / "bus.conf"; std::ofstream(config_path) << std::format(BUS_CONFIG, bus_directory_.string()); @@ -321,6 +383,10 @@ namespace { */ void TearDown() override { portal_.stop(); + if (!token_path_.empty()) { + portal::clear_saved_token(); + portal::reset_saved_token_path_for_testing(); + } logging::log_flush(); for (const auto &[name, previous] : previous_env_) { if (previous) { @@ -344,6 +410,36 @@ namespace { BaseTest::TearDown(); } + /** + * @brief Get the private token path used by this test. + * + * @return Token path inside the private bus directory. + */ + const std::filesystem::path &token_path() const { + return token_path_; + } + + /** + * @brief Write a restore token to the private token path. + * + * @param value Token contents. + */ + void write_token(const std::string &value) const { + std::ofstream file(token_path_); + ASSERT_TRUE(file.is_open()); + file << value; + ASSERT_TRUE(file.good()); + } + + /** + * @brief Access the fake portal used by this test. + * + * @return Fake portal instance. + */ + fake_portal_t &fake_portal() { + return portal_; + } + private: /** * @brief Set an environment variable for the test, remembering its previous value for TearDown. @@ -362,6 +458,7 @@ namespace { GPid daemon_pid_ = 0; FILE *daemon_output_ = nullptr; std::filesystem::path bus_directory_; + std::filesystem::path token_path_; std::map, std::less<>> previous_env_; }; } // namespace @@ -371,4 +468,50 @@ TEST_F(PortalRequestTest, ReceivesResponseEmittedBeforeMethodReturns) { EXPECT_EQ(names, std::vector {"position-7x9-resolution-1234x567"}); } + +/** + * @brief Parameterized stale-token recovery tests for omitted and empty `streams` responses. + */ +class PortalRequestStaleTokenTest: public PortalRequestTest, public testing::WithParamInterface {}; + +TEST_P(PortalRequestStaleTokenTest, DiscardsStaleRestoreTokenWhenStartHasNoStreams) { + fake_portal().set_emit_empty_streams_array(GetParam()); + ASSERT_NO_FATAL_FAILURE(write_token("stale-token")); + ASSERT_TRUE(std::filesystem::exists(token_path())); + + const auto names = platf::portal_display_names(true); + + EXPECT_EQ(names, std::vector {"position-7x9-resolution-1234x567"}); + EXPECT_TRUE(fake_portal().saw_restore_token()); + ASSERT_TRUE(std::filesystem::exists(token_path())); + std::ifstream file(token_path()); + std::string token; + std::getline(file, token); + EXPECT_EQ(token, "fresh-token"); + EXPECT_TRUE(portal::has_saved_token()); +} + +INSTANTIATE_TEST_SUITE_P( + EmptyStartResponses, + PortalRequestStaleTokenTest, + testing::Values(false, true), + [](const testing::TestParamInfo &info) { + return info.param ? "EmptyStreamsArray" : "OmittedStreams"; + } +); + +TEST_F(PortalRequestTest, KeepsRestoreTokenWhenStartReturnsStreams) { + fake_portal().set_reject_restored_sessions(false); + ASSERT_NO_FATAL_FAILURE(write_token("valid-token")); + + const auto names = platf::portal_display_names(true); + + EXPECT_EQ(names, std::vector {"position-7x9-resolution-1234x567"}); + EXPECT_TRUE(fake_portal().saw_restore_token()); + ASSERT_TRUE(std::filesystem::exists(token_path())); + std::ifstream file(token_path()); + std::string token; + std::getline(file, token); + EXPECT_EQ(token, "valid-token"); +} #endif