diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 3a40f3993..fb3ae3ff7 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -170,45 +170,33 @@ If you see the above error in the Sunshine logs, compiling *Mesa* manually may b > Other build options are listed in the > [meson options](https://gitlab.freedesktop.org/mesa/mesa/-/blob/main/meson_options.txt) file. -### XDG Portal Token Issues -Portal capture requires you to approve Remote Desktop permissions using an on-screen prompt on the host. Sunshine saves -the resulting restore token so the desktop portal can reauthorize capture automatically on subsequent starts. The token -can become invalid after events such as a Sunshine crash, switching desktop environments, changing portal -implementations, or connecting and disconnecting monitors. +### XDG Portal Capture Permissions -Reset the token when portal capture previously worked but Sunshine no longer shows the permission prompt, or when the -log shows that a saved token was loaded before the portal returned no streams. For example: +Portal capture requires you to approve Remote Desktop permissions using an on-screen prompt on the host. Sunshine saves the +resulting restore token so the XDG Desktop Portal can reauthorize capture automatically on subsequent starts. -```txt -Info: [portalgrab] Loaded portal restore token from disk -Error: [portalgrab] RemoteDesktop Start: no streams in response -Warning: [portalgrab] Failed to connect to portal. Cannot enumerate displays, returning empty list. -``` +If a restore token doesn't yet exist or becomes stale (for example, after a Sunshine crash, switching desktop environments, +changing portal implementations, or changing the monitor associated with the Portal session), Sunshine will attempt to run +in fallback capture mode. While in this mode, Sunshine will temporarily select another working capture method so that you +can interact with the Portal Remote Desktop dialog. Once a new restore token is negotiated and saved, Sunshine will +automatically restart and switch back to Portal capture. -Do not use this reset for a generic encoder failure unless the log also shows that XDG Portal capture failed. +> [!IMPORTANT] +> If a fallback session cannot be created because no other capture methods are available, you will need to directly +> interact with the host or use an alternative Remote Desktop connection (e.g. VNC, RDP) to complete setup. -In the Web UI, open **Troubleshooting** and select **Reset XDG Portal Capture**. Sunshine deletes the saved token and -restarts. Approve the Remote Desktop prompt and select the display to capture when it appears again. +If the saved Portal token is valid but you want to change the monitor associated with Portal capture, open the Web UI, +open **Troubleshooting**, and select **Reset XDG Portal Capture**. Sunshine deletes the saved token and restarts. +Approve the Remote Desktop prompt again and select the display to capture when it appears. -If the Web UI is inaccessible, stop Sunshine and delete the token manually: +> [!TIP] +> If Sunshine uses a custom configuration directory, you may need to delete the `portal_token` file from the custom +> directory and restart Sunshine manually in lieu of the Web UI. -@tabs{ - @tab{Linux / FreeBSD |:| ```bash - rm "${XDG_CONFIG_HOME:-$HOME/.config}/sunshine/portal_token" - ``` - } - @tab{Flatpak |:| ```bash - rm "$HOME/.var/app/dev.lizardbyte.app.Sunshine/config/sunshine/portal_token" - ``` - } -} +Users of the KDE Plasma desktop can bypass manual permission setup either by switching to `kwin` capture or setting +the following configuration to enable permanent capture authorization for Sunshine via Portal capture: -Start Sunshine again, then approve the new Remote Desktop request. If Sunshine uses a custom configuration directory, -delete the `portal_token` file from that directory instead. - -Users of the KDE Plasma desktop can bypass this issue either by switching to `kwin` capture or setting the following -configuration to enable permanent capture authorization for Sunshine via Portal capture: -``` +```bash flatpak permission-set kde-authorized remote-desktop dev.lizardbyte.app.Sunshine yes ``` > [!NOTE] diff --git a/src/main.cpp b/src/main.cpp index f349a233d..21fb8ef0e 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -16,12 +16,11 @@ #include #endif #ifdef __linux__ + #include "platform/common.h" #include "platform/linux/graphics.h" + #include "platform/linux/misc.h" #include - #if defined(SUNSHINE_BUILD_DRM) - #include "platform/linux/misc.h" - #endif #endif // lib includes @@ -44,11 +43,6 @@ #include "upnp.h" #include "video.h" -#ifdef __linux__ - #include "platform/common.h" - #include "platform/linux/misc.h" -#endif - using namespace std::literals; std::map> signal_handlers; ///< Signal handlers. @@ -387,7 +381,12 @@ int main(int argc, char *argv[]) { #endif - task_pool.start(1); + int task_pool_threads = 1; +#ifdef SUNSHINE_BUILD_PORTAL + // Allocate an extra thread for fallback capture, otherwise a pending XDG user reply can block input. + task_pool_threads = 2; +#endif + task_pool.start(task_pool_threads); // Create signal handler after logging has been initialized auto shutdown_event = mail::man->event(mail::shutdown); diff --git a/src/platform/linux/kmsgrab.cpp b/src/platform/linux/kmsgrab.cpp index 8a0857636..120fe9cc9 100644 --- a/src/platform/linux/kmsgrab.cpp +++ b/src/platform/linux/kmsgrab.cpp @@ -53,14 +53,19 @@ namespace platf { cap_value_t sys_admin = CAP_SYS_ADMIN; if (cap_set_flag(caps, CAP_EFFECTIVE, 1, &sys_admin, CAP_SET) || cap_set_proc(caps)) { - BOOST_LOG(error) << "Failed to gain CAP_SYS_ADMIN"; + BOOST_LOG(error) << "Failed to gain CAP_SYS_ADMIN"sv; } } ~cap_sys_admin() { cap_value_t sys_admin = CAP_SYS_ADMIN; - if (cap_set_flag(caps, CAP_EFFECTIVE, 1, &sys_admin, CAP_CLEAR) || cap_set_proc(caps)) { - BOOST_LOG(error) << "Failed to drop CAP_SYS_ADMIN"; + if (cap_set_flag(caps, CAP_EFFECTIVE, 1, &sys_admin, CAP_CLEAR)) { + BOOST_LOG(error) << "Failed to clear CAP_SYS_ADMIN capability flag"sv; + } else if (cap_set_proc(caps)) { + // CAP_SYS_ADMIN may already have been dropped by privileged_drm_worker. + if (errno != EPERM) { + BOOST_LOG(error) << "Failed to drop CAP_SYS_ADMIN"sv; + } } cap_free(caps); } @@ -207,7 +212,10 @@ namespace platf { * @brief Allows the DRM privileged_drm_worker thread to drop privileges. */ void drop_drm_worker_privileges() { - privileged_drm_worker::drop_worker_privileges(); + static std::once_flag flag; + std::call_once(flag, []() { + privileged_drm_worker::drop_worker_privileges(); + }); } #endif diff --git a/src/platform/linux/kwingrab.cpp b/src/platform/linux/kwingrab.cpp index e82e58090..f7c3b08c7 100644 --- a/src/platform/linux/kwingrab.cpp +++ b/src/platform/linux/kwingrab.cpp @@ -342,9 +342,23 @@ namespace kwin { // We need a second roundtrip after binding outputs to get wl_output events wl_display_roundtrip(wl_display); + if (!is_kwin_screencasting_available()) { + BOOST_LOG(debug) << "[kwingrab] zkde_screencast_unstable_v1 not found in registry."sv; + return -1; + } + return 0; } + /** + * @brief Check if kwin screencasting is currently available + * + * @return true if screencast can be started, false otherwise + */ + bool is_kwin_screencasting_available() const { + return kde_screencast_v1_ != nullptr; + } + /** * @brief Generate a sorted list of known output names. * @return List of strings with output names to pass to start() @@ -720,14 +734,6 @@ namespace platf { * @return KWin display names, or an empty list when KWin capture is unavailable. */ std::vector kwin_display_names() { - if (has_elevated_privileges(false)) { - // We're still in the probing phase of Sunshine startup. Dropping portal security early will break KMS. - // Just return a dummy screen for now. Display re-enumeration after encoder probing will yield full result. - std::vector display_names; - display_names.emplace_back(""); - return display_names; - } - const auto screencast = std::make_unique(); if (screencast->init() < 0) { return {}; diff --git a/src/platform/linux/misc.cpp b/src/platform/linux/misc.cpp index 78cf71e26..0295b5ec3 100644 --- a/src/platform/linux/misc.cpp +++ b/src/platform/linux/misc.cpp @@ -61,6 +61,7 @@ #include "src/boost_process_compat.h" #include "src/config.h" #include "src/entry_handler.h" +#include "src/globals.h" #include "src/logging.h" #include "src/platform/common.h" #include "vaapi.h" @@ -1214,22 +1215,81 @@ namespace platf { #endif #ifdef SUNSHINE_BUILD_PORTAL - std::vector portal_display_names(); + std::vector portal_display_names(bool allow_start_timeout); std::shared_ptr portal_display(mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config); + /** + * @brief Enumerates possible Portal probe responses. + */ + enum class portal_probe_e { + unreachable, ///< Portal service is unreachable. + no_token, ///< Token not found. + stale_token, ///< Had a token, but it didn't produce a working session. + available ///< Portal is available. + }; + + /** + * @brief Probe Portal availability via token existence, DBus availability and timed probe. + * + * @return Can return no_token, unreachable, stale_token or available for processing via verify_portal(). + */ + portal_probe_e probe_portal() { + using enum portal_probe_e; + + if (!portal::is_portal_service_reachable()) { + return unreachable; + } + if (!portal::has_saved_token()) { + return no_token; + } + return portal_display_names(true).empty() ? stale_token : available; + } + + /** + * @brief Verify Portal capture and/or begin token negotiation via TaskPool. + * If negotiation is requested, either queue a TaskPool task if no restore token is detected, + * or if a stale token is detected, delete it and restart Sunshine. + * + * @return True if Portal is available. + */ bool verify_portal() { - return !portal_display_names().empty(); + using enum portal_probe_e; + + auto result = probe_portal(); + switch (result) { + case available: + return true; + case unreachable: + BOOST_LOG(debug) << "[portalgrab] xdg-desktop-portal not reachable; skipping Portal capture."sv; + return false; + case stale_token: + BOOST_LOG(warning) << "[portalgrab] Saved portal token did not produce a session; discarding and restarting."sv; + portal::clear_saved_token(); + platf::restart(); + return false; + case no_token: + BOOST_LOG(fatal) << "Portal capture is awaiting user permission. "sv + << "The current session will attempt to use a fallback capture method."sv; + task_pool.push([]() { + if (!portal_display_names(false).empty()) { + platf::restart(); + } else { + BOOST_LOG(error) << "[portalgrab] Portal session token was not negotiated."sv; + } + }); + return false; + default: + return false; + } } #endif #ifdef SUNSHINE_BUILD_KWIN - bool kwin_available(); std::vector kwin_display_names(); std::shared_ptr kwin_display(mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config); bool verify_kwin() { - // Note: The separate kwin_available check is necessary because with CAP_SYS_ADMIN kwin_display_names is never empty during startup - return window_system == window_system_e::WAYLAND && kwin_available() && !kwin_display_names().empty(); + return !kwin_display_names().empty(); } #endif @@ -1260,7 +1320,7 @@ namespace platf { #endif #ifdef SUNSHINE_BUILD_PORTAL if (sources[source::PORTAL]) { - return portal_display_names(); + return portal_display_names(true); } #endif #ifdef SUNSHINE_BUILD_KWIN @@ -1372,36 +1432,50 @@ namespace platf { } #endif + // Avoid mutating config directly if Portal needs to run in fallback capture mode. + std::string selected_capture = config::video.capture; + + // When Portal is explicitly selected, probe it first so other capture methods can be considered for fallback capture. +#ifdef SUNSHINE_BUILD_PORTAL + bool portal_available = false; + if (selected_capture == "portal") { + portal_available = verify_portal(); + if (!portal_available) { + // Continue probing for fallback capture methods. + selected_capture.clear(); + } + } +#endif #ifdef SUNSHINE_BUILD_CUDA - if (((config::video.capture.empty() && sources.none()) || config::video.capture == "nvfbc") && verify_nvfbc()) { + if (((selected_capture.empty() && sources.none()) || selected_capture == "nvfbc") && verify_nvfbc()) { sources[source::NVFBC] = true; } #endif #ifdef SUNSHINE_BUILD_WAYLAND - if (((config::video.capture.empty() && sources.none()) || config::video.capture == "wlr") && verify_wl()) { + if (((selected_capture.empty() && sources.none()) || selected_capture == "wlr") && verify_wl()) { sources[source::WAYLAND] = true; } #endif #ifdef SUNSHINE_BUILD_DRM - if (((config::video.capture.empty() && sources.none()) || config::video.capture == "kms") && verify_kms()) { + if (((selected_capture.empty() && sources.none()) || selected_capture == "kms") && verify_kms()) { sources[source::KMS] = true; } #endif #ifdef SUNSHINE_BUILD_X11 // We enumerate this capture backend regardless of other suitable sources, // since it may be needed as a NvFBC fallback for software encoding on X11. - if ((config::video.capture.empty() || config::video.capture == "x11") && verify_x11()) { + if ((selected_capture.empty() || selected_capture == "x11") && verify_x11()) { sources[source::X11] = true; } #endif -#ifdef SUNSHINE_BUILD_PORTAL - if ((config::video.capture.empty() || config::video.capture == "portal") && verify_portal()) { - sources[source::PORTAL] = true; +#ifdef SUNSHINE_BUILD_KWIN + if (((selected_capture.empty() && sources.none()) || selected_capture == "kwin") && verify_kwin()) { + sources[source::KWIN] = true; } #endif -#ifdef SUNSHINE_BUILD_KWIN - if (((config::video.capture.empty() && sources.none()) || config::video.capture == "kwin") && verify_kwin()) { - sources[source::KWIN] = true; +#ifdef SUNSHINE_BUILD_PORTAL + if (portal_available || (config::video.capture.empty() && sources.none() && verify_portal())) { + sources[source::PORTAL] = true; } #endif diff --git a/src/platform/linux/misc.h b/src/platform/linux/misc.h index c27932a3c..0754371c2 100644 --- a/src/platform/linux/misc.h +++ b/src/platform/linux/misc.h @@ -50,6 +50,29 @@ namespace dyn { } // namespace dyn +#ifdef SUNSHINE_BUILD_PORTAL +namespace portal { + /** + * @brief Check if a Portal restore token already exists on disk. + * + * @return True if a saved token was found. + */ + bool has_saved_token(); + + /** + * @brief Clear a restore token if it already exists on disk. + */ + void clear_saved_token(); + + /** + * @brief Check if the Portal service responds to a DBus Ping within 2 seconds. + * + * @return True if the Portal is reachable. + */ + bool is_portal_service_reachable(); +} // namespace portal +#endif + namespace platf { /** * @brief Remove environment variables that can load untrusted GUI modules. diff --git a/src/platform/linux/portalgrab.cpp b/src/platform/linux/portalgrab.cpp index 8e8c25d34..1608ab4ed 100644 --- a/src/platform/linux/portalgrab.cpp +++ b/src/platform/linux/portalgrab.cpp @@ -4,6 +4,7 @@ */ // local includes #include "pipewire.cpp" +#include "src/globals.h" namespace { // Portal configuration constants @@ -80,6 +81,25 @@ namespace portal { } } + /** + * @brief Check if a Portal restore token exists on disk without inspecting its contents. + * + * @return True if file exists on disk. + */ + static bool exists() { + std::error_code ec; + return std::filesystem::exists(get_file_path(), ec); + } + + /** + * @brief Clear a restore token if it already exists on disk. + */ + static void clear() { + std::error_code ec; + token_->clear(); + std::filesystem::remove(get_file_path(), ec); + } + /** * @brief Save current state to its backing store. */ @@ -104,6 +124,62 @@ namespace portal { } }; + /** + * @brief Clear a restore token if it already exists on disk. + */ + void clear_saved_token() { + restore_token_t::clear(); + } + + /** + * @brief Check if a Portal restore token exists on disk without inspecting its contents. + * + * @return True if a saved token was found. + */ + bool has_saved_token() { + return restore_token_t::exists(); + } + + /** + * @brief Check if the Portal service responds to a DBus Ping within 2 seconds. + * + * @return True if the Portal is reachable. + */ + bool is_portal_service_reachable() { + g_autoptr(GError) g_error = nullptr; + g_autofree const gchar *address = g_dbus_address_get_for_bus_sync(G_BUS_TYPE_SESSION, nullptr, &g_error); + if (!address) { + return false; + } + + g_autoptr(GError) ping_error = nullptr; + g_autoptr(GDBusConnection) conn = g_dbus_connection_new_for_address_sync( + address, + GDBusConnectionFlags(G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT | G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION), + nullptr, + nullptr, + &ping_error + ); + if (!conn) { + return false; + } + + g_autoptr(GVariant) reply = g_dbus_connection_call_sync( + conn, + "org.freedesktop.portal.Desktop", + "/org/freedesktop/portal/desktop", + "org.freedesktop.DBus.Peer", + "Ping", + nullptr, + nullptr, + G_DBUS_CALL_FLAGS_NONE, + 2000, + nullptr, + &ping_error + ); + return reply != nullptr; + } + /** * @brief DBus response loop and response variant for portal calls. */ @@ -111,6 +187,8 @@ namespace portal { GMainLoop *loop; ///< GLib main loop waiting for a portal response signal. GVariant *response; ///< DBus response payload returned by the portal. guint subscription_id; ///< Subscription ID. + std::string request_path; ///< For Request.Close() on cancellation. + GDBusConnection *conn; ///< Borrowed — owned by the calling dbus_t/portal_t. }; /** @@ -154,6 +232,8 @@ namespace portal { */ class dbus_t { public: + guint dbus_timeout = 10; ///< Timeout in seconds for DBus calls. + dbus_t &operator=(dbus_t &&) = delete; // Do not allow to copying ~dbus_t() noexcept { @@ -170,7 +250,7 @@ namespace portal { nullptr, nullptr, G_DBUS_CALL_FLAGS_NONE, - -1, + dbus_timeout * 1000, nullptr, &err ); @@ -209,15 +289,47 @@ namespace portal { int init() { restore_token_t::load(); - conn = g_bus_get_sync(G_BUS_TYPE_SESSION, nullptr, nullptr); + g_autoptr(GError) g_error = nullptr; + g_autofree gchar *address = g_dbus_address_get_for_bus_sync(G_BUS_TYPE_SESSION, nullptr, &g_error); + if (!address) { + return -1; + } + + conn = g_dbus_connection_new_for_address_sync( + address, + GDBusConnectionFlags(G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT | G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION), + nullptr, + nullptr, + &g_error + ); if (!conn) { return -1; } - remote_desktop_proxy = g_dbus_proxy_new_sync(conn, G_DBUS_PROXY_FLAGS_NONE, nullptr, PORTAL_NAME, PORTAL_PATH, REMOTE_DESKTOP_IFACE, nullptr, nullptr); + + remote_desktop_proxy = g_dbus_proxy_new_sync( + conn, + G_DBUS_PROXY_FLAGS_NONE, + nullptr, + PORTAL_NAME, + PORTAL_PATH, + REMOTE_DESKTOP_IFACE, + nullptr, + &g_error + ); if (!remote_desktop_proxy) { return -1; } - screencast_proxy = g_dbus_proxy_new_sync(conn, G_DBUS_PROXY_FLAGS_NONE, nullptr, PORTAL_NAME, PORTAL_PATH, SCREENCAST_IFACE, nullptr, nullptr); + + screencast_proxy = g_dbus_proxy_new_sync( + conn, + G_DBUS_PROXY_FLAGS_NONE, + nullptr, + PORTAL_NAME, + PORTAL_PATH, + SCREENCAST_IFACE, + nullptr, + &g_error + ); if (!screencast_proxy) { return -1; } @@ -228,10 +340,12 @@ namespace portal { /** * @brief Connect to xdg-desktop-portal and restore or create a screencast session. * + * @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() { - g_autoptr(GMainLoop) loop = g_main_loop_new(nullptr, FALSE); + 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); @@ -244,7 +358,7 @@ namespace portal { return -1; } - if (start_portal_session(loop, session_path, pipewire_streams, use_screencast_only) < 0) { + if (start_portal_session(loop, session_path, pipewire_streams, use_screencast_only, allow_start_timeout) < 0) { return -1; } @@ -327,7 +441,7 @@ namespace portal { g_variant_new("(ss)", "org.freedesktop.portal.Session", "version"), G_VARIANT_TYPE("(v)"), G_DBUS_CALL_FLAGS_NONE, - -1, + dbus_timeout * 1000, nullptr, &err ); @@ -366,7 +480,7 @@ namespace portal { g_variant_builder_close(&builder); g_autoptr(GError) err = nullptr; - g_autoptr(GVariant) reply = g_dbus_proxy_call_sync(proxy, "CreateSession", g_variant_builder_end(&builder), G_DBUS_CALL_FLAGS_NONE, -1, nullptr, &err); + g_autoptr(GVariant) reply = g_dbus_proxy_call_sync(proxy, "CreateSession", g_variant_builder_end(&builder), G_DBUS_CALL_FLAGS_NONE, dbus_timeout * 1000, nullptr, &err); if (err) { BOOST_LOG(error) << "[portalgrab] Could not create "sv << session_type << " session: "sv << err->message; @@ -377,7 +491,7 @@ namespace portal { g_variant_get(reply, "(o)", &request_path); dbus_response_init(&response, loop, conn, request_path); - g_autoptr(GVariant) create_response = dbus_response_wait(&response); + g_autoptr(GVariant) create_response = dbus_response_wait(&response, dbus_timeout); if (!create_response) { BOOST_LOG(error) << "[portalgrab] " << session_type << " CreateSession: no response received"sv; @@ -432,7 +546,7 @@ namespace portal { g_variant_builder_close(&builder); g_autoptr(GError) err = nullptr; - g_autoptr(GVariant) reply = g_dbus_proxy_call_sync(remote_desktop_proxy, "SelectDevices", g_variant_builder_end(&builder), G_DBUS_CALL_FLAGS_NONE, -1, nullptr, &err); + g_autoptr(GVariant) reply = g_dbus_proxy_call_sync(remote_desktop_proxy, "SelectDevices", g_variant_builder_end(&builder), G_DBUS_CALL_FLAGS_NONE, dbus_timeout * 1000, nullptr, &err); if (err) { BOOST_LOG(error) << "[portalgrab] Could not select devices: "sv << err->message; @@ -443,7 +557,7 @@ namespace portal { g_variant_get(reply, "(o)", &request_path); dbus_response_init(&response, loop, conn, request_path); - g_autoptr(GVariant) devices_response = dbus_response_wait(&response); + g_autoptr(GVariant) devices_response = dbus_response_wait(&response, dbus_timeout); if (!devices_response) { BOOST_LOG(error) << "[portalgrab] SelectDevices: no response received"sv; @@ -484,7 +598,7 @@ namespace portal { g_variant_builder_close(&builder); g_autoptr(GError) err = nullptr; - g_autoptr(GVariant) reply = g_dbus_proxy_call_sync(screencast_proxy, "SelectSources", g_variant_builder_end(&builder), G_DBUS_CALL_FLAGS_NONE, -1, nullptr, &err); + g_autoptr(GVariant) reply = g_dbus_proxy_call_sync(screencast_proxy, "SelectSources", g_variant_builder_end(&builder), G_DBUS_CALL_FLAGS_NONE, dbus_timeout * 1000, nullptr, &err); if (err) { BOOST_LOG(error) << "[portalgrab] Could not select sources: "sv << err->message; return -1; @@ -494,7 +608,7 @@ namespace portal { g_variant_get(reply, "(o)", &request_path); dbus_response_init(&response, loop, conn, request_path); - g_autoptr(GVariant) sources_response = dbus_response_wait(&response); + g_autoptr(GVariant) sources_response = dbus_response_wait(&response, dbus_timeout); if (!sources_response) { BOOST_LOG(error) << "[portalgrab] SelectSources: no response received"sv; @@ -513,7 +627,7 @@ namespace portal { return 0; } - int start_portal_session(GMainLoop *loop, const gchar *session_path, std::vector &out_pipewire_streams, bool use_screencast) { + int 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"; @@ -530,7 +644,7 @@ namespace portal { g_variant_builder_close(&builder); g_autoptr(GError) err = nullptr; - g_autoptr(GVariant) reply = g_dbus_proxy_call_sync(proxy, "Start", g_variant_builder_end(&builder), G_DBUS_CALL_FLAGS_NONE, -1, nullptr, &err); + 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; @@ -540,7 +654,7 @@ namespace portal { g_variant_get(reply, "(o)", &request_path); dbus_response_init(&response, loop, conn, request_path); - g_autoptr(GVariant) start_response = dbus_response_wait(&response); + g_autoptr(GVariant) start_response = dbus_response_wait(&response, (allow_start_timeout ? dbus_timeout : 0)); if (!start_response) { BOOST_LOG(error) << "[portalgrab] " << session_type << " Start: no response received"sv; @@ -634,7 +748,7 @@ namespace portal { g_autoptr(GVariant) msg = g_variant_ref_sink(g_variant_new("(oa{sv})", session_path, nullptr)); g_autoptr(GError) err = nullptr; - g_autoptr(GVariant) reply = g_dbus_proxy_call_with_unix_fd_list_sync(screencast_proxy, "OpenPipeWireRemote", msg, G_DBUS_CALL_FLAGS_NONE, -1, nullptr, &fd_list, nullptr, &err); + g_autoptr(GVariant) reply = g_dbus_proxy_call_with_unix_fd_list_sync(screencast_proxy, "OpenPipeWireRemote", msg, G_DBUS_CALL_FLAGS_NONE, dbus_timeout * 1000, nullptr, &fd_list, nullptr, &err); if (err) { BOOST_LOG(error) << "[portalgrab] Could not open pipewire remote: "sv << err->message; return -1; @@ -690,14 +804,117 @@ namespace portal { } } - static void dbus_response_init(struct dbus_response_t *response, GMainLoop *loop, GDBusConnection *conn, const char *request_path) { - response->loop = loop; - response->subscription_id = g_dbus_connection_signal_subscribe(conn, PORTAL_NAME, REQUEST_IFACE, "Response", request_path, nullptr, G_DBUS_SIGNAL_FLAGS_NONE, on_response_received_cb, response, nullptr); + /** + * @brief Asynchronously close a pending Portal request. + */ + static void close_request_async(GDBusConnection *conn, const std::string &request_path) { + g_dbus_connection_call( + conn, + PORTAL_NAME, + request_path.c_str(), + REQUEST_IFACE, + "Close", + nullptr, + nullptr, + G_DBUS_CALL_FLAGS_NONE, + -1, + nullptr, + nullptr, + nullptr + ); } - static GVariant *dbus_response_wait(struct dbus_response_t *response) { + static void dbus_response_init(struct dbus_response_t *response, GMainLoop *loop, GDBusConnection *conn, const char *request_path) { + response->loop = loop; + response->conn = conn; + response->request_path = request_path; + + GMainContext *context = g_main_loop_get_context(loop); + g_main_context_push_thread_default(context); + + response->subscription_id = g_dbus_connection_signal_subscribe( + conn, + PORTAL_NAME, + REQUEST_IFACE, + "Response", + request_path, + nullptr, + G_DBUS_SIGNAL_FLAGS_NONE, + on_response_received_cb, + response, + nullptr + ); + + g_main_context_pop_thread_default(context); + } + + /** + * @brief Check for Sunshine shutdown and quit the Portal response loop if requested. + * + * @result True (continue) if shutdown event is not in progress. + */ + static gboolean check_shutdown_cb(gpointer user_data) { + if (auto shutdown_event = mail::man->event(mail::shutdown); shutdown_event->peek()) { + g_main_loop_quit(static_cast(user_data)); + return G_SOURCE_REMOVE; + } + return G_SOURCE_CONTINUE; + } + + /** + * @brief Check for DBus response with optional timeout guard. + * + * @param response DBus response. + * @param timeout_seconds Timeout in seconds before quitting loop. + * @return Variant containing the requested data. + */ + static GVariant *dbus_response_wait(dbus_response_t *response, guint timeout_seconds = 0) { + GSource *timeout_source = nullptr; + + if (timeout_seconds > 0) { + timeout_source = g_timeout_source_new(timeout_seconds * 1000); + g_source_set_callback( + timeout_source, + [](gpointer user_data) { + g_main_loop_quit(static_cast(user_data)); + return G_SOURCE_REMOVE; + }, + response->loop, + nullptr + ); + g_source_attach(timeout_source, g_main_loop_get_context(response->loop)); + } + + constexpr guint shutdown_poll_interval_ms = 1000; + GSource *shutdown_source = g_timeout_source_new(shutdown_poll_interval_ms); + g_source_set_callback(shutdown_source, check_shutdown_cb, response->loop, nullptr); + g_source_attach(shutdown_source, g_main_loop_get_context(response->loop)); + g_main_loop_run(response->loop); - return response->response; + + if (response->subscription_id != 0) { + g_dbus_connection_signal_unsubscribe( + response->conn, + response->subscription_id + ); + } + response->subscription_id = 0; + + g_source_destroy(shutdown_source); + g_source_unref(shutdown_source); + + if (timeout_source) { + g_source_destroy(timeout_source); + g_source_unref(timeout_source); + } + + if (response->response) { + return response->response; + } + + BOOST_LOG(info) << "[portalgrab] Portal request cancelled, timed out, or shutdown requested"sv; + close_request_async(response->conn, response->request_path); + return nullptr; } }; @@ -712,7 +929,7 @@ namespace portal { BOOST_LOG(error) << "[portalgrab] Failed to connect to dbus. portal_t setup failed."; return -1; } - if (dbus.connect_to_portal() < 0) { + if (dbus.connect_to_portal(false) < 0) { BOOST_LOG(error) << "[portalgrab] Failed to connect to portal. portal_t setup failed."; return -1; } @@ -816,9 +1033,10 @@ namespace platf { /** * @brief Enumerate capture targets available through xdg-desktop-portal. * + * @param allow_start_timeout True if "Start" DBus call is allowed to time out. * @return Portal display names, or an empty list when portal discovery fails. */ - std::vector portal_display_names() { + std::vector portal_display_names(bool allow_start_timeout) { std::vector display_names; auto dbus = std::make_shared(); @@ -827,14 +1045,7 @@ namespace platf { return {}; } - if (has_elevated_privileges(true)) { - // We're still in the probing phase of Sunshine startup. Dropping portal security early will break KMS. - // Just return a dummy screen for now. Display re-enumeration after encoder probing will yield full result. - display_names.emplace_back("init"); - return display_names; - } - - if (dbus->connect_to_portal() < 0) { + if (dbus->connect_to_portal(allow_start_timeout) < 0) { BOOST_LOG(warning) << "[portalgrab] Failed to connect to portal. Cannot enumerate displays, returning empty list."; return {}; }