5#define BOOST_BIND_GLOBAL_PLACEHOLDERS
7#ifndef BOOST_PROCESS_VERSION
8 #define BOOST_PROCESS_VERSION 1
29#include <unordered_map>
52#include <boost/algorithm/string.hpp>
53#include <boost/crc.hpp>
54#include <boost/filesystem.hpp>
55#include <boost/program_options/parsers.hpp>
56#include <boost/process/v1/search_path.hpp>
57#include <boost/property_tree/json_parser.hpp>
58#include <boost/property_tree/ptree.hpp>
59#include <openssl/evp.h>
60#include <openssl/sha.h>
88#define DEFAULT_APP_IMAGE_PATH HERMES_ASSETS_DIR "/box.png"
91 using namespace std::literals;
92 namespace pt = boost::property_tree;
96 int input_only_app_id = -1;
97 std::string input_only_app_id_str;
98 int terminate_app_id = -1;
99 std::string terminate_app_id_str;
103 static void finish_undo_command(
104 boost::process::v1::child &child,
105 boost::process::v1::group &group,
106 std::chrono::seconds exit_timeout
117 if (
app.force_virtual_display) {
129 return "the host runs headless";
131 return "forced by the app";
133 return "the client's choice";
137 return "the client's request or the app's default";
153 if (
app.force_scale_factor) {
159 if (
app.scale_factor != 100) {
165 std::string_view describe(scale_factor_source_e source) {
167 case scale_factor_source_e::app_forced:
168 return "forced by the app";
169 case scale_factor_source_e::client:
170 return "the client's choice";
171 case scale_factor_source_e::app:
172 return "the app's setting (the client sent none)";
173 case scale_factor_source_e::host_default:
176 return "the host default";
181 bool isolated_sessions_enabled,
182 bool virtual_display_requested,
183 std::string_view global_method
185 if (!isolated_sessions_enabled ||
app.host_session) {
186 return session_route_e::shared;
189 if (
app.isolation_method ==
"kwin_virtual") {
190 return session_route_e::isolated_desktop;
193 if (
app.isolation_method ==
"gamescope") {
194 return session_route_e::isolated_application;
197 if (!virtual_display_requested) {
198 return session_route_e::shared;
201 const auto &layout =
app.virtual_display_layout;
202 if (layout ==
"extend" || layout ==
"primary" || layout ==
"mirror" || layout ==
"exclusive") {
203 return session_route_e::shared;
207 return global_method ==
"kwin_virtual" ||
app.cmd.empty() ?
208 session_route_e::isolated_desktop :
209 session_route_e::isolated_application;
214 if (layout ==
"mirror") {
217 if (layout ==
"detached") {
218 return VDISPLAY::virtual_display_layout_e::detached;
220 if (layout ==
"primary") {
221 return VDISPLAY::virtual_display_layout_e::primary;
223 return VDISPLAY::virtual_display_layout_e::extend;
226 struct isolated_runtime_t {
227 uint32_t launch_session_id {};
228 std::string client_uuid;
229 std::string client_name;
232 std::string runtime_id;
234 std::string seatd_socket;
235 std::string runtime_dir;
241 std::string assets_dir;
242 std::optional<platf::session_broker::account_t> account;
246 bool user_unit {
false};
247 std::string kwin_wayland_socket;
248 std::string kwin_pipewire_socket;
249 std::string audio_sink;
250 std::string mic_source;
251 std::unique_ptr<platf::session_audio::server_t> audio_server;
252 pid_t namespace_pid {};
253 std::unique_ptr<platf::session_devices::mirror_t> device_mirror;
254 std::string isolated_seat_flag;
255 std::vector<int> held_x_displays;
256 std::chrono::steady_clock::time_point started_at {std::chrono::steady_clock::now()};
257 std::string wayland_display;
258 std::string drm_device_path;
259 std::string compositor_name;
260 bool discover_socket {
false};
261 std::string display_name;
262 uuid_util::uuid_t display_guid {};
263 boost::process::v1::environment env;
264 std::mutex process_mutex;
265 boost::process::v1::child process;
266 boost::process::v1::group process_group;
268 size_t prep_completed {};
269 std::atomic_bool stopping {
false};
272 std::mutex isolated_runtimes_mutex;
273 std::unordered_map<uint32_t, std::shared_ptr<isolated_runtime_t>> isolated_runtimes;
274 std::unordered_map<std::string, std::shared_ptr<std::atomic_bool>>
275 isolated_launching_clients;
284 std::string host_runtime_dir() {
285 if (
const char *dir = std::getenv(
"XDG_RUNTIME_DIR"); dir && *dir) {
291 std::string x_lock_path(
int display) {
292 return "/tmp/.X" + std::to_string(display) +
"-lock";
296 bool take_x_display(
int display) {
297 const auto path = x_lock_path(display);
298 for (
int attempt = 0; attempt < 2; ++attempt) {
299 if (
const int fd = ::open(path.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0444); fd >= 0) {
300 const auto pid = std::format(
"{:>10}\n", ::getpid());
301 const bool written = ::write(fd, pid.data(), pid.size()) ==
static_cast<ssize_t
>(pid.size());
304 ::unlink(path.c_str());
308 std::ifstream lock {path};
310 if (!(lock >> owner) || owner <= 0 || ::kill(
static_cast<pid_t
>(owner), 0) == 0 || errno != ESRCH) {
313 ::unlink(path.c_str());
322 std::vector<int> hold_x_display_gaps(
int count) {
323 std::vector<int> taken;
325 if (!take_x_display(display)) {
328 taken.push_back(display);
329 if (taken.size() >=
static_cast<size_t>(count) && taken[taken.size() - count] == display - count + 1) {
330 for (
int i = 0; i < count; ++i) {
331 ::unlink(x_lock_path(taken.back()).c_str());
337 for (
const int display : taken) {
338 ::unlink(x_lock_path(display).c_str());
345 void link_host_discord_ipc(
const std::string &runtime_dir) {
346 const auto host_runtime = host_runtime_dir();
347 if (host_runtime.empty()) {
350 for (
int i = 0; i < 10; ++i) {
351 const auto name =
"discord-ipc-" + std::to_string(i);
353 std::filesystem::create_symlink(std::filesystem::path {host_runtime} / name,
354 std::filesystem::path {runtime_dir} / name, ec);
362 std::optional<platf::session_devices::options_t> session_device_options(
const ctx_t &app) {
363 const platf::session_devices::options_t options {
app.isolate_devices !=
"off",
app.isolate_sound !=
"off"};
364 if ((!options.
devices && !options.
sound) || platf::session_devices::available()) {
367 if (
app.isolate_devices ==
"on" ||
app.isolate_sound ==
"on") {
368 BOOST_LOG(error) <<
"[IsolatedSession] " <<
app.name <<
" requires device isolation, but Hermes lacks "
369 "CAP_SYS_ADMIN and CAP_MKNOD (setcap cap_sys_admin,cap_mknod,cap_sys_chroot+p).";
372 BOOST_LOG(warning) <<
"[IsolatedSession] Hermes lacks CAP_SYS_ADMIN and CAP_MKNOD; "
373 <<
app.name <<
" sees the host's devices.";
374 return platf::session_devices::options_t {};
377 bool runs_steam(
const ctx_t &app) {
390 bool session_runs_steam(
const ctx_t &app) {
391 const auto starts_steam = [](
const std::string &
command) {
394 }
catch (
const std::exception &) {
398 return runs_steam(app) || starts_steam(
app.cmd) || std::ranges::any_of(
app.detached, starts_steam);
401 std::string read_proc_line(pid_t pid,
const char *file) {
402 std::ifstream stream {
"/proc/" + std::to_string(pid) +
"/" + file};
404 std::getline(stream, line);
408 std::optional<platf::desktop_steam::client_t> find_desktop_steam() {
409 const char *home = std::getenv(
"HOME");
410 return platf::desktop_steam::find(
"/proc", ::getuid(), std::string {home ? home :
""} +
"/.steam/steam.pid", read_proc_line(getpid(),
"cgroup"));
423 std::optional<platf::desktop_steam::client_t> stop_desktop_steam(std::string_view tag =
"[IsolatedSession]") {
424 const auto client = find_desktop_steam();
428 const pid_t pid = client->pid;
430 BOOST_LOG(info) << tag <<
" Shutting down the desktop's " << (client->flatpak ?
"Flatpak " :
"") <<
"Steam (pid " << pid <<
") first.";
431 ::kill(pid, SIGTERM);
432 const auto deadline = std::chrono::steady_clock::now() + 30s;
433 while (std::filesystem::exists(
"/proc/" + std::to_string(pid)) && std::chrono::steady_clock::now() < deadline) {
434 std::this_thread::sleep_for(100ms);
436 if (!std::filesystem::exists(
"/proc/" + std::to_string(pid))) {
437 BOOST_LOG(info) << tag <<
" The desktop's Steam has exited.";
442 BOOST_LOG(warning) << tag <<
" The desktop's Steam ignored SIGTERM for 30 s; killing it.";
443 std::vector<pid_t> tree {pid};
445 for (
bool grew =
true; grew;) {
447 for (
const auto &entry : std::filesystem::directory_iterator {
"/proc", ec}) {
448 const auto name = entry.path().filename().string();
449 if (!std::isdigit(
static_cast<unsigned char>(name[0]))) {
452 const pid_t child = std::stoi(name);
453 const auto stat = read_proc_line(child,
"stat");
454 const auto end = stat.rfind(
')');
456 if (end != std::string::npos && std::sscanf(stat.c_str() + end + 1,
" %*c %d", &parent) == 1 &&
457 std::ranges::contains(tree, parent) && !std::ranges::contains(tree, child)) {
458 tree.push_back(child);
463 for (
const auto member : tree) {
464 ::kill(member, SIGKILL);
469 std::string isolated_runtime_root() {
470 if (
const char *xdg_runtime_dir = std::getenv(
"XDG_RUNTIME_DIR");
471 xdg_runtime_dir && *xdg_runtime_dir) {
472 return (std::filesystem::path {xdg_runtime_dir} /
"hermes" /
"sessions").
string();
474 return (std::filesystem::path {
"/tmp"} /
475 (
"hermes-" + std::to_string(
static_cast<unsigned long>(::getuid()))) /
476 "sessions").
string();
479 std::string card_basename(
const std::string &device_path) {
480 return std::filesystem::path {device_path}.filename().string();
493 std::vector<std::string> split_command(
const std::string &command) {
494 std::vector<std::string> arguments;
495 std::istringstream stream {
command};
497 while (stream >> word) {
498 arguments.emplace_back(word);
518 struct compositor_profile_t {
520 std::string required_binary;
522 std::vector<std::pair<std::string, std::string>> env;
526 std::string config_template;
527 std::string config_target;
528 std::filesystem::path profile_dir;
531 bool discover_socket =
false;
538 std::vector<std::filesystem::path> compositor_profile_paths(
const std::string &name) {
539 const auto file = name +
".conf";
541 std::filesystem::path {
platf::appdata()} /
"session-compositors" / file,
542 std::filesystem::path {HERMES_ASSETS_DIR} /
"session-compositors" / file,
546 std::vector<std::pair<std::string, std::string>> parse_profile_env(
const std::string &value) {
547 std::vector<std::pair<std::string, std::string>> env;
548 std::stringstream stream {value};
550 while (std::getline(stream, entry,
',')) {
551 const auto begin = entry.find_first_not_of(
" \t");
552 if (begin == std::string::npos) {
555 const auto end = entry.find_last_not_of(
" \t");
556 entry = entry.substr(begin, end - begin + 1);
557 const auto split = entry.find(
'=');
558 if (split == std::string::npos || split == 0) {
561 env.emplace_back(entry.substr(0, split), entry.substr(split + 1));
566 std::optional<compositor_profile_t> read_compositor_profile(
567 const std::filesystem::path &path,
568 const std::string &name
572 const auto value = [&vars](
const std::string &key) -> std::string {
573 const auto it = vars.find(key);
574 return it == vars.end() ? std::string {} : it->second;
577 compositor_profile_t profile;
579 profile.command = value(
"command");
580 if (profile.command.empty()) {
581 BOOST_LOG(error) <<
"[IsolatedSession] Session compositor profile " << path
582 <<
" has no command.";
585 profile.required_binary = value(
"requires");
586 profile.discover_socket = value(
"socket") ==
"discovered";
587 profile.env = parse_profile_env(value(
"env"));
588 profile.config_template = value(
"config-template");
589 profile.config_target = value(
"config-target");
590 profile.profile_dir = path.parent_path();
591 if (profile.config_template.empty() != profile.config_target.empty()) {
592 BOOST_LOG(error) <<
"[IsolatedSession] Session compositor profile " << path
593 <<
" sets only one of config-template and config-target.";
597 BOOST_LOG(debug) <<
"[IsolatedSession] Loaded session compositor profile " << path;
602 std::optional<compositor_profile_t> load_compositor_profile(
const std::string &name) {
603 if (name.empty() || name.find(
'/') != std::string::npos || name ==
"..") {
604 BOOST_LOG(error) <<
"[IsolatedSession] Invalid session compositor name: " << name;
608 for (
const auto &path : compositor_profile_paths(name)) {
610 if (!std::filesystem::is_regular_file(path, ec)) {
613 return read_compositor_profile(path, name);
616 BOOST_LOG(error) <<
"[IsolatedSession] No session compositor profile named \"" << name
617 <<
"\" under " << (std::filesystem::path {
platf::appdata()} /
"session-compositors")
618 <<
" or " << (std::filesystem::path {HERMES_ASSETS_DIR} /
"session-compositors")
631 std::string expand_profile_template(
633 const std::vector<std::pair<std::string, std::string>> &values
635 for (
const auto &[key, value] : values) {
636 const std::string token =
"{" + key +
"}";
637 for (
auto pos = text.find(token); pos != std::string::npos; pos = text.find(token, pos + value.size())) {
638 text.replace(pos, token.size(), value);
665 std::string real_render_node_path() {
666 const auto usable = [](
const std::string &path) {
670 if (!config::video.adapter_name.empty()) {
671 const auto &node = config::video.adapter_name;
675 BOOST_LOG(warning) <<
"[IsolatedSession] adapter_name " << node
676 <<
" cannot allocate buffers; searching the other render nodes.";
680 std::filesystem::directory_iterator dir {
"/dev/dri", ec};
684 std::vector<std::string> nodes;
685 for (
const auto &entry : dir) {
686 const auto name = entry.path().filename().string();
687 if (!name.starts_with(
"renderD")) {
690 const int fd = ::open(entry.path().c_str(), O_RDWR | O_CLOEXEC);
694 drmVersionPtr
version = drmGetVersion(fd);
696 std::string_view {
version->name} !=
"hermes-kms";
698 drmFreeVersion(version);
702 nodes.emplace_back(entry.path().string());
705 std::sort(nodes.begin(), nodes.end());
707 for (
const auto &node : nodes) {
717 if (!nodes.empty()) {
718 BOOST_LOG(warning) <<
"[IsolatedSession] No render node could allocate a buffer; "
719 <<
"falling back to " << nodes.front()
720 <<
". Set adapter_name if the session renders nothing.";
721 return nodes.front();
726 std::string discover_wayland_socket(
const std::string &runtime_dir) {
728 std::vector<std::string> candidates;
729 for (std::filesystem::directory_iterator it {runtime_dir, ec}, end;
732 const auto name = it->path().filename().string();
733 if ((name.starts_with(
"gamescope-") || name.starts_with(
"wayland-")) &&
734 std::filesystem::is_socket(it->symlink_status(ec))) {
735 candidates.emplace_back(name);
738 std::sort(candidates.begin(), candidates.end());
739 return candidates.empty() ? std::string {} : candidates.front();
749 std::optional<std::string> gamescope_help_text(
const std::string &binary) {
751 if (::pipe2(pipe_fds, O_CLOEXEC) != 0) {
755 posix_spawn_file_actions_t actions;
756 ::posix_spawn_file_actions_init(&actions);
757 ::posix_spawn_file_actions_addopen(&actions, STDIN_FILENO,
"/dev/null", O_RDONLY, 0);
758 ::posix_spawn_file_actions_adddup2(&actions, pipe_fds[1], STDOUT_FILENO);
759 ::posix_spawn_file_actions_adddup2(&actions, pipe_fds[1], STDERR_FILENO);
760 std::string help_option {
"--help"};
761 std::string program {binary};
762 char *argv[] {program.data(), help_option.data(),
nullptr};
764 const int spawn_error = ::posix_spawn(&pid, program.c_str(), &actions,
nullptr, argv, environ);
765 ::posix_spawn_file_actions_destroy(&actions);
766 ::close(pipe_fds[1]);
767 if (spawn_error != 0) {
768 ::close(pipe_fds[0]);
769 BOOST_LOG(warning) <<
"[IsolatedSession] Could not run " << binary <<
" --help: "
770 << std::strerror(spawn_error);
775 constexpr std::size_t output_limit = 1 << 20;
776 const auto deadline = std::chrono::steady_clock::now() + 3s;
778 bool complete =
false;
780 const auto remaining = std::chrono::duration_cast<std::chrono::milliseconds>(
781 deadline - std::chrono::steady_clock::now()
783 if (remaining <= 0ms) {
786 pollfd pending {pipe_fds[0], POLLIN, 0};
787 const int ready = ::poll(&pending, 1,
static_cast<int>(remaining.count()));
788 if (ready < 0 && errno == EINTR) {
795 const auto read_size = ::read(pipe_fds[0], buffer,
sizeof(buffer));
796 if (read_size < 0 && errno == EINTR) {
799 if (read_size <= 0) {
800 complete = read_size == 0;
803 output.append(buffer,
static_cast<std::size_t
>(read_size));
804 if (output.size() > output_limit) {
808 ::close(pipe_fds[0]);
810 ::kill(pid, SIGKILL);
813 while (::waitpid(pid, &status, 0) < 0 && errno == EINTR) {
816 BOOST_LOG(warning) <<
"[IsolatedSession] " << binary <<
" --help did not finish in time.";
828 std::optional<platf::gamescope::drm_selector_e> gamescope_drm_selector(
const std::string &binary) {
829 static std::mutex probe_mutex;
830 static std::string probed_binary;
831 static std::filesystem::file_time_type probed_mtime {};
832 static std::optional<platf::gamescope::drm_selector_e> probed_selector;
834 std::error_code mtime_ec;
835 const auto mtime = std::filesystem::last_write_time(binary, mtime_ec);
837 std::lock_guard<std::mutex> lock(probe_mutex);
838 if (!mtime_ec && binary == probed_binary && mtime == probed_mtime) {
839 return probed_selector;
842 const auto help = gamescope_help_text(binary);
850 probed_binary = binary;
851 probed_mtime = mtime;
852 probed_selector = selector;
867 struct gamescope_install_t {
872 gamescope_install_t find_gamescope() {
873 const auto prefix_of = [](
const std::filesystem::path &binary) {
874 const auto dir = binary.parent_path();
875 return dir.filename() ==
"bin" ? dir.parent_path().string() : std::string {};
877 const auto usable = [](
const std::string &path) {
878 return !path.empty() &&
879 std::ranges::none_of(path, [](
unsigned char ch) {
return std::isspace(ch) != 0; }) &&
880 ::access(path.c_str(), X_OK) == 0;
883 if (
const char *forced = std::getenv(
"HERMES_GAMESCOPE"); forced && *forced) {
884 if (usable(forced)) {
885 return {forced, prefix_of(forced)};
887 BOOST_LOG(warning) <<
"[IsolatedSession] Ignoring HERMES_GAMESCOPE=" << forced
888 <<
": not an executable path without spaces.";
890 for (
const auto *prefix : {
"/usr/lib/hermes-gamescope",
"/opt/hermes-gamescope"}) {
891 const auto binary = (std::filesystem::path {prefix} /
"bin" /
"gamescope").
string();
892 if (usable(binary)) {
893 return {binary, prefix};
896 const auto found = boost::process::v1::search_path(
"gamescope").string();
897 return {usable(found) ? found : std::string {}, {}};
909 bool launch_into_session(
910 const std::shared_ptr<isolated_runtime_t> &runtime,
912 const std::string &command,
913 const std::string &scope,
916 if (runtime->account) {
917 const auto arguments = split_command(command);
918 if (arguments.empty()) {
922 for (
const auto &entry : runtime->env) {
923 environment.emplace_back(entry.get_name() +
"=" + entry.to_string());
926 runtime->client_uuid,
934 auto working_dir =
app.working_dir.empty() ?
935 find_working_directory(command, runtime->env) :
936 boost::filesystem::path {
app.working_dir};
938 auto child = platf::session_devices::run_command(
945 &runtime->process_group
954 std::string choose_isolated_profile(
const ctx_t &app) {
956 return route == session_route_e::isolated_desktop ?
"desktop" :
"application";
976 void erase_host_session_environment(boost::process::v1::environment &env) {
977 for (
const auto *name : {
980 "DBUS_SESSION_BUS_ADDRESS",
"DBUS_SESSION_BUS_PID",
981 "DBUS_STARTER_ADDRESS",
"DBUS_STARTER_BUS_TYPE",
983 "PULSE_SERVER",
"PULSE_COOKIE",
"PIPEWIRE_REMOTE",
985 "HOME",
"USER",
"LOGNAME",
"SHELL",
"XDG_RUNTIME_DIR",
986 "XDG_CACHE_HOME",
"XDG_CONFIG_HOME",
"XDG_DATA_HOME",
"XDG_STATE_HOME",
988 "SSH_AUTH_SOCK",
"GPG_AGENT_INFO",
"XAUTHORITY",
990 "XDG_SESSION_ID",
"XDG_SESSION_DESKTOP",
"DESKTOP_SESSION",
991 "KDE_FULL_SESSION",
"KDE_SESSION_UID",
"KDE_SESSION_VERSION",
992 "GNOME_DESKTOP_SESSION_ID",
998 void erase_host_graphical_session_environment(boost::process::v1::environment &env) {
999 for (
const auto *name : {
1000 "DBUS_SESSION_BUS_ADDRESS",
1001 "DBUS_SESSION_BUS_PID",
1002 "DBUS_STARTER_ADDRESS",
1003 "DBUS_STARTER_BUS_TYPE",
1010 "XDG_SESSION_DESKTOP",
1014 "KDE_SESSION_VERSION",
1015 "GNOME_DESKTOP_SESSION_ID",
1021 void populate_session_environment(
1022 boost::process::v1::environment &env,
1024 const rtsp_stream::launch_session_t &session,
1025 const isolated_runtime_t &runtime
1027 const auto render_width = session.width ? session.width : 1920;
1028 const auto render_height = session.height ? session.height : 1080;
1029 const auto fps_millihz = session.fps ? session.fps : 60000;
1030 char fps_buffer[16] {};
1031 std::snprintf(fps_buffer,
sizeof(fps_buffer),
"%.3f",
static_cast<double>(fps_millihz) / 1000.0);
1033 if (runtime.account) {
1036 erase_host_session_environment(env);
1038 erase_host_graphical_session_environment(env);
1039 env[
"XDG_RUNTIME_DIR"] = runtime.runtime_dir;
1045 if (runtime.audio_server) {
1046 env[
"PULSE_SERVER"] = runtime.audio_server->pulse_server();
1047 env[
"PIPEWIRE_REMOTE"] = runtime.audio_server->pipewire_remote();
1048 env[
"PIPEWIRE_RUNTIME_DIR"] = runtime.runtime_dir;
1049 env[
"PULSE_SINK"] = runtime.audio_sink;
1050 if (runtime.mic_source.empty()) {
1051 env.erase(
"PULSE_SOURCE");
1053 env[
"PULSE_SOURCE"] = runtime.mic_source;
1055 }
else if (
const auto host_runtime = host_runtime_dir(); !host_runtime.empty()) {
1056 env[
"PULSE_SERVER"] =
"unix:" + host_runtime +
"/pulse/native";
1057 env[
"PIPEWIRE_REMOTE"] = host_runtime +
"/pipewire-0";
1066 if (!runtime.audio_sink.empty() && !runtime.audio_server) {
1067 env[
"PULSE_SINK"] = runtime.audio_sink;
1069 env[
"XDG_SESSION_TYPE"] =
"wayland";
1070 env[
"XDG_SESSION_CLASS"] =
"user";
1071 env[
"XDG_SEAT"] = runtime.seat_id;
1072 env[
"WAYLAND_DISPLAY"] = runtime.wayland_display;
1073 env[
"DISPLAY"] =
"";
1074 env[
"LIBSEAT_BACKEND"] =
"seatd";
1075 env[
"SEATD_SOCK"] = runtime.seatd_socket;
1076 env[
"WLR_DRM_DEVICES"] = runtime.drm_device_path;
1078 env[
"WLR_LIBINPUT_NO_DEVICES"] =
"1";
1080 env[
"SUNSHINE_APP_ID"] =
app.id;
1081 env[
"SUNSHINE_APP_NAME"] =
app.name;
1082 env[
"SUNSHINE_CLIENT_WIDTH"] = std::to_string(render_width);
1083 env[
"SUNSHINE_CLIENT_HEIGHT"] = std::to_string(render_height);
1084 env[
"SUNSHINE_CLIENT_FPS"] = config::sunshine.envvar_compatibility_mode ?
1085 std::to_string(std::lround(
static_cast<double>(fps_millihz) / 1000.0)) :
1087 env[
"SUNSHINE_CLIENT_HDR"] = session.enable_hdr ?
"true" :
"false";
1089 env[
"APOLLO_APP_ID"] =
app.id;
1090 env[
"APOLLO_APP_NAME"] =
app.name;
1091 env[
"APOLLO_APP_UUID"] =
app.uuid;
1092 env[
"APOLLO_APP_STATUS"] =
"STARTING";
1093 env[
"APOLLO_CLIENT_UUID"] = session.unique_id;
1094 env[
"APOLLO_CLIENT_NAME"] = session.device_name;
1095 env[
"APOLLO_CLIENT_WIDTH"] = std::to_string(render_width);
1096 env[
"APOLLO_CLIENT_HEIGHT"] = std::to_string(render_height);
1097 env[
"APOLLO_CLIENT_RENDER_WIDTH"] = std::to_string(render_width);
1098 env[
"APOLLO_CLIENT_RENDER_HEIGHT"] = std::to_string(render_height);
1099 env[
"APOLLO_CLIENT_FPS"] = fps_buffer;
1101 env[
"HERMES_APP_ID"] =
app.id;
1102 env[
"HERMES_APP_NAME"] =
app.name;
1103 env[
"HERMES_APP_UUID"] =
app.uuid;
1104 env[
"HERMES_APP_STATUS"] =
"STARTING";
1105 env[
"HERMES_CLIENT_UUID"] = session.unique_id;
1106 env[
"HERMES_CLIENT_NAME"] = session.device_name;
1107 env[
"HERMES_CLIENT_WIDTH"] = std::to_string(render_width);
1108 env[
"HERMES_CLIENT_HEIGHT"] = std::to_string(render_height);
1109 env[
"HERMES_CLIENT_RENDER_WIDTH"] = std::to_string(render_width);
1110 env[
"HERMES_CLIENT_RENDER_HEIGHT"] = std::to_string(render_height);
1111 env[
"HERMES_CLIENT_FPS"] = fps_buffer;
1112 if (
app.limit_fps) {
1113 const auto existing = env.find(
"MANGOHUD_CONFIG");
1114 for (
const auto &[name, value] : frame_limit::environment(
1115 static_cast<int>(std::lround(
static_cast<double>(fps_millihz) / 1000.0)),
1116 existing != env.end() ?
existing->to_string() : std::string {})) {
1120 env[
"HERMES_SESSION_ID"] = runtime.runtime_id;
1121 env[
"HERMES_SESSION_SEAT"] = runtime.seat_id;
1122 env[
"HERMES_SEATD_SOCKET"] = runtime.seatd_socket;
1123 env[
"HERMES_SESSION_PROFILE"] = runtime.profile;
1124 env[
"HERMES_DRM_DEVICE"] = runtime.drm_device_path;
1125 env[
"HERMES_WAYLAND_DISPLAY"] = runtime.wayland_display;
1127 if (!session.enable_hdr) {
1128 env[
"DXVK_HDR"] =
"0";
1129 env[
"PROTON_ENABLE_HDR"] =
"0";
1137 int run_program(
const std::vector<std::string> &arguments, std::chrono::seconds timeout) {
1138 if (arguments.empty() || !arguments.front().starts_with(
'/')) {
1141 std::vector<char *> argv;
1142 for (
const auto &argument : arguments) {
1143 argv.push_back(
const_cast<char *
>(argument.c_str()));
1145 argv.push_back(
nullptr);
1146 const pid_t pid = ::fork();
1151 ::execv(argv.front(), argv.data());
1154 const auto deadline = std::chrono::steady_clock::now() +
timeout;
1157 const pid_t waited = ::waitpid(pid, &status, WNOHANG);
1158 if (waited == pid) {
1159 return WIFEXITED(status) ? WEXITSTATUS(status) : -1;
1161 if (waited < 0 && errno != EINTR) {
1164 if (std::chrono::steady_clock::now() >= deadline) {
1165 ::kill(pid, SIGKILL);
1166 ::waitpid(pid, &status, 0);
1167 BOOST_LOG(error) <<
"[IsolatedSession] " << arguments.front() <<
" timed out.";
1170 std::this_thread::sleep_for(20ms);
1174 std::string find_program(
const std::string &name) {
1175 const auto path = boost::process::v1::search_path(name);
1176 return path.empty() ? std::string {} : boost::filesystem::absolute(path).string();
1191 void reopen_desktop_steam(std::vector<std::string> environment,
bool flatpak) {
1192 const auto systemd_run = find_program(
"systemd-run");
1193 const char *launcher = flatpak ?
"flatpak" :
"steam";
1194 const auto steam = find_program(launcher);
1195 if (systemd_run.empty() || steam.empty()) {
1196 BOOST_LOG(warning) <<
"[Gamescope] Cannot start the desktop's Steam again: "
1197 << (systemd_run.empty() ?
"systemd-run" : launcher) <<
" is not in PATH.";
1200 std::thread {[systemd_run, steam, flatpak,
environment = std::move(environment)]() {
1201 const auto steam_running = []() {
1202 return find_desktop_steam().has_value();
1204 const auto deadline = std::chrono::steady_clock::now() + 30s;
1205 while (steam_running() && std::chrono::steady_clock::now() < deadline) {
1206 std::this_thread::sleep_for(250ms);
1208 if (steam_running()) {
1209 BOOST_LOG(warning) <<
"[Gamescope] The app's Steam is still running after 30 s; "
1210 "not starting the desktop's Steam again.";
1214 const auto unit =
"hermes-desktop-steam-" +
1215 std::to_string(std::chrono::duration_cast<std::chrono::seconds>(
1216 std::chrono::system_clock::now().time_since_epoch())
1218 std::vector<std::string> arguments {systemd_run,
"--user",
"--quiet",
"--collect",
"--unit=" + unit};
1219 for (
const auto &variable : environment) {
1220 arguments.push_back(
"--setenv=" + variable);
1222 arguments.push_back(
"--");
1223 arguments.push_back(steam);
1225 arguments.insert(arguments.end(), {
"run", std::string {platf::desktop_steam::flatpak_id}});
1227 arguments.push_back(
"-silent");
1228 if (run_program(arguments, 30s) == 0) {
1229 BOOST_LOG(info) <<
"[Gamescope] Started the desktop's Steam again (" << unit <<
").";
1231 BOOST_LOG(warning) <<
"[Gamescope] Could not start the desktop's Steam again.";
1240 std::string find_detached_session_tool() {
1242 const auto self = std::filesystem::canonical(
"/proc/self/exe", ec);
1244 const auto sibling = self.parent_path() /
"hermes-detached-session";
1245 if (::access(sibling.c_str(), X_OK) == 0) {
1246 return sibling.string();
1249 return find_program(
"hermes-detached-session");
1252 std::string detached_unit_name(
const std::string &runtime_id) {
1253 return "hermes-detached-" + runtime_id +
".scope";
1260 std::string own_service_unit() {
1261 std::ifstream cgroup {
"/proc/self/cgroup"};
1263 while (std::getline(cgroup, line)) {
1264 const auto slash = line.rfind(
'/');
1265 if (slash == std::string::npos) {
1268 const auto unit = line.substr(slash + 1);
1269 if (unit.ends_with(
".service") && !unit.starts_with(
"user@")) {
1276 void stop_user_unit(
const std::string &unit) {
1277 if (
const auto systemctl = find_program(
"systemctl"); !systemctl.empty()) {
1278 run_program({systemctl,
"--user",
"stop", unit}, 30s);
1284 std::mutex encoder_probe_mutex;
1286 std::string read_small_file(
const std::filesystem::path &path) {
1287 std::ifstream file {path};
1288 std::string text {std::istreambuf_iterator<char> {file}, {}};
1289 while (!text.empty() && (text.back() ==
'\n' || text.back() ==
'\r')) {
1292 return text.size() > 512 ? text.substr(0, 512) : text;
1300 std::string detached_wayland_socket(
const std::string &runtime_dir) {
1301 std::ifstream ready {std::filesystem::path {runtime_dir} /
"ready"};
1303 constexpr std::string_view key {
"WAYLAND_DISPLAY="};
1304 while (std::getline(ready, line)) {
1305 if (!line.starts_with(key)) {
1308 const auto name = line.substr(key.size());
1309 if (name.empty() || name.find(
'/') != std::string::npos) {
1312 return (std::filesystem::path {runtime_dir} / name).
string();
1325 bool start_in_detached_desktop(
const isolated_runtime_t &runtime,
const ctx_t &
app,
const std::string &command,
const std::string &name) {
1326 const auto arguments = boost::program_options::split_unix(command);
1327 if (arguments.empty()) {
1330 std::string request =
app.working_dir;
1332 for (
const auto &argument : arguments) {
1333 request += argument;
1337 const auto directory = std::filesystem::path {runtime.runtime_dir} /
"launch";
1338 const auto path = directory / name;
1340 std::filesystem::create_directories(directory, ec);
1341 std::filesystem::remove(std::filesystem::path {path} +=
".error", ec);
1343 std::ofstream stream {std::filesystem::path {path} +=
".tmp", std::ios::binary | std::ios::trunc};
1345 if (!stream.flush()) {
1346 BOOST_LOG(error) <<
"[IsolatedSession] Could not ask detached desktop " << runtime.runtime_id <<
" to start [" <<
command <<
']';
1350 std::filesystem::rename(std::filesystem::path {path} +=
".tmp", path, ec);
1352 BOOST_LOG(error) <<
"[IsolatedSession] Could not ask detached desktop " << runtime.runtime_id <<
" to start [" <<
command <<
"]: " << ec.message();
1356 BOOST_LOG(info) <<
"[IsolatedSession] Starting [" <<
command <<
"] in detached desktop " << runtime.runtime_id;
1357 const auto deadline = std::chrono::steady_clock::now() + 5s;
1358 while (std::filesystem::exists(path, ec) && std::chrono::steady_clock::now() < deadline) {
1359 std::this_thread::sleep_for(50ms);
1361 if (std::filesystem::exists(path, ec)) {
1362 BOOST_LOG(warning) <<
"[IsolatedSession] Detached desktop " << runtime.runtime_id <<
" has not picked up [" <<
command <<
"] yet.";
1365 if (
const auto reason = read_small_file(std::filesystem::path {path} +=
".error"); !reason.empty()) {
1366 BOOST_LOG(error) <<
"[IsolatedSession] Detached desktop " << runtime.runtime_id <<
" could not start [" <<
command <<
"]: " << reason;
1376 bool detached_desktop_alive(
const isolated_runtime_t &runtime) {
1378 if (std::filesystem::exists(std::filesystem::path {runtime.runtime_dir} /
"failure", ec)) {
1379 BOOST_LOG(info) <<
"[IsolatedSession] Detached desktop " << runtime.runtime_id <<
" reported a failure: "
1380 << read_small_file(std::filesystem::path {runtime.runtime_dir} /
"failure");
1383 const auto socket = detached_wayland_socket(runtime.runtime_dir);
1384 if (socket.empty()) {
1393 for (
int attempt = 0; attempt < 5; ++attempt) {
1395 std::this_thread::sleep_for(100ms);
1397 if (VDISPLAY::displayServerReachable(socket, {}, {})) {
1399 BOOST_LOG(info) <<
"[IsolatedSession] Detached desktop " << runtime.runtime_id <<
" answered after "
1400 << attempt + 1 <<
" tries.";
1405 BOOST_LOG(info) <<
"[IsolatedSession] Detached desktop " << runtime.runtime_id <<
" does not answer on " << socket <<
": "
1406 << std::strerror(errno);
1410 bool isolated_runtime_running(
const std::shared_ptr<isolated_runtime_t> &runtime) {
1411 if (!runtime || runtime->stopping.load()) {
1414 if (runtime->user_unit) {
1415 return detached_desktop_alive(*runtime);
1420 if (!runtime->unit.empty()) {
1424 return active && !runtime->stopping.load();
1426 std::lock_guard<std::mutex> lock(runtime->process_mutex);
1427 return !runtime->stopping.load() && runtime->process.valid() && runtime->process.running();
1430 void stop_isolated_runtime(
const std::shared_ptr<isolated_runtime_t> &runtime) {
1431 if (!runtime || runtime->stopping.exchange(
true)) {
1435 BOOST_LOG(info) <<
"[IsolatedSession] Stopping " << runtime->runtime_id
1436 <<
" for client " << runtime->client_name;
1437 if (runtime->user_unit) {
1439 std::lock_guard<std::mutex> lock(runtime->process_mutex);
1441 if (!runtime->unit.empty()) {
1442 stop_user_unit(runtime->unit);
1443 runtime->unit.clear();
1446 if (runtime->process.valid()) {
1447 std::error_code wait_ec;
1448 if (runtime->process.running(wait_ec)) {
1449 runtime->process.terminate(wait_ec);
1451 runtime->process.wait(wait_ec);
1452 runtime->process = boost::process::v1::child {};
1454 }
else if (!runtime->unit.empty()) {
1461 std::lock_guard<std::mutex> lock(runtime->process_mutex);
1464 runtime->process_group,
1465 runtime->app.exit_timeout
1467 runtime->process = boost::process::v1::child {};
1468 runtime->process_group = boost::process::v1::group {};
1470 auto stopping_env = runtime->env;
1471 stopping_env[
"APOLLO_APP_STATUS"] =
"TERMINATING";
1472 stopping_env[
"HERMES_APP_STATUS"] =
"TERMINATING";
1474 for (
size_t index = runtime->prep_completed; index > 0; --index) {
1475 const auto &cmd = runtime->app.prep_cmds[index - 1];
1476 if (cmd.undo_cmd.empty()) {
1480 auto working_dir = runtime->app.working_dir.empty() ?
1481 find_working_directory(cmd.undo_cmd, stopping_env) :
1482 boost::filesystem::path {runtime->
app.working_dir};
1483 BOOST_LOG(info) <<
"[IsolatedSession] Executing Undo Cmd: [" << cmd.undo_cmd <<
']';
1484 boost::process::v1::group undo_group;
1485 auto child = platf::run_command(
1491 runtime->pipe.get(),
1496 finish_undo_command(child, undo_group, runtime->app.exit_timeout);
1498 BOOST_LOG(warning) <<
"[IsolatedSession] Undo command failed to start: " << ec.message();
1502 if (runtime->audio_server) {
1503 runtime->audio_server.reset();
1504 }
else if (!runtime->audio_sink.empty()) {
1507 if (runtime->user_unit && !runtime->seat_id.empty()) {
1511#ifdef HERMES_BUILD_KWIN_TRANSPORT
1512 if (runtime->user_unit && !runtime->kwin_wayland_socket.empty()) {
1514 platf::forget_private_kwin_input(runtime->kwin_wayland_socket);
1517 runtime->device_mirror.reset();
1518 runtime->namespace_pid = 0;
1519 if (!runtime->isolated_seat_flag.empty()) {
1520 std::error_code flag_ec;
1521 std::filesystem::remove(runtime->isolated_seat_flag, flag_ec);
1522 runtime->isolated_seat_flag.clear();
1524 for (
const int display : runtime->held_x_displays) {
1525 ::unlink(x_lock_path(display).c_str());
1527 runtime->held_x_displays.clear();
1529 runtime->pipe.reset();
1530 if (!runtime->display_name.empty()) {
1536 std::error_code remove_ec;
1537 std::filesystem::remove_all(runtime->assets_dir, remove_ec);
1539 BOOST_LOG(debug) <<
"[IsolatedSession] Could not remove runtime directory "
1540 << runtime->assets_dir <<
": " << remove_ec.message();
1544 std::shared_ptr<isolated_runtime_t> find_isolated_client_locked(
const std::string &client_uuid) {
1545 for (
const auto &[
id, runtime] : isolated_runtimes) {
1546 if (runtime && runtime->client_uuid == client_uuid) {
1557 void seed_isolated_runtime_for_test(uint32_t
id,
const std::string &client_uuid) {
1558 auto runtime = std::make_shared<isolated_runtime_t>();
1559 runtime->launch_session_id = id;
1560 runtime->client_uuid = client_uuid;
1561 runtime->app.id =
"123";
1562 runtime->app.uuid =
"runtime-test-app";
1563 runtime->unit =
"hermes-session-01.service";
1564 runtime->env[
"HERMES_REGISTRY_TEST"] =
"ready";
1565 std::lock_guard<std::mutex> lock(isolated_runtimes_mutex);
1566 isolated_runtimes[id] = runtime;
1569 void erase_isolated_runtime_for_test(uint32_t
id) {
1570 std::lock_guard<std::mutex> lock(isolated_runtimes_mutex);
1571 isolated_runtimes.erase(
id);
1575 void onVDisplayWatchdogFailed() {
1584 onVDisplayWatchdogFailed();
1593 proc.terminate_all_isolated();
1601 std::unique_ptr<platf::deinit_t>
init() {
1605 if (
const auto systemctl = find_program(
"systemctl"); !systemctl.empty()) {
1606 run_program({systemctl,
"--user",
"--quiet",
"stop",
"hermes-detached-*.scope",
"hermes-detached-*.service"}, 30s);
1608 return std::make_unique<deinit_t>();
1611 void terminate_process_group(boost::process::v1::child &proc, boost::process::v1::group &group, std::chrono::seconds exit_timeout) {
1612 if (group.valid()) {
1613 const auto handle = (std::uintptr_t) group.native_handle();
1614 const auto running = [handle]() {
1617 platf::process_group::reap_children(handle);
1622 BOOST_LOG(info) <<
"Successfully requested the app to exit. Waiting up to "sv
1623 << exit_timeout.count() <<
" seconds for it to close."sv;
1624 const auto deadline = std::chrono::steady_clock::now() + exit_timeout;
1625 while (running() && std::chrono::steady_clock::now() < deadline) {
1626 std::this_thread::sleep_for(50ms);
1629 BOOST_LOG(warning) <<
"App did not fully exit within the timeout. Terminating the app's remaining processes."sv;
1631 BOOST_LOG(info) <<
"All app processes have successfully exited."sv;
1634 BOOST_LOG(info) <<
"Forcefully terminating the app's remaining processes."sv;
1638 group.terminate(ec);
1639 if (ec && ec != std::errc::no_such_process) {
1640 BOOST_LOG(warning) <<
"Unable to terminate app process group [" << handle <<
"]: " << ec.message();
1644 const auto deadline = std::chrono::steady_clock::now() + 1s;
1645 while (running() && std::chrono::steady_clock::now() < deadline) {
1646 std::this_thread::sleep_for(10ms);
1649 BOOST_LOG(warning) <<
"App process group [" << handle <<
"] still exists after forced termination.";
1662 static void finish_undo_command(
1663 boost::process::v1::child &child,
1664 boost::process::v1::group &group,
1665 std::chrono::seconds exit_timeout
1669 return child.running(ec);
1670 }, std::max(10s, exit_timeout));
1672 BOOST_LOG(warning) <<
"Undo command exceeded its cleanup deadline; terminating its process group.";
1677 BOOST_LOG(warning) <<
"Unable to read undo command status: " << ec.message();
1678 }
else if (child.exit_code() != 0) {
1679 BOOST_LOG(warning) <<
"Undo command exited with code [" << child.exit_code() <<
']';
1685 boost::filesystem::path find_working_directory(
const std::string &cmd,
const boost::process::v1::environment &env) {
1687 auto parts = boost::program_options::split_unix(cmd);
1688 if (parts.empty()) {
1689 BOOST_LOG(error) <<
"Unable to parse command: "sv << cmd;
1690 return boost::filesystem::path();
1693 BOOST_LOG(debug) <<
"Parsed target ["sv << parts.at(0) <<
"] from command ["sv << cmd <<
']';
1696 if (parts.at(0).find(
"://") != std::string::npos) {
1697 return boost::filesystem::path();
1701 boost::filesystem::path cmd_path(parts.at(0));
1702 if (!cmd_path.is_absolute()) {
1703 cmd_path = boost::process::v1::search_path(parts.at(0));
1704 if (cmd_path.empty()) {
1705 BOOST_LOG(error) <<
"Unable to find executable ["sv << parts.at(0) <<
"]. Is it in your PATH?"sv;
1706 return boost::filesystem::path();
1710 BOOST_LOG(debug) <<
"Resolved target ["sv << parts.at(0) <<
"] to path ["sv << cmd_path <<
']';
1713 return cmd_path.parent_path();
1716 void proc_t::launch_input_only() {
1717 _app_id = input_only_app_id;
1718 _app_name =
"Remote Input";
1719 _app.uuid = REMOTE_INPUT_UUID;
1720 _app.terminate_on_pause =
true;
1721 allow_client_commands =
false;
1724#if defined HERMES_TRAY && HERMES_TRAY >= 1
1730 std::shared_ptr<rtsp_stream::launch_session_t> launch_session,
1732 const ctx_t *session_app,
1733 std::optional<uid_t> session_owner_uid,
1734 bool isolated_session
1736 if (config::video.virtual_display_backend !=
"hermes_kms" ||
1738 !config::video.hermes_kms_isolated_sessions :
1739 !config::video.hermes_kms_multi_output)) {
1743 const auto &
app = session_app ? *session_app : _app;
1745 uint32_t render_width = launch_session->width ? launch_session->width : 1920;
1746 uint32_t render_height = launch_session->height ? launch_session->height : 1080;
1747 const int scale_factor =
1749 if (scale_factor != 100) {
1750 render_width =
static_cast<uint32_t
>(render_width * (
static_cast<float>(scale_factor) / 100.0f)) & ~1U;
1751 render_height =
static_cast<uint32_t
>(render_height * (
static_cast<float>(scale_factor) / 100.0f)) & ~1U;
1753 launch_session->width = render_width;
1754 launch_session->height = render_height;
1761 BOOST_LOG(error) <<
"[VDISPLAY/Hermes-KMS] Cannot allocate a session output because the driver is unavailable.";
1765 std::string device_name;
1766 std::string device_uuid_str;
1768 if (
app.use_app_identity) {
1769 device_name =
app.name;
1770 if (
app.per_client_app_identity) {
1771 device_uuid = uuid_util::uuid_t::parse(launch_session->unique_id);
1772 auto app_uuid_string =
app.uuid;
1773 const auto app_uuid = uuid_util::uuid_t::parse(app_uuid_string);
1774 device_uuid.b64[0] ^= app_uuid.b64[0];
1775 device_uuid.b64[1] ^= app_uuid.b64[1];
1776 device_uuid_str = device_uuid.string();
1780 device_uuid = uuid_util::uuid_t::parse(launch_session->unique_id);
1781 device_uuid_str = device_uuid.string();
1784 device_name = launch_session->device_name;
1785 device_uuid_str = launch_session->unique_id;
1786 device_uuid = uuid_util::uuid_t::parse(launch_session->unique_id);
1789 if (isolated_session) {
1792 device_uuid.b32[2] ^= launch_session->id;
1793 device_uuid_str = device_uuid.string();
1796 launch_session->display_guid = device_uuid;
1797 int target_fps = launch_session->fps ? launch_session->fps : 60000;
1798 if (target_fps < 1000) {
1801 if (config::video.double_refreshrate) {
1806 device_uuid_str.c_str(),
1807 device_name.c_str(),
1808 launch_session->width,
1809 launch_session->height,
1811 launch_session->display_guid,
1813 linux_virtual_display_layout(
app.virtual_display_layout),
1816 if (display_name.empty()) {
1821 display_name.c_str(),
1822 launch_session->width,
1823 launch_session->height,
1829 BOOST_LOG(warning) <<
"Virtual display did not reach "sv << launch_session->width <<
'x'
1830 << launch_session->height <<
"; streaming the display's active mode instead."sv;
1832 if (!isolated_session &&
1834 BOOST_LOG(error) <<
"[VDISPLAY/Hermes-KMS] The compositor did not activate session output "
1835 << display_name <<
"; removing it instead of capturing another monitor.";
1840 launch_session->virtual_display =
true;
1841 launch_session->session_scoped_virtual_display =
true;
1842 launch_session->session_virtual_display_cleanup_pending =
true;
1843 launch_session->display_name = display_name;
1845 if (isolated_session &&
1846 launch_session->drm_device_path.empty()) {
1847 BOOST_LOG(error) <<
"[VDISPLAY/Hermes-KMS] Could not resolve the independent DRM card for "
1850 launch_session->session_virtual_display_cleanup_pending =
false;
1851 launch_session->session_scoped_virtual_display =
false;
1852 launch_session->display_name.clear();
1855 BOOST_LOG(info) <<
"[VDISPLAY/Hermes-KMS] Experimental session-scoped output "
1856 << display_name <<
" assigned to client " << launch_session->device_name;
1857 if (config::video.isolated_virtual_display_option) {
1858 BOOST_LOG(warning) <<
"[VDISPLAY/Hermes-KMS] Host exclusive-display mode does not apply to "
1859 "experimental session-scoped outputs; physical and other client "
1860 "sessions remain active.";
1867 std::shared_ptr<rtsp_stream::launch_session_t> launch_session
1869 if (!config::video.hermes_kms_isolated_sessions ||
1870 config::video.virtual_display_backend !=
"hermes_kms") {
1871 launch_session->launch_error_message =
"Independent-session capability is unavailable.";
1874 if (
app.host_session) {
1875 BOOST_LOG(error) <<
"[IsolatedSession] A host-session app was incorrectly routed "
1876 "to the isolated-session executor.";
1880 std::shared_ptr<isolated_runtime_t> stale_runtime;
1881 auto launch_cancelled = std::make_shared<std::atomic_bool>(
false);
1883 std::lock_guard<std::mutex> lock(isolated_runtimes_mutex);
1884 if (isolated_launching_clients.contains(launch_session->unique_id)) {
1885 BOOST_LOG(warning) <<
"[IsolatedSession] Client " << launch_session->device_name
1886 <<
" already has a launch in progress.";
1889 stale_runtime = find_isolated_client_locked(launch_session->unique_id);
1890 isolated_launching_clients.emplace(
1891 launch_session->unique_id,
1895 auto release_launch_reservation = util::fail_guard([
1896 client_uuid = launch_session->unique_id,
1899 std::lock_guard<std::mutex> lock(isolated_runtimes_mutex);
1900 const auto it = isolated_launching_clients.find(client_uuid);
1901 if (it != isolated_launching_clients.end() &&
1902 it->second == launch_cancelled) {
1903 isolated_launching_clients.erase(it);
1909 if (isolated_runtime_running(stale_runtime)) {
1910 BOOST_LOG(warning) <<
"[IsolatedSession] Client " << launch_session->device_name
1911 <<
" already owns runtime " << stale_runtime->runtime_id;
1914 if (stale_runtime) {
1916 std::lock_guard<std::mutex> lock(isolated_runtimes_mutex);
1917 const auto it = isolated_runtimes.find(stale_runtime->launch_session_id);
1918 if (it != isolated_runtimes.end() && it->second == stale_runtime) {
1919 isolated_runtimes.erase(it);
1922 stop_isolated_runtime(stale_runtime);
1924 auto launch_was_cancelled = [&]() {
1925 if (!launch_cancelled->load(std::memory_order_relaxed)) {
1928 BOOST_LOG(info) <<
"[IsolatedSession] Launch cancelled for client "
1929 << launch_session->device_name;
1933 if (launch_was_cancelled()) {
1937 auto runtime = std::make_shared<isolated_runtime_t>();
1938 runtime->launch_session_id = launch_session->id;
1939 runtime->client_uuid = launch_session->unique_id;
1940 runtime->client_name = launch_session->device_name;
1942 runtime->profile = choose_isolated_profile(app);
1943 runtime->runtime_id =
"hermes-s" + std::to_string(launch_session->id);
1944 runtime->wayland_display =
"wayland-" + runtime->runtime_id;
1945 runtime->assets_dir =
1946 (std::filesystem::path {isolated_runtime_root()} / runtime->runtime_id).
string();
1947 runtime->runtime_dir = runtime->assets_dir;
1951 auto cleanup = util::fail_guard([&]() {
1952 stop_isolated_runtime(runtime);
1953 if (launch_session->session_virtual_display_cleanup_pending) {
1956 if (runtime->display_name.empty()) {
1959 launch_session->session_virtual_display_cleanup_pending =
false;
1960 launch_session->session_scoped_virtual_display =
false;
1961 launch_session->display_name.clear();
1971 const bool own_plasma_desktop =
1972 runtime->profile ==
"desktop" && config::video.hermes_kms_session_compositor ==
"plasma";
1975 if (!runtime->account) {
1979 BOOST_LOG(error) <<
"[IsolatedSession] The session broker is running but would not "
1980 "provide an account for this client. Refusing to start the "
1981 "session as the host user.";
1984 runtime->runtime_dir =
"/run/user/" + std::to_string(runtime->account->uid);
1988 if (!runtime->account && (
app.stop_desktop_steam ==
"on" || (
app.stop_desktop_steam !=
"off" && session_runs_steam(app)))) {
1989 stop_desktop_steam();
1990 if (launch_was_cancelled()) {
1995 std::error_code dir_ec;
1996 std::filesystem::create_directories(runtime->assets_dir, dir_ec);
2000 const auto assets_mode = runtime->account ?
2001 static_cast<mode_t
>(S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) :
2002 static_cast<mode_t>(S_IRWXU);
2003 if (dir_ec || ::chmod(runtime->assets_dir.c_str(), assets_mode) != 0) {
2004 BOOST_LOG(error) <<
"[IsolatedSession] Could not create private runtime directory "
2005 << runtime->assets_dir <<
": "
2006 << (dir_ec ? dir_ec.message() : std::strerror(errno));
2009 if (!runtime->account) {
2010 link_host_discord_ipc(runtime->runtime_dir);
2025 if (!runtime->account) {
2026 const int audio_channels = launch_session->surround_info & 65535;
2027 const std::string audio_sink =
"sink-" + runtime->runtime_id;
2031 const auto mic_source = platf::session_mic_source(audio_sink);
2032 runtime->audio_server = platf::session_audio::start(runtime->runtime_dir, audio_sink, audio_channels, mic_source);
2033 if (runtime->audio_server) {
2034 runtime->audio_sink = audio_sink;
2036 if (config::audio.stream_mic) {
2037 runtime->mic_source = mic_source;
2039 }
else if (own_plasma_desktop) {
2042 launch_session->launch_error_message =
"Could not start the KWin virtual desktop's own audio server.";
2043 BOOST_LOG(error) <<
"[IsolatedSession] Could not start a private audio server for "
2044 << runtime->runtime_id <<
"; refusing to share the host's audio devices.";
2047 runtime->audio_sink = audio_sink;
2048 BOOST_LOG(info) <<
"[IsolatedSession] Session " << runtime->runtime_id <<
" plays into "
2049 << audio_sink <<
" on the host's audio server (" << audio_channels <<
" channels).";
2050 }
else if (runtime->profile ==
"desktop") {
2051 launch_session->launch_error_message =
"Could not create the KWin virtual desktop's private audio sink.";
2052 BOOST_LOG(error) <<
"[IsolatedSession] Could not create a private audio sink for "
2053 << runtime->runtime_id <<
"; refusing to capture host audio.";
2056 BOOST_LOG(warning) <<
"[IsolatedSession] Could not create a private audio sink for "
2057 << runtime->runtime_id
2058 <<
"; this session will share the host's audio, and the client will "
2059 "hear whatever the host is playing.";
2062 BOOST_LOG(warning) <<
"[IsolatedSession] Session " << runtime->runtime_id
2063 <<
" runs as its own user, which has an audio server Hermes cannot "
2064 "reach; audio for this session is not isolated yet.";
2077 if (runtime->profile ==
"desktop" && config::video.hermes_kms_session_compositor ==
"plasma") {
2078 if (!app.prep_cmds.empty()) {
2081 BOOST_LOG(info) <<
"[IsolatedSession] Not running " << app.prep_cmds.size()
2082 <<
" prep command(s) for a detached desktop; they act on the host desktop.";
2087 const auto plasma_failed = [&](
const std::string &reason) {
2088 constexpr std::string_view fallback {
2089 " To use Weston instead, if it is installed, set hermes_kms_session_compositor = weston."
2091 launch_session->launch_error_message =
"The KWin virtual desktop " + reason +
'.' + std::string {fallback};
2092 BOOST_LOG(error) <<
"[IsolatedSession] " << launch_session->launch_error_message;
2096 #ifndef HERMES_BUILD_KWIN_TRANSPORT
2097 return plasma_failed(
2098 "is not available: Hermes was built without the KWin transport, which needs "
2099 "plasma-wayland-protocols 1.23 or newer"
2102 const auto systemd_run = find_program(
"systemd-run");
2103 const auto dbus_run_session = find_program(
"dbus-run-session");
2104 const auto session_tool = find_detached_session_tool();
2105 std::error_code self_ec;
2106 const auto self = std::filesystem::canonical(
"/proc/self/exe", self_ec);
2107 std::vector<std::string>
missing;
2108 for (
const auto &[name, path] : std::initializer_list<std::pair<const char *, std::string>> {
2109 {
"kwin_wayland_wrapper", find_program(
"kwin_wayland_wrapper")},
2110 {
"startplasma-wayland", find_program(
"startplasma-wayland")},
2111 {
"kscreen-doctor", find_program(
"kscreen-doctor")},
2112 {
"systemd-run", systemd_run},
2113 {
"dbus-run-session", dbus_run_session},
2114 {
"hermes-detached-session", session_tool},
2122 for (
const auto &name : missing) {
2123 list += (list.empty() ?
"" :
", ") + name;
2125 return plasma_failed(
"cannot start: " + list +
" not found");
2128 return plasma_failed(
"cannot start: Hermes cannot resolve its own executable");
2137 std::lock_guard<std::mutex> probe_lock(encoder_probe_mutex);
2139 launch_session->launch_error_message =
"No working video encoder was found for the KWin virtual desktop.";
2140 BOOST_LOG(error) <<
"[IsolatedSession] " << launch_session->launch_error_message;
2145 const int width =
static_cast<int>(launch_session->width ? launch_session->width : 1920);
2146 const int height =
static_cast<int>(launch_session->height ? launch_session->height : 1080);
2147 runtime->user_unit =
true;
2148 runtime->unit = detached_unit_name(runtime->runtime_id);
2152 runtime->kwin_pipewire_socket = runtime->audio_server->pipewire_remote();
2155 stop_user_unit(runtime->unit);
2156 for (
const auto *stale : {
"ready",
"failure",
"status"}) {
2157 std::error_code remove_ec;
2158 std::filesystem::remove(std::filesystem::path {runtime->runtime_dir} / stale, remove_ec);
2169 std::vector<std::string>
command {
2175 "--unit=" + runtime->unit,
2176 "--property=TimeoutStopSec=15",
2178 if (
const auto owner = own_service_unit(); !owner.empty()) {
2181 command.push_back(
"--property=StopPropagatedFrom=" + owner);
2188 for (
const auto *name : {
"DISPLAY",
"WAYLAND_DISPLAY",
"WAYLAND_SOCKET",
"XAUTHORITY",
"DBUS_SESSION_BUS_ADDRESS",
"SESSION_MANAGER",
"XDG_SESSION_ID",
"XDG_SEAT",
"XDG_VTNR",
"XDG_SESSION_DESKTOP",
"XDG_CURRENT_DESKTOP",
"DESKTOP_SESSION",
"KDE_FULL_SESSION",
"KDE_SESSION_UID",
"KDE_SESSION_VERSION",
"KDE_APPLICATIONS_AS_SCOPE",
"AMD_DEBUG",
"QT_QPA_PLATFORM"}) {
2189 command.push_back(
"--unset="s + name);
2192 "XDG_RUNTIME_DIR=" + runtime->runtime_dir,
2193 "XDG_SESSION_TYPE=wayland",
2194 "PULSE_SERVER=" + runtime->audio_server->pulse_server(),
2195 "PIPEWIRE_REMOTE=" + runtime->kwin_pipewire_socket,
2200 std::to_string(width),
2201 std::to_string(height),
2203 std::to_string(launch_session->fps ? launch_session->fps : 60000),
2206 std::string command_line;
2207 for (
const auto &argument : command) {
2208 if (argument.empty() || argument.find_first_of(
" \t\n\"'\\") != std::string::npos) {
2209 return plasma_failed(
"cannot start: an argument contains whitespace or quotes (" + argument +
")");
2211 command_line += (command_line.empty() ?
"" :
" ") + argument;
2217 std::unique_ptr<platf::session_devices::plan_t> plan;
2218 if (devices.devices) {
2219 const auto staging = std::filesystem::path {runtime->runtime_dir} /
"dev";
2220 std::error_code staging_ec;
2221 std::filesystem::create_directories(staging, staging_ec);
2224 BOOST_LOG(warning) <<
"[IsolatedSession] Hermes lacks CAP_SYS_ADMIN and CAP_MKNOD; detached desktop "
2225 << runtime->runtime_id <<
" sees the host's devices.";
2228 BOOST_LOG(info) <<
"[IsolatedSession] Starting detached desktop " << runtime->runtime_id
2229 <<
" (" << width <<
'x' << height <<
") in user unit " << runtime->unit;
2231 std::lock_guard<std::mutex> lock(runtime->process_mutex);
2232 std::error_code launch_ec;
2233 boost::filesystem::path working_dir {runtime->runtime_dir};
2234 runtime->process = platf::session_devices::run_command(
2238 boost::this_process::environment(),
2244 return plasma_failed(
"could not be started: " + launch_ec.message());
2247 runtime->namespace_pid = runtime->process.id();
2248 BOOST_LOG(info) <<
"[IsolatedSession] Detached desktop " << runtime->runtime_id
2249 <<
" has a private /dev: host input and sound devices hidden.";
2252 if (runtime->namespace_pid) {
2257 const auto tag =
"hermes-detached-" + runtime->runtime_id;
2261 runtime->isolated_seat_flag = (std::filesystem::path {host_runtime_dir()} /
"hermes" /
"isolated" / tag).
string();
2262 std::error_code flag_ec;
2263 std::filesystem::create_directories(std::filesystem::path {runtime->isolated_seat_flag}.parent_path(), flag_ec);
2264 std::ofstream {runtime->isolated_seat_flag}
2265 << std::filesystem::read_symlink(
"/proc/" + std::to_string(runtime->namespace_pid) +
"/ns/mnt", flag_ec).string()
2266 <<
' ' << ::getpid() <<
'\n';
2268 if (runtime->device_mirror) {
2269 runtime->seat_id = tag;
2271 BOOST_LOG(warning) <<
"[IsolatedSession] Detached desktop " << runtime->runtime_id
2272 <<
" gets no gamepads: its private /dev cannot be given devices.";
2276 const auto root = std::filesystem::path {runtime->runtime_dir};
2277 const auto deadline = std::chrono::steady_clock::now() + 60s;
2278 auto next_unit_check = std::chrono::steady_clock::now() + 1s;
2279 const auto systemctl = find_program(
"systemctl");
2281 if (launch_was_cancelled()) {
2285 if (std::filesystem::exists(root /
"failure", ec)) {
2286 return plasma_failed(
2287 "failed to start (" + read_small_file(root /
"failure") +
"; journalctl --user -u " +
2291 if (detached_desktop_alive(*runtime)) {
2294 const auto now = std::chrono::steady_clock::now();
2295 if (now >= next_unit_check) {
2296 next_unit_check = now + 1s;
2297 if (!systemctl.empty() &&
2298 run_program({systemctl,
"--user",
"--quiet",
"is-active", runtime->unit}, 5s) != 0) {
2299 return plasma_failed(
2300 "exited while starting (last stage: " + read_small_file(root /
"status") +
2301 "; journalctl --user -u " + runtime->unit +
")"
2305 if (now >= deadline) {
2306 return plasma_failed(
2307 "was not ready within 60 seconds (last stage: " + read_small_file(root /
"status") +
2308 "; journalctl --user -u " + runtime->unit +
")"
2311 std::this_thread::sleep_for(100ms);
2314 runtime->kwin_wayland_socket = detached_wayland_socket(runtime->runtime_dir);
2315 BOOST_LOG(info) <<
"[IsolatedSession] Detached desktop " << runtime->runtime_id
2316 <<
" is up on " << runtime->kwin_wayland_socket;
2321 if (!
app.cmd.empty()) {
2322 start_in_detached_desktop(*runtime, app,
app.cmd,
"0-app");
2324 for (
size_t index = 0; index <
app.detached.size(); ++index) {
2325 start_in_detached_desktop(*runtime, app,
app.detached[index],
"1-detached-" + std::to_string(index));
2328 launch_session->isolated_session =
true;
2329 launch_session->isolated_runtime_owner_id = runtime->launch_session_id;
2330 launch_session->isolated_session_profile = runtime->profile;
2331 launch_session->isolated_runtime_id = runtime->runtime_id;
2332 launch_session->isolated_seat_id = runtime->seat_id;
2333 launch_session->wayland_display = runtime->kwin_wayland_socket;
2334 launch_session->kwin_wayland_socket = runtime->kwin_wayland_socket;
2335 launch_session->kwin_pipewire_socket = runtime->kwin_pipewire_socket;
2336 launch_session->virtual_display =
true;
2339 std::lock_guard<std::mutex> lock(isolated_runtimes_mutex);
2340 if (launch_cancelled->load(std::memory_order_relaxed)) {
2341 BOOST_LOG(info) <<
"[IsolatedSession] Launch cancelled during runtime handoff for client "
2342 << launch_session->device_name;
2345 isolated_runtimes[runtime->launch_session_id] = runtime;
2349 BOOST_LOG(info) <<
"[IsolatedSession] Detached desktop " << runtime->runtime_id
2350 <<
" ready at " << width <<
'x' << height;
2357 if (
const int result = prepare_session_virtual_display(
2362 std::optional<uid_t> {runtime->account->uid} :
2369 if (launch_was_cancelled()) {
2373 runtime->display_name = launch_session->display_name;
2374 runtime->display_guid = launch_session->display_guid;
2375 runtime->drm_device_path = launch_session->drm_device_path;
2377 if (runtime->seat_id.empty()) {
2378 BOOST_LOG(error) <<
"[IsolatedSession] Could not resolve the independent seat for "
2379 << runtime->display_name;
2382 constexpr std::string_view seat_prefix {
"hermes-kms-"};
2383 if (!runtime->seat_id.starts_with(seat_prefix) ||
2384 runtime->seat_id.size() == seat_prefix.size()) {
2385 BOOST_LOG(error) <<
"[IsolatedSession] Invalid Hermes-KMS seat name "
2386 << runtime->seat_id;
2389 const auto seat_instance = runtime->seat_id.substr(seat_prefix.size());
2390 if (!std::ranges::all_of(seat_instance, [](
unsigned char ch) {
2391 return std::isdigit(ch);
2393 BOOST_LOG(error) <<
"[IsolatedSession] Invalid Hermes-KMS seat instance "
2394 << runtime->seat_id;
2397 runtime->seatd_socket =
2398 (std::filesystem::path {
"/run/hermes-kms-seatd"} /
2402 runtime->env = _env;
2403 populate_session_environment(runtime->env, app, *launch_session, *runtime);
2404 std::error_code socket_ec;
2405 if (!std::filesystem::is_socket(runtime->seatd_socket, socket_ec) ||
2406 ::access(runtime->seatd_socket.c_str(), R_OK | W_OK) != 0) {
2407 BOOST_LOG(error) <<
"[IsolatedSession] Private seat broker is unavailable at "
2408 << runtime->seatd_socket
2409 <<
"; enable hermes-kms-seatd@" << seat_instance
2410 <<
".service and grant this user access to the seat group.";
2414 if (!
app.output.empty() &&
app.output !=
"null") {
2415 runtime->pipe.reset(std::fopen(
app.output.c_str(),
"a"));
2418 for (
size_t index = 0; index <
app.prep_cmds.size(); ++index) {
2419 if (launch_was_cancelled()) {
2422 const auto &cmd =
app.prep_cmds[index];
2423 if (cmd.do_cmd.empty()) {
2424 runtime->prep_completed = index + 1;
2429 auto working_dir =
app.working_dir.empty() ?
2430 find_working_directory(cmd.do_cmd, runtime->env) :
2431 boost::filesystem::path {
app.working_dir};
2432 BOOST_LOG(info) <<
"[IsolatedSession] Executing Do Cmd: [" << cmd.do_cmd
2433 <<
"] elevated: " << cmd.elevated;
2434 auto child = platf::run_command(
2440 runtime->pipe.get(),
2445 BOOST_LOG(error) <<
"[IsolatedSession] Could not start prep command: " << ec.message();
2449 if (child.exit_code() != 0) {
2450 BOOST_LOG(error) <<
"[IsolatedSession] Prep command failed with code "
2451 << child.exit_code();
2454 runtime->prep_completed = index + 1;
2455 if (launch_was_cancelled()) {
2460 const int width =
static_cast<int>(launch_session->width ? launch_session->width : 1920);
2461 const int height =
static_cast<int>(launch_session->height ? launch_session->height : 1080);
2462 const int refresh_hz = std::max(1, (launch_session->fps ? launch_session->fps : 60000) / 1000);
2468 const auto forget_wayland_display = [&runtime]() {
2469 runtime->wayland_display.clear();
2470 for (
const auto *name : {
"WAYLAND_DISPLAY",
"WAYLAND_SOCKET",
2471 "_WAYLAND_DISPLAY",
"DISPLAY",
2472 "HERMES_WAYLAND_DISPLAY"}) {
2473 runtime->env.erase(name);
2477 if (runtime->profile ==
"application") {
2478 forget_wayland_display();
2479 if (
app.cmd.empty()) {
2480 BOOST_LOG(error) <<
"[IsolatedSession] Application profile requires a command.";
2483 const auto gamescope = find_gamescope();
2484 const auto &gamescope_binary = gamescope.binary;
2485 if (gamescope_binary.empty()) {
2486 BOOST_LOG(error) <<
"[IsolatedSession] Application profile requires gamescope; Hermes' own build "
2487 "installs to /usr/lib/hermes-gamescope (see scripts/install.sh).";
2490 if (!gamescope.prefix.empty()) {
2496 const auto bin_dir = (std::filesystem::path {gamescope.prefix} /
"bin").
string();
2497 const auto path = runtime->env.count(
"PATH") ? runtime->env[
"PATH"].to_string() : std::string {};
2498 runtime->env[
"PATH"] = path.empty() ? bin_dir : bin_dir +
":" + path;
2499 const auto layer_dir = std::filesystem::path {gamescope.prefix} /
"share" /
"vulkan" /
"implicit_layer.d";
2500 if (std::error_code layer_ec; std::filesystem::is_directory(layer_dir, layer_ec)) {
2501 const auto layers = runtime->env.count(
"VK_ADD_IMPLICIT_LAYER_PATH") ?
2502 runtime->env[
"VK_ADD_IMPLICIT_LAYER_PATH"].to_string() :
2504 runtime->env[
"VK_ADD_IMPLICIT_LAYER_PATH"] = layers.empty() ? layer_dir.string() : layer_dir.string() +
":" + layers;
2507 BOOST_LOG(info) <<
"[IsolatedSession] Using " << gamescope_binary;
2519 if (
const char *legacy_device = std::getenv(
"HERMES_ISOLATED_GAMESCOPE_DRM_DEVICE");
2520 legacy_device && *legacy_device) {
2521 BOOST_LOG(warning) <<
"[IsolatedSession] HERMES_ISOLATED_GAMESCOPE_DRM_DEVICE is no longer read; "
2522 <<
"each session scans out on its own card, here "
2523 << runtime->drm_device_path <<
'.';
2526 BOOST_LOG(error) <<
"[IsolatedSession] Session card " << runtime->drm_device_path
2527 <<
" is not a DRM primary node; Gamescope cannot scan out on it.";
2531 std::optional<platf::gamescope::drm_selector_e> selector;
2532 if (
const char *forced = std::getenv(
"HERMES_ISOLATED_GAMESCOPE_DRM_FLAG");
2533 forced && *forced) {
2536 BOOST_LOG(warning) <<
"[IsolatedSession] Ignoring HERMES_ISOLATED_GAMESCOPE_DRM_FLAG=" << forced
2537 <<
"; expected --prefer-drm, --drm-device or none.";
2541 selector = gamescope_drm_selector(gamescope_binary);
2544 BOOST_LOG(error) <<
"[IsolatedSession] " << gamescope_binary
2545 <<
" cannot scan out on a different device than it renders with, so it "
2546 "would open the host GPU's display instead of this session's card. Install "
2547 "Hermes' Gamescope (scripts/install.sh), use one with --prefer-drm "
2548 "(ValveSoftware/gamescope#2220), or set "
2549 "HERMES_ISOLATED_GAMESCOPE_DRM_FLAG for a build whose --help does not "
2550 "list the option it accepts.";
2554 BOOST_LOG(warning) <<
"[IsolatedSession] Launching Gamescope without a scanout device "
2555 "(HERMES_ISOLATED_GAMESCOPE_DRM_FLAG=none); it will pick the GPU it "
2556 "renders with, not " << runtime->drm_device_path <<
'.';
2561 runtime->env[
"GAMESCOPE_PREFER_DRM"] = runtime->drm_device_path;
2571 const auto arguments = boost::program_options::split_unix(
app.gamescope_args);
2572 if (
const auto option = platf::gamescope::session_option_override(arguments)) {
2573 BOOST_LOG(error) <<
"[IsolatedSession] gamescope-args cannot override the session's card, backend or mode: " << *option;
2576 }
catch (
const std::exception &exception) {
2577 BOOST_LOG(error) <<
"[IsolatedSession] Invalid gamescope-args: " << exception.what();
2580 if (
const char *forced_steam_mode = std::getenv(
"HERMES_ISOLATED_GAMESCOPE_STEAM_MODE");
2581 forced_steam_mode && std::string_view {forced_steam_mode} ==
"1") {
2585 runtime->held_x_displays = hold_x_display_gaps(2);
2586 if (!runtime->held_x_displays.empty()) {
2589 for (
const int display : runtime->held_x_displays) {
2590 held += (held.empty() ?
"[" :
", ") + std::to_string(display);
2592 BOOST_LOG(info) <<
"[IsolatedSession] Holding X displays below gamescope's so Steam's games land on its Xwayland: "
2598 .binary = gamescope_binary,
2601 .refresh_hz = refresh_hz,
2602 .connector = connector,
2603 .selector = *selector,
2604 .scanout_card = runtime->drm_device_path,
2605 .steam_mode = steam_mode,
2606 .args =
app.gamescope_args,
2611 const auto profile = load_compositor_profile(config::video.hermes_kms_session_compositor);
2615 if (!profile->required_binary.empty() &&
2616 boost::process::v1::search_path(profile->required_binary).empty()) {
2617 BOOST_LOG(error) <<
"[IsolatedSession] Session compositor \"" << profile->name
2618 <<
"\" requires " << profile->required_binary <<
", which is not in PATH.";
2629 if (profile->discover_socket) {
2630 forget_wayland_display();
2637 const auto config_path = expand_profile_template(
2638 profile->config_target,
2639 {{
"runtime_dir", runtime->assets_dir}}
2644 const auto config_dir = config_path.empty() ?
2646 std::filesystem::path {config_path}.parent_path().string();
2648 const std::vector<std::pair<std::string, std::string>> values {
2649 {
"card", card_basename(runtime->drm_device_path)},
2650 {
"card_path", runtime->drm_device_path},
2651 {
"seat", runtime->seat_id},
2652 {
"socket", runtime->wayland_display},
2653 {
"log", (std::filesystem::path {runtime->runtime_dir} /
"compositor.log").
string()},
2654 {
"runtime_dir", runtime->runtime_dir},
2655 {
"render_node", real_render_node_path()},
2656 {
"width", std::to_string(width)},
2657 {
"height", std::to_string(height)},
2658 {
"refresh", std::to_string(refresh_hz)},
2659 {
"connector", connector},
2660 {
"config", config_path},
2661 {
"config_dir", config_dir},
2666 if (!profile->config_template.empty()) {
2667 const auto source = profile->profile_dir / profile->config_template;
2668 std::error_code template_ec;
2669 if (!std::filesystem::is_regular_file(source, template_ec)) {
2670 BOOST_LOG(error) <<
"[IsolatedSession] Session compositor profile \"" << profile->name
2671 <<
"\" names a config template that is missing: " << source;
2674 const auto &target = config_path;
2677 std::error_code dir_ec;
2678 std::filesystem::create_directories(std::filesystem::path {target}.parent_path(), dir_ec);
2680 BOOST_LOG(error) <<
"[IsolatedSession] Could not create compositor config directory "
2681 << std::filesystem::path {target}.parent_path() <<
": " << dir_ec.message();
2684 std::ofstream out {target, std::ios::trunc};
2686 BOOST_LOG(error) <<
"[IsolatedSession] Could not write compositor config " << target;
2691 BOOST_LOG(error) <<
"[IsolatedSession] Could not write compositor config " << target;
2698 if (runtime->account) {
2699 ::chmod(target.c_str(), S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
2707 for (
auto dir = std::filesystem::path {target}.parent_path();
2708 !dir.empty() && dir.string() != runtime->assets_dir && dir != dir.root_path();
2709 dir = dir.parent_path()) {
2710 ::chmod(dir.c_str(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
2713 BOOST_LOG(debug) <<
"[IsolatedSession] Wrote compositor config " << target
2714 <<
" from " << source;
2717 for (
const auto &[key, value] : profile->env) {
2718 runtime->env[key] = expand_profile_template(value, values);
2721 if (!runtime->wayland_display.empty()) {
2722 runtime->env[
"WAYLAND_DISPLAY"] = runtime->wayland_display;
2724 launch_command = expand_profile_template(profile->command, values);
2725 runtime->compositor_name = profile->name;
2726 runtime->discover_socket = profile->discover_socket;
2729 auto working_dir =
app.working_dir.empty() ?
2730 boost::filesystem::path {runtime->runtime_dir} :
2731 boost::filesystem::path {
app.working_dir};
2732 std::error_code launch_ec;
2733 BOOST_LOG(info) <<
"[IsolatedSession] Starting " << runtime->profile
2734 <<
" runtime " << runtime->runtime_id
2735 <<
" on seat " << runtime->seat_id
2736 <<
" on " << runtime->drm_device_path
2737 <<
" for " << runtime->display_name;
2738 if (runtime->account) {
2743 const auto arguments = split_command(launch_command);
2744 if (arguments.empty()) {
2745 BOOST_LOG(error) <<
"[IsolatedSession] The session compositor command is empty.";
2750 for (
const auto &entry : runtime->env) {
2751 environment.emplace_back(entry.get_name() +
"=" + entry.to_string());
2755 runtime->client_uuid,
2760 BOOST_LOG(error) <<
"[IsolatedSession] The broker would not start the session for "
2761 << runtime->account->user <<
'.';
2764 runtime->unit = *unit;
2765 BOOST_LOG(info) <<
"[IsolatedSession] Session " << runtime->runtime_id <<
" runs as "
2766 << runtime->account->user <<
" (uid " << runtime->account->uid
2767 <<
") in " << runtime->unit <<
"; its log is in the journal.";
2769 const auto devices = session_device_options(app);
2775 const bool has_bus = runtime->env.find(
"DBUS_SESSION_BUS_ADDRESS") != runtime->env.end();
2778 BOOST_LOG(info) <<
"[IsolatedSession] Session " << runtime->runtime_id <<
" gets a D-Bus session bus of its own.";
2782 BOOST_LOG(warning) <<
"[IsolatedSession] dbus-run-session is not installed, so session " << runtime->runtime_id
2783 <<
" has no D-Bus session bus; applications that need one, Steam among them, will exit.";
2785 std::unique_ptr<platf::session_devices::plan_t> plan;
2786 if (devices->devices || devices->sound) {
2787 const auto staging = std::filesystem::path {runtime->runtime_dir} /
"dev";
2788 std::error_code staging_ec;
2789 std::filesystem::create_directories(staging, staging_ec);
2792 runtime->process = platf::session_devices::run_command(
2797 runtime->pipe.get(),
2799 &runtime->process_group
2802 BOOST_LOG(error) <<
"[IsolatedSession] Could not start compositor: "
2803 << launch_ec.message();
2807 runtime->namespace_pid = runtime->process.id();
2808 BOOST_LOG(info) <<
"[IsolatedSession] Session " << runtime->runtime_id <<
" has a private /dev: host devices "
2809 << (devices->devices ?
"hidden" :
"visible") <<
", sound devices "
2810 << (devices->sound ?
"hidden" :
"visible") <<
'.';
2812 if (devices->devices) {
2816 runtime->isolated_seat_flag = (std::filesystem::path {host_runtime_dir()} /
"hermes" /
"isolated" / runtime->seat_id).
string();
2817 std::error_code flag_ec;
2818 std::filesystem::create_directories(std::filesystem::path {runtime->isolated_seat_flag}.parent_path(), flag_ec);
2819 std::ofstream {runtime->isolated_seat_flag}
2820 << std::filesystem::read_symlink(
"/proc/" + std::to_string(runtime->namespace_pid) +
"/ns/mnt", flag_ec).string()
2821 <<
' ' << ::getpid() <<
'\n';
2823 if (!runtime->device_mirror) {
2836 const auto first_frame_timeout =
app.first_frame_timeout.count() > 0 ?
2837 app.first_frame_timeout :
2838 runtime->profile ==
"application" ?
2839 std::chrono::seconds {30} :
2840 std::chrono::seconds {5};
2841 const auto first_frame_started = std::chrono::steady_clock::now();
2842 const auto first_frame_deadline = first_frame_started + first_frame_timeout;
2843 bool reported_slow_first_frame =
false;
2844 bool scanout_ready =
false;
2845 int active_width = 0;
2846 int active_height = 0;
2847 while (std::chrono::steady_clock::now() < first_frame_deadline) {
2848 if (launch_was_cancelled()) {
2851 if (!isolated_runtime_running(runtime)) {
2852 if (runtime->account) {
2853 BOOST_LOG(error) <<
"[IsolatedSession] The session unit " << runtime->unit
2854 <<
" stopped before scanout became ready. What the compositor "
2855 "said is in the journal: journalctl -u " << runtime->unit;
2857 BOOST_LOG(error) <<
"[IsolatedSession] Compositor exited before scanout became ready"
2858 <<
" (code=" << runtime->process.native_exit_code() <<
").";
2864 if (capture_fd >= 0) {
2870 ::close(capture_fd);
2872 if (scanout_ready && active_width > 0 && active_height > 0) {
2875 if (!reported_slow_first_frame &&
2876 std::chrono::steady_clock::now() - first_frame_started >= 5s) {
2877 reported_slow_first_frame =
true;
2878 BOOST_LOG(info) <<
"[IsolatedSession] Still waiting for the first frame on "
2879 << runtime->display_name <<
"; allowing up to "
2880 << first_frame_timeout.count() <<
"s.";
2882 std::this_thread::sleep_for(50ms);
2884 if (!scanout_ready) {
2885 BOOST_LOG(error) <<
"[IsolatedSession] No frame reached " << runtime->display_name
2886 <<
" within " << first_frame_timeout.count()
2887 <<
"s. Raise first-frame-timeout for this app if it is only slow to start.";
2890 if (launch_was_cancelled()) {
2893 if (active_width != width || active_height != height) {
2894 BOOST_LOG(warning) <<
"[IsolatedSession] Requested " << width <<
'x' << height
2895 <<
" but compositor scanout is " << active_width <<
'x'
2896 << active_height <<
". Capture will follow scanout.";
2899 if (runtime->profile ==
"application" || runtime->discover_socket) {
2907 std::string compositor_socket;
2908 for (
int attempt = 0; attempt < 100; ++attempt) {
2909 if (launch_was_cancelled()) {
2912 if (!isolated_runtime_running(runtime)) {
2913 BOOST_LOG(error) <<
"[IsolatedSession] "
2914 << (runtime->compositor_name.empty() ?
"Gamescope" : runtime->compositor_name)
2915 <<
" exited before it created a Wayland socket"
2916 << (runtime->account ?
2917 "; see journalctl -u " + runtime->unit :
2918 " (code=" + std::to_string(runtime->process.native_exit_code()) +
")")
2924 compositor_socket = runtime->account ?
2926 .value_or(std::string {}) :
2927 discover_wayland_socket(runtime->runtime_dir);
2928 if (!compositor_socket.empty()) {
2931 std::this_thread::sleep_for(50ms);
2934 if (!compositor_socket.empty()) {
2935 runtime->wayland_display = compositor_socket;
2936 runtime->env[
"WAYLAND_DISPLAY"] = compositor_socket;
2937 runtime->env[
"HERMES_WAYLAND_DISPLAY"] = compositor_socket;
2938 BOOST_LOG(debug) <<
"[IsolatedSession] Discovered Wayland socket " << compositor_socket;
2940 BOOST_LOG(error) <<
"[IsolatedSession] "
2941 << (runtime->compositor_name.empty() ?
"Gamescope" : runtime->compositor_name)
2942 <<
" never created a Wayland socket in " << runtime->runtime_dir
2943 <<
"; nothing can be launched into this session.";
2948 if (runtime->profile ==
"desktop" && !
app.cmd.empty()) {
2949 std::error_code app_ec;
2950 BOOST_LOG(info) <<
"[IsolatedSession] Starting desktop application: ["
2952 if (!launch_into_session(runtime, app,
app.cmd,
"app", app_ec)) {
2953 BOOST_LOG(error) <<
"[IsolatedSession] Could not start desktop application"
2954 << (app_ec ?
": " + app_ec.message() : std::string {
"."});
2958 if (launch_was_cancelled()) {
2962 runtime->env[
"APOLLO_APP_STATUS"] =
"RUNNING";
2963 runtime->env[
"HERMES_APP_STATUS"] =
"RUNNING";
2964 for (
size_t index = 0; index <
app.detached.size(); ++index) {
2968 if (!launch_into_session(runtime, app,
app.detached[index],
"d" + std::to_string(index), ec)) {
2969 BOOST_LOG(warning) <<
"[IsolatedSession] Detached command failed to start"
2970 << (ec ?
": " + ec.message() : std::string {
"."});
2975 std::lock_guard<std::mutex> probe_lock(encoder_probe_mutex);
2976 const auto previous_output = config::video.output_name;
2977 auto mapped_name = display_device::map_display_name(runtime->display_name);
2978 config::video.output_name = mapped_name.empty() ? runtime->display_name : std::move(mapped_name);
2979 auto restore_output = util::fail_guard([&]() {
2980 config::video.output_name = previous_output;
2983 !config::video.ignore_encoder_probe_failure) {
2987 if (launch_was_cancelled()) {
2991 launch_session->isolated_session =
true;
2992 launch_session->isolated_runtime_owner_id = runtime->launch_session_id;
2993 launch_session->isolated_session_profile = runtime->profile;
2994 launch_session->isolated_runtime_id = runtime->runtime_id;
2995 launch_session->isolated_seat_id = runtime->seat_id;
2996 launch_session->wayland_display = runtime->wayland_display;
2997 launch_session->virtual_display =
true;
3000 std::lock_guard<std::mutex> lock(isolated_runtimes_mutex);
3004 if (launch_cancelled->load(std::memory_order_relaxed)) {
3005 BOOST_LOG(info) <<
"[IsolatedSession] Launch cancelled during runtime handoff for client "
3006 << launch_session->device_name;
3009 isolated_runtimes[runtime->launch_session_id] = runtime;
3013 BOOST_LOG(info) <<
"[IsolatedSession] Runtime " << runtime->runtime_id
3014 <<
" ready at " << active_width <<
'x' << active_height
3015 <<
'@' << refresh_hz <<
"Hz";
3020 std::shared_ptr<isolated_runtime_t> runtime;
3022 std::lock_guard<std::mutex> lock(isolated_runtimes_mutex);
3023 const auto it = isolated_runtimes.find(launch_session_id);
3024 if (it == isolated_runtimes.end()) {
3027 runtime = std::move(it->second);
3028 isolated_runtimes.erase(it);
3030 stop_isolated_runtime(runtime);
3034 bool terminate_on_pause =
false;
3036 std::lock_guard<std::mutex> lock(isolated_runtimes_mutex);
3037 const auto it = isolated_runtimes.find(launch_session_id);
3038 if (it == isolated_runtimes.end() || !it->second) {
3041 terminate_on_pause = it->second->app.terminate_on_pause;
3042 if (!terminate_on_pause) {
3043 BOOST_LOG(info) <<
"[IsolatedSession] Keeping " << it->second->runtime_id
3044 <<
" alive for client resume.";
3052 std::shared_ptr<isolated_runtime_t> runtime;
3054 std::lock_guard<std::mutex> lock(isolated_runtimes_mutex);
3055 if (
const auto launching = isolated_launching_clients.find(client_uuid);
3056 launching != isolated_launching_clients.end() &&
3057 launching->second) {
3058 launching->second->store(
true, std::memory_order_relaxed);
3060 runtime = find_isolated_client_locked(client_uuid);
3062 isolated_runtimes.erase(runtime->launch_session_id);
3065 stop_isolated_runtime(runtime);
3069 std::lock_guard<std::mutex> lock(isolated_runtimes_mutex);
3070 return isolated_launching_clients.contains(client_uuid) ||
3071 find_isolated_client_locked(client_uuid) !=
nullptr;
3075 std::vector<std::shared_ptr<isolated_runtime_t>> runtimes;
3077 std::lock_guard<std::mutex> lock(isolated_runtimes_mutex);
3078 for (
const auto &[client_uuid, cancelled] : isolated_launching_clients) {
3080 cancelled->store(
true, std::memory_order_relaxed);
3083 for (
auto &[
id, runtime] : isolated_runtimes) {
3084 runtimes.emplace_back(std::move(runtime));
3086 isolated_runtimes.clear();
3088 for (
const auto &runtime : runtimes) {
3089 stop_isolated_runtime(runtime);
3094 std::shared_ptr<isolated_runtime_t> runtime;
3096 std::lock_guard<std::mutex> lock(isolated_runtimes_mutex);
3097 runtime = find_isolated_client_locked(client_uuid);
3102 const bool active = isolated_runtime_running(runtime);
3104 std::lock_guard<std::mutex> lock(isolated_runtimes_mutex);
3105 const auto it = isolated_runtimes.find(runtime->launch_session_id);
3106 if (it == isolated_runtimes.end() || it->second != runtime) {
3109 if (active && !runtime->stopping.load()) {
3110 return util::from_view(runtime->app.id);
3112 isolated_runtimes.erase(it);
3114 stop_isolated_runtime(runtime);
3118 std::string proc_t::running_app_uuid_for_client(
const std::string &client_uuid) {
3119 std::shared_ptr<isolated_runtime_t> runtime;
3121 std::lock_guard<std::mutex> lock(isolated_runtimes_mutex);
3122 runtime = find_isolated_client_locked(client_uuid);
3124 if (!isolated_runtime_running(runtime)) {
3127 std::lock_guard<std::mutex> lock(isolated_runtimes_mutex);
3128 const auto it = isolated_runtimes.find(runtime->launch_session_id);
3129 return it != isolated_runtimes.end() && it->second == runtime && !runtime->stopping.load() ?
3142 std::vector<std::shared_ptr<isolated_runtime_t>> runtimes;
3144 std::lock_guard<std::mutex> lock(isolated_runtimes_mutex);
3145 for (
const auto &[
id, runtime] : isolated_runtimes) {
3147 runtimes.push_back(runtime);
3152 bool isolated_running =
false;
3153 std::vector<std::shared_ptr<isolated_runtime_t>> stopped;
3154 for (
const auto &runtime : runtimes) {
3155 if (isolated_runtime_running(runtime)) {
3156 isolated_running =
true;
3158 stopped.push_back(runtime);
3163 std::lock_guard<std::mutex> lock(isolated_runtimes_mutex);
3164 for (
const auto &runtime : stopped) {
3165 const auto it = isolated_runtimes.find(runtime->launch_session_id);
3166 if (it != isolated_runtimes.end() && it->second == runtime) {
3167 isolated_runtimes.erase(it);
3171 for (
const auto &runtime : stopped) {
3172 stop_isolated_runtime(runtime);
3174 if (isolated_running) {
3181 std::lock_guard<std::mutex> lock(isolated_runtimes_mutex);
3182 const auto it = isolated_runtimes.find(launch_session_id);
3183 if (it != isolated_runtimes.end() && it->second) {
3184 return it->second->env;
3190 std::vector<isolated_session_t> sessions;
3191 std::vector<std::shared_ptr<isolated_runtime_t>> runtimes;
3193 std::lock_guard<std::mutex> lock(isolated_runtimes_mutex);
3194 runtimes.reserve(isolated_runtimes.size());
3195 for (
const auto &[
id, runtime] : isolated_runtimes) {
3197 runtimes.push_back(runtime);
3206 const auto now = std::chrono::steady_clock::now();
3207 std::vector<std::shared_ptr<isolated_runtime_t>> stopped;
3208 for (
const auto &runtime : runtimes) {
3209 const bool running = isolated_runtime_running(runtime);
3211 stopped.push_back(runtime);
3216 session.launch_session_id = runtime->launch_session_id;
3217 session.client_uuid = runtime->client_uuid;
3218 session.client_name = runtime->client_name;
3219 session.app_id = runtime->app.id;
3220 session.app_name = runtime->app.name;
3221 session.
profile = runtime->profile;
3222 session.compositor = runtime->compositor_name;
3223 session.seat = runtime->seat_id;
3224 session.display = runtime->display_name;
3225 if (runtime->account) {
3227 session.account_uid = runtime->account->uid;
3229 session.
unit = runtime->unit;
3232 session.uptime_seconds =
3233 std::chrono::duration_cast<std::chrono::seconds>(now - runtime->started_at).count();
3234 sessions.push_back(std::move(session));
3237 std::vector<std::shared_ptr<isolated_runtime_t>> removed;
3239 std::lock_guard<std::mutex> lock(isolated_runtimes_mutex);
3240 for (
const auto &runtime : stopped) {
3241 const auto it = isolated_runtimes.find(runtime->launch_session_id);
3242 if (it != isolated_runtimes.end() && it->second == runtime) {
3243 isolated_runtimes.erase(it);
3244 removed.push_back(runtime);
3249 for (
const auto &runtime : removed) {
3250 BOOST_LOG(info) <<
"[IsolatedSession] Removing stale runtime "
3251 << runtime->runtime_id <<
" while listing sessions.";
3252 stop_isolated_runtime(runtime);
3255 std::ranges::sort(sessions, [](
const auto &left,
const auto &right) {
3256 return left.launch_session_id < right.launch_session_id;
3262 std::lock_guard<std::mutex> lock(isolated_runtimes_mutex);
3263 const auto it = isolated_runtimes.find(launch_session_id);
3264 if (it != isolated_runtimes.end() && it->second) {
3265 return it->second->audio_sink;
3274 std::lock_guard<std::mutex> lock(isolated_runtimes_mutex);
3275 const auto it = isolated_runtimes.find(launch_session_id);
3276 if (it != isolated_runtimes.end() && it->second && it->second->audio_server) {
3277 return it->second->audio_server->pulse_server();
3283 std::lock_guard<std::mutex> lock(isolated_runtimes_mutex);
3284 const auto it = isolated_runtimes.find(launch_session_id);
3285 if (it != isolated_runtimes.end() && it->second) {
3286 return it->second->mic_source;
3292 std::lock_guard<std::mutex> lock(isolated_runtimes_mutex);
3293 const auto it = isolated_runtimes.find(launch_session_id);
3294 return it != isolated_runtimes.end() && it->second && it->second->account;
3298 std::shared_ptr<rtsp_stream::launch_session_t> launch_session
3300 std::shared_ptr<isolated_runtime_t> runtime;
3302 std::lock_guard<std::mutex> lock(isolated_runtimes_mutex);
3303 runtime = find_isolated_client_locked(launch_session->unique_id);
3305 if (!isolated_runtime_running(runtime)) {
3307 bool removed =
false;
3309 std::lock_guard<std::mutex> lock(isolated_runtimes_mutex);
3310 const auto it = isolated_runtimes.find(runtime->launch_session_id);
3311 if (it != isolated_runtimes.end() && it->second == runtime) {
3312 isolated_runtimes.erase(it);
3317 BOOST_LOG(info) <<
"[IsolatedSession] Removing stale runtime "
3318 << runtime->runtime_id <<
" before resume.";
3319 stop_isolated_runtime(runtime);
3324 if (runtime->user_unit) {
3325 std::lock_guard<std::mutex> mode_lock(runtime->process_mutex);
3326 if (runtime->stopping.load()) {
3329 const auto helper = find_detached_session_tool();
3330 const int width =
static_cast<int>(launch_session->width ? launch_session->width : 1920);
3331 const int height =
static_cast<int>(launch_session->height ? launch_session->height : 1080);
3332 const int refresh = launch_session->fps ? launch_session->fps : 60000;
3333 if (helper.empty() || run_program({helper,
"--configure-output", runtime->runtime_dir, std::to_string(width), std::to_string(height), std::to_string(refresh)}, 8s) != 0) {
3334 launch_session->launch_error_message =
"Could not apply the requested Detached display mode; see the Hermes log";
3335 BOOST_LOG(error) <<
"[IsolatedSession] " << launch_session->launch_error_message;
3339 std::lock_guard<std::mutex> lock(isolated_runtimes_mutex);
3340 const auto it = isolated_runtimes.find(runtime->launch_session_id);
3342 if (it == isolated_runtimes.end() || it->second != runtime || runtime->stopping.load() ||
3343 find_isolated_client_locked(launch_session->unique_id) != runtime) {
3347 launch_session->isolated_session =
true;
3348 launch_session->isolated_runtime_owner_id = runtime->launch_session_id;
3349 launch_session->isolated_session_profile = runtime->profile;
3350 launch_session->isolated_runtime_id = runtime->runtime_id;
3351 launch_session->isolated_seat_id = runtime->seat_id;
3352 launch_session->session_scoped_virtual_display =
true;
3353 launch_session->session_virtual_display_cleanup_pending =
false;
3354 launch_session->virtual_display =
true;
3355 launch_session->display_name = runtime->display_name;
3356 launch_session->display_guid = runtime->display_guid;
3357 launch_session->drm_device_path = runtime->drm_device_path;
3358 launch_session->wayland_display = runtime->wayland_display;
3359 launch_session->kwin_wayland_socket = runtime->kwin_wayland_socket;
3360 launch_session->kwin_pipewire_socket = runtime->kwin_pipewire_socket;
3361 if (!runtime->app.allow_client_commands) {
3362 launch_session->client_do_cmds.clear();
3363 launch_session->client_undo_cmds.clear();
3368 int proc_t::execute(
const ctx_t& app, std::shared_ptr<rtsp_stream::launch_session_t> launch_session) {
3369 if (_app_id == input_only_app_id) {
3370 terminate(
false,
false);
3371 std::this_thread::sleep_for(1s);
3374 terminate(
false,
false);
3378 _app_id = util::from_view(
app.id);
3379 _app_name =
app.name;
3380 _launch_session = launch_session;
3381 allow_client_commands =
app.allow_client_commands;
3383 uint32_t client_width = launch_session->width ? launch_session->width : 1920;
3384 uint32_t client_height = launch_session->height ? launch_session->height : 1080;
3386 uint32_t render_width = client_width;
3387 uint32_t render_height = client_height;
3389 const int scale_factor =
3392 if (scale_factor != 100) {
3393 render_width *= ((float)scale_factor / 100);
3394 render_height *= ((float)scale_factor / 100);
3399 render_height &= ~1;
3402 launch_session->width = render_width;
3403 launch_session->height = render_height;
3405 this->initial_display = config::video.output_name;
3407 auto fg = util::fail_guard([&]() {
3408 if (launch_session->session_virtual_display_cleanup_pending) {
3410 launch_session->session_virtual_display_cleanup_pending =
false;
3411 launch_session->session_scoped_virtual_display =
false;
3412 launch_session->display_name.clear();
3415 config::video.output_name = this->initial_display;
3420 if (!
app.gamepad.empty()) {
3421 _saved_input_config = std::make_shared<config::input_t>(config::input);
3422 if (
app.gamepad ==
"disabled") {
3423 config::input.controller =
false;
3425 config::input.controller =
true;
3426 config::input.gamepad =
app.gamepad;
3438 if (gamescope_session) {
3439 BOOST_LOG(info) <<
"Gamescope session detected; capturing the Gamescope output directly "
3440 "instead of creating a virtual display.";
3441 launch_session->virtual_display =
false;
3446 const bool virtual_display_requested =
3447 launch_session->virtual_display_decided ?
3448 (config::video.headless_mode || launch_session->virtual_display) :
3454 const bool needs_virtual_display =
3456 (virtual_display_requested ||
3460 if (needs_virtual_display && !virtual_display_requested) {
3461 BOOST_LOG(info) <<
"No monitor is lit on this host; using a virtual display for this session.";
3472 BOOST_LOG(warning) <<
"[Session] Host-session unlock was requested for '" << _app.name
3473 <<
"' but could not be completed; launch will continue.";
3481 if (!needs_virtual_display) {
3482 if (gamescope_session) {
3483 BOOST_LOG(info) <<
"Virtual display skipped: this is a standalone Gamescope session, "
3484 "which provides its own display.";
3486 BOOST_LOG(info) <<
"Virtual display not requested for this session; capturing the existing "
3487 "display instead. Enabling a backend only makes virtual displays "
3488 "available - something still has to ask for one. Turn on 'virtual "
3489 "display' for the app being launched (Desktop, Steam Big Picture and so "
3490 "on) to have every session on it use one; the alternatives are the "
3491 "client sending virtualDisplay=1, the client's certificate set to always "
3492 "use one, or headless mode. 'virtual_display_backend' and "
3493 "'hermes_kms_multi_output' pick which backend serves the request, never "
3494 "whether one is made.";
3501 bool session_scoped_display_prepared =
false;
3502 if (needs_virtual_display &&
3503 config::video.virtual_display_backend ==
"hermes_kms" &&
3504 config::video.hermes_kms_multi_output) {
3505 if (
const int result = prepare_session_virtual_display(launch_session,
false); result != 0) {
3508 session_scoped_display_prepared =
true;
3510 this->display_name = launch_session->display_name;
3511 config::video.output_name = display_device::map_display_name(this->display_name);
3514 if (needs_virtual_display && !session_scoped_display_prepared) {
3522 if (!config::video.adapter_name.empty()) {
3526 std::string device_name;
3527 std::string device_uuid_str;
3530 if (_app.use_app_identity) {
3531 device_name = _app.name;
3532 if (_app.per_client_app_identity) {
3533 device_uuid = uuid_util::uuid_t::parse(launch_session->unique_id);
3534 auto app_uuid = uuid_util::uuid_t::parse(_app.uuid);
3537 device_uuid.b64[0] ^= app_uuid.b64[0];
3538 device_uuid.b64[1] ^= app_uuid.b64[1];
3540 device_uuid_str = device_uuid.string();
3542 device_uuid_str = _app.uuid;
3543 device_uuid = uuid_util::uuid_t::parse(_app.uuid);
3546 device_name = launch_session->device_name;
3547 device_uuid_str = launch_session->unique_id;
3548 device_uuid = uuid_util::uuid_t::parse(launch_session->unique_id);
3551 launch_session->display_guid = device_uuid;
3553 int target_fps = launch_session->fps ? launch_session->fps : 60000;
3555 if (target_fps < 1000) {
3559 if (config::video.double_refreshrate) {
3571 const std::string &vd_layout = _app.virtual_display_layout;
3572 const bool vd_layout_explicit =
3573 vd_layout ==
"extend" || vd_layout ==
"primary" || vd_layout ==
"detached" || vd_layout ==
"mirror";
3574 const bool want_exclusive = vd_layout ==
"exclusive" ||
3575 (config::video.isolated_virtual_display_option && !vd_layout_explicit);
3576 if (config::video.isolated_virtual_display_option && vd_layout_explicit) {
3577 BOOST_LOG(info) <<
"[VDISPLAY] Application layout '" << vd_layout
3578 <<
"' overrides the global exclusive-display setting; physical outputs remain enabled. "
3579 "Select Auto or Exclusive in this application's Virtual Display Layout to disable them.";
3583 device_uuid_str.c_str(),
3584 device_name.c_str(),
3588 launch_session->display_guid,
3590 linux_virtual_display_layout(vd_layout)
3595 launch_session->virtual_display =
true;
3597 if (!vdisplayName.empty()) {
3598 BOOST_LOG(info) <<
"Virtual Display created at " << vdisplayName;
3601 if (launch_session->width && launch_session->height && launch_session->fps) {
3604 if (mode_result != 0) {
3606 BOOST_LOG(warning) <<
"Virtual display did not reach "sv << render_width <<
'x' << render_height
3607 <<
"; streaming the display's active mode instead."sv;
3618 BOOST_LOG(error) <<
"The compositor did not activate the " << backend_label
3619 <<
" output; refusing physical-display fallback for a virtual-display session.";
3620 launch_session->launch_error_message =
3621 "Virtual display setup failed. Physical display fallback was not attempted.";
3628 if (want_exclusive) {
3640 BOOST_LOG(warning) <<
"Virtual display is active, but exclusive mode could not disable physical outputs.";
3645 this->display_name = vdisplayName;
3655 config::video.output_name = this->display_name;
3657 BOOST_LOG(error) <<
"Virtual display was requested but creation failed or no display name became available; "
3658 <<
"refusing physical-display fallback.";
3659 launch_session->launch_error_message =
3660 "Virtual display setup failed. Physical display fallback was not attempted.";
3664 BOOST_LOG(error) <<
"Virtual display was requested but the virtual-display driver is unavailable; "
3665 <<
"refusing physical-display fallback.";
3666 launch_session->launch_error_message =
3667 "Virtual display setup failed. Physical display fallback was not attempted.";
3675 if (this->virtual_display) {
3684 if (config::video.ignore_encoder_probe_failure) {
3685 BOOST_LOG(warning) <<
"Encoder probe failed, but continuing due to user configuration.";
3691 std::string fps_str;
3693 snprintf(fps_buf,
sizeof(fps_buf),
"%.3f", (
float)launch_session->fps / 1000.0f);
3698 _env[
"SUNSHINE_APP_ID"] = _app.id;
3699 _env[
"SUNSHINE_APP_NAME"] = _app.name;
3700 _env[
"SUNSHINE_CLIENT_WIDTH"] = std::to_string(render_width);
3701 _env[
"SUNSHINE_CLIENT_HEIGHT"] = std::to_string(render_height);
3702 _env[
"SUNSHINE_CLIENT_FPS"] = config::sunshine.envvar_compatibility_mode ? std::to_string(std::round((
float)launch_session->fps / 1000.0f)) : fps_str;
3703 _env[
"SUNSHINE_CLIENT_HDR"] = launch_session->enable_hdr ?
"true" :
"false";
3704 _env[
"SUNSHINE_CLIENT_GCMAP"] = std::to_string(launch_session->gcmap);
3705 _env[
"SUNSHINE_CLIENT_HOST_AUDIO"] = launch_session->host_audio ?
"true" :
"false";
3706 _env[
"SUNSHINE_CLIENT_ENABLE_SOPS"] = launch_session->enable_sops ?
"true" :
"false";
3708 _env[
"APOLLO_APP_ID"] = _app.id;
3709 _env[
"APOLLO_APP_NAME"] = _app.name;
3710 _env[
"APOLLO_APP_UUID"] = _app.uuid;
3711 _env[
"APOLLO_APP_STATUS"] =
"STARTING";
3712 _env[
"APOLLO_CLIENT_UUID"] = launch_session->unique_id;
3713 _env[
"APOLLO_CLIENT_NAME"] = launch_session->device_name;
3714 _env[
"APOLLO_CLIENT_WIDTH"] = std::to_string(render_width);
3715 _env[
"APOLLO_CLIENT_HEIGHT"] = std::to_string(render_height);
3716 _env[
"APOLLO_CLIENT_RENDER_WIDTH"] = std::to_string(launch_session->width);
3717 _env[
"APOLLO_CLIENT_RENDER_HEIGHT"] = std::to_string(launch_session->height);
3718 _env[
"APOLLO_CLIENT_SCALE_FACTOR"] = std::to_string(scale_factor);
3719 _env[
"APOLLO_CLIENT_FPS"] = fps_str;
3720 _env[
"APOLLO_CLIENT_HDR"] = launch_session->enable_hdr ?
"true" :
"false";
3721 _env[
"APOLLO_CLIENT_GCMAP"] = std::to_string(launch_session->gcmap);
3722 _env[
"APOLLO_CLIENT_HOST_AUDIO"] = launch_session->host_audio ?
"true" :
"false";
3723 _env[
"APOLLO_CLIENT_ENABLE_SOPS"] = launch_session->enable_sops ?
"true" :
"false";
3728 _env[
"HERMES_APP_ID"] = _app.id;
3729 _env[
"HERMES_APP_NAME"] = _app.name;
3730 _env[
"HERMES_APP_UUID"] = _app.uuid;
3731 _env[
"HERMES_APP_STATUS"] =
"STARTING";
3732 _env[
"HERMES_CLIENT_UUID"] = launch_session->unique_id;
3733 _env[
"HERMES_CLIENT_NAME"] = launch_session->device_name;
3734 _env[
"HERMES_CLIENT_WIDTH"] = std::to_string(render_width);
3735 _env[
"HERMES_CLIENT_HEIGHT"] = std::to_string(render_height);
3736 _env[
"HERMES_CLIENT_RENDER_WIDTH"] = std::to_string(launch_session->width);
3737 _env[
"HERMES_CLIENT_RENDER_HEIGHT"] = std::to_string(launch_session->height);
3738 _env[
"HERMES_CLIENT_SCALE_FACTOR"] = std::to_string(scale_factor);
3739 _env[
"HERMES_CLIENT_FPS"] = fps_str;
3740 _env[
"HERMES_CLIENT_HDR"] = launch_session->enable_hdr ?
"true" :
"false";
3741 _env[
"HERMES_CLIENT_GCMAP"] = std::to_string(launch_session->gcmap);
3742 _env[
"HERMES_CLIENT_HOST_AUDIO"] = launch_session->host_audio ?
"true" :
"false";
3743 _env[
"HERMES_CLIENT_ENABLE_SOPS"] = launch_session->enable_sops ?
"true" :
"false";
3744 _env[
"HERMES_GAMESCOPE_BACKEND"] = config::video.gamescope_backend;
3745 _env[
"HERMES_SESSION_ENVIRONMENT"] = session_env.describe();
3746 if (!launch_session->enable_hdr) {
3747 _env[
"DXVK_HDR"] =
"0";
3748 _env[
"PROTON_ENABLE_HDR"] =
"0";
3751 if (_app.limit_fps) {
3752 const auto existing = _env.find(
"MANGOHUD_CONFIG");
3753 const auto limits = frame_limit::environment(
3754 static_cast<int>(std::lround(
static_cast<double>(launch_session->fps) / 1000.0)),
3755 existing != _env.end() ?
existing->to_string() : std::string {}
3759 for (
const auto &[name, value] : limits) {
3760 const auto previous = _env.find(name);
3761 _frame_limit_restore.emplace_back(name, previous != _env.end() ? std::optional<std::string> {previous->to_string()} : std::nullopt);
3764 if (!limits.empty()) {
3765 BOOST_LOG(info) <<
"Capping " << _app.name <<
" at the stream's " << limits.front().second
3766 <<
" FPS (DXVK, VKD3D-Proton, and MangoHud where it is enabled)";
3770 int channelCount = launch_session->surround_info & 65535;
3771 switch (channelCount) {
3773 _env[
"SUNSHINE_CLIENT_AUDIO_CONFIGURATION"] =
"2.0";
3774 _env[
"APOLLO_CLIENT_AUDIO_CONFIGURATION"] =
"2.0";
3777 _env[
"SUNSHINE_CLIENT_AUDIO_CONFIGURATION"] =
"5.1";
3778 _env[
"APOLLO_CLIENT_AUDIO_CONFIGURATION"] =
"5.1";
3781 _env[
"SUNSHINE_CLIENT_AUDIO_CONFIGURATION"] =
"7.1";
3782 _env[
"APOLLO_CLIENT_AUDIO_CONFIGURATION"] =
"7.1";
3785 _env[
"SUNSHINE_CLIENT_AUDIO_SURROUND_PARAMS"] = launch_session->surround_params;
3786 _env[
"APOLLO_CLIENT_AUDIO_SURROUND_PARAMS"] = launch_session->surround_params;
3788 if (!_app.output.empty() && _app.output !=
"null"sv) {
3789 _pipe.reset(fopen(_app.output.c_str(),
"a"));
3793 _app_prep_begin = std::begin(_app.prep_cmds);
3794 _app_prep_it = _app_prep_begin;
3796 for (; _app_prep_it != std::end(_app.prep_cmds); ++_app_prep_it) {
3797 auto &cmd = *_app_prep_it;
3800 if (cmd.do_cmd.empty()) {
3804 boost::filesystem::path working_dir = _app.working_dir.empty() ?
3805 find_working_directory(cmd.do_cmd, _env) :
3806 boost::filesystem::path(_app.working_dir);
3807 BOOST_LOG(info) <<
"Executing Do Cmd: ["sv << cmd.do_cmd <<
"] elevated: " << cmd.elevated;
3808 auto child = platf::run_command(cmd.elevated,
true, cmd.do_cmd, working_dir, _env, _pipe.get(), ec,
nullptr);
3811 BOOST_LOG(error) <<
"Couldn't run ["sv << cmd.do_cmd <<
"]: System: "sv << ec.message();
3815 if (!(_app.cmd.empty() && ec == std::errc::permission_denied)) {
3821 auto ret = child.exit_code();
3822 if (ret != 0 && ec != std::errc::permission_denied) {
3823 BOOST_LOG(error) <<
'[' << cmd.do_cmd <<
"] failed with code ["sv << ret <<
']';
3828 _env[
"APOLLO_APP_STATUS"] =
"RUNNING";
3832 const auto placement_arguments = [](
const std::string &
command) {
3834 return boost::program_options::split_unix(command);
3835 }
catch (
const std::exception &error) {
3836 BOOST_LOG(warning) <<
"[VDISPLAY] Could not parse window placement command: " << error.what();
3837 return std::vector<std::string> {};
3840 const auto app_arguments = placement_arguments(_app.cmd);
3841 bool place_steam = platf::window_placement::opens_big_picture(app_arguments);
3843 (platf::window_placement::launches_gamescope(app_arguments) ||
3844 launch_session->launch_mode ==
"gamescope");
3845 std::vector<std::uint32_t> gamescope_pids;
3853 if (!gamescope_session && _app.stop_desktop_steam !=
"off") {
3855 (launch_session->launch_mode ==
"gamescope" && runs_steam(_app));
3856 for (
const auto &cmd : _app.detached) {
3861 if (
const auto stopped = stop_desktop_steam(
"[Gamescope]")) {
3862 _reopen_desktop_steam =
true;
3863 _desktop_steam_flatpak = stopped->flatpak;
3872 _detached_units.clear();
3873 const auto systemd_run = find_program(
"systemd-run");
3874 const bool scoped = _app.stop_detached && !_app.elevated && !systemd_run.empty() &&
3875 std::filesystem::exists(
"/run/user/" + std::to_string(::getuid()) +
"/bus");
3876 static std::atomic<unsigned> detached_launches {0};
3877 const unsigned launch = ++detached_launches;
3878 for (
auto &cmd : _app.detached) {
3879 boost::filesystem::path working_dir = _app.working_dir.empty() ?
3880 find_working_directory(cmd, _env) :
3881 boost::filesystem::path(_app.working_dir);
3882 BOOST_LOG(info) <<
"Spawning ["sv << cmd <<
"] in ["sv << working_dir <<
']';
3883 std::string spawn = cmd;
3889 auto child = platf::run_command(_app.elevated,
true, spawn, working_dir, _env, _pipe.get(), ec,
nullptr);
3891 BOOST_LOG(warning) <<
"Couldn't spawn ["sv << cmd <<
"]: System: "sv << ec.message();
3893 const auto arguments = placement_arguments(cmd);
3894 place_steam = place_steam || platf::window_placement::opens_big_picture(arguments);
3895 if (!gamescope_session && platf::window_placement::launches_gamescope(arguments)) {
3896 gamescope_pids.push_back(
static_cast<std::uint32_t
>(child.id()));
3898 if (!unit.empty()) {
3899 _detached_units.push_back(unit);
3905 if (_app.cmd.empty()) {
3906 BOOST_LOG(info) <<
"No commands configured, showing desktop..."sv;
3909 boost::filesystem::path working_dir = _app.working_dir.empty() ?
3910 find_working_directory(_app.cmd, _env) :
3911 boost::filesystem::path(_app.working_dir);
3913 if (launch_session->launch_mode ==
"gamescope") {
3914 if (gamescope_session) {
3918 BOOST_LOG(info) <<
"Gamescope launch mode requested inside an existing Gamescope session; "
3919 "running the application directly.";
3920 }
else if (boost::process::v1::search_path(
"gamescope").empty()) {
3921 BOOST_LOG(error) <<
"Gamescope launch mode was requested, but gamescope is not available in PATH";
3924 const int gamescope_fps = std::max(1, (launch_session->fps ? launch_session->fps : 60000) / 1000);
3936 const std::string &configured_backend = config::video.gamescope_backend;
3937 const std::string gamescope_backend = (configured_backend.empty() || configured_backend ==
"auto") ?
3940 launch_command = std::format(
"gamescope --backend={} -W {} -H {} -r {} -o {} -f -e -F fsr --fsr-sharpness 4 -- {}",
3942 launch_session->width,
3943 launch_session->height,
3950 BOOST_LOG(info) <<
"Executing: ["sv <<
launch_command <<
"] in ["sv << working_dir <<
']';
3951 _process = platf::run_command(_app.elevated,
true, launch_command, working_dir, _env, _pipe.get(), ec, &_process_group);
3953 BOOST_LOG(warning) <<
"Couldn't run ["sv <<
launch_command <<
"]: System: "sv << ec.message();
3958 if (!this->display_name.empty()) {
3959 if (app_gamescope && _process.valid()) {
3960 gamescope_pids.push_back(
static_cast<std::uint32_t
>(_process.id()));
3964 if (!gamescope_pids.empty()) {
3966 }
else if (place_steam) {
3971 _app_launch_time = std::chrono::steady_clock::now();
3976#if defined HERMES_TRAY && HERMES_TRAY >= 1
3988 auto reaper = util::fail_guard([]() {
3997 while (waitpid(-1,
nullptr, WNOHANG) > 0);
4005 }
else if (_process.running()) {
4008 }
else if (_app.auto_detach && std::chrono::steady_clock::now() - _app_launch_time < 5s) {
4009 BOOST_LOG(info) <<
"App exited with code ["sv << _process.native_exit_code() <<
"] within 5 seconds of launch. Treating the app as a detached command."sv;
4010 BOOST_LOG(info) <<
"Adjust this behavior in the Applications tab or apps.json if this is not what you want."sv;
4013 #if defined HERMES_TRAY && HERMES_TRAY >= 1
4014 if (_process.native_exit_code() != 0) {
4015 system_tray::update_tray_launch_error(proc::proc.get_last_run_app_name(), _process.native_exit_code());
4030 void proc_t::resume() {
4031 BOOST_LOG(info) <<
"Session resuming for app [" << _app_name <<
"].";
4033 if (!_app.state_cmds.empty()) {
4034 auto exec_thread = std::thread([cmd_list = _app.state_cmds, app_working_dir = _app.working_dir, _env = _env]()
mutable {
4036 _env[
"APOLLO_APP_STATUS"] =
"RESUMING";
4039 auto _state_resume_it = std::begin(cmd_list);
4041 for (; _state_resume_it != std::end(cmd_list); ++_state_resume_it) {
4042 auto &cmd = *_state_resume_it;
4045 if (cmd.do_cmd.empty()) {
4049 boost::filesystem::path working_dir = app_working_dir.empty() ?
4050 find_working_directory(cmd.do_cmd, _env) :
4051 boost::filesystem::path(app_working_dir);
4052 BOOST_LOG(info) <<
"Executing Resume Cmd: ["sv << cmd.do_cmd <<
"] elevated: " << cmd.elevated;
4053 auto child = platf::run_command(cmd.elevated, true, cmd.do_cmd, working_dir, _env, nullptr, ec, nullptr);
4056 BOOST_LOG(error) <<
"Couldn't run ["sv << cmd.do_cmd <<
"]: System: "sv << ec.message();
4062 auto ret = child.exit_code();
4063 if (ret != 0 && ec != std::errc::permission_denied) {
4064 BOOST_LOG(error) <<
'[' << cmd.do_cmd <<
"] failed with code ["sv << ret <<
']';
4070 exec_thread.detach();
4074 void proc_t::pause() {
4076 BOOST_LOG(info) <<
"Session already stopped, do not run pause commands.";
4080 if (_app.terminate_on_pause) {
4081 BOOST_LOG(info) <<
"Terminating app [" << _app_name <<
"] when all clients are disconnected. Pause commands are skipped.";
4086 BOOST_LOG(info) <<
"Session pausing for app [" << _app_name <<
"].";
4088 if (!_app.state_cmds.empty()) {
4089 auto exec_thread = std::thread([cmd_list = _app.state_cmds, app_working_dir = _app.working_dir, _env = _env]()
mutable {
4090 _env[
"APOLLO_APP_STATUS"] =
"PAUSING";
4093 auto _state_pause_it = std::begin(cmd_list);
4095 for (; _state_pause_it != std::end(cmd_list); ++_state_pause_it) {
4096 auto &cmd = *_state_pause_it;
4099 if (cmd.undo_cmd.empty()) {
4103 boost::filesystem::path working_dir = app_working_dir.empty() ?
4104 find_working_directory(cmd.undo_cmd, _env) :
4105 boost::filesystem::path(app_working_dir);
4106 BOOST_LOG(info) <<
"Executing Pause Cmd: ["sv << cmd.undo_cmd <<
"] elevated: " << cmd.elevated;
4107 auto child = platf::run_command(cmd.elevated, true, cmd.undo_cmd, working_dir, _env, nullptr, ec, nullptr);
4110 BOOST_LOG(error) <<
"Couldn't run ["sv << cmd.undo_cmd <<
"]: System: "sv << ec.message();
4116 auto ret = child.exit_code();
4117 if (ret != 0 && ec != std::errc::permission_denied) {
4118 BOOST_LOG(error) <<
'[' << cmd.undo_cmd <<
"] failed with code ["sv << ret <<
']';
4124 exec_thread.detach();
4127#if defined HERMES_TRAY && HERMES_TRAY >= 1
4132 void proc_t::terminate(
bool immediate,
bool needs_refresh) {
4137 VDISPLAY::endPhysicalOutputSession();
4143 _process = boost::process::v1::child();
4144 _process_group = boost::process::v1::group();
4146 _env[
"APOLLO_APP_STATUS"] =
"TERMINATING";
4148 for (; _app_prep_it != _app_prep_begin; --_app_prep_it) {
4149 auto &cmd = *(_app_prep_it - 1);
4151 if (cmd.undo_cmd.empty()) {
4155 boost::filesystem::path working_dir = _app.working_dir.empty() ?
4156 find_working_directory(cmd.undo_cmd, _env) :
4157 boost::filesystem::path(_app.working_dir);
4158 BOOST_LOG(info) <<
"Executing Undo Cmd: ["sv << cmd.undo_cmd <<
']';
4159 boost::process::v1::group undo_group;
4160 auto child = platf::run_command(cmd.elevated,
true, cmd.undo_cmd, working_dir, _env, _pipe.get(), ec, &undo_group);
4163 BOOST_LOG(warning) <<
"Undo command could not start: "sv << ec.message();
4167 finish_undo_command(child, undo_group, _app.exit_timeout);
4174 if (!_detached_units.empty()) {
4175 if (
const auto systemctl = find_program(
"systemctl"); !systemctl.empty()) {
4176 const auto timeout = std::max(_app.exit_timeout, std::chrono::seconds {15});
4177 for (
const auto &unit : _detached_units) {
4178 BOOST_LOG(info) <<
"Stopping "sv << unit <<
", what this app's detached commands started"sv;
4179 run_program({systemctl,
"--user",
"--quiet",
"stop", unit},
timeout + 10s);
4182 _detached_units.clear();
4189 for (
auto it = _frame_limit_restore.rbegin(); it != _frame_limit_restore.rend(); ++it) {
4191 _env[it->first] = *it->second;
4193 _env.erase(it->first);
4196 _frame_limit_restore.clear();
4198 if (std::exchange(_reopen_desktop_steam,
false)) {
4200 for (
const char *name : {
"DISPLAY",
"WAYLAND_DISPLAY",
"XAUTHORITY",
"XDG_RUNTIME_DIR",
"DBUS_SESSION_BUS_ADDRESS"}) {
4201 if (
const auto variable = _env.find(name); variable != _env.end()) {
4202 environment.push_back(std::string {name} +
'=' + variable->to_string());
4205 reopen_desktop_steam(std::move(environment), _desktop_steam_flatpak);
4208 bool has_run = _app_id > 0;
4211 if (has_run && !mode_changed_display.empty()) {
4213 BOOST_LOG(info) <<
"HDR reverted for display " << mode_changed_display;
4215 BOOST_LOG(info) <<
"HDR revert failed for display " << mode_changed_display;
4219 bool used_virtual_display = vDisplayDriverStatus ==
VDISPLAY::DRIVER_STATUS::OK && _launch_session && _launch_session->virtual_display;
4220 const bool session_scoped_virtual_display =
4221 used_virtual_display && _launch_session->session_scoped_virtual_display;
4222 if (used_virtual_display && !session_scoped_virtual_display) {
4226 VDISPLAY::restoreExclusiveVirtualDisplay();
4228 BOOST_LOG(info) <<
"Virtual Display removed successfully";
4229 }
else if (this->virtual_display) {
4230 BOOST_LOG(warning) <<
"Virtual Display remove failed";
4232 BOOST_LOG(warning) <<
"Virtual Display remove failed, but it seems it was not created correctly either.";
4234 }
else if (session_scoped_virtual_display) {
4235 BOOST_LOG(debug) <<
"Session-scoped virtual display cleanup is owned by the streaming session.";
4246 if (proc::proc.get_last_run_app_name().length() > 0 && has_run) {
4247 if (used_virtual_display) {
4253#if defined HERMES_TRAY && HERMES_TRAY >= 1
4260 if (!has_run && initial_display.empty()) {
4261 initial_display = config::video.output_name;
4264 config::video.output_name = initial_display;
4270 display_name.clear();
4271 initial_display.clear();
4272 mode_changed_display.clear();
4273 _launch_session.reset();
4275 allow_client_commands =
false;
4277 if (_saved_input_config) {
4278 config::input = *_saved_input_config;
4279 _saved_input_config.reset();
4282 if (needs_refresh) {
4283 refresh(config::stream.file_apps,
false);
4287 const std::vector<ctx_t> &proc_t::get_apps()
const {
4291 std::vector<ctx_t> &proc_t::get_apps() {
4299 std::string proc_t::get_app_image(
int app_id) {
4300 auto iter = std::find_if(_apps.begin(), _apps.end(), [&app_id](
const auto app) {
4301 return app.id == std::to_string(app_id);
4303 auto app_image_path = iter == _apps.end() ? std::string() : iter->image_path;
4305 return validate_app_image_path(app_image_path);
4308 std::string proc_t::get_last_run_app_name() {
4312 std::string proc_t::get_running_app_uuid() {
4316 boost::process::environment proc_t::get_env() {
4326 assert(!_process.running());
4329 std::string_view::iterator find_match(std::string_view::iterator begin, std::string_view::iterator end) {
4342 }
while (begin != end && stack != 0);
4345 throw std::out_of_range(
"Missing closing bracket \')\'");
4350 std::string parse_env_val(boost::process::v1::native_environment &env,
const std::string_view &val_raw) {
4351 auto pos = std::begin(val_raw);
4352 auto dollar = std::find(pos, std::end(val_raw),
'$');
4354 std::stringstream ss;
4356 while (dollar != std::end(val_raw)) {
4357 auto next = dollar + 1;
4358 if (next != std::end(val_raw)) {
4362 ss.write(pos, (dollar - pos));
4363 auto var_begin = next + 1;
4364 auto var_end = find_match(next, std::end(val_raw));
4365 auto var_name = std::string {var_begin, var_end};
4368 ss << env[var_name].to_string();
4376 ss.write(pos, (next - pos));
4382 dollar = std::find(next, std::end(val_raw),
'$');
4388 ss.write(pos, (dollar - pos));
4393 std::string validate_app_image_path(std::string app_image_path) {
4394 if (app_image_path.empty()) {
4395 return DEFAULT_APP_IMAGE_PATH;
4399 auto image_extension = std::filesystem::path(app_image_path).extension().string();
4400 boost::to_lower(image_extension);
4403 if (image_extension !=
".png") {
4404 return DEFAULT_APP_IMAGE_PATH;
4408 auto full_image_path = std::filesystem::path(HERMES_ASSETS_DIR) / app_image_path;
4409 if (std::filesystem::exists(full_image_path)) {
4410 return full_image_path.string();
4411 }
else if (app_image_path ==
"./assets/steam.png") {
4413 return HERMES_ASSETS_DIR
"/steam.png";
4417 std::error_code code;
4418 if (!std::filesystem::exists(app_image_path, code)) {
4420 BOOST_LOG(warning) <<
"Couldn't find app image at path ["sv << app_image_path <<
']';
4421 return DEFAULT_APP_IMAGE_PATH;
4426 return app_image_path;
4429 std::optional<std::string> calculate_sha256(
const std::string &filename) {
4430 crypto::md_ctx_t ctx {EVP_MD_CTX_create()};
4432 return std::nullopt;
4435 if (!EVP_DigestInit_ex(ctx.get(), EVP_sha256(),
nullptr)) {
4436 return std::nullopt;
4440 char buf[1024 * 16];
4441 std::ifstream file(filename, std::ifstream::binary);
4442 while (file.good()) {
4443 file.read(buf,
sizeof(buf));
4444 if (!EVP_DigestUpdate(ctx.get(), buf, file.gcount())) {
4445 return std::nullopt;
4450 unsigned char result[SHA256_DIGEST_LENGTH];
4451 if (!EVP_DigestFinal_ex(ctx.get(), result,
nullptr)) {
4452 return std::nullopt;
4456 std::stringstream ss;
4457 ss << std::hex << std::setfill(
'0');
4458 for (
const auto &
byte : result) {
4459 ss << std::setw(2) << (int)
byte;
4464 uint32_t calculate_crc32(
const std::string &input) {
4465 boost::crc_32_type result;
4466 result.process_bytes(input.data(), input.length());
4467 return result.checksum();
4470 std::tuple<std::string, std::string>
calculate_app_id(
const std::string &app_name, std::string app_image_path,
int index) {
4472 std::vector<std::string> to_hash;
4473 to_hash.push_back(app_name);
4474 auto file_path = validate_app_image_path(app_image_path);
4475 if (file_path != DEFAULT_APP_IMAGE_PATH) {
4476 auto file_hash = calculate_sha256(file_path);
4478 to_hash.push_back(file_hash.value());
4481 to_hash.push_back(file_path);
4486 std::stringstream ss;
4487 for_each(to_hash.begin(), to_hash.end(), [&ss](
const std::string &s) {
4490 auto input_no_index = ss.str();
4492 auto input_with_index = ss.str();
4495 auto id_no_index = std::to_string(abs((int32_t) calculate_crc32(input_no_index)));
4496 auto id_with_index = std::to_string(abs((int32_t) calculate_crc32(input_with_index)));
4498 return std::make_tuple(id_no_index, id_with_index);
4521 void migrate_apps(nlohmann::json* fileTree_p, nlohmann::json* inputTree_p) {
4522 std::string new_app_uuid;
4526 if (inputTree_p->contains(
"uuid") && !(*inputTree_p)[
"uuid"].get<std::string>().empty()) {
4527 new_app_uuid = (*inputTree_p)[
"uuid"].get<std::string>();
4529 new_app_uuid = uuid_util::uuid_t::generate().string();
4530 (*inputTree_p)[
"uuid"] = new_app_uuid;
4534 if (inputTree_p->contains(
"prep-cmd") && (*inputTree_p)[
"prep-cmd"].empty()) {
4535 inputTree_p->erase(
"prep-cmd");
4539 if (inputTree_p->contains(
"detached") && (*inputTree_p)[
"detached"].empty()) {
4540 inputTree_p->erase(
"detached");
4544 inputTree_p->erase(
"launching");
4545 inputTree_p->erase(
"index");
4549 nlohmann::json newApps = nlohmann::json::array();
4550 if (fileTree_p->contains(
"apps") && (*fileTree_p)[
"apps"].is_array()) {
4551 for (
auto &
app : (*fileTree_p)[
"apps"]) {
4553 if (!
app.contains(
"uuid") ||
app[
"uuid"].get<std::string>().empty()) {
4554 app[
"uuid"] = uuid_util::uuid_t::generate().string();
4555 app.erase(
"launching");
4556 newApps.push_back(std::move(
app));
4559 if (!new_app_uuid.empty() &&
app[
"uuid"].get<std::string>() == new_app_uuid) {
4560 newApps.push_back(*inputTree_p);
4561 new_app_uuid.clear();
4563 newApps.push_back(std::move(
app));
4569 if (!new_app_uuid.empty() && inputTree_p) {
4570 newApps.push_back(*inputTree_p);
4572 (*fileTree_p)[
"apps"] = newApps;
4575 void migration_v2(nlohmann::json& fileTree) {
4576 static const int this_version = 2;
4578 int file_version = 1;
4579 if (fileTree.contains(
"version")) {
4581 file_version = fileTree[
"version"].get<
int>();
4582 }
catch (
const std::exception& e) {
4583 BOOST_LOG(info) <<
"Cannot parse apps.json version, treating as v1: " << e.what();
4588 if (file_version < this_version) {
4589 BOOST_LOG(info) <<
"Migrating app list from v1 to v2...";
4593 std::vector<std::string> boolean_keys = {
4594 "allow-client-commands",
4595 "exclude-global-prep-cmd",
4600 "per-client-app-identity",
4602 "force-virtual-display",
4603 "force-scale-factor"
4607 std::vector<std::string> integer_keys = {
4613 for (
auto &app : fileTree[
"apps"]) {
4614 for (
const auto &key : boolean_keys) {
4615 if (
app.contains(key)) {
4616 auto& _key =
app[key];
4617 if (_key.is_string()) {
4618 std::string s = _key.get<std::string>();
4619 std::transform(s.begin(), s.end(), s.begin(), ::tolower);
4620 _key = (s ==
"true" || s ==
"on" || s ==
"yes");
4621 }
else if (_key.is_array()) {
4623 if (!_key.empty() && _key[0].is_string()) {
4624 std::string first = _key[0].get<std::string>();
4625 std::transform(first.begin(), first.end(), first.begin(), ::tolower);
4626 if (first ==
"on" || first ==
"true" || first ==
"yes") {
4628 }
else if (first ==
"off" || first ==
"false" || first ==
"no") {
4638 if (_key.is_boolean()) {
4640 }
else if (_key.is_number()) {
4641 _key = (_key.get<
double>() != 0);
4642 }
else if (_key.is_null()) {
4645 _key = !_key.empty();
4651 for (
const auto &key : integer_keys) {
4652 if (
app.contains(key) && app[key].is_string()) {
4653 std::string s =
app[key].get<std::string>();
4654 app[key] = std::stoi(s);
4659 if (
app.contains(
"prep-cmd") && app[
"prep-cmd"].is_array()) {
4660 for (
auto &prep : app[
"prep-cmd"]) {
4661 if (prep.contains(
"elevated") && prep[
"elevated"].is_string()) {
4662 std::string s = prep[
"elevated"].get<std::string>();
4663 prep[
"elevated"] = (s ==
"true");
4670 fileTree[
"version"] = this_version;
4672 BOOST_LOG(info) <<
"Migrated app list from v1 to v2.";
4685 static const int this_version = 3;
4687 if (fileTree.contains(
"apps") && fileTree[
"apps"].is_array()) {
4688 for (
auto &
app : fileTree[
"apps"]) {
4689 if (!
app.is_object() ||
app.contains(
"virtual-display-layout")) {
4693 const std::string cmd =
app.value(
"cmd",
"");
4694 std::string first_token;
4695 std::istringstream tokens {cmd};
4696 tokens >> first_token;
4698 bool is_launcher = first_token ==
"hermes-gamescope-launch" ||
4699 first_token ==
"apollo-gamescope-launch";
4701 app.value(
"name",
"") ==
"Gamescope Steam Session" &&
4702 cmd.find(
"gamescope-launch") != std::string::npos) {
4707 app[
"virtual-display-layout"] =
"mirror";
4708 BOOST_LOG(info) <<
"Migrating app '" <<
app.value(
"name", cmd)
4709 <<
"': gamescope launcher now uses the mirror virtual-display layout.";
4714 fileTree[
"version"] = this_version;
4724 static const int this_version = 5;
4725 if (!fileTree.contains(
"apps") || !fileTree[
"apps"].is_array()) {
4726 fileTree[
"apps"] = nlohmann::json::array();
4728 auto &apps = fileTree[
"apps"];
4729 const auto add = [&](
const char *uuid,
const char *after, nlohmann::json entry) {
4730 for (
const auto &
app : apps) {
4731 if (
app.is_object() &&
app.value(
"uuid",
"") == uuid) {
4735 entry[
"uuid"] = uuid;
4736 auto position = apps.end();
4737 for (
auto it = apps.begin(); it != apps.end(); ++it) {
4738 if (it->is_object() && it->value(
"name",
"") == after) {
4739 position = std::next(it);
4743 BOOST_LOG(info) <<
"Adding app '" << entry.value(
"name",
"") <<
"'.";
4744 apps.insert(position, std::move(entry));
4746 add(DETACHED_DESKTOP_UUID,
"Desktop", {
4747 {
"name",
"Detached Desktop"},
4748 {
"image-path",
"detached-desktop.png"},
4749 {
"session-type",
"desktop"},
4750 {
"allow-client-commands",
false},
4752 add(DETACHED_STEAM_UUID,
"Steam Big Picture", {
4753 {
"name",
"Detached Steam"},
4754 {
"image-path",
"detached-steam.png"},
4755 {
"session-type",
"desktop"},
4756 {
"cmd",
"steam steam://open/bigpicture"},
4757 {
"allow-client-commands",
false},
4759 fileTree[
"version"] = this_version;
4769 static const int this_version = 6;
4770 if (fileTree.contains(
"apps") && fileTree[
"apps"].is_array()) {
4771 static const std::array<std::array<const char *, 3>, 3> covers {{
4772 {
"Low Res Desktop",
"desktop.png",
"desktop-low-res.png"},
4773 {
"Steam Big Picture",
"steam.png",
"steam-big-picture.png"},
4774 {
"Gamescope Steam Session",
"steam.png",
"steam-gamescope.png"},
4776 for (
auto &
app : fileTree[
"apps"]) {
4777 if (!
app.is_object()) {
4780 for (
const auto &[name, old_cover, cover] : covers) {
4781 if (
app.value(
"name",
"") == name &&
app.value(
"image-path",
"") == old_cover) {
4782 app[
"image-path"] = cover;
4783 BOOST_LOG(info) <<
"Giving app '" << name <<
"' the cover " << cover <<
'.';
4788 fileTree[
"version"] = this_version;
4797 static const int this_version = 7;
4799 if (fileTree.contains(
"apps") && fileTree[
"apps"].is_array()) {
4800 static const std::map<std::string, std::string> methods {
4801 {
"application",
"gamescope"},
4802 {
"desktop",
"kwin_virtual"},
4804 static const std::map<std::string, std::string> names {
4805 {
"Detached Desktop",
"Desktop (KWin virtual)"},
4806 {
"Detached Steam",
"Steam (KWin virtual)"},
4808 for (
auto &
app : fileTree[
"apps"]) {
4809 if (!
app.is_object()) {
4812 const auto method = methods.find(
app.value(
"session-type",
""));
4813 if (method != methods.end() && !
app.contains(
"isolation-method")) {
4814 app[
"isolation-method"] = method->second;
4816 if (
app.value(
"session-type",
"") ==
"shared") {
4817 app[
"host-session"] =
true;
4819 app.erase(
"session-type");
4821 const auto name = names.find(
app.value(
"name",
""));
4822 const auto uuid =
app.value(
"uuid",
"");
4823 if (name != names.end() && (uuid == DETACHED_DESKTOP_UUID || uuid == DETACHED_STEAM_UUID)) {
4824 app[
"name"] = name->second;
4829 fileTree[
"version"] = this_version;
4832 void migrate(nlohmann::json& fileTree,
const std::string& fileName,
bool persist =
true) {
4833 int file_version = 0;
4834 if (fileTree.contains(
"version")) {
4835 file_version = fileTree[
"version"].get<
int>();
4838 bool changed =
false;
4839 if (file_version < 2) {
4840 migration_v2(fileTree);
4843 if (file_version < 3) {
4847 if (file_version < 5) {
4851 if (file_version < 6) {
4855 if (file_version < 7) {
4859 if (changed && persist) {
4864 std::optional<proc::proc_t>
parse(
const std::string &file_name,
bool fallback_on_failure) {
4867 auto this_env = boost::this_process::environment();
4869 std::set<std::string> ids;
4870 std::vector<proc::ctx_t> apps;
4873 size_t fail_count = 0;
4878 bool loaded =
false;
4881 nlohmann::json tree;
4884 tree = nlohmann::json::parse(content);
4885 }
catch (
const std::exception& e) {
4886 BOOST_LOG(warning) <<
"Couldn't read apps.json properly! Apps will not be loaded."sv;
4891 migrate(tree, file_name);
4893 if (tree.contains(
"env") && tree[
"env"].is_object()) {
4894 for (
auto &item : tree[
"env"].items()) {
4895 this_env[item.key()] = parse_env_val(this_env, item.value().get<std::string>());
4900 if (!tree.contains(
"apps") || !tree[
"apps"].is_array()) {
4901 BOOST_LOG(warning) <<
"No apps were defined in apps.json!!!"sv;
4906 for (
auto &app_node : tree[
"apps"]) {
4908 ctx.idx = std::to_string(i);
4909 ctx.uuid = app_node.at(
"uuid");
4912 if ((ctx.uuid == DETACHED_DESKTOP_UUID || ctx.uuid == DETACHED_STEAM_UUID) &&
4913 (!config::video.hermes_kms_isolated_sessions || config::video.virtual_display_backend !=
"hermes_kms")) {
4918 std::vector<proc::cmd_t> prep_cmds;
4919 bool exclude_global_prep = app_node.value(
"exclude-global-prep-cmd",
false);
4920 if (!exclude_global_prep) {
4921 prep_cmds.reserve(config::sunshine.prep_cmds.size());
4922 for (
auto &prep_cmd : config::sunshine.prep_cmds) {
4923 auto do_cmd = parse_env_val(this_env, prep_cmd.do_cmd);
4924 auto undo_cmd = parse_env_val(this_env, prep_cmd.undo_cmd);
4925 prep_cmds.emplace_back(
4927 std::move(undo_cmd),
4928 std::move(prep_cmd.elevated)
4932 if (app_node.contains(
"prep-cmd") && app_node[
"prep-cmd"].is_array()) {
4933 for (
auto &prep_node : app_node[
"prep-cmd"]) {
4934 std::string do_cmd = parse_env_val(this_env, prep_node.value(
"do",
""));
4935 std::string undo_cmd = parse_env_val(this_env, prep_node.value(
"undo",
""));
4936 bool elevated = prep_node.value(
"elevated",
false);
4937 prep_cmds.emplace_back(
4939 std::move(undo_cmd),
4946 std::vector<proc::cmd_t> state_cmds;
4947 bool exclude_global_state_cmds = app_node.value(
"exclude-global-state-cmd",
false);
4948 if (!exclude_global_state_cmds) {
4949 state_cmds.reserve(config::sunshine.state_cmds.size());
4950 for (
auto &state_cmd : config::sunshine.state_cmds) {
4951 auto do_cmd = parse_env_val(this_env, state_cmd.do_cmd);
4952 auto undo_cmd = parse_env_val(this_env, state_cmd.undo_cmd);
4953 state_cmds.emplace_back(
4955 std::move(undo_cmd),
4956 std::move(state_cmd.elevated)
4960 if (app_node.contains(
"state-cmd") && app_node[
"state-cmd"].is_array()) {
4961 for (
auto &prep_node : app_node[
"state-cmd"]) {
4962 std::string do_cmd = parse_env_val(this_env, prep_node.value(
"do",
""));
4963 std::string undo_cmd = parse_env_val(this_env, prep_node.value(
"undo",
""));
4964 bool elevated = prep_node.value(
"elevated",
false);
4965 state_cmds.emplace_back(
4967 std::move(undo_cmd),
4974 std::vector<std::string> detached;
4975 if (app_node.contains(
"detached") && app_node[
"detached"].is_array()) {
4976 for (
auto &detached_val : app_node[
"detached"]) {
4977 detached.emplace_back(parse_env_val(this_env, detached_val.get<std::string>()));
4982 if (app_node.contains(
"output"))
4983 ctx.output = parse_env_val(this_env, app_node.value(
"output",
""));
4984 std::string name = parse_env_val(this_env, app_node.value(
"name",
""));
4985 if (app_node.contains(
"cmd"))
4986 ctx.cmd = parse_env_val(this_env, app_node.value(
"cmd",
""));
4987 if (app_node.contains(
"working-dir")) {
4988 ctx.working_dir = parse_env_val(this_env, app_node.value(
"working-dir",
""));
4990 if (app_node.contains(
"image-path"))
4991 ctx.image_path = parse_env_val(this_env, app_node.value(
"image-path",
""));
4993 ctx.elevated = app_node.value(
"elevated",
false);
4994 ctx.auto_detach = app_node.value(
"auto-detach",
true);
4995 ctx.wait_all = app_node.value(
"wait-all",
true);
4996 ctx.exit_timeout = std::chrono::seconds { app_node.value(
"exit-timeout", 5) };
4997 ctx.virtual_display = app_node.value(
"virtual-display",
false);
4998 ctx.force_virtual_display = app_node.value(
"force-virtual-display",
false);
4999 ctx.force_scale_factor = app_node.value(
"force-scale-factor",
false);
5000 ctx.scale_factor = app_node.value(
"scale-factor", 100);
5001 ctx.use_app_identity = app_node.value(
"use-app-identity",
false);
5002 ctx.per_client_app_identity = app_node.value(
"per-client-app-identity",
false);
5003 ctx.allow_client_commands = app_node.value(
"allow-client-commands",
true);
5004 ctx.terminate_on_pause = app_node.value(
"terminate-on-pause",
false);
5005 ctx.unlock_host_session = app_node.value(
"unlock-host-session",
false);
5006 ctx.stop_detached = app_node.value(
"stop-detached",
true);
5007 ctx.limit_fps = app_node.value(
"limit-fps",
false);
5008 ctx.isolation_method = app_node.value(
"isolation-method",
"default");
5009 if (ctx.isolation_method !=
"default" &&
5010 ctx.isolation_method !=
"gamescope" &&
5011 ctx.isolation_method !=
"kwin_virtual") {
5012 BOOST_LOG(warning) <<
"Unknown isolation-method '" << ctx.isolation_method
5013 <<
"' for app " << name <<
"; using the global setting.";
5014 ctx.isolation_method =
"default";
5016 ctx.host_session = app_node.value(
"host-session",
false);
5020 int first_frame_timeout = 0;
5021 if (
const auto it = app_node.find(
"first-frame-timeout"); it != app_node.end()) {
5022 if (it->is_number_integer()) {
5023 first_frame_timeout = it->get<
int>();
5024 }
else if (it->is_string()) {
5026 first_frame_timeout = std::stoi(it->get<std::string>());
5027 }
catch (
const std::exception &) {
5028 first_frame_timeout = 0;
5032 if (first_frame_timeout < 0) {
5033 BOOST_LOG(warning) <<
"Negative first-frame-timeout for app " << name <<
"; using the default.";
5035 ctx.first_frame_timeout = std::chrono::seconds {std::clamp(first_frame_timeout, 0, 600)};
5037 ctx.virtual_display_layout = app_node.value(
"virtual-display-layout",
"auto");
5038 if (ctx.virtual_display_layout !=
"auto" &&
5039 ctx.virtual_display_layout !=
"extend" &&
5040 ctx.virtual_display_layout !=
"primary" &&
5041 ctx.virtual_display_layout !=
"detached" &&
5042 ctx.virtual_display_layout !=
"mirror" &&
5043 ctx.virtual_display_layout !=
"exclusive") {
5044 BOOST_LOG(warning) <<
"Unknown virtual-display-layout '" << ctx.virtual_display_layout
5045 <<
"' for app " << name <<
"; using auto.";
5046 ctx.virtual_display_layout =
"auto";
5048 auto mode = [&](
const char *key) {
5049 std::string value =
"auto";
5050 if (
const auto it = app_node.find(key); it != app_node.end()) {
5053 value = it->is_boolean() ? (it->get<
bool>() ?
"on" :
"off") :
5054 it->is_string() ? it->get<std::string>() :
5055 std::string {
"auto"};
5057 if (value !=
"auto" && value !=
"on" && value !=
"off") {
5058 BOOST_LOG(warning) <<
"Unknown " << key <<
" '" << value <<
"' for app " << name <<
"; using auto.";
5063 ctx.gamescope_steam_mode = mode(
"gamescope-steam-mode");
5064 ctx.isolate_devices = mode(
"isolate-devices");
5065 ctx.isolate_sound = mode(
"isolate-sound");
5066 ctx.stop_desktop_steam = mode(
"stop-desktop-steam");
5067 ctx.gamescope_args = parse_env_val(this_env, app_node.value(
"gamescope-args",
""));
5068 ctx.gamepad = app_node.value(
"gamepad",
"");
5072 if (ids.count(std::get<0>(possible_ids)) == 0) {
5073 ctx.id = std::get<0>(possible_ids);
5075 ctx.id = std::get<1>(possible_ids);
5079 ctx.name = std::move(name);
5080 ctx.prep_cmds = std::move(prep_cmds);
5081 ctx.state_cmds = std::move(state_cmds);
5082 ctx.detached = std::move(detached);
5084 apps.emplace_back(std::move(ctx));
5089 }
catch (std::exception &e) {
5090 BOOST_LOG(error) <<
"Error happened during app loading: "sv << e.what();
5094 if (fail_count >= 3) {
5096 BOOST_LOG(warning) <<
"Couldn't parse/migrate apps.json properly! Apps will not be loaded."sv;
5100 BOOST_LOG(warning) <<
"App format is still invalid! Trying to re-migrate the app list..."sv;
5103 tree[
"version"] = 0;
5106 migrate(tree, file_name,
false);
5107 }
catch (std::exception &e) {
5108 BOOST_LOG(error) <<
"Error happened during migration: "sv << e.what();
5112 this_env = boost::this_process::environment();
5121 }
while (fail_count < 3);
5123 if (!loaded && !fallback_on_failure) {
5126 BOOST_LOG(warning) <<
"Keeping the current application list: "sv << file_name <<
" could not be loaded"sv;
5127 return std::nullopt;
5130 if (fail_count > 0) {
5131 BOOST_LOG(warning) <<
"No applications configured, adding fallback Desktop entry.";
5133 ctx.idx = std::to_string(i);
5134 ctx.uuid = FALLBACK_DESKTOP_UUID;
5135 ctx.name =
"Desktop (fallback)";
5136 ctx.image_path = parse_env_val(this_env,
"desktop-alt.png");
5137 ctx.virtual_display =
false;
5138 ctx.scale_factor = 100;
5139 ctx.use_app_identity =
false;
5140 ctx.per_client_app_identity =
false;
5141 ctx.allow_client_commands =
false;
5142 ctx.terminate_on_pause =
false;
5143 ctx.unlock_host_session =
false;
5144 ctx.isolation_method =
"default";
5146 ctx.elevated =
false;
5147 ctx.auto_detach =
true;
5148 ctx.wait_all =
false;
5149 ctx.exit_timeout = 5s;
5153 if (ids.count(std::get<0>(possible_ids)) == 0) {
5155 ctx.id = std::get<0>(possible_ids);
5158 ctx.id = std::get<1>(possible_ids);
5162 apps.emplace_back(std::move(ctx));
5167 if (config::input.enable_input_only_mode) {
5171 ctx.idx = std::to_string(i);
5172 ctx.uuid = REMOTE_INPUT_UUID;
5173 ctx.name =
"Remote Input";
5174 ctx.image_path = parse_env_val(this_env,
"input_only.png");
5175 ctx.virtual_display =
false;
5176 ctx.scale_factor = 100;
5177 ctx.use_app_identity =
false;
5178 ctx.per_client_app_identity =
false;
5179 ctx.allow_client_commands =
false;
5180 ctx.terminate_on_pause =
true;
5181 ctx.unlock_host_session =
false;
5182 ctx.host_session =
true;
5184 ctx.elevated =
false;
5185 ctx.auto_detach =
true;
5186 ctx.wait_all =
true;
5187 ctx.exit_timeout = 5s;
5190 if (ids.count(std::get<0>(possible_ids)) == 0) {
5192 ctx.id = std::get<0>(possible_ids);
5196 ctx.id = std::get<1>(possible_ids);
5200 input_only_app_id_str = ctx.id;
5201 input_only_app_id = util::from_view(ctx.id);
5203 apps.emplace_back(std::move(ctx));
5209 ctx.idx = std::to_string(i);
5210 ctx.uuid = TERMINATE_APP_UUID;
5211 ctx.name =
"Terminate";
5212 ctx.image_path = parse_env_val(this_env,
"terminate.png");
5213 ctx.virtual_display =
false;
5214 ctx.scale_factor = 100;
5215 ctx.use_app_identity =
false;
5216 ctx.per_client_app_identity =
false;
5217 ctx.allow_client_commands =
false;
5218 ctx.terminate_on_pause =
false;
5219 ctx.unlock_host_session =
false;
5220 ctx.host_session =
true;
5222 ctx.elevated =
false;
5223 ctx.auto_detach =
true;
5224 ctx.wait_all =
true;
5225 ctx.exit_timeout = 5s;
5228 if (ids.count(std::get<0>(possible_ids)) == 0) {
5230 ctx.id = std::get<0>(possible_ids);
5234 ctx.id = std::get<1>(possible_ids);
5238 terminate_app_id_str = ctx.id;
5239 terminate_app_id = util::from_view(ctx.id);
5241 apps.emplace_back(std::move(ctx));
5246 std::move(this_env),
5251 void refresh(
const std::string &file_name,
bool needs_terminate) {
5252 if (needs_terminate) {
5253 proc.terminate_all_isolated();
5254 proc.terminate(
false,
false);
5260 auto proc_opt =
proc::parse(file_name, proc.get_apps().empty());
5263 proc = std::move(*proc_opt);
5276 bool expand_compositor_profile_for_test(
5277 const std::string &path,
5278 const std::string &name,
5279 const std::vector<std::pair<std::string, std::string>> &values,
5280 std::string &command,
5281 std::vector<std::pair<std::string, std::string>> &env,
5282 std::string &config_template,
5283 std::string &config_target,
5284 bool &discover_socket,
5285 std::string &required_binary
5287 const auto profile = read_compositor_profile(std::filesystem::path {path}, name);
5292 command = expand_profile_template(profile->command, values);
5294 for (
const auto &[key, value] : profile->env) {
5295 env.emplace_back(key, expand_profile_template(value, values));
5297 config_template = profile->config_template.empty() ?
5299 (profile->profile_dir / profile->config_template).
string();
5300 config_target = expand_profile_template(profile->config_target, values);
5301 discover_socket = profile->discover_socket;
5302 required_binary = profile->required_binary;
void release_host_sink()
Let go of a hold_host_sink() hold and restore the sink it recorded.
void hold_host_sink()
Record the host's default sink before a display change can move it.
void remove_session_sink(const std::string &name)
Remove a sink made by create_session_sink(). Removing one that is already gone is not an error.
bool create_session_sink(const std::string &name, int channels)
Create the sink an isolated session records, and its own alone.
Declarations for audio capture and encoding.
Capture a shell helper's output without an unbounded shutdown wait.
std::shared_mutex & reap_mutex()
static std::unique_ptr< plan_t > isolate(const std::string &staging, options_t options)
A new mount namespace with /dev built on the empty directory staging.
static std::unique_ptr< plan_t > join(pid_t pid)
The mount namespace of a running session process.
int execute_isolated(const ctx_t &app, std::shared_ptr< rtsp_stream::launch_session_t > launch_session)
int running_for_client(const std::string &client_uuid)
void terminate_isolated_client(const std::string &client_uuid)
std::string isolated_audio_sink(uint32_t launch_session_id)
The sink an isolated session plays into, or empty for one that shares the host's.
bool isolated_client_present(const std::string &client_uuid)
std::string isolated_audio_server(uint32_t launch_session_id)
std::string isolated_mic_source(uint32_t launch_session_id)
bool isolated_session_has_account(uint32_t launch_session_id)
Whether an isolated session runs under a helper account of its own, whose audio server the host's can...
void terminate_isolated(uint32_t launch_session_id)
void disconnect_isolated(uint32_t launch_session_id)
int prepare_session_virtual_display(std::shared_ptr< rtsp_stream::launch_session_t > launch_session, bool apply_scale=true, const ctx_t *session_app=nullptr, std::optional< uid_t > session_owner_uid=std::nullopt, bool isolated_session=false)
boost::process::v1::environment get_session_env(uint32_t launch_session_id)
bool prepare_isolated_resume(std::shared_ptr< rtsp_stream::launch_session_t > launch_session)
std::vector< isolated_session_t > list_isolated()
void terminate_all_isolated()
Declarations for common platform specific utilities.
bool process_group_running(std::uintptr_t native_handle)
Check if a process group still has running children.
std::shared_ptr< display_t > display(mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config)
Get the display_t instance for the given hwdevice_type. If display_name is empty, use the first monit...
void forget_kept_gamepads(const std::string &session_tag)
Remove the gamepads a session tag kept between streams.
@ gamescope_session
Standalone Gamescope compositor (SteamOS Game Mode).
bool request_process_group_exit(std::uintptr_t native_handle)
Attempt to gracefully terminate a process group.
session_environment_t detect_session_environment()
Detect the current session/compositor environment.
std::filesystem::path appdata()
Performs migration if necessary, then returns the appdata directory.
Declarations for the configuration of Sunshine.
Declarations for cryptography functions.
Find the user's Steam client, native or Flatpak.
std::optional< client_t > find(const std::filesystem::path &proc, uid_t uid, const std::filesystem::path &pid_file, std::string_view own_cgroup)
The user's running Steam client.
Run an app's detached commands in transient systemd scopes.
std::string unit_name(long hermes_pid, unsigned launch, std::size_t index)
std::string wrap(const std::string &systemd_run, const std::string &unit, std::chrono::seconds stop_timeout, const std::string &command)
void revert_configuration()
Revert the display configuration and restore the previous state.
void configure_display(const config::video_t &video_config, const rtsp_stream::launch_session_t &session)
Configure the display device based on the user configuration and the session information.
bool reset_persistence()
Reset the persistence and currently held initial display state.
Declarations for display device handling.
Declarations for file handling functions.
Environment that caps an application's frame rate at the stream's.
std::vector< std::pair< std::string, std::string > > environment(int fps, std::string_view existing_mangohud_config)
The Gamescope command line an isolated application session runs.
@ none
No option: the build scans out on the device it renders with.
bool steam_mode_for(std::string_view mode, std::string_view command)
std::optional< drm_selector_e > drm_selector_from_help(std::string_view help)
bool is_primary_card_path(std::string_view path)
std::string launch_command(const launch_t &launch)
std::optional< drm_selector_e > drm_selector_from_override(std::string_view value)
Declarations for common HTTP.
Declarations for logging related functions.
int version()
Print the version to stdout, then exit.
int help(const char *name)
Print help to stdout, then exit.
std::string read_file(const char *path)
Read a file to string.
int write_file(const char *path, const std::string_view &contents)
Writes a file.
void update_tray_playing(std::string app_name)
Sets the tray icon in playing mode and spawns the appropriate notification.
void update_tray_pausing(std::string app_name)
Sets the tray icon in pausing mode (stream stopped but app running) and spawns the appropriate notifi...
void update_tray_stopped(std::string app_name)
Sets the tray icon in stopped mode (app and stream stopped) and spawns the appropriate notification.
@ existing
Someone else's rule already forwards to the requested destination.
bool render_node_can_allocate(const char *node)
Whether GBM can actually allocate a buffer on this render node.
int command(const char *name, int argc, char *argv[])
hermes --prelogin status|enable|disable.
@ missing
Known to be absent; fix says what to do.
session_route_e resolve_session_route(const ctx_t &app, bool isolated_sessions_enabled, bool virtual_display_requested, std::string_view global_method)
void migrate_apps(nlohmann::json *fileTree_p, nlohmann::json *inputTree_p)
Migrate the applications stored in the file tree by merging in a new app.
std::string_view describe(virtual_display_source_e source)
bool launch_requests_virtual_display(const ctx_t &app, const rtsp_stream::launch_session_t &launch_session, bool headless_mode)
void migration_v7(nlohmann::json &fileTree)
void terminate_process_group(boost::process::v1::child &proc, boost::process::v1::group &group, std::chrono::seconds exit_timeout)
Terminates all child processes in a process group.
std::unique_ptr< platf::deinit_t > init()
Initialize proc functions.
virtual_display_decision_t decide_virtual_display(const ctx_t &app, const rtsp_stream::launch_session_t &launch_session, bool headless_mode)
void migration_v3(nlohmann::json &fileTree)
std::tuple< std::string, std::string > calculate_app_id(const std::string &app_name, std::string app_image_path, int index)
Calculate a stable id based on name and image data.
std::optional< proc::proc_t > parse(const std::string &file_name, bool fallback_on_failure)
Load the applications from apps.json.
void migration_v5(nlohmann::json &fileTree)
void migration_v6(nlohmann::json &fileTree)
void initVDisplayDriver()
Initialize the virtual display driver. This should be called early in startup to enable virtual displ...
scale_factor_decision_t decide_scale_factor(const ctx_t &app, const rtsp_stream::launch_session_t &launch_session, int host_default)
Declarations for the startup and shutdown of the apps started by a streaming Session.
@ app_forced
The app forces its scale on every client.
@ client
The client sent a scale.
@ host_default
Neither did; the host's default_scale_factor.
@ app
The client sent none; the app's own scale.
@ app_forced
The app forces its setting on every client.
@ client
The client chose (Hestia's session/prepare).
@ headless
The host runs headless; there is nothing else to stream.
@ default_rule
No explicit choice: client request, per-client or app setting.
Non-destructive process-group liveness checks and bounded cleanup helpers.
bool wait_for_exit(Running running, std::chrono::steady_clock::duration timeout)
int session_count()
Get the number of active sessions.
An isolated session's own PipeWire server.
std::optional< std::string > start(const std::string &client_uuid, const std::vector< std::string > &arguments, const std::vector< std::string > &environment, const std::string &scope)
Start arguments as the client's account, and return the unit name.
std::optional< account_t > ensure(const std::string &client_uuid)
The client's account, created if this is the first time it asked.
bool available()
Whether a broker socket is there to talk to.
std::optional< bool > query_active(const std::string &client_uuid)
Query liveness without treating communication failure as session exit.
bool stop(const std::string &client_uuid)
Stop the client's session unit. Stopping one that is already gone succeeds, so this is safe to call o...
std::optional< std::string > wayland_socket(const std::string &client_uuid)
The name of the Wayland socket the session's compositor created.
Ask the privileged broker for a client's own Unix account, and for a session running under it.
A D-Bus session bus for an isolated session of the Hermes user.
std::optional< std::string > with_private_bus(std::string_view command, bool has_bus, std::string_view dbus_run_session)
The command that starts an isolated session with a session bus of its own.
std::unique_ptr< mirror_t > mirror(pid_t pid, const std::string &seat, bool hide_hid_gamepads)
Mirror into the /dev of pid's mount namespace; nullptr on failure.
bool available()
Whether Hermes holds what isolation needs: CAP_SYS_ADMIN and CAP_MKNOD.
What an isolated session sees of the host's /dev.
bool sound
No /dev/snd; the session's audio server is its only way to sound.
One live isolated session, as the host needs to see it.
std::string unit
The systemd unit, where the session has one.
std::string profile
"desktop" or "application".
bool running
False for one whose compositor has died but was not reaped.
std::string account_user
Empty where the session runs as the Hermes user.
std::string audio_sink
Empty where the session shares the host's audio.
std::optional< int > client_scale_factor
std::optional< bool > client_virtual_display
Declarations for the system tray icon and notification system.
Declarations for utility functions.
Declarations for UUID generation.
bool display_present()
Whether the host has a display to capture without creating one.
int probe_encoders()
Probe encoders and select the preferred encoder. This is called once at startup and each time a strea...
int probe_encoders_without_display()
Probe encoders without opening any screen.
bool unlockHostSessionIfLocked()
Unlock the active graphical login session for the Hermes user when locked.
bool setDisplayHDRByName(const char *displayName, bool enableAdvancedColor)
Set the HDR status of a display by name.
int changeDisplaySettings(const char *deviceName, int width, int height, int refresh_rate, int deadline_ms)
Change the display settings of a virtual display.
std::string createVirtualDisplay(const char *s_client_uid, const char *s_client_name, uint32_t width, uint32_t height, uint32_t fps, const uuid_util::uuid_t &guid, std::optional< uid_t > session_owner_uid, virtual_display_layout_e layout, bool isolated_session)
Create a virtual display.
bool startPingThread(std::function< void()> failCb)
Start a ping thread to keep the virtual display alive.
int hermesKmsOpenCapture(const std::string &display_name)
std::string getHermesKmsDevicePath(const std::string &displayName)
DRIVER_STATUS openVDisplayDevice()
Initialize the virtual display driver.
void placeWindowsOnVirtualDisplay(const std::string &displayName, const std::vector< std::string > &windowClasses, const std::vector< std::uint32_t > &gamescopePids)
bool configureVirtualDisplayHdr(const std::string &displayName, bool hdr)
std::string getHermesKmsConnectorName(const std::string &displayName)
bool setRenderAdapterByName(const std::string &adapterName)
Set the render adapter by name.
bool hermesKmsCaptureSize(int render_fd, int &width, int &height, uint32_t timeout_ms)
bool removeVirtualDisplay(const uuid_util::uuid_t &guid)
Remove a virtual display.
void beginPhysicalOutputSession()
int changeDisplaySettings2(const char *deviceName, int width, int height, int refresh_rate, bool bApplyIsolated)
Change the display settings with isolated display option.
bool isHermesKmsDisplay(const std::string &displayName)
void closeVDisplayDevice()
Close the virtual display driver.
bool activateVirtualDisplayOutput(const std::string &displayName)
bool enableExclusiveVirtualDisplay(const std::string &displayName)
bool wakeSleepingMonitor()
Wake a monitor the compositor has put to sleep.
std::string getHermesKmsSeatName(const std::string &displayName)
Virtual display declarations for Linux.
@ virtual_display
Create a virtual display and have it composited onto.
virtual_display_layout_e
Where the host compositor places a newly created virtual output.
@ mirror
Overlapped with the primary output, so the desktop is cloned.
DRIVER_STATUS
Status of the virtual display driver.
@ WATCHDOG_FAILED
Driver watchdog failed.
@ OK
Driver is operational.
Declarations for Wayland capture.
Identify supported launch commands and build scoped KWin placement scripts.
bool gamescope_runs_steam(const std::vector< std::string > &arguments)
bool launches_steam(const std::vector< std::string > &arguments)