Hermes 0.7.0
Linux game streaming host
Loading...
Searching...
No Matches
process.cpp
Go to the documentation of this file.
1
5#define BOOST_BIND_GLOBAL_PLACEHOLDERS
6
7#ifndef BOOST_PROCESS_VERSION
8 #define BOOST_PROCESS_VERSION 1
9#endif
10// standard includes
11#include <algorithm>
12#include <array>
13#include <atomic>
14#include <csignal>
15#include <cstdio>
16#include <cctype>
17#include <cstdlib>
18#include <chrono>
19#include <cstring>
20#include <filesystem>
21#include <fstream>
22#include <map>
23#include <mutex>
24#include <optional>
25#include <sstream>
26#include <string>
27#include <string_view>
28#include <thread>
29#include <unordered_map>
30#include <utility>
31#include <vector>
32
33 #include <fcntl.h>
34 #include <poll.h>
35 #include <signal.h>
36 #include <spawn.h>
37 #include <sys/wait.h>
38 #include <unistd.h>
39 #include <xf86drm.h>
40
45 // For the GBM allocation probe: picking the render node an isolated session
46 // renders on is the same question the capture path answers, so it uses the
47 // same answer rather than a second heuristic. Compiles to "yes" where Wayland
48 // is not built, which leaves the search as it was.
50
51// lib includes
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>
61
62// local includes
63#include "config.h"
64#include "crypto.h"
65#include "display_device.h"
66#include "file_handler.h"
67#include "logging.h"
68#include "platform/common.h"
69#include "process.h"
70#include "frame_limit_env.h"
71#include "httpcommon.h"
72#include "system_tray.h"
73#include "utility.h"
74#include "audio.h"
75#include "video.h"
76#include "uuid.h"
77
85 #include <sys/stat.h>
86 #include <unistd.h>
87
88#define DEFAULT_APP_IMAGE_PATH HERMES_ASSETS_DIR "/box.png"
89
90namespace proc {
91 using namespace std::literals;
92 namespace pt = boost::property_tree;
93
94 proc_t proc;
95
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;
100
101 VDISPLAY::DRIVER_STATUS vDisplayDriverStatus = VDISPLAY::DRIVER_STATUS::UNKNOWN;
102
103 static void finish_undo_command(
104 boost::process::v1::child &child,
105 boost::process::v1::group &group,
106 std::chrono::seconds exit_timeout
107 );
108
110 const ctx_t &app,
111 const rtsp_stream::launch_session_t &launch_session,
112 bool headless_mode
113 ) {
114 if (headless_mode) {
116 }
117 if (app.force_virtual_display) {
118 return {app.virtual_display, virtual_display_source_e::app_forced};
119 }
120 if (launch_session.client_virtual_display) {
122 }
123 return {launch_session.virtual_display || app.virtual_display, virtual_display_source_e::default_rule};
124 }
125
126 std::string_view describe(virtual_display_source_e source) {
127 switch (source) {
129 return "the host runs headless";
131 return "forced by the app";
133 return "the client's choice";
135 break;
136 }
137 return "the client's request or the app's default";
138 }
139
141 const ctx_t &app,
142 const rtsp_stream::launch_session_t &launch_session,
143 bool headless_mode
144 ) {
145 return decide_virtual_display(app, launch_session, headless_mode).use;
146 }
147
149 const ctx_t &app,
150 const rtsp_stream::launch_session_t &launch_session,
151 int host_default
152 ) {
153 if (app.force_scale_factor) {
154 return {app.scale_factor, scale_factor_source_e::app_forced};
155 }
156 if (launch_session.client_scale_factor) {
157 return {*launch_session.client_scale_factor, scale_factor_source_e::client};
158 }
159 if (app.scale_factor != 100) {
160 return {app.scale_factor, scale_factor_source_e::app};
161 }
163 }
164
165 std::string_view describe(scale_factor_source_e source) {
166 switch (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:
174 break;
175 }
176 return "the host default";
177 }
178
180 const ctx_t &app,
181 bool isolated_sessions_enabled,
182 bool virtual_display_requested,
183 std::string_view global_method
184 ) {
185 if (!isolated_sessions_enabled || app.host_session) {
186 return session_route_e::shared;
187 }
188
189 if (app.isolation_method == "kwin_virtual") {
190 return session_route_e::isolated_desktop;
191 }
192
193 if (app.isolation_method == "gamescope") {
194 return session_route_e::isolated_application;
195 }
196
197 if (!virtual_display_requested) {
198 return session_route_e::shared;
199 }
200
201 const auto &layout = app.virtual_display_layout;
202 if (layout == "extend" || layout == "primary" || layout == "mirror" || layout == "exclusive") {
203 return session_route_e::shared;
204 }
205
206 // Gamescope needs a command to run; without one, the only thing to show is a desktop.
207 return global_method == "kwin_virtual" || app.cmd.empty() ?
208 session_route_e::isolated_desktop :
209 session_route_e::isolated_application;
210 }
211
212 namespace {
213 VDISPLAY::virtual_display_layout_e linux_virtual_display_layout(const std::string &layout) {
214 if (layout == "mirror") {
216 }
217 if (layout == "detached") {
218 return VDISPLAY::virtual_display_layout_e::detached;
219 }
220 if (layout == "primary") {
221 return VDISPLAY::virtual_display_layout_e::primary;
222 }
223 return VDISPLAY::virtual_display_layout_e::extend;
224 }
225
226 struct isolated_runtime_t {
227 uint32_t launch_session_id {};
228 std::string client_uuid;
229 std::string client_name;
230 ctx_t app;
231 std::string profile;
232 std::string runtime_id;
233 std::string seat_id;
234 std::string seatd_socket;
235 std::string runtime_dir;
236 // Where Hermes writes what the session only reads - a generated
237 // compositor config, chiefly. It is the same directory as runtime_dir
238 // until the session gets a uid of its own, at which point the two have to
239 // part: runtime_dir becomes the session's, which Hermes cannot write, and
240 // this stays Hermes', which the session cannot write.
241 std::string assets_dir;
242 std::optional<platf::session_broker::account_t> account;
243 std::string unit;
244 // A detached desktop runs as the user's own transient systemd unit, and
245 // Hermes reaches it only through these two explicit sockets.
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;
267 file_t pipe;
268 size_t prep_completed {};
269 std::atomic_bool stopping {false};
270 };
271
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;
276
277 // NOTE: the isolated-session command below is handed to run_command(),
278 // which passes the string straight to boost::process. That splits on
279 // whitespace and never interprets shell syntax, so quoting an argument
280 // only buries the quotes in argv. Every value interpolated there is a
281 // generated identifier (a card basename, a seat id, a Wayland socket
282 // name) or a path under XDG_RUNTIME_DIR, none of which carry whitespace.
283
284 std::string host_runtime_dir() {
285 if (const char *dir = std::getenv("XDG_RUNTIME_DIR"); dir && *dir) {
286 return dir;
287 }
288 return {};
289 }
290
291 std::string x_lock_path(int display) {
292 return "/tmp/.X" + std::to_string(display) + "-lock";
293 }
294
295 // Takes a display's lock as Xorg and wlroots do; a lock whose pid is gone is stale.
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());
302 ::close(fd);
303 if (!written) {
304 ::unlink(path.c_str());
305 }
306 return written;
307 }
308 std::ifstream lock {path};
309 long owner = 0;
310 if (!(lock >> owner) || owner <= 0 || ::kill(static_cast<pid_t>(owner), 0) == 0 || errno != ESRCH) {
311 return false;
312 }
313 ::unlink(path.c_str());
314 }
315 return false;
316 }
317
318 // Steam in gamescope's Steam mode sends games to its own DISPLAY plus one,
319 // but wlroots gives each Xwayland the lowest free display. An X server in
320 // between (desktop Xorg restarted on :1) puts the games on it. Hold every
321 // free display below the first `count` adjacent free ones; returns those held.
322 std::vector<int> hold_x_display_gaps(int count) {
323 std::vector<int> taken;
324 for (int display = 0; display <= 32; ++display) {
325 if (!take_x_display(display)) {
326 continue;
327 }
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());
332 taken.pop_back();
333 }
334 return taken;
335 }
336 }
337 for (const int display : taken) {
338 ::unlink(x_lock_path(display).c_str());
339 }
340 return {};
341 }
342
343 // Discord listens on discord-ipc-N in the host's runtime directory, which a
344 // session's XDG_RUNTIME_DIR replaces; link them so Rich Presence still works.
345 void link_host_discord_ipc(const std::string &runtime_dir) {
346 const auto host_runtime = host_runtime_dir();
347 if (host_runtime.empty()) {
348 return;
349 }
350 for (int i = 0; i < 10; ++i) {
351 const auto name = "discord-ipc-" + std::to_string(i);
352 std::error_code ec;
353 std::filesystem::create_symlink(std::filesystem::path {host_runtime} / name,
354 std::filesystem::path {runtime_dir} / name, ec);
355 }
356 }
357
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()) {
365 return options;
366 }
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).";
370 return std::nullopt;
371 }
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 {};
375 }
376
377 bool runs_steam(const ctx_t &app) {
378 // The same test Steam mode's auto uses, so the two never disagree.
379 return platf::gamescope::steam_mode_for("auto", app.cmd);
380 }
381
390 bool session_runs_steam(const ctx_t &app) {
391 const auto starts_steam = [](const std::string &command) {
392 try {
393 return platf::window_placement::launches_steam(boost::program_options::split_unix(command));
394 } catch (const std::exception &) {
395 return false;
396 }
397 };
398 return runs_steam(app) || starts_steam(app.cmd) || std::ranges::any_of(app.detached, starts_steam);
399 }
400
401 std::string read_proc_line(pid_t pid, const char *file) {
402 std::ifstream stream {"/proc/" + std::to_string(pid) + "/" + file};
403 std::string line;
404 std::getline(stream, line);
405 return line;
406 }
407
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"));
411 }
412
423 std::optional<platf::desktop_steam::client_t> stop_desktop_steam(std::string_view tag = "[IsolatedSession]") {
424 const auto client = find_desktop_steam();
425 if (!client) {
426 return std::nullopt;
427 }
428 const pid_t pid = client->pid;
429
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);
435 }
436 if (!std::filesystem::exists("/proc/" + std::to_string(pid))) {
437 BOOST_LOG(info) << tag << " The desktop's Steam has exited.";
438 return client;
439 }
440
441 // Not graceful: no log-off, unsaved config and cloud sync are lost.
442 BOOST_LOG(warning) << tag << " The desktop's Steam ignored SIGTERM for 30 s; killing it.";
443 std::vector<pid_t> tree {pid};
444 std::error_code ec;
445 for (bool grew = true; grew;) {
446 grew = false;
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]))) {
450 continue;
451 }
452 const pid_t child = std::stoi(name);
453 const auto stat = read_proc_line(child, "stat");
454 const auto end = stat.rfind(')');
455 pid_t parent = 0;
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);
459 grew = true;
460 }
461 }
462 }
463 for (const auto member : tree) {
464 ::kill(member, SIGKILL);
465 }
466 return client;
467 }
468
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();
473 }
474 return (std::filesystem::path {"/tmp"} /
475 ("hermes-" + std::to_string(static_cast<unsigned long>(::getuid()))) /
476 "sessions").string();
477 }
478
479 std::string card_basename(const std::string &device_path) {
480 return std::filesystem::path {device_path}.filename().string();
481 }
482
493 std::vector<std::string> split_command(const std::string &command) {
494 std::vector<std::string> arguments;
495 std::istringstream stream {command};
496 std::string word;
497 while (stream >> word) {
498 arguments.emplace_back(word);
499 }
500 return arguments;
501 }
502
518 struct compositor_profile_t {
519 std::string name;
520 std::string required_binary;
521 std::string command;
522 std::vector<std::pair<std::string, std::string>> env;
523 // Some compositors take settings only through a config file. The
524 // template is read from beside the profile and written, expanded, into
525 // the session's own runtime directory.
526 std::string config_template;
527 std::string config_target;
528 std::filesystem::path profile_dir;
529 // Compositors that take a socket name are told one; the rest pick their
530 // own and are discovered afterwards.
531 bool discover_socket = false;
532 };
533
538 std::vector<std::filesystem::path> compositor_profile_paths(const std::string &name) {
539 const auto file = name + ".conf";
540 return {
541 std::filesystem::path {platf::appdata()} / "session-compositors" / file,
542 std::filesystem::path {HERMES_ASSETS_DIR} / "session-compositors" / file,
543 };
544 }
545
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};
549 std::string entry;
550 while (std::getline(stream, entry, ',')) {
551 const auto begin = entry.find_first_not_of(" \t");
552 if (begin == std::string::npos) {
553 continue;
554 }
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) {
559 continue;
560 }
561 env.emplace_back(entry.substr(0, split), entry.substr(split + 1));
562 }
563 return env;
564 }
565
566 std::optional<compositor_profile_t> read_compositor_profile(
567 const std::filesystem::path &path,
568 const std::string &name
569 ) {
570 {
571 const auto vars = config::parse_config(file_handler::read_file(path.string().c_str()));
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;
575 };
576
577 compositor_profile_t profile;
578 profile.name = name;
579 profile.command = value("command");
580 if (profile.command.empty()) {
581 BOOST_LOG(error) << "[IsolatedSession] Session compositor profile " << path
582 << " has no command.";
583 return std::nullopt;
584 }
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.";
594 return std::nullopt;
595 }
596
597 BOOST_LOG(debug) << "[IsolatedSession] Loaded session compositor profile " << path;
598 return profile;
599 }
600 }
601
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;
605 return std::nullopt;
606 }
607
608 for (const auto &path : compositor_profile_paths(name)) {
609 std::error_code ec;
610 if (!std::filesystem::is_regular_file(path, ec)) {
611 continue;
612 }
613 return read_compositor_profile(path, name);
614 }
615
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")
619 << '.';
620 return std::nullopt;
621 }
622
631 std::string expand_profile_template(
632 std::string text,
633 const std::vector<std::pair<std::string, std::string>> &values
634 ) {
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);
639 }
640 }
641 return text;
642 }
643
665 std::string real_render_node_path() {
666 const auto usable = [](const std::string &path) {
667 return wl::render_node_can_allocate(path.c_str());
668 };
669
670 if (!config::video.adapter_name.empty()) {
671 const auto &node = config::video.adapter_name;
672 if (usable(node)) {
673 return node;
674 }
675 BOOST_LOG(warning) << "[IsolatedSession] adapter_name " << node
676 << " cannot allocate buffers; searching the other render nodes.";
677 }
678
679 std::error_code ec;
680 std::filesystem::directory_iterator dir {"/dev/dri", ec};
681 if (ec) {
682 return {};
683 }
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")) {
688 continue;
689 }
690 const int fd = ::open(entry.path().c_str(), O_RDWR | O_CLOEXEC);
691 if (fd < 0) {
692 continue;
693 }
694 drmVersionPtr version = drmGetVersion(fd);
695 const bool candidate = version && version->name &&
696 std::string_view {version->name} != "hermes-kms";
697 if (version) {
698 drmFreeVersion(version);
699 }
700 ::close(fd);
701 if (candidate) {
702 nodes.emplace_back(entry.path().string());
703 }
704 }
705 std::sort(nodes.begin(), nodes.end());
706
707 for (const auto &node : nodes) {
708 if (usable(node)) {
709 return node;
710 }
711 }
712
713 // Nothing proved itself. The first candidate is still a better answer
714 // than none - it is what this returned before there was a probe, and a
715 // session that fails loudly on it beats one that never starts - but say
716 // so, because this is the shape the black-screen failure takes.
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();
722 }
723 return {};
724 }
725
726 std::string discover_wayland_socket(const std::string &runtime_dir) {
727 std::error_code ec;
728 std::vector<std::string> candidates;
729 for (std::filesystem::directory_iterator it {runtime_dir, ec}, end;
730 !ec && it != end;
731 it.increment(ec)) {
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);
736 }
737 }
738 std::sort(candidates.begin(), candidates.end());
739 return candidates.empty() ? std::string {} : candidates.front();
740 }
741
749 std::optional<std::string> gamescope_help_text(const std::string &binary) {
750 int pipe_fds[2];
751 if (::pipe2(pipe_fds, O_CLOEXEC) != 0) {
752 return std::nullopt;
753 }
754
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};
763 pid_t pid = -1;
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);
771 return std::nullopt;
772 }
773
774 // Usage text is a few kilobytes; anything far past that is not it.
775 constexpr std::size_t output_limit = 1 << 20;
776 const auto deadline = std::chrono::steady_clock::now() + 3s;
777 std::string output;
778 bool complete = false;
779 for (;;) {
780 const auto remaining = std::chrono::duration_cast<std::chrono::milliseconds>(
781 deadline - std::chrono::steady_clock::now()
782 );
783 if (remaining <= 0ms) {
784 break;
785 }
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) {
789 continue;
790 }
791 if (ready <= 0) {
792 break;
793 }
794 char buffer[4096];
795 const auto read_size = ::read(pipe_fds[0], buffer, sizeof(buffer));
796 if (read_size < 0 && errno == EINTR) {
797 continue;
798 }
799 if (read_size <= 0) {
800 complete = read_size == 0;
801 break;
802 }
803 output.append(buffer, static_cast<std::size_t>(read_size));
804 if (output.size() > output_limit) {
805 break;
806 }
807 }
808 ::close(pipe_fds[0]);
809 if (!complete) {
810 ::kill(pid, SIGKILL);
811 }
812 int status = 0;
813 while (::waitpid(pid, &status, 0) < 0 && errno == EINTR) {
814 }
815 if (!complete) {
816 BOOST_LOG(warning) << "[IsolatedSession] " << binary << " --help did not finish in time.";
817 return std::nullopt;
818 }
819 return output;
820 }
821
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;
833
834 std::error_code mtime_ec;
835 const auto mtime = std::filesystem::last_write_time(binary, mtime_ec);
836
837 std::lock_guard<std::mutex> lock(probe_mutex);
838 if (!mtime_ec && binary == probed_binary && mtime == probed_mtime) {
839 return probed_selector;
840 }
841
842 const auto help = gamescope_help_text(binary);
843 if (!help) {
844 // Not remembered: a probe that could not run says nothing about the
845 // build, and the next launch should ask again.
846 return std::nullopt;
847 }
848 const auto selector = platf::gamescope::drm_selector_from_help(*help);
849 if (!mtime_ec) {
850 probed_binary = binary;
851 probed_mtime = mtime;
852 probed_selector = selector;
853 }
854 return selector;
855 }
856
867 struct gamescope_install_t {
868 std::string binary;
869 std::string prefix;
870 };
871
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 {};
876 };
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;
881 };
882
883 if (const char *forced = std::getenv("HERMES_GAMESCOPE"); forced && *forced) {
884 if (usable(forced)) {
885 return {forced, prefix_of(forced)};
886 }
887 BOOST_LOG(warning) << "[IsolatedSession] Ignoring HERMES_GAMESCOPE=" << forced
888 << ": not an executable path without spaces.";
889 }
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};
894 }
895 }
896 const auto found = boost::process::v1::search_path("gamescope").string();
897 return {usable(found) ? found : std::string {}, {}};
898 }
899
909 bool launch_into_session(
910 const std::shared_ptr<isolated_runtime_t> &runtime,
911 const ctx_t &app,
912 const std::string &command,
913 const std::string &scope,
914 std::error_code &ec
915 ) {
916 if (runtime->account) {
917 const auto arguments = split_command(command);
918 if (arguments.empty()) {
919 return false;
920 }
921 std::vector<std::string> environment;
922 for (const auto &entry : runtime->env) {
923 environment.emplace_back(entry.get_name() + "=" + entry.to_string());
924 }
926 runtime->client_uuid,
927 arguments,
928 environment,
929 scope
930 )
931 .has_value();
932 }
933
934 auto working_dir = app.working_dir.empty() ?
935 find_working_directory(command, runtime->env) :
936 boost::filesystem::path {app.working_dir};
937 const auto join = runtime->namespace_pid ? platf::session_devices::plan_t::join(runtime->namespace_pid) : nullptr;
938 auto child = platf::session_devices::run_command(
939 join.get(),
940 command,
941 working_dir,
942 runtime->env,
943 runtime->pipe.get(),
944 ec,
945 &runtime->process_group
946 );
947 if (ec) {
948 return false;
949 }
950 child.detach();
951 return true;
952 }
953
954 std::string choose_isolated_profile(const ctx_t &app) {
955 const auto route = resolve_session_route(app, true, true, config::video.isolation_method);
956 return route == session_route_e::isolated_desktop ? "desktop" : "application";
957 }
958
976 void erase_host_session_environment(boost::process::v1::environment &env) {
977 for (const auto *name : {
978 // The host's session bus, and the two variables that would let a
979 // client find it again after the first is gone.
980 "DBUS_SESSION_BUS_ADDRESS", "DBUS_SESSION_BUS_PID",
981 "DBUS_STARTER_ADDRESS", "DBUS_STARTER_BUS_TYPE",
982 // The host's audio server.
983 "PULSE_SERVER", "PULSE_COOKIE", "PIPEWIRE_REMOTE",
984 // Who the process is, and where its files are.
985 "HOME", "USER", "LOGNAME", "SHELL", "XDG_RUNTIME_DIR",
986 "XDG_CACHE_HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_STATE_HOME",
987 // Credentials the host user holds and the session has no claim to.
988 "SSH_AUTH_SOCK", "GPG_AGENT_INFO", "XAUTHORITY",
989 // Leftovers that make a desktop believe it is already inside one.
990 "XDG_SESSION_ID", "XDG_SESSION_DESKTOP", "DESKTOP_SESSION",
991 "KDE_FULL_SESSION", "KDE_SESSION_UID", "KDE_SESSION_VERSION",
992 "GNOME_DESKTOP_SESSION_ID",
993 }) {
994 env.erase(name);
995 }
996 }
997
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",
1004 "WAYLAND_DISPLAY",
1005 "WAYLAND_SOCKET",
1006 "_WAYLAND_DISPLAY",
1007 "DISPLAY",
1008 "XAUTHORITY",
1009 "XDG_SESSION_ID",
1010 "XDG_SESSION_DESKTOP",
1011 "DESKTOP_SESSION",
1012 "KDE_FULL_SESSION",
1013 "KDE_SESSION_UID",
1014 "KDE_SESSION_VERSION",
1015 "GNOME_DESKTOP_SESSION_ID",
1016 }) {
1017 env.erase(name);
1018 }
1019 }
1020
1021 void populate_session_environment(
1022 boost::process::v1::environment &env,
1023 const ctx_t &app,
1024 const rtsp_stream::launch_session_t &session,
1025 const isolated_runtime_t &runtime
1026 ) {
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);
1032
1033 if (runtime.account) {
1034 // The broker sets XDG_RUNTIME_DIR to the one systemd made for that uid,
1035 // and setting it here would only be a chance to disagree with it.
1036 erase_host_session_environment(env);
1037 } else {
1038 erase_host_graphical_session_environment(env);
1039 env["XDG_RUNTIME_DIR"] = runtime.runtime_dir;
1040 // That is also how a PulseAudio or PipeWire client finds its server.
1041 // The session's own lives there; named explicitly all the same, so
1042 // nothing (an X11 root window property, client.conf) overrides it.
1043 // Without one, the session would fail to connect to audio at all, so
1044 // it is pointed at the host's server and plays into its session sink.
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");
1052 } else {
1053 env["PULSE_SOURCE"] = runtime.mic_source;
1054 }
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";
1058 }
1059 }
1060
1061 // Everything this session plays goes to the sink made for it, so it
1062 // reaches the client it belongs to and nobody else's stream. Without this
1063 // the session would play to whichever sink the machine currently defaults
1064 // to, which is the host's - audible on the host's speakers and captured
1065 // by whichever stream moved that default.
1066 if (!runtime.audio_sink.empty() && !runtime.audio_server) {
1067 env["PULSE_SINK"] = runtime.audio_sink;
1068 }
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;
1077 // The seat's input devices appear once the client streams.
1078 env["WLR_LIBINPUT_NO_DEVICES"] = "1";
1079
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)) :
1086 fps_buffer;
1087 env["SUNSHINE_CLIENT_HDR"] = session.enable_hdr ? "true" : "false";
1088
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;
1100
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 {})) {
1117 env[name] = value;
1118 }
1119 }
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;
1126
1127 if (!session.enable_hdr) {
1128 env["DXVK_HDR"] = "0";
1129 env["PROTON_ENABLE_HDR"] = "0";
1130 }
1131 }
1132
1137 int run_program(const std::vector<std::string> &arguments, std::chrono::seconds timeout) {
1138 if (arguments.empty() || !arguments.front().starts_with('/')) {
1139 return -1;
1140 }
1141 std::vector<char *> argv;
1142 for (const auto &argument : arguments) {
1143 argv.push_back(const_cast<char *>(argument.c_str()));
1144 }
1145 argv.push_back(nullptr);
1146 const pid_t pid = ::fork();
1147 if (pid < 0) {
1148 return -1;
1149 }
1150 if (pid == 0) {
1151 ::execv(argv.front(), argv.data());
1152 ::_exit(127);
1153 }
1154 const auto deadline = std::chrono::steady_clock::now() + timeout;
1155 int status = 0;
1156 for (;;) {
1157 const pid_t waited = ::waitpid(pid, &status, WNOHANG);
1158 if (waited == pid) {
1159 return WIFEXITED(status) ? WEXITSTATUS(status) : -1;
1160 }
1161 if (waited < 0 && errno != EINTR) {
1162 return -1;
1163 }
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.";
1168 return -1;
1169 }
1170 std::this_thread::sleep_for(20ms);
1171 }
1172 }
1173
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();
1177 }
1178
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.";
1198 return;
1199 }
1200 std::thread {[systemd_run, steam, flatpak, environment = std::move(environment)]() {
1201 const auto steam_running = []() {
1202 return find_desktop_steam().has_value();
1203 };
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);
1207 }
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.";
1211 return;
1212 }
1213
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())
1217 .count());
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);
1221 }
1222 arguments.push_back("--");
1223 arguments.push_back(steam);
1224 if (flatpak) {
1225 arguments.insert(arguments.end(), {"run", std::string {platf::desktop_steam::flatpak_id}});
1226 }
1227 arguments.push_back("-silent");
1228 if (run_program(arguments, 30s) == 0) {
1229 BOOST_LOG(info) << "[Gamescope] Started the desktop's Steam again (" << unit << ").";
1230 } else {
1231 BOOST_LOG(warning) << "[Gamescope] Could not start the desktop's Steam again.";
1232 }
1233 }}.detach();
1234 }
1235
1240 std::string find_detached_session_tool() {
1241 std::error_code ec;
1242 const auto self = std::filesystem::canonical("/proc/self/exe", ec);
1243 if (!ec) {
1244 const auto sibling = self.parent_path() / "hermes-detached-session";
1245 if (::access(sibling.c_str(), X_OK) == 0) {
1246 return sibling.string();
1247 }
1248 }
1249 return find_program("hermes-detached-session");
1250 }
1251
1252 std::string detached_unit_name(const std::string &runtime_id) {
1253 return "hermes-detached-" + runtime_id + ".scope";
1254 }
1255
1260 std::string own_service_unit() {
1261 std::ifstream cgroup {"/proc/self/cgroup"};
1262 std::string line;
1263 while (std::getline(cgroup, line)) {
1264 const auto slash = line.rfind('/');
1265 if (slash == std::string::npos) {
1266 continue;
1267 }
1268 const auto unit = line.substr(slash + 1);
1269 if (unit.ends_with(".service") && !unit.starts_with("user@")) {
1270 return unit;
1271 }
1272 }
1273 return {};
1274 }
1275
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);
1279 }
1280 }
1281
1282 // Isolated launches probe encoders while another may be doing the same;
1283 // one at a time, since a probe resets the chosen encoder while it runs.
1284 std::mutex encoder_probe_mutex;
1285
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')) {
1290 text.pop_back();
1291 }
1292 return text.size() > 512 ? text.substr(0, 512) : text;
1293 }
1294
1300 std::string detached_wayland_socket(const std::string &runtime_dir) {
1301 std::ifstream ready {std::filesystem::path {runtime_dir} / "ready"};
1302 std::string line;
1303 constexpr std::string_view key {"WAYLAND_DISPLAY="};
1304 while (std::getline(ready, line)) {
1305 if (!line.starts_with(key)) {
1306 continue;
1307 }
1308 const auto name = line.substr(key.size());
1309 if (name.empty() || name.find('/') != std::string::npos) {
1310 return {};
1311 }
1312 return (std::filesystem::path {runtime_dir} / name).string();
1313 }
1314 return {};
1315 }
1316
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()) {
1328 return false;
1329 }
1330 std::string request = app.working_dir;
1331 request += '\0';
1332 for (const auto &argument : arguments) {
1333 request += argument;
1334 request += '\0';
1335 }
1336
1337 const auto directory = std::filesystem::path {runtime.runtime_dir} / "launch";
1338 const auto path = directory / name;
1339 std::error_code ec;
1340 std::filesystem::create_directories(directory, ec);
1341 std::filesystem::remove(std::filesystem::path {path} += ".error", ec);
1342 {
1343 std::ofstream stream {std::filesystem::path {path} += ".tmp", std::ios::binary | std::ios::trunc};
1344 stream << request;
1345 if (!stream.flush()) {
1346 BOOST_LOG(error) << "[IsolatedSession] Could not ask detached desktop " << runtime.runtime_id << " to start [" << command << ']';
1347 return false;
1348 }
1349 }
1350 std::filesystem::rename(std::filesystem::path {path} += ".tmp", path, ec);
1351 if (ec) {
1352 BOOST_LOG(error) << "[IsolatedSession] Could not ask detached desktop " << runtime.runtime_id << " to start [" << command << "]: " << ec.message();
1353 return false;
1354 }
1355
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);
1360 }
1361 if (std::filesystem::exists(path, ec)) {
1362 BOOST_LOG(warning) << "[IsolatedSession] Detached desktop " << runtime.runtime_id << " has not picked up [" << command << "] yet.";
1363 return false;
1364 }
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;
1367 return false;
1368 }
1369 return true;
1370 }
1371
1376 bool detached_desktop_alive(const isolated_runtime_t &runtime) {
1377 std::error_code ec;
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");
1381 return false;
1382 }
1383 const auto socket = detached_wayland_socket(runtime.runtime_dir);
1384 if (socket.empty()) {
1385 // Not ready yet while it starts; gone once its supervisor has exited.
1386 return false;
1387 }
1388 // Never a blocking connect: this runs under the runtime registry lock,
1389 // and a compositor that stopped accepting would hold that lock forever
1390 // once its backlog filled. A full backlog still means it is there. A
1391 // compositor busy for a moment is not gone, and a false answer here
1392 // ends the desktop and everything in it, so it gets a few tries.
1393 for (int attempt = 0; attempt < 5; ++attempt) {
1394 if (attempt) {
1395 std::this_thread::sleep_for(100ms);
1396 }
1397 if (VDISPLAY::displayServerReachable(socket, {}, {})) {
1398 if (attempt) {
1399 BOOST_LOG(info) << "[IsolatedSession] Detached desktop " << runtime.runtime_id << " answered after "
1400 << attempt + 1 << " tries.";
1401 }
1402 return true;
1403 }
1404 }
1405 BOOST_LOG(info) << "[IsolatedSession] Detached desktop " << runtime.runtime_id << " does not answer on " << socket << ": "
1406 << std::strerror(errno);
1407 return false;
1408 }
1409
1410 bool isolated_runtime_running(const std::shared_ptr<isolated_runtime_t> &runtime) {
1411 if (!runtime || runtime->stopping.load()) {
1412 return false;
1413 }
1414 if (runtime->user_unit) {
1415 return detached_desktop_alive(*runtime);
1416 }
1417 // A session with an account of its own is a systemd unit rather than a
1418 // child of this process, so there is no handle here to ask and systemd is
1419 // the only thing that knows.
1420 if (!runtime->unit.empty()) {
1421 // A broker restart or slow account operation is not evidence that
1422 // this session exited. Tear down only after a confirmed inactive reply.
1423 const bool active = platf::session_broker::query_active(runtime->client_uuid).value_or(true);
1424 return active && !runtime->stopping.load();
1425 }
1426 std::lock_guard<std::mutex> lock(runtime->process_mutex);
1427 return !runtime->stopping.load() && runtime->process.valid() && runtime->process.running();
1428 }
1429
1430 void stop_isolated_runtime(const std::shared_ptr<isolated_runtime_t> &runtime) {
1431 if (!runtime || runtime->stopping.exchange(true)) {
1432 return;
1433 }
1434
1435 BOOST_LOG(info) << "[IsolatedSession] Stopping " << runtime->runtime_id
1436 << " for client " << runtime->client_name;
1437 if (runtime->user_unit) {
1438 // Mode changes finish before this generation's compositor is stopped.
1439 std::lock_guard<std::mutex> lock(runtime->process_mutex);
1440 // Stopping the unit takes everything the desktop started with it.
1441 if (!runtime->unit.empty()) {
1442 stop_user_unit(runtime->unit);
1443 runtime->unit.clear();
1444 }
1445 // The unit's first process is this one's child: reap it.
1446 if (runtime->process.valid()) {
1447 std::error_code wait_ec;
1448 if (runtime->process.running(wait_ec)) {
1449 runtime->process.terminate(wait_ec);
1450 }
1451 runtime->process.wait(wait_ec);
1452 runtime->process = boost::process::v1::child {};
1453 }
1454 } else if (!runtime->unit.empty()) {
1455 // Stopping the unit takes the whole session with it: systemd kills the
1456 // cgroup, so a game that outlived its compositor goes too, which a
1457 // process group could only manage for children that stayed in it.
1458 platf::session_broker::stop(runtime->client_uuid);
1459 // Keep published identity fields immutable for registry snapshots.
1460 } else {
1461 std::lock_guard<std::mutex> lock(runtime->process_mutex);
1463 runtime->process,
1464 runtime->process_group,
1465 runtime->app.exit_timeout
1466 );
1467 runtime->process = boost::process::v1::child {};
1468 runtime->process_group = boost::process::v1::group {};
1469 }
1470 auto stopping_env = runtime->env;
1471 stopping_env["APOLLO_APP_STATUS"] = "TERMINATING";
1472 stopping_env["HERMES_APP_STATUS"] = "TERMINATING";
1473
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()) {
1477 continue;
1478 }
1479 std::error_code ec;
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(
1486 cmd.elevated,
1487 true,
1488 cmd.undo_cmd,
1489 working_dir,
1490 stopping_env,
1491 runtime->pipe.get(),
1492 ec,
1493 &undo_group
1494 );
1495 if (!ec) {
1496 finish_undo_command(child, undo_group, runtime->app.exit_timeout);
1497 } else {
1498 BOOST_LOG(warning) << "[IsolatedSession] Undo command failed to start: " << ec.message();
1499 }
1500 }
1501
1502 if (runtime->audio_server) {
1503 runtime->audio_server.reset();
1504 } else if (!runtime->audio_sink.empty()) {
1505 audio::remove_session_sink(runtime->audio_sink);
1506 }
1507 if (runtime->user_unit && !runtime->seat_id.empty()) {
1508 // The desktop's gamepads, kept between its streams, go with it.
1509 platf::forget_kept_gamepads(runtime->seat_id);
1510 }
1511#ifdef HERMES_BUILD_KWIN_TRANSPORT
1512 if (runtime->user_unit && !runtime->kwin_wayland_socket.empty()) {
1513 // So do its pointer and keyboard.
1514 platf::forget_private_kwin_input(runtime->kwin_wayland_socket);
1515 }
1516#endif
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();
1523 }
1524 for (const int display : runtime->held_x_displays) {
1525 ::unlink(x_lock_path(display).c_str());
1526 }
1527 runtime->held_x_displays.clear();
1528
1529 runtime->pipe.reset();
1530 if (!runtime->display_name.empty()) {
1531 VDISPLAY::removeVirtualDisplay(runtime->display_guid);
1532 }
1533 // The assets directory, never runtime_dir: once the session has an
1534 // account those are different places, and runtime_dir is then the
1535 // session user's own /run/user, which belongs to systemd and not to us.
1536 std::error_code remove_ec;
1537 std::filesystem::remove_all(runtime->assets_dir, remove_ec);
1538 if (remove_ec) {
1539 BOOST_LOG(debug) << "[IsolatedSession] Could not remove runtime directory "
1540 << runtime->assets_dir << ": " << remove_ec.message();
1541 }
1542 }
1543
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) {
1547 return runtime;
1548 }
1549 }
1550 return {};
1551 }
1552 } // namespace
1553
1554 #ifdef HERMES_TESTS
1555 // Exercise the production registry/RPC lock ordering without a compositor,
1556 // display card or account manager. The test owns this synthetic entry.
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;
1567 }
1568
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);
1572 }
1573 #endif
1574
1575 void onVDisplayWatchdogFailed() {
1576 vDisplayDriverStatus = VDISPLAY::DRIVER_STATUS::WATCHDOG_FAILED;
1578 }
1579
1581 vDisplayDriverStatus = VDISPLAY::openVDisplayDevice();
1582 if (vDisplayDriverStatus == VDISPLAY::DRIVER_STATUS::OK) {
1583 if (!VDISPLAY::startPingThread(onVDisplayWatchdogFailed)) {
1584 onVDisplayWatchdogFailed();
1585 return;
1586 }
1587 }
1588 }
1589
1591 public:
1592 ~deinit_t() {
1593 proc.terminate_all_isolated();
1594 proc.terminate();
1595 // Join the watchdog thread before global destructors run, otherwise a
1596 // still-joinable std::thread aborts the process on exit.
1598 }
1599 };
1600
1601 std::unique_ptr<platf::deinit_t> init() {
1602 // Detached desktops are units of the user's manager, not children of this
1603 // process, so a Hermes that crashed or was killed leaves them running with
1604 // nothing to stream them. None of them can belong to this instance yet.
1605 if (const auto systemctl = find_program("systemctl"); !systemctl.empty()) {
1606 run_program({systemctl, "--user", "--quiet", "stop", "hermes-detached-*.scope", "hermes-detached-*.service"}, 30s);
1607 }
1608 return std::make_unique<deinit_t>();
1609 }
1610
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]() {
1615 // Reap our own terminated children while waiting; zombies alone must
1616 // not keep signal-0 liveness true until the entire grace period expires.
1617 platf::process_group::reap_children(handle);
1618 return platf::process_group_running(handle);
1619 };
1620 if (running()) {
1621 if (exit_timeout.count() > 0 && platf::request_process_group_exit(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);
1627 }
1628 if (running()) {
1629 BOOST_LOG(warning) << "App did not fully exit within the timeout. Terminating the app's remaining processes."sv;
1630 } else {
1631 BOOST_LOG(info) << "All app processes have successfully exited."sv;
1632 }
1633 } else {
1634 BOOST_LOG(info) << "Forcefully terminating the app's remaining processes."sv;
1635 }
1636
1637 std::error_code ec;
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();
1641 }
1642 // SIGKILL delivery is asynchronous. Give reaping a bounded window before
1643 // releasing process/pipe/display ownership and handing control to systemd.
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);
1647 }
1648 if (running()) {
1649 BOOST_LOG(warning) << "App process group [" << handle << "] still exists after forced termination.";
1650 }
1651 }
1652 // Also detach an already-exited group so resetting its Boost wrapper
1653 // cannot issue an implicit, unlogged kill later in cleanup.
1654 group.detach();
1655 }
1656
1657 if (proc.valid()) {
1658 proc.detach();
1659 }
1660 }
1661
1662 static void finish_undo_command(
1663 boost::process::v1::child &child,
1664 boost::process::v1::group &group,
1665 std::chrono::seconds exit_timeout
1666 ) {
1667 std::error_code ec;
1668 const bool finished = platf::process_group::wait_for_exit([&]() {
1669 return child.running(ec);
1670 }, std::max(10s, exit_timeout));
1671 if (!finished) {
1672 BOOST_LOG(warning) << "Undo command exceeded its cleanup deadline; terminating its process group.";
1673 terminate_process_group(child, group, 0s);
1674 return;
1675 }
1676 if (ec) {
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() << ']';
1680 }
1681 group.detach();
1682 child.detach();
1683 }
1684
1685 boost::filesystem::path find_working_directory(const std::string &cmd, const boost::process::v1::environment &env) {
1686 // Parse the raw command string into parts to get the actual command portion
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();
1691 }
1692
1693 BOOST_LOG(debug) << "Parsed target ["sv << parts.at(0) << "] from command ["sv << cmd << ']';
1694
1695 // If the target is a URL, don't parse any further here
1696 if (parts.at(0).find("://") != std::string::npos) {
1697 return boost::filesystem::path();
1698 }
1699
1700 // If the cmd path is not an absolute path, resolve it using our PATH variable
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();
1707 }
1708 }
1709
1710 BOOST_LOG(debug) << "Resolved target ["sv << parts.at(0) << "] to path ["sv << cmd_path << ']';
1711
1712 // Now that we have a complete path, we can just use parent_path()
1713 return cmd_path.parent_path();
1714 }
1715
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;
1722 placebo = true;
1723
1724#if defined HERMES_TRAY && HERMES_TRAY >= 1
1726#endif
1727 }
1728
1730 std::shared_ptr<rtsp_stream::launch_session_t> launch_session,
1731 bool apply_scale,
1732 const ctx_t *session_app,
1733 std::optional<uid_t> session_owner_uid,
1734 bool isolated_session
1735 ) {
1736 if (config::video.virtual_display_backend != "hermes_kms" ||
1737 (isolated_session ?
1738 !config::video.hermes_kms_isolated_sessions :
1739 !config::video.hermes_kms_multi_output)) {
1740 return 0;
1741 }
1742
1743 const auto &app = session_app ? *session_app : _app;
1744 if (apply_scale) {
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 =
1748 decide_scale_factor(app, *launch_session, config::video.default_scale_factor).percent;
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;
1752 }
1753 launch_session->width = render_width;
1754 launch_session->height = render_height;
1755 }
1756
1757 if (vDisplayDriverStatus != VDISPLAY::DRIVER_STATUS::OK) {
1759 }
1760 if (vDisplayDriverStatus != VDISPLAY::DRIVER_STATUS::OK) {
1761 BOOST_LOG(error) << "[VDISPLAY/Hermes-KMS] Cannot allocate a session output because the driver is unavailable.";
1762 return 503;
1763 }
1764
1765 std::string device_name;
1766 std::string device_uuid_str;
1767 uuid_util::uuid_t device_uuid;
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();
1777 } else {
1778 // Session-scoped outputs must remain distinct for simultaneous
1779 // clients, even when the app normally requests one shared identity.
1780 device_uuid = uuid_util::uuid_t::parse(launch_session->unique_id);
1781 device_uuid_str = device_uuid.string();
1782 }
1783 } else {
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);
1787 }
1788
1789 if (isolated_session) {
1790 // The display is a session resource. Mix in the launch ID so a stale
1791 // connection from the same paired client cannot collide with a new one.
1792 device_uuid.b32[2] ^= launch_session->id;
1793 device_uuid_str = device_uuid.string();
1794 }
1795
1796 launch_session->display_guid = device_uuid;
1797 int target_fps = launch_session->fps ? launch_session->fps : 60000;
1798 if (target_fps < 1000) {
1799 target_fps *= 1000;
1800 }
1801 if (config::video.double_refreshrate) {
1802 target_fps *= 2;
1803 }
1804
1805 const auto display_name = VDISPLAY::createVirtualDisplay(
1806 device_uuid_str.c_str(),
1807 device_name.c_str(),
1808 launch_session->width,
1809 launch_session->height,
1810 target_fps,
1811 launch_session->display_guid,
1812 session_owner_uid,
1813 linux_virtual_display_layout(app.virtual_display_layout),
1814 isolated_session
1815 );
1816 if (display_name.empty()) {
1817 return 503;
1818 }
1819
1821 display_name.c_str(),
1822 launch_session->width,
1823 launch_session->height,
1824 target_fps
1825 ) != 0) {
1826 // Not fatal: capture re-reads the real scanout geometry, so the stream
1827 // follows the display rather than the request. Say it, though - a
1828 // resolution the client did not ask for is otherwise a silent surprise.
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;
1831 }
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.";
1836 VDISPLAY::removeVirtualDisplay(launch_session->display_guid);
1837 return 503;
1838 }
1839
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;
1844 launch_session->drm_device_path = VDISPLAY::getHermesKmsDevicePath(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 "
1848 << display_name;
1849 VDISPLAY::removeVirtualDisplay(launch_session->display_guid);
1850 launch_session->session_virtual_display_cleanup_pending = false;
1851 launch_session->session_scoped_virtual_display = false;
1852 launch_session->display_name.clear();
1853 return 503;
1854 }
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.";
1861 }
1862 return 0;
1863 }
1864
1866 const ctx_t &app,
1867 std::shared_ptr<rtsp_stream::launch_session_t> launch_session
1868 ) {
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.";
1872 return 503;
1873 }
1874 if (app.host_session) {
1875 BOOST_LOG(error) << "[IsolatedSession] A host-session app was incorrectly routed "
1876 "to the isolated-session executor.";
1877 return 400;
1878 }
1879
1880 std::shared_ptr<isolated_runtime_t> stale_runtime;
1881 auto launch_cancelled = std::make_shared<std::atomic_bool>(false);
1882 {
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.";
1887 return 409;
1888 }
1889 stale_runtime = find_isolated_client_locked(launch_session->unique_id);
1890 isolated_launching_clients.emplace(
1891 launch_session->unique_id,
1892 launch_cancelled
1893 );
1894 }
1895 auto release_launch_reservation = util::fail_guard([
1896 client_uuid = launch_session->unique_id,
1897 launch_cancelled
1898 ]() {
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);
1904 }
1905 });
1906 // The reservation prevents a second launch for this client while liveness
1907 // is queried. A broker timeout must not hold every other client's registry
1908 // lock while we wait for 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;
1912 return 409;
1913 }
1914 if (stale_runtime) {
1915 {
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);
1920 }
1921 }
1922 stop_isolated_runtime(stale_runtime);
1923 }
1924 auto launch_was_cancelled = [&]() {
1925 if (!launch_cancelled->load(std::memory_order_relaxed)) {
1926 return false;
1927 }
1928 BOOST_LOG(info) << "[IsolatedSession] Launch cancelled for client "
1929 << launch_session->device_name;
1930 return true;
1931 };
1932
1933 if (launch_was_cancelled()) {
1934 return 503;
1935 }
1936
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;
1941 runtime->app = app;
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;
1948
1949 // Install cleanup before acquiring the audio sink or creating directories.
1950 // Every failed launch must release the resources it has acquired so far.
1951 auto cleanup = util::fail_guard([&]() {
1952 stop_isolated_runtime(runtime);
1953 if (launch_session->session_virtual_display_cleanup_pending) {
1954 // stop_isolated_runtime() owns the actual display removal once the
1955 // runtime has copied display_name/display_guid.
1956 if (runtime->display_name.empty()) {
1957 VDISPLAY::removeVirtualDisplay(launch_session->display_guid);
1958 }
1959 launch_session->session_virtual_display_cleanup_pending = false;
1960 launch_session->session_scoped_virtual_display = false;
1961 launch_session->display_name.clear();
1962 }
1963 });
1964
1965 // With a broker present the session gets a uid of its own, and the single
1966 // runtime directory has to become two: the session's, which systemd made
1967 // for that uid and Hermes cannot write, and this one, which Hermes writes
1968 // the generated compositor config into and the session only reads.
1969 // A detached Plasma desktop is the user's own, by definition, so it never
1970 // takes a helper account; every other isolated session still does.
1971 const bool own_plasma_desktop =
1972 runtime->profile == "desktop" && config::video.hermes_kms_session_compositor == "plasma";
1973 if (!own_plasma_desktop && platf::session_broker::available()) {
1974 runtime->account = platf::session_broker::ensure(runtime->client_uuid);
1975 if (!runtime->account) {
1976 // Falling back to the host user here would quietly hand this client the
1977 // host's files, which is the one thing installing the broker was meant
1978 // to prevent. A refusal is the safe direction.
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.";
1982 return 503;
1983 }
1984 runtime->runtime_dir = "/run/user/" + std::to_string(runtime->account->uid);
1985 }
1986
1987 // Only a session of the Hermes user shares its Steam instance.
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()) {
1991 return 503;
1992 }
1993 }
1994
1995 std::error_code dir_ec;
1996 std::filesystem::create_directories(runtime->assets_dir, dir_ec);
1997 // Traversable and readable when the session is somebody else, because that
1998 // is the only way it can read the config written here; it holds nothing
1999 // secret. Private otherwise, the way it always was.
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));
2007 return -1;
2008 }
2009 if (!runtime->account) {
2010 link_host_discord_ipc(runtime->runtime_dir);
2011 }
2012
2013 // One sink per session, with the layout this client negotiated at launch.
2014 //
2015 // Only where the session shares the host's audio server. A session with a
2016 // uid of its own gets a user manager, and with it an audio server of its
2017 // own that nothing here can reach - /run/user/<uid> is 0700 and somebody
2018 // else's. A sink created in the host's server would then be one the session
2019 // never plays into, and capturing it would hand the client silence, which
2020 // is worse than the host's audio it hears today.
2021 //
2022 // A failure is not fatal for an application: it falls back to what it did
2023 // before any of this existed. A same-user desktop must never fall back to
2024 // recording the host's sink, so it is refused instead.
2025 if (!runtime->account) {
2026 const int audio_channels = launch_session->surround_info & 65535;
2027 const std::string audio_sink = "sink-" + runtime->runtime_id;
2028 // Preferably in a PipeWire server of its own, which knows no host device
2029 // and which the host's server never sees. Its mic is silent until a
2030 // client's microphone streams into it, so nothing records the host's.
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;
2035 // Clients that negotiate a microphone are heard through this source.
2036 if (config::audio.stream_mic) {
2037 runtime->mic_source = mic_source;
2038 }
2039 } else if (own_plasma_desktop) {
2040 // A sink on the host's server would only steer PulseAudio clients:
2041 // native PipeWire ones would still play on the host's own outputs.
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.";
2045 return 503;
2046 } else if (audio::create_session_sink(audio_sink, audio_channels)) {
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.";
2054 return 503;
2055 } else {
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.";
2060 }
2061 } else {
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.";
2065 }
2066
2067 // hermes_kms_session_compositor = plasma, the default: the user's own
2068 // Plasma, detached.
2069 //
2070 // A detached desktop is stock KWin on a virtual output of its own, run as
2071 // this same user in a transient unit of the user's own systemd manager:
2072 // same uid, same home, same files, a private D-Bus and runtime directory.
2073 // It has no DRM device, so it can neither wake nor rearrange a physical
2074 // monitor, and no libinput, so the keyboard and mouse at the machine never
2075 // reach it. Hermes captures it and drives its input over two explicit
2076 // sockets, and never falls back to the host desktop.
2077 if (runtime->profile == "desktop" && config::video.hermes_kms_session_compositor == "plasma") {
2078 if (!app.prep_cmds.empty()) {
2079 // They exist to rearrange the host's displays for a stream, which is
2080 // exactly what a detached desktop must leave alone.
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.";
2083 }
2084
2085 // Weston is an opt-in fallback, never a requirement, so every way this
2086 // can fail names it - for the client and in the log alike.
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."
2090 };
2091 launch_session->launch_error_message = "The KWin virtual desktop " + reason + '.' + std::string {fallback};
2092 BOOST_LOG(error) << "[IsolatedSession] " << launch_session->launch_error_message;
2093 return 503;
2094 };
2095
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"
2100 );
2101 #endif
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},
2115 }) {
2116 if (path.empty()) {
2117 missing.emplace_back(name);
2118 }
2119 }
2120 if (!missing.empty()) {
2121 std::string list;
2122 for (const auto &name : missing) {
2123 list += (list.empty() ? "" : ", ") + name;
2124 }
2125 return plasma_failed("cannot start: " + list + " not found");
2126 }
2127 if (self_ec) {
2128 return plasma_failed("cannot start: Hermes cannot resolve its own executable");
2129 }
2130 // Startup leaves the encoders unprobed when nothing is on screen, and a
2131 // probe can fail; capture needs a chosen encoder either way. Validate one
2132 // before starting the desktop, without a screen, as startup would have:
2133 // a temporary host output would wake the monitors this desktop leaves
2134 // alone. A failure here cannot be ignored, as there is nothing to encode
2135 // with.
2136 {
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;
2141 return 503;
2142 }
2143 }
2144
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);
2149 // The desktop's own PipeWire carries both its sound and KWin's
2150 // screencast. It knows no hardware, so nothing played in the desktop
2151 // can reach the host's outputs, whatever output an app asks for.
2152 runtime->kwin_pipewire_socket = runtime->audio_server->pipewire_remote();
2153 // Runtime ids restart with Hermes, so an earlier instance may have left
2154 // a unit of this name behind, and its status files with it.
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);
2159 }
2160
2161 // Hermes starts the desktop itself, in a mount namespace with a private
2162 // /dev where it can (isolate-devices, as for isolated Gamescope
2163 // sessions): host input devices and sound cards are hidden, and the
2164 // desktop gets only what Hermes gives it. systemd-run --scope then puts
2165 // it in a transient unit of the user's manager and execs in place, so
2166 // the namespace stays and the desktop keeps a cgroup of its own. It
2167 // reaches that manager over the host's bus; env then sets the desktop's
2168 // own environment for everything below it.
2169 std::vector<std::string> command {
2170 systemd_run,
2171 "--user",
2172 "--scope",
2173 "--quiet",
2174 "--collect",
2175 "--unit=" + runtime->unit,
2176 "--property=TimeoutStopSec=15",
2177 };
2178 if (const auto owner = own_service_unit(); !owner.empty()) {
2179 // Stopping Hermes stops every desktop it started. PartOf= would also
2180 // restart one alongside Hermes, bringing up a desktop nobody asked for.
2181 command.push_back("--property=StopPropagatedFrom=" + owner);
2182 }
2183 command.insert(command.end(), {"--", "env"});
2184 // The user manager carries the host desktop's session variables once
2185 // Plasma has imported them; none of them may leak into this one. Nor
2186 // may what Hermes sets on itself: AMD_DEBUG for its own encoder, and
2187 // the tray's QT_QPA_PLATFORM=minimal when it found no display.
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);
2190 }
2191 command.insert(command.end(), {
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,
2196 dbus_run_session,
2197 "--",
2198 session_tool,
2199 "--bootstrap",
2200 std::to_string(width),
2201 std::to_string(height),
2202 self.string(),
2203 std::to_string(launch_session->fps ? launch_session->fps : 60000),
2204 });
2205 // run_command takes one command line; refuse what would not survive it.
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 + ")");
2210 }
2211 command_line += (command_line.empty() ? "" : " ") + argument;
2212 }
2213
2214 const auto devices = platf::session_devices::available() ?
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);
2222 plan = platf::session_devices::plan_t::isolate(staging.string(), devices);
2223 } else {
2224 BOOST_LOG(warning) << "[IsolatedSession] Hermes lacks CAP_SYS_ADMIN and CAP_MKNOD; detached desktop "
2225 << runtime->runtime_id << " sees the host's devices.";
2226 }
2227
2228 BOOST_LOG(info) << "[IsolatedSession] Starting detached desktop " << runtime->runtime_id
2229 << " (" << width << 'x' << height << ") in user unit " << runtime->unit;
2230 {
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(
2235 plan.get(),
2236 command_line,
2237 working_dir,
2238 boost::this_process::environment(),
2239 nullptr,
2240 launch_ec,
2241 nullptr
2242 );
2243 if (launch_ec) {
2244 return plasma_failed("could not be started: " + launch_ec.message());
2245 }
2246 if (plan) {
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.";
2250 }
2251 }
2252 if (runtime->namespace_pid) {
2253 // The client's gamepads carry this tag. udev keeps devices so tagged
2254 // off every seat and closed to the user's processes (60-hermes.rules);
2255 // Hermes gives the desktop its own copies of their nodes instead.
2256 // Without it, gamepads are refused rather than shown to the host.
2257 const auto tag = "hermes-detached-" + runtime->runtime_id;
2258 // For 60-hermes.rules, as for isolated Gamescope sessions: the
2259 // desktop's mount namespace and Hermes' pid, so that the Steam Input
2260 // pads a Steam in this desktop makes are kept off the host too.
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';
2267 runtime->device_mirror = platf::session_devices::mirror(runtime->namespace_pid, tag, config::input.isolated_hide_hid_gamepads);
2268 if (runtime->device_mirror) {
2269 runtime->seat_id = tag;
2270 } else {
2271 BOOST_LOG(warning) << "[IsolatedSession] Detached desktop " << runtime->runtime_id
2272 << " gets no gamepads: its private /dev cannot be given devices.";
2273 }
2274 }
2275
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");
2280 for (;;) {
2281 if (launch_was_cancelled()) {
2282 return 503;
2283 }
2284 std::error_code ec;
2285 if (std::filesystem::exists(root / "failure", ec)) {
2286 return plasma_failed(
2287 "failed to start (" + read_small_file(root / "failure") + "; journalctl --user -u " +
2288 runtime->unit + ")"
2289 );
2290 }
2291 if (detached_desktop_alive(*runtime)) {
2292 break;
2293 }
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 + ")"
2302 );
2303 }
2304 }
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 + ")"
2309 );
2310 }
2311 std::this_thread::sleep_for(100ms);
2312 }
2313
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;
2317
2318 // The app's command and detached commands run inside the desktop, as
2319 // if started from its menu. A command that does not start leaves the
2320 // desktop up, as it would at the machine.
2321 if (!app.cmd.empty()) {
2322 start_in_detached_desktop(*runtime, app, app.cmd, "0-app");
2323 }
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));
2326 }
2327
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;
2337
2338 {
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;
2343 return 503;
2344 }
2345 isolated_runtimes[runtime->launch_session_id] = runtime;
2346 }
2347 cleanup.disable();
2348
2349 BOOST_LOG(info) << "[IsolatedSession] Detached desktop " << runtime->runtime_id
2350 << " ready at " << width << 'x' << height;
2351 return 0;
2352 }
2353
2354 // The account was ensured above, before the display exists, so a card the
2355 // broker creates here can be made for it: the session's compositor runs as
2356 // that uid, and the card's device nodes follow its access_uid.
2357 if (const int result = prepare_session_virtual_display(
2358 launch_session,
2359 true,
2360 &app,
2361 runtime->account ?
2362 std::optional<uid_t> {runtime->account->uid} :
2363 std::nullopt,
2364 true
2365 );
2366 result != 0) {
2367 return result;
2368 }
2369 if (launch_was_cancelled()) {
2370 return 503;
2371 }
2372
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;
2376 runtime->seat_id = VDISPLAY::getHermesKmsSeatName(runtime->display_name);
2377 if (runtime->seat_id.empty()) {
2378 BOOST_LOG(error) << "[IsolatedSession] Could not resolve the independent seat for "
2379 << runtime->display_name;
2380 return 503;
2381 }
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;
2387 return 503;
2388 }
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);
2392 })) {
2393 BOOST_LOG(error) << "[IsolatedSession] Invalid Hermes-KMS seat instance "
2394 << runtime->seat_id;
2395 return 503;
2396 }
2397 runtime->seatd_socket =
2398 (std::filesystem::path {"/run/hermes-kms-seatd"} /
2399 seat_instance /
2400 "seatd.sock")
2401 .string();
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.";
2411 return 503;
2412 }
2413
2414 if (!app.output.empty() && app.output != "null") {
2415 runtime->pipe.reset(std::fopen(app.output.c_str(), "a"));
2416 }
2417
2418 for (size_t index = 0; index < app.prep_cmds.size(); ++index) {
2419 if (launch_was_cancelled()) {
2420 return 503;
2421 }
2422 const auto &cmd = app.prep_cmds[index];
2423 if (cmd.do_cmd.empty()) {
2424 runtime->prep_completed = index + 1;
2425 continue;
2426 }
2427
2428 std::error_code ec;
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(
2435 cmd.elevated,
2436 true,
2437 cmd.do_cmd,
2438 working_dir,
2439 runtime->env,
2440 runtime->pipe.get(),
2441 ec,
2442 nullptr
2443 );
2444 if (ec) {
2445 BOOST_LOG(error) << "[IsolatedSession] Could not start prep command: " << ec.message();
2446 return -1;
2447 }
2448 child.wait();
2449 if (child.exit_code() != 0) {
2450 BOOST_LOG(error) << "[IsolatedSession] Prep command failed with code "
2451 << child.exit_code();
2452 return -1;
2453 }
2454 runtime->prep_completed = index + 1;
2455 if (launch_was_cancelled()) {
2456 return 503;
2457 }
2458 }
2459
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);
2463 const auto connector = VDISPLAY::getHermesKmsConnectorName(runtime->display_name);
2464 std::string launch_command;
2465
2466 // Erased, not emptied: wlroots and gamescope try to nest whenever these are
2467 // set at all, and exit before touching the DRM device they were handed.
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);
2474 }
2475 };
2476
2477 if (runtime->profile == "application") {
2478 forget_wayland_display();
2479 if (app.cmd.empty()) {
2480 BOOST_LOG(error) << "[IsolatedSession] Application profile requires a command.";
2481 return -1;
2482 }
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).";
2488 return -1;
2489 }
2490 if (!gamescope.prefix.empty()) {
2491 // Gamescope starts its children through gamescopereaper, which it
2492 // finds on PATH: the reaper has to be the one from the same build.
2493 // Its WSI layer lives in the same prefix and is not registered with
2494 // the system loader, so the session's Vulkan applications are pointed
2495 // at it.
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() :
2503 std::string {};
2504 runtime->env["VK_ADD_IMPLICIT_LAYER_PATH"] = layers.empty() ? layer_dir.string() : layer_dir.string() + ":" + layers;
2505 }
2506 }
2507 BOOST_LOG(info) << "[IsolatedSession] Using " << gamescope_binary;
2508
2509 // Gamescope scans out on this session's own Hermes-KMS card and renders
2510 // on the real GPU. Upstream cannot be told the two apart: it opens the
2511 // primary node of the GPU it renders with, which is the card the host's
2512 // desktop is on, and either fails to become DRM master there or fights
2513 // the desktop for it. So the card goes to Gamescope explicitly, and a
2514 // build that cannot take it is refused rather than let loose on the
2515 // host's display.
2516 //
2517 // The card is this session's, never a process-wide setting: two
2518 // sessions are two cards.
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 << '.';
2524 }
2525 if (!platf::gamescope::is_primary_card_path(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.";
2528 return 503;
2529 }
2530
2531 std::optional<platf::gamescope::drm_selector_e> selector;
2532 if (const char *forced = std::getenv("HERMES_ISOLATED_GAMESCOPE_DRM_FLAG");
2533 forced && *forced) {
2535 if (!selector) {
2536 BOOST_LOG(warning) << "[IsolatedSession] Ignoring HERMES_ISOLATED_GAMESCOPE_DRM_FLAG=" << forced
2537 << "; expected --prefer-drm, --drm-device or none.";
2538 }
2539 }
2540 if (!selector) {
2541 selector = gamescope_drm_selector(gamescope_binary);
2542 }
2543 if (!selector) {
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.";
2551 return 503;
2552 }
2553 if (*selector == platf::gamescope::drm_selector_e::none) {
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 << '.';
2557 } else {
2558 // Also read by #2220 when the flag is absent. Setting both costs
2559 // nothing and keeps the device in the session's environment, where a
2560 // Gamescope started by a script inside the session finds it too.
2561 runtime->env["GAMESCOPE_PREFER_DRM"] = runtime->drm_device_path;
2562 }
2563
2564 // Steam picks the visible app and shows its overlay only in gamescope's
2565 // Steam mode (-e). Games need an Xwayland apart from Steam's: sharing
2566 // one, the overlay takes their X focus and Wine minimizes them for good.
2567 // auto turns it on for a steam command; the environment switch predates
2568 // the setting and still forces it on everywhere, for testing.
2569 bool steam_mode = platf::gamescope::steam_mode_for(app.gamescope_steam_mode, app.cmd);
2570 try {
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;
2574 return 400;
2575 }
2576 } catch (const std::exception &exception) {
2577 BOOST_LOG(error) << "[IsolatedSession] Invalid gamescope-args: " << exception.what();
2578 return 400;
2579 }
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") {
2582 steam_mode = true;
2583 }
2584 if (steam_mode) {
2585 runtime->held_x_displays = hold_x_display_gaps(2);
2586 if (!runtime->held_x_displays.empty()) {
2587 // Joined by hand: GCC 13 (Ubuntu 24.04) has no std::format for ranges.
2588 std::string held;
2589 for (const int display : runtime->held_x_displays) {
2590 held += (held.empty() ? "[" : ", ") + std::to_string(display);
2591 }
2592 BOOST_LOG(info) << "[IsolatedSession] Holding X displays below gamescope's so Steam's games land on its Xwayland: "
2593 << held << ']';
2594 }
2595 }
2596
2598 .binary = gamescope_binary,
2599 .width = width,
2600 .height = height,
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,
2607 .command = app.cmd,
2608 });
2609 BOOST_LOG(info) << "[IsolatedSession] " << launch_command;
2610 } else {
2611 const auto profile = load_compositor_profile(config::video.hermes_kms_session_compositor);
2612 if (!profile) {
2613 return -1;
2614 }
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.";
2619 return -1;
2620 }
2621
2622 // A compositor that names its own socket is discovered after scanout;
2623 // until then nothing may be launched into it. Clearing the environment
2624 // matters as much as clearing the field: populate_session_environment()
2625 // has already written a WAYLAND_DISPLAY, and wlroots reads that as "nest
2626 // yourself inside this compositor" - so it picks its Wayland backend,
2627 // fails to connect to a socket that will never exist, and exits before
2628 // it ever looks at the DRM device it was given.
2629 if (profile->discover_socket) {
2630 forget_wayland_display();
2631 }
2632
2633 // Expanded against the assets directory, not the session's runtime
2634 // directory: Hermes writes this file and the session only reads it, and
2635 // once the session has a uid of its own those are two different places.
2636 // Profiles go on saying {runtime_dir} and never learn the difference.
2637 const auto config_path = expand_profile_template(
2638 profile->config_target,
2639 {{"runtime_dir", runtime->assets_dir}}
2640 );
2641 // Some compositors take a directory rather than a file - labwc is given
2642 // one with -C and reads several names out of it - so a profile needs to be
2643 // able to name the directory its config was written into.
2644 const auto config_dir = config_path.empty() ?
2645 std::string {} :
2646 std::filesystem::path {config_path}.parent_path().string();
2647
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},
2662 };
2663
2664 // A profile that needs a config file gets one written into the session's
2665 // own runtime directory, so two sessions never share it.
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;
2672 return -1;
2673 }
2674 const auto &target = config_path;
2675 // A config-target may name a subdirectory that does not exist yet -
2676 // a compositor given a config directory rather than a file expects one.
2677 std::error_code dir_ec;
2678 std::filesystem::create_directories(std::filesystem::path {target}.parent_path(), dir_ec);
2679 if (dir_ec) {
2680 BOOST_LOG(error) << "[IsolatedSession] Could not create compositor config directory "
2681 << std::filesystem::path {target}.parent_path() << ": " << dir_ec.message();
2682 return -1;
2683 }
2684 std::ofstream out {target, std::ios::trunc};
2685 if (!out) {
2686 BOOST_LOG(error) << "[IsolatedSession] Could not write compositor config " << target;
2687 return -1;
2688 }
2689 out << expand_profile_template(file_handler::read_file(source.string().c_str()), values);
2690 if (!out) {
2691 BOOST_LOG(error) << "[IsolatedSession] Could not write compositor config " << target;
2692 return -1;
2693 }
2694 out.close();
2695 // The session reads this as another user once it has an account, so it
2696 // is readable rather than private. It is generated from a template that
2697 // ships with Hermes and holds nothing the session may not see.
2698 if (runtime->account) {
2699 ::chmod(target.c_str(), S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
2700 // A directory created here inherits Hermes' umask, which a service
2701 // may well have set to 0077 - and a config the session cannot
2702 // traverse to is the same as no config at all.
2703 // Every level, not just the last one. create_directories() can build
2704 // a whole chain, and a single untraversable link in it is the same as
2705 // no config at all - which is the failure the comment above describes,
2706 // reintroduced one directory higher up.
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);
2711 }
2712 }
2713 BOOST_LOG(debug) << "[IsolatedSession] Wrote compositor config " << target
2714 << " from " << source;
2715 }
2716
2717 for (const auto &[key, value] : profile->env) {
2718 runtime->env[key] = expand_profile_template(value, values);
2719 }
2720 // The socket the profile was given is also what clients must connect to.
2721 if (!runtime->wayland_display.empty()) {
2722 runtime->env["WAYLAND_DISPLAY"] = runtime->wayland_display;
2723 }
2724 launch_command = expand_profile_template(profile->command, values);
2725 runtime->compositor_name = profile->name;
2726 runtime->discover_socket = profile->discover_socket;
2727 }
2728
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) {
2739 // The session cannot be a child of Hermes, because it runs as a uid
2740 // Hermes may not assume. The broker asks systemd for a transient unit
2741 // instead - which is also what gives the session a cgroup, a lifetime and
2742 // a runtime directory that are its own rather than borrowed.
2743 const auto arguments = split_command(launch_command);
2744 if (arguments.empty()) {
2745 BOOST_LOG(error) << "[IsolatedSession] The session compositor command is empty.";
2746 return -1;
2747 }
2748
2749 std::vector<std::string> environment;
2750 for (const auto &entry : runtime->env) {
2751 environment.emplace_back(entry.get_name() + "=" + entry.to_string());
2752 }
2753
2754 const auto unit = platf::session_broker::start(
2755 runtime->client_uuid,
2756 arguments,
2757 environment
2758 );
2759 if (!unit) {
2760 BOOST_LOG(error) << "[IsolatedSession] The broker would not start the session for "
2761 << runtime->account->user << '.';
2762 return -1;
2763 }
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.";
2768 } else {
2769 const auto devices = session_device_options(app);
2770 if (!devices) {
2771 return 503;
2772 }
2773 // The desktop's bus was removed from the session's environment, and
2774 // only a uid of its own would get a bus from systemd.
2775 const bool has_bus = runtime->env.find("DBUS_SESSION_BUS_ADDRESS") != runtime->env.end();
2776 if (const auto with_bus = platf::session_bus::with_private_bus(launch_command, has_bus, find_program("dbus-run-session"))) {
2777 if (!has_bus) {
2778 BOOST_LOG(info) << "[IsolatedSession] Session " << runtime->runtime_id << " gets a D-Bus session bus of its own.";
2779 }
2780 launch_command = *with_bus;
2781 } else {
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.";
2784 }
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);
2790 plan = platf::session_devices::plan_t::isolate(staging.string(), *devices);
2791 }
2792 runtime->process = platf::session_devices::run_command(
2793 plan.get(),
2794 launch_command,
2795 working_dir,
2796 runtime->env,
2797 runtime->pipe.get(),
2798 launch_ec,
2799 &runtime->process_group
2800 );
2801 if (launch_ec) {
2802 BOOST_LOG(error) << "[IsolatedSession] Could not start compositor: "
2803 << launch_ec.message();
2804 return -1;
2805 }
2806 if (plan) {
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") << '.';
2811 }
2812 if (devices->devices) {
2813 // Before any of the seat's devices, which come with the stream. For
2814 // 60-hermes.rules: the session's mount namespace and Hermes' pid, to
2815 // tell the Steam Input pads the session makes; for 74-: no ACL.
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';
2822 runtime->device_mirror = platf::session_devices::mirror(runtime->namespace_pid, runtime->seat_id, config::input.isolated_hide_hid_gamepads);
2823 if (!runtime->device_mirror) {
2824 return -1;
2825 }
2826 }
2827 }
2828
2829 // How long the compositor has to attach a framebuffer to the session's
2830 // output, which is what Hermes-KMS reports as ready. A desktop compositor
2831 // does that as it starts. An application session can take far longer to
2832 // put anything up - Steam's gamepad UI under Gamescope was reported in #57
2833 // to need up to 30 seconds - and giving up at the old five seconds failed
2834 // sessions that were only slow. A compositor that dies is still caught on
2835 // the next poll, so the longer deadline costs nothing when it fails.
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()) {
2849 return 503;
2850 }
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;
2856 } else {
2857 BOOST_LOG(error) << "[IsolatedSession] Compositor exited before scanout became ready"
2858 << " (code=" << runtime->process.native_exit_code() << ").";
2859 }
2860 return 503;
2861 }
2862
2863 const int capture_fd = VDISPLAY::hermesKmsOpenCapture(runtime->display_name);
2864 if (capture_fd >= 0) {
2865 scanout_ready = VDISPLAY::hermesKmsCaptureSize(
2866 capture_fd,
2867 active_width,
2868 active_height
2869 );
2870 ::close(capture_fd);
2871 }
2872 if (scanout_ready && active_width > 0 && active_height > 0) {
2873 break;
2874 }
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.";
2881 }
2882 std::this_thread::sleep_for(50ms);
2883 }
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.";
2888 return 503;
2889 }
2890 if (launch_was_cancelled()) {
2891 return 503;
2892 }
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.";
2897 }
2898
2899 if (runtime->profile == "application" || runtime->discover_socket) {
2900 // The scanout wait above clears on its first poll - the driver reports
2901 // the configured mode as soon as the output exists, whether or not
2902 // anything has drawn - so by itself it says nothing about the compositor
2903 // being up. A compositor that names its own socket has not usually
2904 // created it yet at that point, and launching into a session with no
2905 // WAYLAND_DISPLAY leaves the client to die on its own. Wait for the
2906 // socket, which is a signal the compositor actually produces.
2907 std::string compositor_socket;
2908 for (int attempt = 0; attempt < 100; ++attempt) {
2909 if (launch_was_cancelled()) {
2910 return 503;
2911 }
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()) + ")")
2919 << '.';
2920 return 503;
2921 }
2922 // The session's runtime directory is 0700 and somebody else's once it
2923 // has an account, so the broker does the listing and returns the name.
2924 compositor_socket = runtime->account ?
2925 platf::session_broker::wayland_socket(runtime->client_uuid)
2926 .value_or(std::string {}) :
2927 discover_wayland_socket(runtime->runtime_dir);
2928 if (!compositor_socket.empty()) {
2929 break;
2930 }
2931 std::this_thread::sleep_for(50ms);
2932 }
2933
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;
2939 } else {
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.";
2944 return 503;
2945 }
2946 }
2947
2948 if (runtime->profile == "desktop" && !app.cmd.empty()) {
2949 std::error_code app_ec;
2950 BOOST_LOG(info) << "[IsolatedSession] Starting desktop application: ["
2951 << app.cmd << ']';
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 {"."});
2955 return -1;
2956 }
2957 }
2958 if (launch_was_cancelled()) {
2959 return 503;
2960 }
2961
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) {
2965 std::error_code ec;
2966 // One scope per command, because each becomes a unit and two units
2967 // cannot share a name.
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 {"."});
2971 }
2972 }
2973
2974 {
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;
2981 });
2983 !config::video.ignore_encoder_probe_failure) {
2984 return 503;
2985 }
2986 }
2987 if (launch_was_cancelled()) {
2988 return 503;
2989 }
2990
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;
2998
2999 {
3000 std::lock_guard<std::mutex> lock(isolated_runtimes_mutex);
3001 // Atomically hand the launch from the cancellation registry to the
3002 // runtime registry. A concurrent /cancel either marks us before this
3003 // check or waits for the lock and finds the newly registered runtime.
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;
3007 return 503;
3008 }
3009 isolated_runtimes[runtime->launch_session_id] = runtime;
3010 }
3011 cleanup.disable();
3012
3013 BOOST_LOG(info) << "[IsolatedSession] Runtime " << runtime->runtime_id
3014 << " ready at " << active_width << 'x' << active_height
3015 << '@' << refresh_hz << "Hz";
3016 return 0;
3017 }
3018
3019 void proc_t::terminate_isolated(uint32_t launch_session_id) {
3020 std::shared_ptr<isolated_runtime_t> runtime;
3021 {
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()) {
3025 return;
3026 }
3027 runtime = std::move(it->second);
3028 isolated_runtimes.erase(it);
3029 }
3030 stop_isolated_runtime(runtime);
3031 }
3032
3033 void proc_t::disconnect_isolated(uint32_t launch_session_id) {
3034 bool terminate_on_pause = false;
3035 {
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) {
3039 return;
3040 }
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.";
3045 return;
3046 }
3047 }
3048 terminate_isolated(launch_session_id);
3049 }
3050
3051 void proc_t::terminate_isolated_client(const std::string &client_uuid) {
3052 std::shared_ptr<isolated_runtime_t> runtime;
3053 {
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);
3059 }
3060 runtime = find_isolated_client_locked(client_uuid);
3061 if (runtime) {
3062 isolated_runtimes.erase(runtime->launch_session_id);
3063 }
3064 }
3065 stop_isolated_runtime(runtime);
3066 }
3067
3068 bool proc_t::isolated_client_present(const std::string &client_uuid) {
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;
3072 }
3073
3075 std::vector<std::shared_ptr<isolated_runtime_t>> runtimes;
3076 {
3077 std::lock_guard<std::mutex> lock(isolated_runtimes_mutex);
3078 for (const auto &[client_uuid, cancelled] : isolated_launching_clients) {
3079 if (cancelled) {
3080 cancelled->store(true, std::memory_order_relaxed);
3081 }
3082 }
3083 for (auto &[id, runtime] : isolated_runtimes) {
3084 runtimes.emplace_back(std::move(runtime));
3085 }
3086 isolated_runtimes.clear();
3087 }
3088 for (const auto &runtime : runtimes) {
3089 stop_isolated_runtime(runtime);
3090 }
3091 }
3092
3093 int proc_t::running_for_client(const std::string &client_uuid) {
3094 std::shared_ptr<isolated_runtime_t> runtime;
3095 {
3096 std::lock_guard<std::mutex> lock(isolated_runtimes_mutex);
3097 runtime = find_isolated_client_locked(client_uuid);
3098 }
3099 if (!runtime) {
3100 return 0;
3101 }
3102 const bool active = isolated_runtime_running(runtime);
3103 {
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) {
3107 return 0;
3108 }
3109 if (active && !runtime->stopping.load()) {
3110 return util::from_view(runtime->app.id);
3111 }
3112 isolated_runtimes.erase(it);
3113 }
3114 stop_isolated_runtime(runtime);
3115 return 0;
3116 }
3117
3118 std::string proc_t::running_app_uuid_for_client(const std::string &client_uuid) {
3119 std::shared_ptr<isolated_runtime_t> runtime;
3120 {
3121 std::lock_guard<std::mutex> lock(isolated_runtimes_mutex);
3122 runtime = find_isolated_client_locked(client_uuid);
3123 }
3124 if (!isolated_runtime_running(runtime)) {
3125 return {};
3126 }
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() ?
3130 runtime->app.uuid :
3131 std::string {};
3132 }
3133
3135 // Liveness is asked for outside the lock, the way list_isolated() does it:
3136 // where the session is a systemd unit the answer comes from the broker
3137 // over a socket, and holding the registry lock across that stalls every
3138 // launch and teardown behind a round trip - or, when a broker peer stalls
3139 // it, behind a timeout. The runtimes are snapshotted under the lock, the
3140 // lock is dropped for the ask, and only entries that still map to the
3141 // same runtime afterwards are erased.
3142 std::vector<std::shared_ptr<isolated_runtime_t>> runtimes;
3143 {
3144 std::lock_guard<std::mutex> lock(isolated_runtimes_mutex);
3145 for (const auto &[id, runtime] : isolated_runtimes) {
3146 if (runtime) {
3147 runtimes.push_back(runtime);
3148 }
3149 }
3150 }
3151
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;
3157 } else {
3158 stopped.push_back(runtime);
3159 }
3160 }
3161
3162 {
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);
3168 }
3169 }
3170 }
3171 for (const auto &runtime : stopped) {
3172 stop_isolated_runtime(runtime);
3173 }
3174 if (isolated_running) {
3175 return true;
3176 }
3177 return running() != 0;
3178 }
3179
3180 boost::process::v1::environment proc_t::get_session_env(uint32_t launch_session_id) {
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;
3185 }
3186 return _env;
3187 }
3188
3189 std::vector<proc_t::isolated_session_t> proc_t::list_isolated() {
3190 std::vector<isolated_session_t> sessions;
3191 std::vector<std::shared_ptr<isolated_runtime_t>> runtimes;
3192 {
3193 std::lock_guard<std::mutex> lock(isolated_runtimes_mutex);
3194 runtimes.reserve(isolated_runtimes.size());
3195 for (const auto &[id, runtime] : isolated_runtimes) {
3196 if (runtime) {
3197 runtimes.push_back(runtime);
3198 }
3199 }
3200 }
3201
3202 // Liveness is asked for outside the lock. Where the session is a systemd
3203 // unit the answer comes from the broker over a socket, and holding the
3204 // registry lock across that would stall every launch and teardown behind a
3205 // round trip.
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);
3210 if (!running) {
3211 stopped.push_back(runtime);
3212 continue;
3213 }
3214
3215 isolated_session_t session;
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) {
3226 session.account_user = runtime->account->user;
3227 session.account_uid = runtime->account->uid;
3228 }
3229 session.unit = runtime->unit;
3230 session.audio_sink = runtime->audio_sink;
3231 session.running = true;
3232 session.uptime_seconds =
3233 std::chrono::duration_cast<std::chrono::seconds>(now - runtime->started_at).count();
3234 sessions.push_back(std::move(session));
3235 }
3236
3237 std::vector<std::shared_ptr<isolated_runtime_t>> removed;
3238 {
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);
3245 }
3246 }
3247 }
3248
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);
3253 }
3254
3255 std::ranges::sort(sessions, [](const auto &left, const auto &right) {
3256 return left.launch_session_id < right.launch_session_id;
3257 });
3258 return sessions;
3259 }
3260
3261 std::string proc_t::isolated_audio_sink(uint32_t 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;
3266 }
3267 // Empty for every session that is not isolated, and for one whose private
3268 // sink could not be made - both of which mean "capture the way you always
3269 // did".
3270 return {};
3271 }
3272
3273 std::string proc_t::isolated_audio_server(uint32_t launch_session_id) {
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();
3278 }
3279 return {};
3280 }
3281
3282 std::string proc_t::isolated_mic_source(uint32_t launch_session_id) {
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;
3287 }
3288 return {};
3289 }
3290
3291 bool proc_t::isolated_session_has_account(uint32_t launch_session_id) {
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;
3295 }
3296
3298 std::shared_ptr<rtsp_stream::launch_session_t> launch_session
3299 ) {
3300 std::shared_ptr<isolated_runtime_t> runtime;
3301 {
3302 std::lock_guard<std::mutex> lock(isolated_runtimes_mutex);
3303 runtime = find_isolated_client_locked(launch_session->unique_id);
3304 }
3305 if (!isolated_runtime_running(runtime)) {
3306 if (runtime) {
3307 bool removed = false;
3308 {
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);
3313 removed = true;
3314 }
3315 }
3316 if (removed) {
3317 BOOST_LOG(info) << "[IsolatedSession] Removing stale runtime "
3318 << runtime->runtime_id << " before resume.";
3319 stop_isolated_runtime(runtime);
3320 }
3321 }
3322 return false;
3323 }
3324 if (runtime->user_unit) {
3325 std::lock_guard<std::mutex> mode_lock(runtime->process_mutex);
3326 if (runtime->stopping.load()) {
3327 return false;
3328 }
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;
3336 return false;
3337 }
3338 }
3339 std::lock_guard<std::mutex> lock(isolated_runtimes_mutex);
3340 const auto it = isolated_runtimes.find(runtime->launch_session_id);
3341 // The client may have started a newer runtime while the broker replied.
3342 if (it == isolated_runtimes.end() || it->second != runtime || runtime->stopping.load() ||
3343 find_isolated_client_locked(launch_session->unique_id) != runtime) {
3344 return false;
3345 }
3346
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();
3364 }
3365 return true;
3366 }
3367
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);
3372 } else {
3373 // Ensure starting from a clean slate
3374 terminate(false, false);
3375 }
3376
3377 _app = app;
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;
3382
3383 uint32_t client_width = launch_session->width ? launch_session->width : 1920;
3384 uint32_t client_height = launch_session->height ? launch_session->height : 1080;
3385
3386 uint32_t render_width = client_width;
3387 uint32_t render_height = client_height;
3388
3389 const int scale_factor =
3390 decide_scale_factor(_app, *launch_session, config::video.default_scale_factor).percent;
3391
3392 if (scale_factor != 100) {
3393 render_width *= ((float)scale_factor / 100);
3394 render_height *= ((float)scale_factor / 100);
3395
3396 // Chop the last bit to ensure the scaled resolution is even numbered
3397 // Most odd resolutions won't work well
3398 render_width &= ~1;
3399 render_height &= ~1;
3400 }
3401
3402 launch_session->width = render_width;
3403 launch_session->height = render_height;
3404
3405 this->initial_display = config::video.output_name;
3406 // Executed when returning from function
3407 auto fg = util::fail_guard([&]() {
3408 if (launch_session->session_virtual_display_cleanup_pending) {
3409 VDISPLAY::removeVirtualDisplay(launch_session->display_guid);
3410 launch_session->session_virtual_display_cleanup_pending = false;
3411 launch_session->session_scoped_virtual_display = false;
3412 launch_session->display_name.clear();
3413 }
3414 // Restore to user defined output name
3415 config::video.output_name = this->initial_display;
3416 terminate();
3418 });
3419
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;
3424 } else {
3425 config::input.controller = true;
3426 config::input.gamepad = app.gamepad;
3427 }
3428 }
3429
3430 // In a standalone Gamescope session (e.g. SteamOS Game Mode), Gamescope is
3431 // itself the compositor and already provides an isolated, client-sized
3432 // surface on DRM/KMS. Creating a Hermes virtual display there is both
3433 // redundant and unactivatable (there's no desktop output-management to
3434 // adopt the connector), so we skip virtual-display creation and capture the
3435 // Gamescope output directly via the normal (non-virtual) capture path.
3436 const auto session_env = platf::detect_session_environment();
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;
3442 }
3443
3444 // A client launch has already decided under the app's rules; other
3445 // launches (the web UI, resumes of old sessions) still combine them.
3446 const bool virtual_display_requested =
3447 launch_session->virtual_display_decided ?
3448 (config::video.headless_mode || launch_session->virtual_display) :
3449 launch_requests_virtual_display(_app, *launch_session, config::video.headless_mode);
3450 // Screens put to sleep read as unlit, the same as no monitor at all.
3451 if (!virtual_display_requested && !gamescope_session && !video::display_present()) {
3453 }
3454 const bool needs_virtual_display =
3455 !gamescope_session && // Not in a standalone Gamescope session
3456 (virtual_display_requested ||
3457 !video::display_present() // No active display presents
3458 );
3459
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.";
3462 }
3463
3464 // A nested application launched into the host compositor cannot appear above
3465 // the desktop's screen locker. For unattended same-session streaming, an app
3466 // may explicitly ask Hermes to unlock the host graphical session first. This
3467 // is deliberately independent of virtual-display layout: that controls monitor
3468 // arrangement, while this controls the security state of the existing host
3469 // desktop. Failure is non-fatal so the stream can still present the lock
3470 // screen and be unlocked manually.
3471 if (_app.unlock_host_session && !VDISPLAY::unlockHostSessionIfLocked()) {
3472 BOOST_LOG(warning) << "[Session] Host-session unlock was requested for '" << _app.name
3473 << "' but could not be completed; launch will continue.";
3474 }
3475
3476 // Two independent reports arrived from users whose Hermes-KMS status panel
3477 // read "ready", who then found their physical monitor being streamed and no
3478 // explanation anywhere. Nothing was wrong with the driver in either case:
3479 // selecting a backend is not the same as asking for a virtual display, and
3480 // when nothing asks, this block is skipped without a word. Say so.
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.";
3485 } else {
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.";
3495 // Bind touch and pen to the monitor this session streams once the capture
3496 // reports it, instead of wherever KWin puts an unbound touchscreen.
3498 }
3499 }
3500
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) {
3506 return result;
3507 }
3508 session_scoped_display_prepared = true;
3509 this->virtual_display = true;
3510 this->display_name = launch_session->display_name;
3511 config::video.output_name = display_device::map_display_name(this->display_name);
3512 }
3513
3514 if (needs_virtual_display && !session_scoped_display_prepared) {
3515 if (vDisplayDriverStatus != VDISPLAY::DRIVER_STATUS::OK) {
3516 // Try init driver again
3518 }
3519
3520 if (vDisplayDriverStatus == VDISPLAY::DRIVER_STATUS::OK) {
3521 // Try set the render adapter matching the capture adapter if user has specified one
3522 if (!config::video.adapter_name.empty()) {
3523 VDISPLAY::setRenderAdapterByName(config::video.adapter_name);
3524 }
3525
3526 std::string device_name;
3527 std::string device_uuid_str;
3528 uuid_util::uuid_t device_uuid;
3529
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);
3535
3536 // Use XOR to mix the two UUIDs
3537 device_uuid.b64[0] ^= app_uuid.b64[0];
3538 device_uuid.b64[1] ^= app_uuid.b64[1];
3539
3540 device_uuid_str = device_uuid.string();
3541 } else {
3542 device_uuid_str = _app.uuid;
3543 device_uuid = uuid_util::uuid_t::parse(_app.uuid);
3544 }
3545 } else {
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);
3549 }
3550
3551 launch_session->display_guid = device_uuid;
3552
3553 int target_fps = launch_session->fps ? launch_session->fps : 60000;
3554
3555 if (target_fps < 1000) {
3556 target_fps *= 1000;
3557 }
3558
3559 if (config::video.double_refreshrate) {
3560 target_fps *= 2;
3561 }
3562
3563 // Per-app virtual display layout: "mirror" overlaps the primary
3564 // output so the desktop is cloned, "exclusive" hands the desktop to
3565 // the virtual display for the session, "extend" forces the default
3566 // side-by-side placement, "primary" does the same with the virtual
3567 // display as the primary output, "detached" places it beside the physical
3568 // desktop without intentionally rewriting physical-output state, and
3569 // "auto" follows the global exclusive option. Any explicit non-exclusive
3570 // placement also disables the global exclusive option for this session.
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.";
3580 }
3581
3582 std::string vdisplayName = VDISPLAY::createVirtualDisplay(
3583 device_uuid_str.c_str(),
3584 device_name.c_str(),
3585 render_width,
3586 render_height,
3587 target_fps,
3588 launch_session->display_guid,
3589 std::nullopt,
3590 linux_virtual_display_layout(vd_layout)
3591 );
3592
3593 // No matter we get the display name or not, the virtual display might still be created.
3594 // We need to track it properly to remove the display when the session terminates.
3595 launch_session->virtual_display = true;
3596
3597 if (!vdisplayName.empty()) {
3598 BOOST_LOG(info) << "Virtual Display created at " << vdisplayName;
3599
3600 // Don't change display settings when no params are given
3601 if (launch_session->width && launch_session->height && launch_session->fps) {
3602 // Apply display settings
3603 const int mode_result = VDISPLAY::changeDisplaySettings(vdisplayName.c_str(), render_width, render_height, target_fps);
3604 if (mode_result != 0) {
3605 // Capture follows the display's active mode when mode setting fails.
3606 BOOST_LOG(warning) << "Virtual display did not reach "sv << render_width << 'x' << render_height
3607 << "; streaming the display's active mode instead."sv;
3608 }
3609 }
3610
3611 // Some Wayland compositors expose the DRM connector but cannot add it
3612 // to their output layout; encoding that untouched virtual buffer
3613 // yields a black stream while audio continues normally. Streaming a
3614 // physical monitor instead would hand the client the host desktop it
3615 // asked to be kept away from, so the launch fails here.
3616 if (!VDISPLAY::activateVirtualDisplayOutput(vdisplayName)) {
3617 const char *backend_label = VDISPLAY::isHermesKmsDisplay(vdisplayName) ? "Hermes-KMS" : "EVDI";
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.";
3622 return 503;
3623 }
3624
3625 // Rearrange the displays when this session asked for the virtual
3626 // display exclusively - through the global ISOLATED DISPLAY setting
3627 // or the app's virtual-display-layout.
3628 if (want_exclusive) {
3629 // Read the host's default sink before the monitors go dark, not
3630 // after. A monitor's audio device leaves with the monitor, and the
3631 // sound server hands the default to whatever is still there - so a
3632 // session that looks afterwards records the substitute and restores
3633 // that, leaving the user on the wrong speakers once the stream
3634 // ends. terminate() releases this once the monitors are back.
3636
3637 // Apply the isolated display settings
3638 VDISPLAY::changeDisplaySettings2(vdisplayName.c_str(), render_width, render_height, target_fps, true);
3639 if (!VDISPLAY::enableExclusiveVirtualDisplay(vdisplayName)) {
3640 BOOST_LOG(warning) << "Virtual display is active, but exclusive mode could not disable physical outputs.";
3641 }
3642 }
3643
3644 this->virtual_display = true;
3645 this->display_name = vdisplayName;
3646
3647 if (!VDISPLAY::configureVirtualDisplayHdr(this->display_name, launch_session->enable_hdr)) {
3648 return -1;
3649 }
3650
3651 // When using virtual display, we don't care which display user configured to use.
3652 // So we always set output_name to the newly created virtual display as a workaround for
3653 // empty name when probing graphics cards.
3654 //
3655 config::video.output_name = this->display_name;
3656 } else {
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.";
3661 return 503;
3662 }
3663 } else {
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.";
3668 return 503;
3669 }
3670 }
3671
3672 display_device::configure_display(config::video, *launch_session);
3673
3674 // We should not preserve display state when using virtual display.
3675 if (this->virtual_display) {
3677 }
3678
3679 // Probe encoders again before streaming to ensure our chosen
3680 // encoder matches the active GPU (which could have changed
3681 // due to hotplugging, driver crash, primary monitor change,
3682 // or any number of other factors).
3684 if (config::video.ignore_encoder_probe_failure) {
3685 BOOST_LOG(warning) << "Encoder probe failed, but continuing due to user configuration.";
3686 } else {
3687 return 503;
3688 }
3689 }
3690
3691 std::string fps_str;
3692 char fps_buf[8];
3693 snprintf(fps_buf, sizeof(fps_buf), "%.3f", (float)launch_session->fps / 1000.0f);
3694 fps_str = fps_buf;
3695
3696 // Add Stream-specific environment variables
3697 // Sunshine Compatibility
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";
3707
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";
3724
3725 // Hermes-branded env vars (mirror the APOLLO_* lineage contract). New
3726 // tooling (e.g. hermes-gamescope-launch) reads these; APOLLO_*/SUNSHINE_*
3727 // remain for client/lineage compatibility.
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";
3749 }
3750
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 {}
3756 );
3757 // _env outlives the app: remember what was there, so terminate() can
3758 // give the next app the environment without this app's limit.
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);
3762 _env[name] = value;
3763 }
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)";
3767 }
3768 }
3769
3770 int channelCount = launch_session->surround_info & 65535;
3771 switch (channelCount) {
3772 case 2:
3773 _env["SUNSHINE_CLIENT_AUDIO_CONFIGURATION"] = "2.0";
3774 _env["APOLLO_CLIENT_AUDIO_CONFIGURATION"] = "2.0";
3775 break;
3776 case 6:
3777 _env["SUNSHINE_CLIENT_AUDIO_CONFIGURATION"] = "5.1";
3778 _env["APOLLO_CLIENT_AUDIO_CONFIGURATION"] = "5.1";
3779 break;
3780 case 8:
3781 _env["SUNSHINE_CLIENT_AUDIO_CONFIGURATION"] = "7.1";
3782 _env["APOLLO_CLIENT_AUDIO_CONFIGURATION"] = "7.1";
3783 break;
3784 }
3785 _env["SUNSHINE_CLIENT_AUDIO_SURROUND_PARAMS"] = launch_session->surround_params;
3786 _env["APOLLO_CLIENT_AUDIO_SURROUND_PARAMS"] = launch_session->surround_params;
3787
3788 if (!_app.output.empty() && _app.output != "null"sv) {
3789 _pipe.reset(fopen(_app.output.c_str(), "a"));
3790 }
3791
3792 std::error_code ec;
3793 _app_prep_begin = std::begin(_app.prep_cmds);
3794 _app_prep_it = _app_prep_begin;
3795
3796 for (; _app_prep_it != std::end(_app.prep_cmds); ++_app_prep_it) {
3797 auto &cmd = *_app_prep_it;
3798
3799 // Skip empty commands
3800 if (cmd.do_cmd.empty()) {
3801 continue;
3802 }
3803
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);
3809
3810 if (ec) {
3811 BOOST_LOG(error) << "Couldn't run ["sv << cmd.do_cmd << "]: System: "sv << ec.message();
3812 // We don't want any prep commands failing launch of the desktop.
3813 // This is to prevent the issue where users reboot their PC and need to log in with Sunshine.
3814 // permission_denied is typically returned when the user impersonation fails, which can happen when user is not signed in yet.
3815 if (!(_app.cmd.empty() && ec == std::errc::permission_denied)) {
3816 return -1;
3817 }
3818 }
3819
3820 child.wait();
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 << ']';
3824 return -1;
3825 }
3826 }
3827
3828 _env["APOLLO_APP_STATUS"] = "RUNNING";
3829
3830 // Parse exactly as application commands are parsed elsewhere. Quoted
3831 // executable paths and Flatpak Steam entries must not silently miss this.
3832 const auto placement_arguments = [](const std::string &command) {
3833 try {
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> {};
3838 }
3839 };
3840 const auto app_arguments = placement_arguments(_app.cmd);
3841 bool place_steam = platf::window_placement::opens_big_picture(app_arguments);
3842 const bool app_gamescope = !gamescope_session &&
3843 (platf::window_placement::launches_gamescope(app_arguments) ||
3844 launch_session->launch_mode == "gamescope");
3845 std::vector<std::uint32_t> gamescope_pids;
3846
3847 // A Gamescope nested in the desktop starts a Steam of its own. Steam runs
3848 // once per user: with another Steam running, that one takes the request,
3849 // the new one exits, and Gamescope and the app end within a second. Shut
3850 // the other Steam down first, as independent sessions do. Inside a
3851 // standalone Gamescope session the running Steam is the session's own and
3852 // is meant to take the request.
3853 if (!gamescope_session && _app.stop_desktop_steam != "off") {
3854 bool nested_steam = platf::window_placement::gamescope_runs_steam(app_arguments) ||
3855 (launch_session->launch_mode == "gamescope" && runs_steam(_app));
3856 for (const auto &cmd : _app.detached) {
3857 nested_steam = nested_steam || platf::window_placement::gamescope_runs_steam(placement_arguments(cmd));
3858 }
3859 // It was the user's, so it comes back when the app ends.
3860 if (nested_steam) {
3861 if (const auto stopped = stop_desktop_steam("[Gamescope]")) {
3862 _reopen_desktop_steam = true;
3863 _desktop_steam_flatpak = stopped->flatpak;
3864 }
3865 }
3866 }
3867
3868 // Detached commands outlive the process Hermes starts (Steam's first
3869 // process updates itself and exits), so a process group cannot hold them.
3870 // A scope of the user's systemd manager does, however they fork, setsid or
3871 // enter containers, and ending the app stops it (terminate()).
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;
3884 std::string unit;
3885 if (scoped) {
3886 unit = platf::detached_scope::unit_name(::getpid(), launch, _detached_units.size());
3887 spawn = platf::detached_scope::wrap(systemd_run, unit, std::max(_app.exit_timeout, std::chrono::seconds {15}), cmd);
3888 }
3889 auto child = platf::run_command(_app.elevated, true, spawn, working_dir, _env, _pipe.get(), ec, nullptr);
3890 if (ec) {
3891 BOOST_LOG(warning) << "Couldn't spawn ["sv << cmd << "]: System: "sv << ec.message();
3892 } else {
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()));
3897 }
3898 if (!unit.empty()) {
3899 _detached_units.push_back(unit);
3900 }
3901 child.detach();
3902 }
3903 }
3904
3905 if (_app.cmd.empty()) {
3906 BOOST_LOG(info) << "No commands configured, showing desktop..."sv;
3907 placebo = true;
3908 } else {
3909 boost::filesystem::path working_dir = _app.working_dir.empty() ?
3910 find_working_directory(_app.cmd, _env) :
3911 boost::filesystem::path(_app.working_dir);
3912 std::string launch_command = _app.cmd;
3913 if (launch_session->launch_mode == "gamescope") {
3914 if (gamescope_session) {
3915 // We are already inside a standalone Gamescope session (SteamOS Game
3916 // Mode). Nesting another Gamescope here would be redundant, so run the
3917 // application directly in the existing 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";
3922 return -1;
3923 } else {
3924 const int gamescope_fps = std::max(1, (launch_session->fps ? launch_session->fps : 60000) / 1000);
3925 // This path is only used when a client explicitly requested Gamescope
3926 // on a desktop session. The primary session path above has already
3927 // created/activated the virtual display, and Gamescope is nested in
3928 // the desktop compositor instead of taking a DRM card of its own.
3929 // A nested Gamescope is a window like any other: the compositor places
3930 // it, normally on the primary monitor, and it only lands on the
3931 // virtual display when that output is the one the compositor chooses
3932 // (e.g. with the exclusive virtual display option enabled). The
3933 // backend defaults to wayland (nesting in the desktop compositor);
3934 // override with the gamescope_backend setting when a different
3935 // backend is needed.
3936 const std::string &configured_backend = config::video.gamescope_backend;
3937 const std::string gamescope_backend = (configured_backend.empty() || configured_backend == "auto") ?
3938 "wayland" :
3939 configured_backend;
3940 launch_command = std::format("gamescope --backend={} -W {} -H {} -r {} -o {} -f -e -F fsr --fsr-sharpness 4 -- {}",
3941 gamescope_backend,
3942 launch_session->width,
3943 launch_session->height,
3944 gamescope_fps,
3945 gamescope_fps,
3946 _app.cmd);
3947 }
3948 }
3949
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);
3952 if (ec) {
3953 BOOST_LOG(warning) << "Couldn't run ["sv << launch_command << "]: System: "sv << ec.message();
3954 return -1;
3955 }
3956 }
3957
3958 if (!this->display_name.empty()) {
3959 if (app_gamescope && _process.valid()) {
3960 gamescope_pids.push_back(static_cast<std::uint32_t>(_process.id()));
3961 }
3962 // Install after spawning: exact PIDs are now known. The script visits
3963 // existing windows too, so a fast launch cannot miss its placement.
3964 if (!gamescope_pids.empty()) {
3965 VDISPLAY::placeWindowsOnVirtualDisplay(this->display_name, {"gamescope"}, gamescope_pids);
3966 } else if (place_steam) {
3967 VDISPLAY::placeWindowsOnVirtualDisplay(this->display_name, {"steam"});
3968 }
3969 }
3970
3971 _app_launch_time = std::chrono::steady_clock::now();
3972
3973
3974 fg.disable();
3975
3976#if defined HERMES_TRAY && HERMES_TRAY >= 1
3978#endif
3979
3980 return 0;
3981 }
3982
3984 // On POSIX OSes, we must periodically wait for our children to avoid
3985 // them becoming zombies. This must be synchronized carefully with
3986 // calls to bp::wait() and platf::process_group_running() which both
3987 // invoke waitpid() under the hood.
3988 auto reaper = util::fail_guard([]() {
3989 // A bounded command (kscreen-doctor and the like) reaps its own child.
3990 // Reaping it here would take its exit status, and its complete reply
3991 // would be thrown away. Skip this round while one runs; whatever exits
3992 // meanwhile is reaped on a later call.
3993 std::unique_lock lock {platf::bounded_command::reap_mutex(), std::try_to_lock};
3994 if (!lock) {
3995 return;
3996 }
3997 while (waitpid(-1, nullptr, WNOHANG) > 0);
3998 });
3999
4000 if (placebo) {
4001 return _app_id;
4002 } else if (_app.wait_all && _process_group && platf::process_group_running((std::uintptr_t) _process_group.native_handle())) {
4003 // The app is still running if any process in the group is still running
4004 return _app_id;
4005 } else if (_process.running()) {
4006 // The app is still running only if the initial process launched is still running
4007 return _app_id;
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;
4011 placebo = true;
4012
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());
4016 }
4017 #endif
4018
4019 return _app_id;
4020 }
4021
4022 // Perform cleanup actions now if needed
4023 if (_process) {
4024 terminate();
4025 }
4026
4027 return 0;
4028 }
4029
4030 void proc_t::resume() {
4031 BOOST_LOG(info) << "Session resuming for app [" << _app_name << "].";
4032
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 {
4035
4036 _env["APOLLO_APP_STATUS"] = "RESUMING";
4037
4038 std::error_code ec;
4039 auto _state_resume_it = std::begin(cmd_list);
4040
4041 for (; _state_resume_it != std::end(cmd_list); ++_state_resume_it) {
4042 auto &cmd = *_state_resume_it;
4043
4044 // Skip empty commands
4045 if (cmd.do_cmd.empty()) {
4046 continue;
4047 }
4048
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);
4054
4055 if (ec) {
4056 BOOST_LOG(error) << "Couldn't run ["sv << cmd.do_cmd << "]: System: "sv << ec.message();
4057 break;
4058 }
4059
4060 child.wait();
4061
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 << ']';
4065 break;
4066 }
4067 }
4068 });
4069
4070 exec_thread.detach();
4071 }
4072 }
4073
4074 void proc_t::pause() {
4075 if (!running()) {
4076 BOOST_LOG(info) << "Session already stopped, do not run pause commands.";
4077 return;
4078 }
4079
4080 if (_app.terminate_on_pause) {
4081 BOOST_LOG(info) << "Terminating app [" << _app_name << "] when all clients are disconnected. Pause commands are skipped.";
4082 terminate();
4083 return;
4084 }
4085
4086 BOOST_LOG(info) << "Session pausing for app [" << _app_name << "].";
4087
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";
4091
4092 std::error_code ec;
4093 auto _state_pause_it = std::begin(cmd_list);
4094
4095 for (; _state_pause_it != std::end(cmd_list); ++_state_pause_it) {
4096 auto &cmd = *_state_pause_it;
4097
4098 // Skip empty commands
4099 if (cmd.undo_cmd.empty()) {
4100 continue;
4101 }
4102
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);
4108
4109 if (ec) {
4110 BOOST_LOG(error) << "Couldn't run ["sv << cmd.undo_cmd << "]: System: "sv << ec.message();
4111 break;
4112 }
4113
4114 child.wait();
4115
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 << ']';
4119 break;
4120 }
4121 }
4122 });
4123
4124 exec_thread.detach();
4125 }
4126
4127#if defined HERMES_TRAY && HERMES_TRAY >= 1
4128 system_tray::update_tray_pausing(proc::proc.get_last_run_app_name());
4129#endif
4130 }
4131
4132 void proc_t::terminate(bool immediate, bool needs_refresh) {
4133 std::error_code ec;
4134 placebo = false;
4135
4136 // Put back the touch and pen binding a physical-monitor session made.
4137 VDISPLAY::endPhysicalOutputSession();
4138
4139 if (!immediate) {
4140 terminate_process_group(_process, _process_group, _app.exit_timeout);
4141 }
4142
4143 _process = boost::process::v1::child();
4144 _process_group = boost::process::v1::group();
4145
4146 _env["APOLLO_APP_STATUS"] = "TERMINATING";
4147
4148 for (; _app_prep_it != _app_prep_begin; --_app_prep_it) {
4149 auto &cmd = *(_app_prep_it - 1);
4150
4151 if (cmd.undo_cmd.empty()) {
4152 continue;
4153 }
4154
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);
4161
4162 if (ec) {
4163 BOOST_LOG(warning) << "Undo command could not start: "sv << ec.message();
4164 continue;
4165 }
4166
4167 finish_undo_command(child, undo_group, _app.exit_timeout);
4168 }
4169
4170 // After the undo commands, which may still talk to them (Steam's
4171 // steam://close/bigpicture). A command that handed its work to a program
4172 // already running, such as a Steam the user opened, has left its scope
4173 // empty and gone; only what Hermes started is stopped.
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);
4180 }
4181 }
4182 _detached_units.clear();
4183 }
4184
4185 _pipe.reset();
4186
4187 // Undo this app's frame limit, newest first, so a variable set twice ends
4188 // with the value it had before either.
4189 for (auto it = _frame_limit_restore.rbegin(); it != _frame_limit_restore.rend(); ++it) {
4190 if (it->second) {
4191 _env[it->first] = *it->second;
4192 } else {
4193 _env.erase(it->first);
4194 }
4195 }
4196 _frame_limit_restore.clear();
4197
4198 if (std::exchange(_reopen_desktop_steam, false)) {
4199 std::vector<std::string> environment;
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());
4203 }
4204 }
4205 reopen_desktop_steam(std::move(environment), _desktop_steam_flatpak);
4206 }
4207
4208 bool has_run = _app_id > 0;
4209
4210 // Revert HDR state
4211 if (has_run && !mode_changed_display.empty()) {
4212 if (VDISPLAY::setDisplayHDRByName(mode_changed_display.c_str(), initial_hdr)) {
4213 BOOST_LOG(info) << "HDR reverted for display " << mode_changed_display;
4214 } else {
4215 BOOST_LOG(info) << "HDR revert failed for display " << mode_changed_display;
4216 }
4217 }
4218
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) {
4223 // Unconditionally: exclusive mode is also reachable per app, through the
4224 // app's virtual-display-layout, and those sessions have to give the
4225 // monitors back too. The call knows whether it took them.
4226 VDISPLAY::restoreExclusiveVirtualDisplay();
4227 if (VDISPLAY::removeVirtualDisplay(_launch_session->display_guid)) {
4228 BOOST_LOG(info) << "Virtual Display removed successfully";
4229 } else if (this->virtual_display) {
4230 BOOST_LOG(warning) << "Virtual Display remove failed";
4231 } else {
4232 BOOST_LOG(warning) << "Virtual Display remove failed, but it seems it was not created correctly either.";
4233 }
4234 } else if (session_scoped_virtual_display) {
4235 BOOST_LOG(debug) << "Session-scoped virtual display cleanup is owned by the streaming session.";
4236 }
4237
4238 // Only now are the monitors on their way back - on KWin it is removing the
4239 // virtual display that re-enables them - so this is the earliest the sink
4240 // that left with them can be restored. The release does the waiting itself
4241 // and returns straight away; a no-op when nothing was held.
4243
4244 // Only show the Stopped notification if we actually have an app to stop
4245 // Since terminate() is always run when a new app has started
4246 if (proc::proc.get_last_run_app_name().length() > 0 && has_run) {
4247 if (used_virtual_display) {
4249 } else {
4251 }
4252
4253#if defined HERMES_TRAY && HERMES_TRAY >= 1
4254 system_tray::update_tray_stopped(proc::proc.get_last_run_app_name());
4255#endif
4256 }
4257
4258 // Load the configured output_name first
4259 // to prevent the value being write to empty when the initial terminate happens
4260 if (!has_run && initial_display.empty()) {
4261 initial_display = config::video.output_name;
4262 } else {
4263 // Restore output name to its original value
4264 config::video.output_name = initial_display;
4265 }
4266
4267 _app_id = -1;
4268 _app_name.clear();
4269 _app = {};
4270 display_name.clear();
4271 initial_display.clear();
4272 mode_changed_display.clear();
4273 _launch_session.reset();
4274 virtual_display = false;
4275 allow_client_commands = false;
4276
4277 if (_saved_input_config) {
4278 config::input = *_saved_input_config;
4279 _saved_input_config.reset();
4280 }
4281
4282 if (needs_refresh) {
4283 refresh(config::stream.file_apps, false);
4284 }
4285 }
4286
4287 const std::vector<ctx_t> &proc_t::get_apps() const {
4288 return _apps;
4289 }
4290
4291 std::vector<ctx_t> &proc_t::get_apps() {
4292 return _apps;
4293 }
4294
4295 // Gets application image from application list.
4296 // Returns image from assets directory if found there.
4297 // Returns default image if image configuration is not set.
4298 // Returns http content-type header compatible image type.
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);
4302 });
4303 auto app_image_path = iter == _apps.end() ? std::string() : iter->image_path;
4304
4305 return validate_app_image_path(app_image_path);
4306 }
4307
4308 std::string proc_t::get_last_run_app_name() {
4309 return _app_name;
4310 }
4311
4312 std::string proc_t::get_running_app_uuid() {
4313 return _app.uuid;
4314 }
4315
4316 boost::process::environment proc_t::get_env() {
4317 return _env;
4318 }
4319
4320 proc_t::~proc_t() {
4321 // It's not safe to call terminate() here because our proc_t is a static variable
4322 // that may be destroyed after the Boost loggers have been destroyed. Instead,
4323 // we return a deinit_t to main() to handle termination when we're exiting.
4324 // Once we reach this point here, termination must have already happened.
4325 assert(!placebo);
4326 assert(!_process.running());
4327 }
4328
4329 std::string_view::iterator find_match(std::string_view::iterator begin, std::string_view::iterator end) {
4330 int stack = 0;
4331
4332 --begin;
4333 do {
4334 ++begin;
4335 switch (*begin) {
4336 case '(':
4337 ++stack;
4338 break;
4339 case ')':
4340 --stack;
4341 }
4342 } while (begin != end && stack != 0);
4343
4344 if (begin == end) {
4345 throw std::out_of_range("Missing closing bracket \')\'");
4346 }
4347 return begin;
4348 }
4349
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), '$');
4353
4354 std::stringstream ss;
4355
4356 while (dollar != std::end(val_raw)) {
4357 auto next = dollar + 1;
4358 if (next != std::end(val_raw)) {
4359 switch (*next) {
4360 case '(':
4361 {
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};
4366
4367
4368 ss << env[var_name].to_string();
4369
4370 pos = var_end + 1;
4371 next = var_end;
4372
4373 break;
4374 }
4375 case '$':
4376 ss.write(pos, (next - pos));
4377 pos = next + 1;
4378 ++next;
4379 break;
4380 }
4381
4382 dollar = std::find(next, std::end(val_raw), '$');
4383 } else {
4384 dollar = next;
4385 }
4386 }
4387
4388 ss.write(pos, (dollar - pos));
4389
4390 return ss.str();
4391 }
4392
4393 std::string validate_app_image_path(std::string app_image_path) {
4394 if (app_image_path.empty()) {
4395 return DEFAULT_APP_IMAGE_PATH;
4396 }
4397
4398 // get the image extension and convert it to lowercase
4399 auto image_extension = std::filesystem::path(app_image_path).extension().string();
4400 boost::to_lower(image_extension);
4401
4402 // return the default box image if extension is not "png"
4403 if (image_extension != ".png") {
4404 return DEFAULT_APP_IMAGE_PATH;
4405 }
4406
4407 // check if image is in assets directory
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") {
4412 // handle old default steam image definition
4413 return HERMES_ASSETS_DIR "/steam.png";
4414 }
4415
4416 // check if specified image exists
4417 std::error_code code;
4418 if (!std::filesystem::exists(app_image_path, code)) {
4419 // return default box image if image does not exist
4420 BOOST_LOG(warning) << "Couldn't find app image at path ["sv << app_image_path << ']';
4421 return DEFAULT_APP_IMAGE_PATH;
4422 }
4423
4424 // image is a png, and not in assets directory
4425 // return only "content-type" http header compatible image type
4426 return app_image_path;
4427 }
4428
4429 std::optional<std::string> calculate_sha256(const std::string &filename) {
4430 crypto::md_ctx_t ctx {EVP_MD_CTX_create()};
4431 if (!ctx) {
4432 return std::nullopt;
4433 }
4434
4435 if (!EVP_DigestInit_ex(ctx.get(), EVP_sha256(), nullptr)) {
4436 return std::nullopt;
4437 }
4438
4439 // Read file and update calculated SHA
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;
4446 }
4447 }
4448 file.close();
4449
4450 unsigned char result[SHA256_DIGEST_LENGTH];
4451 if (!EVP_DigestFinal_ex(ctx.get(), result, nullptr)) {
4452 return std::nullopt;
4453 }
4454
4455 // Transform byte-array to string
4456 std::stringstream ss;
4457 ss << std::hex << std::setfill('0');
4458 for (const auto &byte : result) {
4459 ss << std::setw(2) << (int) byte;
4460 }
4461 return ss.str();
4462 }
4463
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();
4468 }
4469
4470 std::tuple<std::string, std::string> calculate_app_id(const std::string &app_name, std::string app_image_path, int index) {
4471 // Generate id by hashing name with image data if present
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);
4477 if (file_hash) {
4478 to_hash.push_back(file_hash.value());
4479 } else {
4480 // Fallback to just hashing image path
4481 to_hash.push_back(file_path);
4482 }
4483 }
4484
4485 // Create combined strings for hash
4486 std::stringstream ss;
4487 for_each(to_hash.begin(), to_hash.end(), [&ss](const std::string &s) {
4488 ss << s;
4489 });
4490 auto input_no_index = ss.str();
4491 ss << index;
4492 auto input_with_index = ss.str();
4493
4494 // CRC32 then truncate to signed 32-bit range due to client limitations
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)));
4497
4498 return std::make_tuple(id_no_index, id_with_index);
4499 }
4500
4521 void migrate_apps(nlohmann::json* fileTree_p, nlohmann::json* inputTree_p) {
4522 std::string new_app_uuid;
4523
4524 if (inputTree_p) {
4525 // If the input contains a non-empty "uuid", use it; otherwise generate one.
4526 if (inputTree_p->contains("uuid") && !(*inputTree_p)["uuid"].get<std::string>().empty()) {
4527 new_app_uuid = (*inputTree_p)["uuid"].get<std::string>();
4528 } else {
4529 new_app_uuid = uuid_util::uuid_t::generate().string();
4530 (*inputTree_p)["uuid"] = new_app_uuid;
4531 }
4532
4533 // Remove "prep-cmd" if empty.
4534 if (inputTree_p->contains("prep-cmd") && (*inputTree_p)["prep-cmd"].empty()) {
4535 inputTree_p->erase("prep-cmd");
4536 }
4537
4538 // Remove "detached" if empty.
4539 if (inputTree_p->contains("detached") && (*inputTree_p)["detached"].empty()) {
4540 inputTree_p->erase("detached");
4541 }
4542
4543 // Remove keys that are no longer needed.
4544 inputTree_p->erase("launching");
4545 inputTree_p->erase("index");
4546 }
4547
4548 // Get the current apps array; if it doesn't exist, create one.
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"]) {
4552 // For apps without a UUID, generate one and remove "launching".
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));
4557 } else {
4558 // If an app with the same UUID as the new app is found, replace it.
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();
4562 } else {
4563 newApps.push_back(std::move(app));
4564 }
4565 }
4566 }
4567 }
4568 // If the new app's UUID has not been merged yet, add it.
4569 if (!new_app_uuid.empty() && inputTree_p) {
4570 newApps.push_back(*inputTree_p);
4571 }
4572 (*fileTree_p)["apps"] = newApps;
4573 }
4574
4575 void migration_v2(nlohmann::json& fileTree) {
4576 static const int this_version = 2;
4577 // Determine the current migration version (default to 1 if not present).
4578 int file_version = 1;
4579 if (fileTree.contains("version")) {
4580 try {
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();
4584 }
4585 }
4586
4587 // If the version is less than this_version, perform legacy conversion.
4588 if (file_version < this_version) {
4589 BOOST_LOG(info) << "Migrating app list from v1 to v2...";
4590 migrate_apps(&fileTree, nullptr);
4591
4592 // List of keys to convert to booleans.
4593 std::vector<std::string> boolean_keys = {
4594 "allow-client-commands",
4595 "exclude-global-prep-cmd",
4596 "elevated",
4597 "auto-detach",
4598 "wait-all",
4599 "use-app-identity",
4600 "per-client-app-identity",
4601 "virtual-display",
4602 "force-virtual-display",
4603 "force-scale-factor"
4604 };
4605
4606 // List of keys to convert to integers.
4607 std::vector<std::string> integer_keys = {
4608 "exit-timeout",
4609 "scale-factor"
4610 };
4611
4612 // Walk through each app and convert legacy string values.
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); // Normalize to lowercase for comparison
4620 _key = (s == "true" || s == "on" || s == "yes");
4621 } else if (_key.is_array()) {
4622 // Check if the array contains at least one item and interpret the first element
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); // Normalize
4626 if (first == "on" || first == "true" || first == "yes") {
4627 _key = true;
4628 } else if (first == "off" || first == "false" || first == "no") {
4629 _key = false;
4630 } else {
4631 _key = false; // Default for unknown values
4632 }
4633 } else {
4634 _key = false; // Treat empty arrays or non-string first elements as false
4635 }
4636 } else {
4637 // Fallback: Treat truthy/falsey cases
4638 if (_key.is_boolean()) {
4639 // Leave booleans as they are
4640 } else if (_key.is_number()) {
4641 _key = (_key.get<double>() != 0); // Non-zero numbers are truthy
4642 } else if (_key.is_null()) {
4643 _key = false; // Null is false
4644 } else {
4645 _key = !_key.empty(); // Non-empty objects/arrays are truthy, empty ones are falsey
4646 }
4647 }
4648 }
4649 }
4650
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);
4655 }
4656 }
4657
4658 // For each entry in the "prep-cmd" array, convert "elevated" if necessary.
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");
4664 }
4665 }
4666 }
4667 }
4668
4669 // Update migration version to this_version.
4670 fileTree["version"] = this_version;
4671
4672 BOOST_LOG(info) << "Migrated app list from v1 to v2.";
4673 }
4674 }
4675
4684 void migration_v3(nlohmann::json& fileTree) {
4685 static const int this_version = 3;
4686
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")) {
4690 continue;
4691 }
4692
4693 const std::string cmd = app.value("cmd", "");
4694 std::string first_token;
4695 std::istringstream tokens {cmd};
4696 tokens >> first_token;
4697
4698 bool is_launcher = first_token == "hermes-gamescope-launch" ||
4699 first_token == "apollo-gamescope-launch";
4700 if (!is_launcher &&
4701 app.value("name", "") == "Gamescope Steam Session" &&
4702 cmd.find("gamescope-launch") != std::string::npos) {
4703 is_launcher = true;
4704 }
4705
4706 if (is_launcher) {
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.";
4710 }
4711 }
4712 }
4713
4714 fileTree["version"] = this_version;
4715 }
4716
4723 void migration_v5(nlohmann::json& fileTree) {
4724 static const int this_version = 5;
4725 if (!fileTree.contains("apps") || !fileTree["apps"].is_array()) {
4726 fileTree["apps"] = nlohmann::json::array();
4727 }
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) {
4732 return;
4733 }
4734 }
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);
4740 break;
4741 }
4742 }
4743 BOOST_LOG(info) << "Adding app '" << entry.value("name", "") << "'.";
4744 apps.insert(position, std::move(entry));
4745 };
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},
4751 });
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},
4758 });
4759 fileTree["version"] = this_version;
4760 }
4761
4768 void migration_v6(nlohmann::json& fileTree) {
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"},
4775 }};
4776 for (auto &app : fileTree["apps"]) {
4777 if (!app.is_object()) {
4778 continue;
4779 }
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 << '.';
4784 }
4785 }
4786 }
4787 }
4788 fileTree["version"] = this_version;
4789 }
4790
4796 void migration_v7(nlohmann::json& fileTree) {
4797 static const int this_version = 7;
4798
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"},
4803 };
4804 static const std::map<std::string, std::string> names {
4805 {"Detached Desktop", "Desktop (KWin virtual)"},
4806 {"Detached Steam", "Steam (KWin virtual)"},
4807 };
4808 for (auto &app : fileTree["apps"]) {
4809 if (!app.is_object()) {
4810 continue;
4811 }
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;
4815 }
4816 if (app.value("session-type", "") == "shared") {
4817 app["host-session"] = true;
4818 }
4819 app.erase("session-type");
4820
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;
4825 }
4826 }
4827 }
4828
4829 fileTree["version"] = this_version;
4830 }
4831
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>();
4836 }
4837
4838 bool changed = false;
4839 if (file_version < 2) {
4840 migration_v2(fileTree);
4841 changed = true;
4842 }
4843 if (file_version < 3) {
4844 migration_v3(fileTree);
4845 changed = true;
4846 }
4847 if (file_version < 5) {
4848 migration_v5(fileTree);
4849 changed = true;
4850 }
4851 if (file_version < 6) {
4852 migration_v6(fileTree);
4853 changed = true;
4854 }
4855 if (file_version < 7) {
4856 migration_v7(fileTree);
4857 changed = true;
4858 }
4859 if (changed && persist) {
4860 file_handler::write_file(fileName.c_str(), fileTree.dump(4));
4861 }
4862 }
4863
4864 std::optional<proc::proc_t> parse(const std::string &file_name, bool fallback_on_failure) {
4865
4866 // Prepare environment variables.
4867 auto this_env = boost::this_process::environment();
4868
4869 std::set<std::string> ids;
4870 std::vector<proc::ctx_t> apps;
4871 int i = 0;
4872
4873 size_t fail_count = 0;
4874 // Whether every app in the file was loaded. A retry re-migrates from
4875 // scratch in memory only and never writes the file: a from-scratch
4876 // migration can add back entries the user removed (migration_v5 inserts
4877 // the detached apps when they're missing).
4878 bool loaded = false;
4879 do {
4880 // Read the JSON file into a tree.
4881 nlohmann::json tree;
4882 try {
4883 std::string content = file_handler::read_file(file_name.c_str());
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;
4887 break;
4888 }
4889
4890 try {
4891 migrate(tree, file_name);
4892
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>());
4896 }
4897 }
4898
4899 // Ensure the "apps" array exists.
4900 if (!tree.contains("apps") || !tree["apps"].is_array()) {
4901 BOOST_LOG(warning) << "No apps were defined in apps.json!!!"sv;
4902 break;
4903 }
4904
4905 // Iterate over each application in the "apps" array.
4906 for (auto &app_node : tree["apps"]) {
4907 proc::ctx_t ctx;
4908 ctx.idx = std::to_string(i);
4909 ctx.uuid = app_node.at("uuid");
4910 // Hermes' own detached entries exist only with independent sessions,
4911 // which are what makes a desktop detached.
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")) {
4914 continue;
4915 }
4916
4917 // Build the list of preparation commands.
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(
4926 std::move(do_cmd),
4927 std::move(undo_cmd),
4928 std::move(prep_cmd.elevated)
4929 );
4930 }
4931 }
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(
4938 std::move(do_cmd),
4939 std::move(undo_cmd),
4940 std::move(elevated)
4941 );
4942 }
4943 }
4944
4945 // Build the list of pause/resume commands.
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(
4954 std::move(do_cmd),
4955 std::move(undo_cmd),
4956 std::move(state_cmd.elevated)
4957 );
4958 }
4959 }
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(
4966 std::move(do_cmd),
4967 std::move(undo_cmd),
4968 std::move(elevated)
4969 );
4970 }
4971 }
4972
4973 // Build the list of detached commands.
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>()));
4978 }
4979 }
4980
4981 // Process other fields.
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", ""));
4989 }
4990 if (app_node.contains("image-path"))
4991 ctx.image_path = parse_env_val(this_env, app_node.value("image-path", ""));
4992
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";
5015 }
5016 ctx.host_session = app_node.value("host-session", false);
5017 {
5018 // Accepted as a number or a numeric string, the way an edited
5019 // apps.json tends to hold it; anything else means the default.
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()) {
5025 try {
5026 first_frame_timeout = std::stoi(it->get<std::string>());
5027 } catch (const std::exception &) {
5028 first_frame_timeout = 0;
5029 }
5030 }
5031 }
5032 if (first_frame_timeout < 0) {
5033 BOOST_LOG(warning) << "Negative first-frame-timeout for app " << name << "; using the default.";
5034 }
5035 ctx.first_frame_timeout = std::chrono::seconds {std::clamp(first_frame_timeout, 0, 600)};
5036 }
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";
5047 }
5048 auto mode = [&](const char *key) {
5049 std::string value = "auto";
5050 if (const auto it = app_node.find(key); it != app_node.end()) {
5051 // A boolean is how an earlier build of this branch stored
5052 // gamescope-steam-mode.
5053 value = it->is_boolean() ? (it->get<bool>() ? "on" : "off") :
5054 it->is_string() ? it->get<std::string>() :
5055 std::string {"auto"};
5056 }
5057 if (value != "auto" && value != "on" && value != "off") {
5058 BOOST_LOG(warning) << "Unknown " << key << " '" << value << "' for app " << name << "; using auto.";
5059 value = "auto";
5060 }
5061 return value;
5062 };
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", "");
5069
5070 // Calculate a unique application id.
5071 auto possible_ids = calculate_app_id(name, ctx.image_path, i++);
5072 if (ids.count(std::get<0>(possible_ids)) == 0) {
5073 ctx.id = std::get<0>(possible_ids);
5074 } else {
5075 ctx.id = std::get<1>(possible_ids);
5076 }
5077 ids.insert(ctx.id);
5078
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);
5083
5084 apps.emplace_back(std::move(ctx));
5085 }
5086
5087 fail_count = 0;
5088 loaded = true;
5089 } catch (std::exception &e) {
5090 BOOST_LOG(error) << "Error happened during app loading: "sv << e.what();
5091
5092 fail_count += 1;
5093
5094 if (fail_count >= 3) {
5095 // No hope for recovering
5096 BOOST_LOG(warning) << "Couldn't parse/migrate apps.json properly! Apps will not be loaded."sv;
5097 break;
5098 }
5099
5100 BOOST_LOG(warning) << "App format is still invalid! Trying to re-migrate the app list..."sv;
5101
5102 // Always try migrating from scratch when error happened
5103 tree["version"] = 0;
5104
5105 try {
5106 migrate(tree, file_name, false);
5107 } catch (std::exception &e) {
5108 BOOST_LOG(error) << "Error happened during migration: "sv << e.what();
5109 break;
5110 }
5111
5112 this_env = boost::this_process::environment();
5113 ids.clear();
5114 apps.clear();
5115 i = 0;
5116
5117 continue;
5118 }
5119
5120 break;
5121 } while (fail_count < 3);
5122
5123 if (!loaded && !fallback_on_failure) {
5124 // A reload that fails must not replace a working list with a fallback
5125 // (or with nothing but the built-in entries).
5126 BOOST_LOG(warning) << "Keeping the current application list: "sv << file_name << " could not be loaded"sv;
5127 return std::nullopt;
5128 }
5129
5130 if (fail_count > 0) {
5131 BOOST_LOG(warning) << "No applications configured, adding fallback Desktop entry.";
5132 proc::ctx_t ctx;
5133 ctx.idx = std::to_string(i);
5134 ctx.uuid = FALLBACK_DESKTOP_UUID; // Placeholder 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";
5145
5146 ctx.elevated = false;
5147 ctx.auto_detach = true;
5148 ctx.wait_all = false; // Desktop doesn't have a specific command to wait for
5149 ctx.exit_timeout = 5s;
5150
5151 // Calculate unique ID
5152 auto possible_ids = calculate_app_id(ctx.name, ctx.image_path, i++);
5153 if (ids.count(std::get<0>(possible_ids)) == 0) {
5154 // Avoid using index to generate id if possible
5155 ctx.id = std::get<0>(possible_ids);
5156 } else {
5157 // Fallback to include index on collision
5158 ctx.id = std::get<1>(possible_ids);
5159 }
5160 ids.insert(ctx.id);
5161
5162 apps.emplace_back(std::move(ctx));
5163 }
5164
5165 // Virtual Display entry
5166
5167 if (config::input.enable_input_only_mode) {
5168 // Input Only entry
5169 {
5170 proc::ctx_t ctx;
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; // There's no need to keep an active input only session ongoing
5181 ctx.unlock_host_session = false;
5182 ctx.host_session = true;
5183
5184 ctx.elevated = false;
5185 ctx.auto_detach = true;
5186 ctx.wait_all = true;
5187 ctx.exit_timeout = 5s;
5188
5189 auto possible_ids = calculate_app_id(ctx.name, ctx.image_path, i++);
5190 if (ids.count(std::get<0>(possible_ids)) == 0) {
5191 // Avoid using index to generate id if possible
5192 ctx.id = std::get<0>(possible_ids);
5193 }
5194 else {
5195 // Fallback to include index on collision
5196 ctx.id = std::get<1>(possible_ids);
5197 }
5198 ids.insert(ctx.id);
5199
5200 input_only_app_id_str = ctx.id;
5201 input_only_app_id = util::from_view(ctx.id);
5202
5203 apps.emplace_back(std::move(ctx));
5204 }
5205
5206 // Terminate entry
5207 {
5208 proc::ctx_t 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;
5221
5222 ctx.elevated = false;
5223 ctx.auto_detach = true;
5224 ctx.wait_all = true;
5225 ctx.exit_timeout = 5s;
5226
5227 auto possible_ids = calculate_app_id(ctx.name, ctx.image_path, i++);
5228 if (ids.count(std::get<0>(possible_ids)) == 0) {
5229 // Avoid using index to generate id if possible
5230 ctx.id = std::get<0>(possible_ids);
5231 }
5232 else {
5233 // Fallback to include index on collision
5234 ctx.id = std::get<1>(possible_ids);
5235 }
5236 // ids.insert(ctx.id);
5237
5238 terminate_app_id_str = ctx.id;
5239 terminate_app_id = util::from_view(ctx.id);
5240
5241 apps.emplace_back(std::move(ctx));
5242 }
5243 }
5244
5245 return proc::proc_t {
5246 std::move(this_env),
5247 std::move(apps)
5248 };
5249 }
5250
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);
5255 }
5256
5257
5258 // At startup there is no list to keep, so a file that can't be loaded
5259 // still gives the fallback Desktop entry.
5260 auto proc_opt = proc::parse(file_name, proc.get_apps().empty());
5261
5262 if (proc_opt) {
5263 proc = std::move(*proc_opt);
5264 }
5265 }
5266
5267#ifdef HERMES_TESTS
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
5286 ) {
5287 const auto profile = read_compositor_profile(std::filesystem::path {path}, name);
5288 if (!profile) {
5289 return false;
5290 }
5291
5292 command = expand_profile_template(profile->command, values);
5293 env.clear();
5294 for (const auto &[key, value] : profile->env) {
5295 env.emplace_back(key, expand_profile_template(value, values));
5296 }
5297 config_template = profile->config_template.empty() ?
5298 std::string {} :
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;
5303 return true;
5304 }
5305#endif
5306
5307} // namespace proc
5308
void release_host_sink()
Let go of a hold_host_sink() hold and restore the sink it recorded.
Definition audio.cpp:461
void hold_host_sink()
Record the host's default sink before a display change can move it.
Definition audio.cpp:435
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.
Definition audio.cpp:496
bool create_session_sink(const std::string &name, int channels)
Create the sink an isolated session records, and its own alone.
Definition audio.cpp:483
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)
Definition process.cpp:1865
int running_for_client(const std::string &client_uuid)
Definition process.cpp:3093
void terminate_isolated_client(const std::string &client_uuid)
Definition process.cpp:3051
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.
Definition process.cpp:3261
bool isolated_client_present(const std::string &client_uuid)
Definition process.cpp:3068
std::string isolated_audio_server(uint32_t launch_session_id)
Definition process.cpp:3273
std::string isolated_mic_source(uint32_t launch_session_id)
Definition process.cpp:3282
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...
Definition process.cpp:3291
void terminate_isolated(uint32_t launch_session_id)
Definition process.cpp:3019
void disconnect_isolated(uint32_t launch_session_id)
Definition process.cpp:3033
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)
Definition process.cpp:1729
bool any_running()
Definition process.cpp:3134
boost::process::v1::environment get_session_env(uint32_t launch_session_id)
Definition process.cpp:3180
bool prepare_isolated_resume(std::shared_ptr< rtsp_stream::launch_session_t > launch_session)
Definition process.cpp:3297
std::vector< isolated_session_t > list_isolated()
Definition process.cpp:3189
void terminate_all_isolated()
Definition process.cpp:3074
Declarations for common platform specific utilities.
bool process_group_running(std::uintptr_t native_handle)
Check if a process group still has running children.
Definition misc.cpp:1064
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...
Definition misc.cpp:1658
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).
Definition common.h:1025
bool request_process_group_exit(std::uintptr_t native_handle)
Attempt to gracefully terminate a process group.
Definition misc.cpp:1054
session_environment_t detect_session_environment()
Detect the current session/compositor environment.
Definition misc.cpp:1882
std::filesystem::path appdata()
Performs migration if necessary, then returns the appdata directory.
Definition misc.cpp:301
@ timeout
Timeout.
Definition common.h:438
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.
Definition wayland.cpp:1745
int command(const char *name, int argc, char *argv[])
hermes --prelogin status|enable|disable.
Definition prelogin.cpp:632
@ missing
Known to be absent; fix says what to do.
Definition prelogin.h:25
session_route_e resolve_session_route(const ctx_t &app, bool isolated_sessions_enabled, bool virtual_display_requested, std::string_view global_method)
Definition process.cpp:179
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.
Definition process.cpp:4521
std::string_view describe(virtual_display_source_e source)
Definition process.cpp:126
bool launch_requests_virtual_display(const ctx_t &app, const rtsp_stream::launch_session_t &launch_session, bool headless_mode)
Definition process.cpp:140
void migration_v7(nlohmann::json &fileTree)
Definition process.cpp:4796
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.
Definition process.cpp:1611
std::unique_ptr< platf::deinit_t > init()
Initialize proc functions.
Definition process.cpp:1601
virtual_display_decision_t decide_virtual_display(const ctx_t &app, const rtsp_stream::launch_session_t &launch_session, bool headless_mode)
Definition process.cpp:109
void migration_v3(nlohmann::json &fileTree)
Definition process.cpp:4684
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.
Definition process.cpp:4470
std::optional< proc::proc_t > parse(const std::string &file_name, bool fallback_on_failure)
Load the applications from apps.json.
Definition process.cpp:4864
void migration_v5(nlohmann::json &fileTree)
Definition process.cpp:4723
void migration_v6(nlohmann::json &fileTree)
Definition process.cpp:4768
void initVDisplayDriver()
Initialize the virtual display driver. This should be called early in startup to enable virtual displ...
Definition process.cpp:1580
scale_factor_decision_t decide_scale_factor(const ctx_t &app, const rtsp_stream::launch_session_t &launch_session, int host_default)
Definition process.cpp:148
Declarations for the startup and shutdown of the apps started by a streaming Session.
@ app_forced
The app forces its scale on every client.
Definition process.h:199
@ client
The client sent a scale.
Definition process.h:200
@ host_default
Neither did; the host's default_scale_factor.
Definition process.h:202
@ app
The client sent none; the app's own scale.
Definition process.h:201
virtual_display_source_e
Definition process.h:168
@ app_forced
The app forces its setting on every client.
Definition process.h:170
@ client
The client chose (Hestia's session/prepare).
Definition process.h:171
@ headless
The host runs headless; there is nothing else to stream.
Definition process.h:169
@ default_rule
No explicit choice: client request, per-client or app setting.
Definition process.h:172
session_route_e
Definition process.h:58
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.
Definition rtsp.cpp:773
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.
Definition session_bus.h:31
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.
Definition process.h:315
std::string unit
The systemd unit, where the session has one.
Definition process.h:327
std::string profile
"desktop" or "application".
Definition process.h:321
bool running
False for one whose compositor has died but was not reaped.
Definition process.h:329
std::string account_user
Empty where the session runs as the Hermes user.
Definition process.h:325
std::string audio_sink
Empty where the session shares the host's audio.
Definition process.h:328
std::optional< int > client_scale_factor
Definition rtsp.h:63
std::optional< bool > client_virtual_display
Definition rtsp.h:60
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.
Definition video.cpp:52
int probe_encoders()
Probe encoders and select the preferred encoder. This is called once at startup and each time a strea...
Definition video.cpp:3232
int probe_encoders_without_display()
Probe encoders without opening any screen.
Definition video.cpp:3224
Declarations for video.
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)