Hermes 0.7.0
Linux game streaming host
Loading...
Searching...
No Matches
misc.cpp
Go to the documentation of this file.
1
5
6// Required for in6_pktinfo with glibc headers
7#ifndef _GNU_SOURCE
8 #define _GNU_SOURCE 1
9#endif
10
11// standard includes
12#include <fstream>
13#include <iostream>
14#include <cstdio>
15#include <cerrno>
16#include <csignal>
17#include <cstring>
18#include <algorithm>
19#include <array>
20#include <chrono>
21#include <climits>
22#include <cstdint>
23#include <ctime>
24#include <mutex>
25#include <thread>
26#include <string_view>
27#include <utility>
28
29// platform includes
30#include <arpa/inet.h>
31#include <dlfcn.h>
32#include <ifaddrs.h>
33#include <netinet/udp.h>
34#include <pwd.h>
35
36// lib includes
37#include <boost/algorithm/string/case_conv.hpp>
38#include <boost/asio/ip/address.hpp>
39#include <boost/asio/ip/host_name.hpp>
40#include <boost/process/v1/group.hpp>
41#include <boost/process/v1/child.hpp>
42#include <boost/process/v1/env.hpp>
43#include <boost/process/v1/environment.hpp>
44#include <boost/process/v1/group.hpp>
45#include <boost/process/v1/handles.hpp>
46#include <boost/process/v1/io.hpp>
47#include <boost/process/v1/search_path.hpp>
48#include <boost/process/v1/start_dir.hpp>
49#include <fcntl.h>
50#include <sys/wait.h>
51#include <unistd.h>
52#include <xf86drm.h>
53
54// local includes
55#include "clipboard_process.h"
56#include "graphics.h"
57#include "misc.h"
58#include "process_group.h"
59#include "service_lifecycle.h"
60#include "session_attach.h"
61#include "src/config.h"
62#include "src/entry_handler.h"
63#include "src/logging.h"
64#include "src/network.h"
65#include "src/platform/common.h"
66#include "src/video.h"
67#include "vaapi.h"
68#include "virtual_display.h"
69
70#ifdef HERMES_BUILD_KWIN_TRANSPORT
71 #include "kwin_display.h"
72#endif
73
74#include <linux/rtnetlink.h>
75
76#ifdef HERMES_BUILD_SDBUS
77 #include <poll.h>
78 #include <sys/eventfd.h>
79 #include <systemd/sd-bus.h>
80#endif
81
82#ifdef __GNUC__
83 #define HERMES_GNUC_EXTENSION __extension__
84#else
85 #define HERMES_GNUC_EXTENSION
86#endif
87
88using namespace std::literals;
89namespace fs = std::filesystem;
90namespace bp = boost::process::v1;
91
92window_system_e window_system;
93
94namespace dyn {
95 void *handle(const std::vector<const char *> &libs) {
96 void *handle;
97
98 for (auto lib : libs) {
99 handle = dlopen(lib, RTLD_LAZY | RTLD_LOCAL);
100 if (handle) {
101 return handle;
102 }
103 }
104
105 std::stringstream ss;
106 ss << "Couldn't find any of the following libraries: ["sv << libs.front();
107 std::for_each(std::begin(libs) + 1, std::end(libs), [&](auto lib) {
108 ss << ", "sv << lib;
109 });
110
111 ss << ']';
112
113 BOOST_LOG(error) << ss.str();
114
115 return nullptr;
116 }
117
118 int load(void *handle, const std::vector<std::tuple<apiproc *, const char *>> &funcs, bool strict) {
119 int err = 0;
120 for (auto &func : funcs) {
121 TUPLE_2D_REF(fn, name, func);
122
123 *fn = HERMES_GNUC_EXTENSION(apiproc) dlsym(handle, name);
124
125 if (!*fn && strict) {
126 BOOST_LOG(error) << "Couldn't find function: "sv << name;
127
128 err = -1;
129 }
130 }
131
132 return err;
133 }
134} // namespace dyn
135
136namespace platf {
137
138 int open_drm_node(const char *path, int flags) {
139 const int fd = ::open(path, flags | O_CLOEXEC);
140 if (fd >= 0) {
141 // EINVAL when this fd is not master, and render nodes refuse the
142 // ioctl: either way there is nothing to give back.
143 const int saved_errno = errno;
144 (void) drmDropMaster(fd);
145 errno = saved_errno;
146 }
147 return fd;
148 }
149
150#ifdef HERMES_BUILD_SDBUS
151 int open_user_bus(sd_bus **result) {
152 if (!result) {
153 return -EINVAL;
154 }
155 *result = nullptr;
156
157 const int discovered = sd_bus_open_user(result);
158 if (discovered >= 0) {
159 return discovered;
160 }
161 if (*result) {
162 sd_bus_unref(*result);
163 *result = nullptr;
164 }
165 if (discovered != -ENOMEDIUM) {
166 return discovered;
167 }
168
169 sd_bus *bus = nullptr;
170 int status = sd_bus_new(&bus);
171 if (status < 0) {
172 return status;
173 }
174 const auto fail = [&bus](int error) {
175 sd_bus_unref(bus);
176 return error;
177 };
178
179 const auto address = VDISPLAY::systemdUserBusAddress(static_cast<uint32_t>(::getuid()));
180 status = sd_bus_set_address(bus, address.c_str());
181 if (status < 0) {
182 return fail(status);
183 }
184 status = sd_bus_set_bus_client(bus, 1);
185 if (status < 0) {
186 return fail(status);
187 }
188 status = sd_bus_start(bus);
189 if (status < 0) {
190 return fail(status);
191 }
192
193 *result = bus;
194 return 0;
195 }
196#endif
197
199 // KWin picks an output for every touchscreen and tablet (its own guess
200 // when nothing is configured, the streamed output once Hermes binds it),
201 // and Mutter does the same through MetaInputMapper. wlroots compositors
202 // leave an unmapped device spanning the whole layout, and X11 has no
203 // per-output mapping at all, so there the desktop is the surface.
204 const auto compositor = VDISPLAY::sessionCompositor();
205 return compositor == VDISPLAY::compositor_e::kwin || compositor == VDISPLAY::compositor_e::mutter;
206 }
207
208 using ifaddr_t = util::safe_ptr<ifaddrs, freeifaddrs>;
209
210 ifaddr_t get_ifaddrs() {
211 ifaddrs *p {nullptr};
212
213 getifaddrs(&p);
214
215 return ifaddr_t {p};
216 }
217
218 namespace {
219 // Hermes used to store its configuration in ~/.config/sunshine, the very directory
220 // Apollo and Sunshine use. All three then shared one credentials file, one apps list
221 // and one paired-client list, so installing Hermes next to either of them silently
222 // took over their setup — and made a reinstall look like it had kept the old
223 // password. Hermes now keeps its own directory.
224 constexpr auto CONFIG_DIR_NAME = "hermes"sv;
225 constexpr auto SHARED_CONFIG_DIR_NAME = "sunshine"sv;
226
227 // Files that are renamed along with the directory. Keep in sync with the defaults in
228 // src/config.cpp.
229 constexpr std::pair<std::string_view, std::string_view> RENAMED_CONFIG_FILES[] {
230 {"sunshine.conf"sv, "hermes.conf"sv},
231 {"sunshine_state.json"sv, "hermes_state.json"sv},
232 };
233
240 void rename_shared_config_files(const fs::path &config_path) {
241 for (const auto &[shared_name, name] : RENAMED_CONFIG_FILES) {
242 std::error_code ec;
243 const fs::path shared_file = config_path / shared_name;
244 const fs::path file = config_path / name;
245 if (fs::exists(shared_file, ec) && !fs::exists(file, ec)) {
246 fs::rename(shared_file, file, ec);
247 if (ec) {
248 std::cerr << "Failed to rename "sv << shared_file << " to "sv << file << ": "sv << ec.message() << std::endl;
249 }
250 }
251 }
252 }
253
262 void seed_from_shared_config(const fs::path &config_path, const fs::path &shared_path) {
263 std::error_code ec;
264 if (!fs::is_directory(shared_path, ec)) {
265 return;
266 }
267 // An empty directory still counts as a first run. The AppImage's AppRun pre-creates
268 // the config directory before launching, and users creating it by hand is common
269 // enough that treating it as "already migrated" would silently skip the seeding.
270 if (fs::is_directory(config_path, ec) && !fs::is_empty(config_path, ec)) {
271 return;
272 }
273
274 std::cout << "Seeding "sv << config_path << " from "sv << shared_path << std::endl;
275 fs::create_directories(config_path, ec);
276 if (!ec) {
277 fs::copy(shared_path, config_path, fs::copy_options::recursive | fs::copy_options::copy_symlinks, ec);
278 }
279 if (ec) {
280 std::cerr << "Could not seed the Hermes config directory: "sv << ec.message() << std::endl;
281 std::cerr << "Hermes will start with a fresh configuration in "sv << config_path << std::endl;
282 return;
283 }
284
285 // Logs are the one thing not worth inheriting: a log that starts mid-way through
286 // another host's session is actively misleading when diagnosing Hermes.
287 for (const auto &name : {"sunshine.log"sv, "sunshine.log.backup"sv}) {
288 fs::remove(config_path / name, ec);
289 }
290 ec.clear();
291
292 std::cout << shared_path << " was left untouched; Apollo and Sunshine keep using it."sv << std::endl;
293 }
294 } // namespace
295
301 fs::path appdata() {
302 static std::once_flag migration_flag;
303 static fs::path config_path;
304
305 // Ensure migration is only attempted once
306 std::call_once(migration_flag, []() {
307 bool found = false;
308 bool migrate_config = true;
309 const char *dir;
310 const char *homedir;
311 const char *migrate_envvar;
312
313 // Get the home directory
314 if ((homedir = getenv("HOME")) == nullptr || strlen(homedir) == 0) {
315 // If HOME is empty or not set, use the current user's home directory
316 homedir = getpwuid(geteuid())->pw_dir;
317 }
318
319 // May be set if running under a systemd service with the ConfigurationDirectory= option set.
320 if ((dir = getenv("CONFIGURATION_DIRECTORY")) != nullptr && strlen(dir) > 0) {
321 found = true;
322 config_path = fs::path(dir) / CONFIG_DIR_NAME;
323 }
324 // Otherwise, follow the XDG base directory specification:
325 // https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
326 if (!found && (dir = getenv("XDG_CONFIG_HOME")) != nullptr && strlen(dir) > 0) {
327 found = true;
328 config_path = fs::path(dir) / CONFIG_DIR_NAME;
329 }
330 // As a last resort, use the home directory
331 if (!found) {
332 migrate_config = false;
333 config_path = fs::path(homedir) / ".config" / CONFIG_DIR_NAME;
334 }
335
336 // migrate from the old config location if necessary
337 migrate_envvar = getenv("SUNSHINE_MIGRATE_CONFIG");
338 if (migrate_config && found && migrate_envvar && strcmp(migrate_envvar, "1") == 0) {
339 std::error_code ec;
340 fs::path old_config_path = fs::path(homedir) / ".config" / CONFIG_DIR_NAME;
341 if (old_config_path != config_path && fs::exists(old_config_path, ec)) {
342 if (!fs::exists(config_path, ec)) {
343 std::cout << "Migrating config from "sv << old_config_path << " to "sv << config_path << std::endl;
344 if (!ec) {
345 // Create the new directory tree if it doesn't already exist
346 fs::create_directories(config_path, ec);
347 }
348 if (!ec) {
349 // Copy the old directory into the new location
350 // NB: We use a copy instead of a move so that cross-volume migrations work
351 fs::copy(old_config_path, config_path, fs::copy_options::recursive | fs::copy_options::copy_symlinks, ec);
352 }
353 if (!ec) {
354 // If the copy was successful, delete the original directory
355 fs::remove_all(old_config_path, ec);
356 if (ec) {
357 std::cerr << "Failed to clean up old config directory: " << ec.message() << std::endl;
358
359 // This is not fatal. Next time we start, we'll warn the user to delete the old one.
360 ec.clear();
361 }
362 }
363 if (ec) {
364 std::cerr << "Migration failed: " << ec.message() << std::endl;
365 config_path = old_config_path;
366 }
367 } else {
368 // We cannot use Boost logging because it hasn't been initialized yet!
369 std::cerr << "Config exists in both "sv << old_config_path << " and "sv << config_path << ". Using "sv << config_path << " for config" << std::endl;
370 std::cerr << "It is recommended to remove "sv << old_config_path << std::endl;
371 }
372 }
373 }
374
375 // Carry an install that predates the rename over from the shared Sunshine directory.
376 seed_from_shared_config(config_path, config_path.parent_path() / SHARED_CONFIG_DIR_NAME);
377 rename_shared_config_files(config_path);
378 });
379
380 return config_path;
381 }
382
383 std::string from_sockaddr(const sockaddr *const ip_addr) {
384 char data[INET6_ADDRSTRLEN] = {};
385
386 auto family = ip_addr->sa_family;
387 if (family == AF_INET6) {
388 inet_ntop(AF_INET6, &((sockaddr_in6 *) ip_addr)->sin6_addr, data, INET6_ADDRSTRLEN);
389 } else if (family == AF_INET) {
390 inet_ntop(AF_INET, &((sockaddr_in *) ip_addr)->sin_addr, data, INET_ADDRSTRLEN);
391 }
392
393 return std::string {data};
394 }
395
396 std::pair<std::uint16_t, std::string> from_sockaddr_ex(const sockaddr *const ip_addr) {
397 char data[INET6_ADDRSTRLEN] = {};
398
399 auto family = ip_addr->sa_family;
400 std::uint16_t port = 0;
401 if (family == AF_INET6) {
402 inet_ntop(AF_INET6, &((sockaddr_in6 *) ip_addr)->sin6_addr, data, INET6_ADDRSTRLEN);
403 port = ((sockaddr_in6 *) ip_addr)->sin6_port;
404 } else if (family == AF_INET) {
405 inet_ntop(AF_INET, &((sockaddr_in *) ip_addr)->sin_addr, data, INET_ADDRSTRLEN);
406 port = ((sockaddr_in *) ip_addr)->sin_port;
407 }
408
409 return {port, std::string {data}};
410 }
411
412 std::string get_mac_address(const std::string_view &address) {
413 // Compare addresses, not text: the address a client reached prints a
414 // link-local scope (`fe80::1%eth0`) that inet_ntop() leaves out, so a
415 // string match never found the interface of a link-local connection.
416 boost::system::error_code ec;
417 const auto parsed = boost::asio::ip::make_address(std::string {address}, ec);
418 if (ec) {
419 BOOST_LOG(warning) << "Unable to find MAC address for "sv << address << ": "sv << ec.message();
420 return "00:00:00:00:00:00"s;
421 }
422 const auto wanted = net::to_raw_address(parsed);
423
424 auto ifaddrs = get_ifaddrs();
425 for (auto pos = ifaddrs.get(); pos != nullptr; pos = pos->ifa_next) {
426 const auto candidate = net::raw_from_sockaddr(pos->ifa_addr);
427 if (candidate && net::same_address(*candidate, wanted)) {
428 std::ifstream mac_file("/sys/class/net/"s + pos->ifa_name + "/address");
429 if (mac_file.good()) {
430 std::string mac_address;
431 std::getline(mac_file, mac_address);
432 return mac_address;
433 }
434 }
435 }
436
437 BOOST_LOG(warning) << "Unable to find MAC address for "sv << address;
438 return "00:00:00:00:00:00"s;
439 }
440
441std::string get_local_ip_for_gateway() {
442 int fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
443 if (fd < 0) {
444 BOOST_LOG(warning) << "Socket creation failed: " << strerror(errno);
445 return "";
446 }
447
448 char buffer[8192];
449 struct nlmsghdr *nlMsg = (struct nlmsghdr *)buffer;
450 struct rtmsg *rtMsg = (struct rtmsg *)NLMSG_DATA(nlMsg);
451 struct rtattr *rtAttr;
452 int len = 0;
453
454 memset(nlMsg, 0, sizeof(struct nlmsghdr));
455 nlMsg->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));
456 nlMsg->nlmsg_type = RTM_GETROUTE;
457 nlMsg->nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST;
458 nlMsg->nlmsg_seq = 1;
459 nlMsg->nlmsg_pid = getpid();
460
461 if (send(fd, nlMsg, nlMsg->nlmsg_len, 0) < 0) {
462 BOOST_LOG(warning) << "Send message failed: " << strerror(errno);
463 close(fd);
464 return "";
465 }
466
467 std::string local_ip;
468 bool found = false;
469
470 while ((len = recv(fd, nlMsg, sizeof(buffer), 0)) > 0) {
471 for (; NLMSG_OK(nlMsg, len); nlMsg = NLMSG_NEXT(nlMsg, len)) {
472 if (nlMsg->nlmsg_type == NLMSG_DONE) {
473 found = true;
474 break;
475 }
476
477 rtMsg = (struct rtmsg *)NLMSG_DATA(nlMsg);
478 if (rtMsg->rtm_family != AF_INET || rtMsg->rtm_table != RT_TABLE_MAIN)
479 continue;
480
481 rtAttr = (struct rtattr *)RTM_RTA(rtMsg);
482 int rtLen = RTM_PAYLOAD(nlMsg);
483
484 in_addr gateway;
485 in_addr local;
486 memset(&gateway, 0, sizeof(gateway));
487 memset(&local, 0, sizeof(local));
488
489 for (; RTA_OK(rtAttr, rtLen); rtAttr = RTA_NEXT(rtAttr, rtLen)) {
490 switch(rtAttr->rta_type) {
491 case RTA_GATEWAY:
492 gateway.s_addr = *reinterpret_cast<uint32_t *>(RTA_DATA(rtAttr));
493 break;
494 case RTA_PREFSRC:
495 local.s_addr = *reinterpret_cast<uint32_t *>(RTA_DATA(rtAttr));
496 break;
497 default:
498 break;
499 }
500 }
501
502 if (gateway.s_addr != 0 && local.s_addr != 0) {
503 local_ip = inet_ntoa(local);
504 found = true;
505 break;
506 }
507 }
508
509 if (found) break;
510 }
511
512 close(fd);
513
514 if (local_ip.empty()) {
515 BOOST_LOG(warning) << "No associated IP address found for the default gateway";
516 }
517
518 return local_ip;
519}
520
521 bp::child run_command(bool elevated, bool interactive, const std::string &cmd, boost::filesystem::path &working_dir, const bp::environment &env, FILE *file, std::error_code &ec, bp::group *group) {
522 // clang-format off
523 if (!group) {
524 if (!file) {
525 return bp::child(cmd, env, bp::start_dir(working_dir), bp::std_in < bp::null, bp::std_out > bp::null, bp::std_err > bp::null, bp::limit_handles, ec);
526 }
527 else {
528 return bp::child(cmd, env, bp::start_dir(working_dir), bp::std_in < bp::null, bp::std_out > file, bp::std_err > file, bp::limit_handles, ec);
529 }
530 }
531 else {
532 if (!file) {
533 return bp::child(cmd, env, bp::start_dir(working_dir), bp::std_in < bp::null, bp::std_out > bp::null, bp::std_err > bp::null, bp::limit_handles, ec, *group);
534 }
535 else {
536 return bp::child(cmd, env, bp::start_dir(working_dir), bp::std_in < bp::null, bp::std_out > file, bp::std_err > file, bp::limit_handles, ec, *group);
537 }
538 }
539 // clang-format on
540 }
541
546 void open_url(const std::string &url) {
547 // set working dir to user home directory
548 auto working_dir = boost::filesystem::path(std::getenv("HOME"));
549 std::string cmd = R"(xdg-open ")" + url + R"(")";
550
551 boost::process::v1::environment _env = boost::this_process::environment();
552 std::error_code ec;
553 auto child = run_command(false, false, cmd, working_dir, _env, nullptr, ec, nullptr);
554 if (ec) {
555 BOOST_LOG(warning) << "Couldn't open url ["sv << url << "]: System: "sv << ec.message();
556 } else {
557 BOOST_LOG(info) << "Opened url ["sv << url << "]"sv;
558 child.detach();
559 }
560 }
561
562 void adjust_thread_priority(thread_priority_e priority) {
563 // Unimplemented
564 }
565
566 namespace {
567#ifdef HERMES_BUILD_SDBUS
568 constexpr auto screen_saver_service = "org.freedesktop.ScreenSaver"sv;
569 constexpr auto screen_saver_path = "/org/freedesktop/ScreenSaver"sv;
570 constexpr auto screen_saver_interface = "org.freedesktop.ScreenSaver"sv;
571
572 // All sd-bus operations belong to a worker thread. The stream hooks only
573 // publish the desired state and wake the worker, so a slow or wedged
574 // screensaver cannot block session transitions, which are serialized by
575 // stream::session_activity_counter_t while these hooks run.
576 struct screen_lock_bus_t {
577 using clock = std::chrono::steady_clock;
578
579 sd_bus *bus {nullptr};
580 sd_bus_slot *owner_watch {nullptr};
581 std::uint32_t cookie {0};
582 // Unique bus name of the service instance which issued the cookie.
583 // NameOwnerChanged signals from *older* instances must not invalidate
584 // an inhibition already re-established on a replacement instance.
585 std::string cookie_owner;
586 bool inhibited {false};
587 bool failure_logged {false};
588 // Earliest time to connect or call Inhibit again. clock::time_point::max()
589 // means "wait until org.freedesktop.ScreenSaver gets an owner".
590 clock::time_point retry_at {};
591 // Next back-off step; zero restarts the back-off.
592 clock::duration retry_delay {};
593 };
594
595 std::string bus_error_message(const sd_bus_error &error, int status) {
596 if (error.message) {
597 return error.message;
598 }
599 return std::strerror(-status);
600 }
601
602 bool screen_saver_has_no_owner(const sd_bus_error &error) {
603 return sd_bus_error_has_name(&error, SD_BUS_ERROR_SERVICE_UNKNOWN) ||
604 sd_bus_error_has_name(&error, SD_BUS_ERROR_NAME_HAS_NO_OWNER);
605 }
606
607 class screen_lock_inhibitor_t {
608 public:
609 screen_lock_inhibitor_t():
610 wake_fd_ {::eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK)},
611 wake_errno_ {wake_fd_ < 0 ? errno : 0} {
612 }
613
614 screen_lock_inhibitor_t(const screen_lock_inhibitor_t &) = delete;
615 screen_lock_inhibitor_t &operator=(const screen_lock_inhibitor_t &) = delete;
616
617 ~screen_lock_inhibitor_t() {
618 // The eventfd is level-triggered, so this wakeup cannot be lost even if
619 // the worker is between checking the stop token and blocking in poll().
620 // Join explicitly so wake_fd_ outlives the worker.
621 worker_.request_stop();
622 wake();
623 if (worker_.joinable()) {
624 worker_.join();
625 }
626 if (wake_fd_ >= 0) {
627 ::close(wake_fd_);
628 }
629 }
630
631 void set_streaming(bool streaming) {
632 {
633 std::lock_guard lock {mutex_};
634 streaming_ = streaming;
635 if (streaming && !worker_.joinable()) {
636 if (wake_fd_ < 0) {
637 if (!wake_failure_logged_) {
638 BOOST_LOG(warning) << "Could not inhibit screen locking: eventfd() failed: "sv
639 << std::strerror(wake_errno_);
640 wake_failure_logged_ = true;
641 }
642 return;
643 }
644 worker_ = std::jthread {[this](std::stop_token stop) {
645 run(stop);
646 }};
647 }
648 }
649 wake();
650 }
651
652 private:
653 using clock = screen_lock_bus_t::clock;
654
655 static constexpr auto initial_retry_delay = std::chrono::seconds {2};
656 static constexpr auto max_retry_delay = std::chrono::seconds {30};
657 static constexpr auto never = clock::time_point::max();
658
659 std::mutex mutex_;
660 bool streaming_ {false};
661 bool wake_failure_logged_ {false};
662 const int wake_fd_;
663 const int wake_errno_;
664 std::jthread worker_;
665
666 void wake() {
667 if (wake_fd_ < 0) {
668 return;
669 }
670 const std::uint64_t one = 1;
671 while (::write(wake_fd_, &one, sizeof(one)) < 0 && errno == EINTR) {
672 }
673 }
674
675 void consume_wakeups() {
676 std::uint64_t count = 0;
677 while (::read(wake_fd_, &count, sizeof(count)) < 0 && errno == EINTR) {
678 }
679 }
680
681 bool wants_inhibition() {
682 std::lock_guard lock {mutex_};
683 return streaming_;
684 }
685
690 bool wait_for_event(const screen_lock_bus_t &state, clock::time_point deadline) {
691 std::array<pollfd, 2> fds {};
692 nfds_t count = 0;
693 fds[count++] = pollfd {wake_fd_, POLLIN, 0};
694
695 if (state.bus) {
696 const int fd = sd_bus_get_fd(state.bus);
697 const int events = sd_bus_get_events(state.bus);
698 std::uint64_t bus_deadline_usec = UINT64_MAX;
699 const int has_bus_deadline = sd_bus_get_timeout(state.bus, &bus_deadline_usec);
700 if (fd < 0 || events < 0 || has_bus_deadline < 0) {
701 return false;
702 }
703 fds[count++] = pollfd {fd, static_cast<short>(events), 0};
704
705 // sd-bus reports an absolute CLOCK_MONOTONIC deadline. It is zero
706 // when messages are already queued, so poll() returns immediately.
707 if (has_bus_deadline > 0 && bus_deadline_usec != UINT64_MAX) {
708 timespec now {};
709 ::clock_gettime(CLOCK_MONOTONIC, &now);
710 const auto now_usec = static_cast<std::uint64_t>(now.tv_sec) * 1'000'000u +
711 static_cast<std::uint64_t>(now.tv_nsec) / 1'000u;
712 const auto remaining = std::chrono::microseconds {
713 bus_deadline_usec > now_usec ? bus_deadline_usec - now_usec : 0
714 };
715 deadline = std::min(deadline, clock::now() + remaining);
716 }
717 }
718
719 int timeout_ms = -1;
720 if (deadline != never) {
721 const auto remaining = std::chrono::ceil<std::chrono::milliseconds>(deadline - clock::now());
722 timeout_ms = static_cast<int>(std::clamp<std::chrono::milliseconds::rep>(remaining.count(), 0, INT_MAX));
723 }
724
725 if (::poll(fds.data(), count, timeout_ms) < 0 && errno != EINTR) {
726 // Not expected for valid descriptors; avoid spinning if it happens.
727 std::this_thread::sleep_for(std::chrono::milliseconds {100});
728 return !state.bus;
729 }
730 return true;
731 }
732
733 static void warn_once(screen_lock_bus_t &state, const std::string &message) {
734 if (!state.failure_logged) {
735 BOOST_LOG(warning) << message;
736 state.failure_logged = true;
737 }
738 }
739
740 static void retry_now(screen_lock_bus_t &state) {
741 state.retry_at = clock::now();
742 state.retry_delay = {};
743 }
744
745 static void schedule_retry(screen_lock_bus_t &state) {
746 const clock::duration delay = state.retry_delay > clock::duration::zero() ? state.retry_delay : clock::duration {initial_retry_delay};
747 state.retry_at = clock::now() + delay;
748 state.retry_delay = std::min<clock::duration>(delay * 2, max_retry_delay);
749 }
750
751 static int on_owner_changed(sd_bus_message *message, void *userdata, sd_bus_error *) {
752 auto *state = static_cast<screen_lock_bus_t *>(userdata);
753 const char *name = nullptr;
754 const char *old_owner = nullptr;
755 const char *new_owner = nullptr;
756 if (sd_bus_message_read(message, "sss", &name, &old_owner, &new_owner) < 0) {
757 return 0;
758 }
759 if (std::strcmp(name, screen_saver_service.data()) != 0 ||
760 std::strcmp(old_owner, new_owner) == 0) {
761 return 0;
762 }
763
764 // A late NameOwnerChanged for the PREVIOUS screensaver may be queued
765 // after an Inhibit reply from the NEW screensaver. Only invalidate
766 // cookies issued by the owner which actually disappeared.
767 if (state->inhibited && state->cookie_owner == old_owner) {
768 state->inhibited = false;
769 state->cookie = 0;
770 state->cookie_owner.clear();
771 if (new_owner[0] != '\0') {
772 retry_now(*state);
773 } else {
774 // Give a restarting screensaver a moment; its NameOwnerChanged
775 // brings the retry forward as soon as it is back.
776 state->retry_delay = {};
777 schedule_retry(*state);
778 }
779 } else if (!state->inhibited && new_owner[0] != '\0') {
780 // A service just appeared after a failed attempt: retry promptly.
781 retry_now(*state);
782 }
783 return 0;
784 }
785
786 static bool dispatch(screen_lock_bus_t &state) {
787 int processed = 0;
788 while ((processed = sd_bus_process(state.bus, nullptr)) > 0) {
789 }
790 return processed >= 0;
791 }
792
793 static void close_bus(screen_lock_bus_t &state, bool release_inhibition) {
794 if (!state.bus) {
795 return;
796 }
797 if (release_inhibition && state.inhibited) {
798 // If the issuing screensaver is already gone, its queued
799 // NameOwnerChanged clears the cookie and there is nothing to release.
800 dispatch(state);
801 }
802 if (release_inhibition && state.inhibited) {
803 sd_bus_error error = SD_BUS_ERROR_NULL;
804 // Target the instance which issued this cookie, not the well-known
805 // name that may now belong to a different screensaver process.
806 const int status = sd_bus_call_method(
807 state.bus,
808 state.cookie_owner.c_str(),
809 screen_saver_path.data(),
810 screen_saver_interface.data(),
811 "UnInhibit",
812 &error,
813 nullptr,
814 "u",
815 state.cookie
816 );
817 if (status >= 0) {
818 BOOST_LOG(info) << "Released screen-lock inhibition."sv;
819 } else if (screen_saver_has_no_owner(error)) {
820 BOOST_LOG(debug) << "The screensaver holding our inhibition is gone; nothing to release."sv;
821 } else {
822 BOOST_LOG(warning) << "Could not release screen-lock inhibition: "sv
823 << bus_error_message(error, status);
824 }
825 sd_bus_error_free(&error);
826 }
827 // Closing the caller's bus connection also releases the inhibition
828 // if UnInhibit failed.
829 sd_bus_slot_unref(state.owner_watch);
830 state.owner_watch = nullptr;
831 sd_bus_unref(state.bus);
832 state.bus = nullptr;
833 state.inhibited = false;
834 state.cookie = 0;
835 state.cookie_owner.clear();
836 state.retry_at = {};
837 }
838
839 static bool connect_bus(screen_lock_bus_t &state) {
840 sd_bus *bus = nullptr;
841 const int opened = open_user_bus(&bus);
842 if (opened < 0 || !bus) {
843 warn_once(state, "Could not connect to the D-Bus session bus to inhibit screen locking.");
844 return false;
845 }
846
847 state.bus = bus;
848 sd_bus_set_method_call_timeout(bus, 2'000'000);
849
850 // Watch the owner, not merely the connection. Desktop components can
851 // restart without disconnecting Hermes from the user bus.
852 constexpr auto match =
853 "type='signal',sender='org.freedesktop.DBus',"
854 "interface='org.freedesktop.DBus',member='NameOwnerChanged',"
855 "arg0='org.freedesktop.ScreenSaver'";
856 const int matched = sd_bus_add_match(bus, &state.owner_watch, match, on_owner_changed, &state);
857 if (matched < 0) {
858 warn_once(state, "Could not watch org.freedesktop.ScreenSaver ownership changes.");
859 close_bus(state, false);
860 return false;
861 }
862
863 state.retry_at = clock::now();
864 return true;
865 }
866
867 static void acquire_inhibition(screen_lock_bus_t &state) {
868 sd_bus_error error = SD_BUS_ERROR_NULL;
869 sd_bus_message *reply = nullptr;
870 const int status = sd_bus_call_method(
871 state.bus,
872 screen_saver_service.data(),
873 screen_saver_path.data(),
874 screen_saver_interface.data(),
875 "Inhibit",
876 &error,
877 &reply,
878 "ss",
879 "Hermes",
880 "Streaming a client"
881 );
882
883 std::uint32_t cookie = 0;
884 const int read_status = status < 0 ? status : (reply ? sd_bus_message_read(reply, "u", &cookie) : -EIO);
885 const char *reply_owner = read_status >= 0 ? sd_bus_message_get_sender(reply) : nullptr;
886 if (read_status < 0) {
887 if (status < 0) {
888 warn_once(state, "Could not inhibit screen locking through org.freedesktop.ScreenSaver: " + bus_error_message(error, status));
889 } else {
890 warn_once(state, "The screensaver returned an unexpected Inhibit reply.");
891 }
892 if (status < 0 && screen_saver_has_no_owner(error)) {
893 // Nothing to retry until a screensaver appears; NameOwnerChanged
894 // reports that without polling the bus for the whole stream.
895 state.retry_at = never;
896 } else {
897 schedule_retry(state);
898 }
899 } else if (!reply_owner || !*reply_owner) {
900 warn_once(state, "The screensaver did not identify the owner of its inhibition cookie.");
901 schedule_retry(state);
902 } else {
903 state.cookie = cookie;
904 state.cookie_owner = reply_owner;
905 state.inhibited = true;
906 state.failure_logged = false;
907 state.retry_delay = {};
908 BOOST_LOG(info) << "Inhibited screen locking while a client is connected."sv;
909 }
910
911 sd_bus_error_free(&error);
912 sd_bus_message_unref(reply);
913 }
914
915 void run(std::stop_token stop) {
916 screen_lock_bus_t state;
917 for (;;) {
918 // Consume wakeups BEFORE reading the state they announce: a stop or
919 // set_streaming() racing with this iteration leaves the eventfd
920 // readable, so the next poll() returns instead of sleeping on it.
921 consume_wakeups();
922 if (stop.stop_requested()) {
923 break;
924 }
925
926 if (!wants_inhibition()) {
927 close_bus(state, true);
928 state.retry_delay = {};
929 wait_for_event(state, never);
930 continue;
931 }
932
933 if (!state.bus) {
934 if (clock::now() < state.retry_at) {
935 wait_for_event(state, state.retry_at);
936 continue;
937 }
938 if (!connect_bus(state)) {
939 schedule_retry(state);
940 continue;
941 }
942 }
943
944 // Dispatch owner changes queued on the socket or by an earlier
945 // synchronous call before deciding whether to (re)acquire.
946 if (!dispatch(state)) {
947 warn_once(state, "Lost the D-Bus session bus while inhibiting screen locking.");
948 close_bus(state, false);
949 schedule_retry(state);
950 continue;
951 }
952
953 if (!state.inhibited && clock::now() >= state.retry_at) {
954 acquire_inhibition(state);
955 // Dispatch whatever arrived during the call before sleeping.
956 continue;
957 }
958
959 if (!wait_for_event(state, state.inhibited ? never : state.retry_at)) {
960 warn_once(state, "Lost the D-Bus session bus while inhibiting screen locking.");
961 close_bus(state, false);
962 schedule_retry(state);
963 }
964 }
965 close_bus(state, true);
966 }
967 };
968
969 screen_lock_inhibitor_t &screen_lock() {
970 static screen_lock_inhibitor_t inhibitor;
971 return inhibitor;
972 }
973
974 void inhibit_screen_lock() {
975 screen_lock().set_streaming(true);
976 }
977
978 void uninhibit_screen_lock() {
979 screen_lock().set_streaming(false);
980 }
981#else
982 void inhibit_screen_lock() {
983 static std::once_flag warned;
984 std::call_once(warned, [] {
985 BOOST_LOG(warning) << "inhibit_screen_lock is enabled, but this build has no libsystemd "
986 "support for org.freedesktop.ScreenSaver."sv;
987 });
988 }
989
990 void uninhibit_screen_lock() {}
991#endif
992 } // namespace
993
994 void streaming_will_start() {
995 if (config::sunshine.inhibit_screen_lock) {
996 inhibit_screen_lock();
997 }
998 }
999
1000 void streaming_will_stop() {
1001 // Uninhibit even when the setting was just turned off, so the bus
1002 // connection cannot outlive the configuration that opened it.
1003 uninhibit_screen_lock();
1004 }
1005
1006 void restart_on_exit() {
1007 char executable[PATH_MAX];
1008 ssize_t len = readlink("/proc/self/exe", executable, PATH_MAX - 1);
1009 if (len == -1) {
1010 BOOST_LOG(fatal) << "readlink() failed: "sv << errno;
1011 return;
1012 }
1013 executable[len] = '\0';
1014
1015 // ASIO doesn't use O_CLOEXEC, so we have to close all fds ourselves
1016 int openmax = (int) sysconf(_SC_OPEN_MAX);
1017 for (int fd = STDERR_FILENO + 1; fd < openmax; fd++) {
1018 close(fd);
1019 }
1020
1021 // Re-exec ourselves with the same arguments, and with the environment
1022 // Hermes was started with rather than the one it has changed since: what
1023 // a restart of the unit would give it. If a graphical session started
1024 // after Hermes did, this is also where Hermes joins it.
1026 if (!environment.empty()) {
1027 std::vector<char *> envp;
1028 envp.reserve(environment.size() + 1);
1029 for (const auto &assignment : environment) {
1030 envp.push_back(const_cast<char *>(assignment.c_str()));
1031 }
1032 envp.push_back(nullptr);
1033 execve(executable, lifetime::get_argv(), envp.data());
1034 } else {
1035 execv(executable, lifetime::get_argv());
1036 }
1037 BOOST_LOG(fatal) << "execv() failed: "sv << errno;
1038 }
1039
1040 void restart() {
1041 // Gracefully clean up and restart ourselves instead of exiting
1042 atexit(restart_on_exit);
1043 lifetime::exit_sunshine(0, true);
1044 }
1045
1046 int set_env(const std::string &name, const std::string &value) {
1047 return setenv(name.c_str(), value.c_str(), 1);
1048 }
1049
1050 int unset_env(const std::string &name) {
1051 return unsetenv(name.c_str());
1052 }
1053
1054 bool request_process_group_exit(std::uintptr_t native_handle) {
1055 if (process_group::signal(native_handle, SIGTERM)) {
1056 BOOST_LOG(debug) << "Successfully sent SIGTERM to process group: "sv << native_handle;
1057 return true;
1058 } else {
1059 BOOST_LOG(warning) << "Unable to send SIGTERM to process group ["sv << native_handle << "]: "sv << errno;
1060 return false;
1061 }
1062 }
1063
1064 bool process_group_running(std::uintptr_t native_handle) {
1065 return process_group::running(native_handle);
1066 }
1067
1069 std::ifstream cgroups {"/proc/self/cgroup"};
1070 std::string entry;
1071 bool managed = false;
1072 while (std::getline(cgroups, entry)) {
1073 if (is_hermes_user_service_cgroup(entry)) {
1074 managed = true;
1075 break;
1076 }
1077 }
1078 if (!managed) {
1079 return false;
1080 }
1081
1082 // --no-block only queues the stop job; waiting for the unit to stop here
1083 // would deadlock against our own exit. A deliberate stop also suppresses
1084 // Restart=on-failure if a remaining workload hits systemd's stop timeout.
1085 std::error_code ec;
1086 boost::filesystem::path working_dir {"/"};
1087 auto child = run_command(false, false, "systemctl --user --no-block stop hermes.service",
1088 working_dir, boost::this_process::environment(), nullptr, ec, nullptr);
1089 if (!ec && child.valid()) {
1090 if (child.wait_for(2s, ec) && !ec && child.exit_code() == 0) {
1091 BOOST_LOG(info) << "Requested intentional stop of hermes.service from system tray";
1092 return true;
1093 }
1094 child.terminate(ec);
1095 child.detach();
1096 }
1097 BOOST_LOG(warning) << "Unable to request user-service stop; continuing normal shutdown";
1098 return false;
1099 }
1100
1101 struct sockaddr_in to_sockaddr(boost::asio::ip::address_v4 address, uint16_t port) {
1102 struct sockaddr_in saddr_v4 = {};
1103
1104 saddr_v4.sin_family = AF_INET;
1105 saddr_v4.sin_port = htons(port);
1106
1107 auto addr_bytes = address.to_bytes();
1108 memcpy(&saddr_v4.sin_addr, addr_bytes.data(), sizeof(saddr_v4.sin_addr));
1109
1110 return saddr_v4;
1111 }
1112
1113 struct sockaddr_in6 to_sockaddr(boost::asio::ip::address_v6 address, uint16_t port) {
1114 struct sockaddr_in6 saddr_v6 = {};
1115
1116 saddr_v6.sin6_family = AF_INET6;
1117 saddr_v6.sin6_port = htons(port);
1118 saddr_v6.sin6_scope_id = address.scope_id();
1119
1120 auto addr_bytes = address.to_bytes();
1121 memcpy(&saddr_v6.sin6_addr, addr_bytes.data(), sizeof(saddr_v6.sin6_addr));
1122
1123 return saddr_v6;
1124 }
1125
1126 bool send_batch(batched_send_info_t &send_info) {
1127 auto sockfd = (int) send_info.native_socket;
1128 struct msghdr msg = {};
1129
1130 // Convert the target address into a sockaddr
1131 struct sockaddr_in taddr_v4 = {};
1132 struct sockaddr_in6 taddr_v6 = {};
1133 if (send_info.target_address.is_v6()) {
1134 taddr_v6 = to_sockaddr(send_info.target_address.to_v6(), send_info.target_port);
1135
1136 msg.msg_name = (struct sockaddr *) &taddr_v6;
1137 msg.msg_namelen = sizeof(taddr_v6);
1138 } else {
1139 taddr_v4 = to_sockaddr(send_info.target_address.to_v4(), send_info.target_port);
1140
1141 msg.msg_name = (struct sockaddr *) &taddr_v4;
1142 msg.msg_namelen = sizeof(taddr_v4);
1143 }
1144
1145 union {
1146 char buf[CMSG_SPACE(sizeof(uint16_t)) + std::max(CMSG_SPACE(sizeof(struct in_pktinfo)), CMSG_SPACE(sizeof(struct in6_pktinfo)))];
1147 struct cmsghdr alignment;
1148 } cmbuf = {}; // Must be zeroed for CMSG_NXTHDR()
1149
1150 socklen_t cmbuflen = 0;
1151
1152 msg.msg_control = cmbuf.buf;
1153 msg.msg_controllen = sizeof(cmbuf.buf);
1154
1155 // The PKTINFO option will always be first, then we will conditionally
1156 // append the UDP_SEGMENT option next if applicable.
1157 auto pktinfo_cm = CMSG_FIRSTHDR(&msg);
1158 if (send_info.source_address.is_v6()) {
1159 struct in6_pktinfo pktInfo;
1160
1161 struct sockaddr_in6 saddr_v6 = to_sockaddr(send_info.source_address.to_v6(), 0);
1162 pktInfo.ipi6_addr = saddr_v6.sin6_addr;
1163 pktInfo.ipi6_ifindex = 0;
1164
1165 cmbuflen += CMSG_SPACE(sizeof(pktInfo));
1166
1167 pktinfo_cm->cmsg_level = IPPROTO_IPV6;
1168 pktinfo_cm->cmsg_type = IPV6_PKTINFO;
1169 pktinfo_cm->cmsg_len = CMSG_LEN(sizeof(pktInfo));
1170 memcpy(CMSG_DATA(pktinfo_cm), &pktInfo, sizeof(pktInfo));
1171 } else {
1172 struct in_pktinfo pktInfo;
1173
1174 struct sockaddr_in saddr_v4 = to_sockaddr(send_info.source_address.to_v4(), 0);
1175 pktInfo.ipi_spec_dst = saddr_v4.sin_addr;
1176 pktInfo.ipi_ifindex = 0;
1177
1178 cmbuflen += CMSG_SPACE(sizeof(pktInfo));
1179
1180 pktinfo_cm->cmsg_level = IPPROTO_IP;
1181 pktinfo_cm->cmsg_type = IP_PKTINFO;
1182 pktinfo_cm->cmsg_len = CMSG_LEN(sizeof(pktInfo));
1183 memcpy(CMSG_DATA(pktinfo_cm), &pktInfo, sizeof(pktInfo));
1184 }
1185
1186 auto const max_iovs_per_msg = send_info.payload_buffers.size() + (send_info.headers ? 1 : 0);
1187
1188#ifdef UDP_SEGMENT
1189 {
1190 // UDP GSO on Linux currently only supports sending 64K or 64 segments at a time
1191 size_t seg_index = 0;
1192 const size_t seg_max = 65536 / 1500;
1193 struct iovec iovs[(send_info.headers ? std::min(seg_max, send_info.block_count) : 1) * max_iovs_per_msg];
1194 auto msg_size = send_info.header_size + send_info.payload_size;
1195 while (seg_index < send_info.block_count) {
1196 int iovlen = 0;
1197 auto segs_in_batch = std::min(send_info.block_count - seg_index, seg_max);
1198 if (send_info.headers) {
1199 // Interleave iovs for headers and payloads
1200 for (auto i = 0; i < segs_in_batch; i++) {
1201 iovs[iovlen].iov_base = (void *) &send_info.headers[(send_info.block_offset + seg_index + i) * send_info.header_size];
1202 iovs[iovlen].iov_len = send_info.header_size;
1203 iovlen++;
1204 auto payload_desc = send_info.buffer_for_payload_offset((send_info.block_offset + seg_index + i) * send_info.payload_size);
1205 iovs[iovlen].iov_base = (void *) payload_desc.buffer;
1206 iovs[iovlen].iov_len = send_info.payload_size;
1207 iovlen++;
1208 }
1209 } else {
1210 // Translate buffer descriptors into iovs
1211 auto payload_offset = (send_info.block_offset + seg_index) * send_info.payload_size;
1212 auto payload_length = payload_offset + (segs_in_batch * send_info.payload_size);
1213 while (payload_offset < payload_length) {
1214 auto payload_desc = send_info.buffer_for_payload_offset(payload_offset);
1215 iovs[iovlen].iov_base = (void *) payload_desc.buffer;
1216 iovs[iovlen].iov_len = std::min(payload_desc.size, payload_length - payload_offset);
1217 payload_offset += iovs[iovlen].iov_len;
1218 iovlen++;
1219 }
1220 }
1221
1222 msg.msg_iov = iovs;
1223 msg.msg_iovlen = iovlen;
1224
1225 // We should not use GSO if the data is <= one full block size
1226 if (segs_in_batch > 1) {
1227 msg.msg_controllen = cmbuflen + CMSG_SPACE(sizeof(uint16_t));
1228
1229 // Enable GSO to perform segmentation of our buffer for us
1230 auto cm = CMSG_NXTHDR(&msg, pktinfo_cm);
1231 cm->cmsg_level = SOL_UDP;
1232 cm->cmsg_type = UDP_SEGMENT;
1233 cm->cmsg_len = CMSG_LEN(sizeof(uint16_t));
1234 *((uint16_t *) CMSG_DATA(cm)) = msg_size;
1235 } else {
1236 msg.msg_controllen = cmbuflen;
1237 }
1238
1239 // This will fail if GSO is not available, so we will fall back to non-GSO if
1240 // it's the first sendmsg() call. On subsequent calls, we will treat errors as
1241 // actual failures and return to the caller.
1242 auto bytes_sent = sendmsg(sockfd, &msg, 0);
1243 if (bytes_sent < 0) {
1244 // If there's no send buffer space, wait for some to be available
1245 if (errno == EAGAIN) {
1246 struct pollfd pfd;
1247
1248 pfd.fd = sockfd;
1249 pfd.events = POLLOUT;
1250
1251 if (poll(&pfd, 1, -1) != 1) {
1252 BOOST_LOG(warning) << "poll() failed: "sv << errno;
1253 break;
1254 }
1255
1256 // Try to send again
1257 continue;
1258 }
1259
1260 BOOST_LOG(verbose) << "sendmsg() failed: "sv << errno;
1261 break;
1262 }
1263
1264 seg_index += bytes_sent / msg_size;
1265 }
1266
1267 // If we sent something, return the status and don't fall back to the non-GSO path.
1268 if (seg_index != 0) {
1269 return seg_index >= send_info.block_count;
1270 }
1271 }
1272#endif
1273
1274 {
1275 // If GSO is not supported, use sendmmsg() instead.
1276 struct mmsghdr msgs[send_info.block_count];
1277 struct iovec iovs[send_info.block_count * (send_info.headers ? 2 : 1)];
1278 int iov_idx = 0;
1279 for (size_t i = 0; i < send_info.block_count; i++) {
1280 msgs[i].msg_len = 0;
1281 msgs[i].msg_hdr.msg_iov = &iovs[iov_idx];
1282 msgs[i].msg_hdr.msg_iovlen = send_info.headers ? 2 : 1;
1283
1284 if (send_info.headers) {
1285 iovs[iov_idx].iov_base = (void *) &send_info.headers[(send_info.block_offset + i) * send_info.header_size];
1286 iovs[iov_idx].iov_len = send_info.header_size;
1287 iov_idx++;
1288 }
1289 auto payload_desc = send_info.buffer_for_payload_offset((send_info.block_offset + i) * send_info.payload_size);
1290 iovs[iov_idx].iov_base = (void *) payload_desc.buffer;
1291 iovs[iov_idx].iov_len = send_info.payload_size;
1292 iov_idx++;
1293
1294 msgs[i].msg_hdr.msg_name = msg.msg_name;
1295 msgs[i].msg_hdr.msg_namelen = msg.msg_namelen;
1296 msgs[i].msg_hdr.msg_control = cmbuf.buf;
1297 msgs[i].msg_hdr.msg_controllen = cmbuflen;
1298 msgs[i].msg_hdr.msg_flags = 0;
1299 }
1300
1301 // Call sendmmsg() until all messages are sent
1302 size_t blocks_sent = 0;
1303 while (blocks_sent < send_info.block_count) {
1304 int msgs_sent = sendmmsg(sockfd, &msgs[blocks_sent], send_info.block_count - blocks_sent, 0);
1305 if (msgs_sent < 0) {
1306 // If there's no send buffer space, wait for some to be available
1307 if (errno == EAGAIN) {
1308 struct pollfd pfd;
1309
1310 pfd.fd = sockfd;
1311 pfd.events = POLLOUT;
1312
1313 if (poll(&pfd, 1, -1) != 1) {
1314 BOOST_LOG(warning) << "poll() failed: "sv << errno;
1315 break;
1316 }
1317
1318 // Try to send again
1319 continue;
1320 }
1321
1322 BOOST_LOG(warning) << "sendmmsg() failed: "sv << errno;
1323 return false;
1324 }
1325
1326 blocks_sent += msgs_sent;
1327 }
1328
1329 return true;
1330 }
1331 }
1332
1333 bool send(send_info_t &send_info) {
1334 auto sockfd = (int) send_info.native_socket;
1335 struct msghdr msg = {};
1336
1337 // Convert the target address into a sockaddr
1338 struct sockaddr_in taddr_v4 = {};
1339 struct sockaddr_in6 taddr_v6 = {};
1340 if (send_info.target_address.is_v6()) {
1341 taddr_v6 = to_sockaddr(send_info.target_address.to_v6(), send_info.target_port);
1342
1343 msg.msg_name = (struct sockaddr *) &taddr_v6;
1344 msg.msg_namelen = sizeof(taddr_v6);
1345 } else {
1346 taddr_v4 = to_sockaddr(send_info.target_address.to_v4(), send_info.target_port);
1347
1348 msg.msg_name = (struct sockaddr *) &taddr_v4;
1349 msg.msg_namelen = sizeof(taddr_v4);
1350 }
1351
1352 union {
1353 char buf[std::max(CMSG_SPACE(sizeof(struct in_pktinfo)), CMSG_SPACE(sizeof(struct in6_pktinfo)))];
1354 struct cmsghdr alignment;
1355 } cmbuf;
1356
1357 socklen_t cmbuflen = 0;
1358
1359 msg.msg_control = cmbuf.buf;
1360 msg.msg_controllen = sizeof(cmbuf.buf);
1361
1362 auto pktinfo_cm = CMSG_FIRSTHDR(&msg);
1363 if (send_info.source_address.is_v6()) {
1364 struct in6_pktinfo pktInfo;
1365
1366 struct sockaddr_in6 saddr_v6 = to_sockaddr(send_info.source_address.to_v6(), 0);
1367 pktInfo.ipi6_addr = saddr_v6.sin6_addr;
1368 pktInfo.ipi6_ifindex = 0;
1369
1370 cmbuflen += CMSG_SPACE(sizeof(pktInfo));
1371
1372 pktinfo_cm->cmsg_level = IPPROTO_IPV6;
1373 pktinfo_cm->cmsg_type = IPV6_PKTINFO;
1374 pktinfo_cm->cmsg_len = CMSG_LEN(sizeof(pktInfo));
1375 memcpy(CMSG_DATA(pktinfo_cm), &pktInfo, sizeof(pktInfo));
1376 } else {
1377 struct in_pktinfo pktInfo;
1378
1379 struct sockaddr_in saddr_v4 = to_sockaddr(send_info.source_address.to_v4(), 0);
1380 pktInfo.ipi_spec_dst = saddr_v4.sin_addr;
1381 pktInfo.ipi_ifindex = 0;
1382
1383 cmbuflen += CMSG_SPACE(sizeof(pktInfo));
1384
1385 pktinfo_cm->cmsg_level = IPPROTO_IP;
1386 pktinfo_cm->cmsg_type = IP_PKTINFO;
1387 pktinfo_cm->cmsg_len = CMSG_LEN(sizeof(pktInfo));
1388 memcpy(CMSG_DATA(pktinfo_cm), &pktInfo, sizeof(pktInfo));
1389 }
1390
1391 struct iovec iovs[2];
1392 int iovlen = 0;
1393 if (send_info.header) {
1394 iovs[iovlen].iov_base = (void *) send_info.header;
1395 iovs[iovlen].iov_len = send_info.header_size;
1396 iovlen++;
1397 }
1398 iovs[iovlen].iov_base = (void *) send_info.payload;
1399 iovs[iovlen].iov_len = send_info.payload_size;
1400 iovlen++;
1401
1402 msg.msg_iov = iovs;
1403 msg.msg_iovlen = iovlen;
1404
1405 msg.msg_controllen = cmbuflen;
1406
1407 auto bytes_sent = sendmsg(sockfd, &msg, 0);
1408
1409 // If there's no send buffer space, wait for some to be available
1410 while (bytes_sent < 0 && errno == EAGAIN) {
1411 struct pollfd pfd;
1412
1413 pfd.fd = sockfd;
1414 pfd.events = POLLOUT;
1415
1416 if (poll(&pfd, 1, -1) != 1) {
1417 BOOST_LOG(warning) << "poll() failed: "sv << errno;
1418 break;
1419 }
1420
1421 // Try to send again
1422 bytes_sent = sendmsg(sockfd, &msg, 0);
1423 }
1424
1425 if (bytes_sent < 0) {
1426 BOOST_LOG(warning) << "sendmsg() failed: "sv << errno;
1427 return false;
1428 }
1429
1430 return true;
1431 }
1432
1433 // We can't track QoS state separately for each destination on this OS,
1434 // so we keep a ref count to only disable QoS options when all clients
1435 // are disconnected.
1436 static std::atomic<int> qos_ref_count = 0;
1437
1438 class qos_t: public deinit_t {
1439 public:
1440 qos_t(int sockfd, std::vector<std::tuple<int, int, int>> options):
1441 sockfd(sockfd),
1442 options(options) {
1443 qos_ref_count++;
1444 }
1445
1446 virtual ~qos_t() {
1447 if (--qos_ref_count == 0) {
1448 for (const auto &tuple : options) {
1449 auto reset_val = std::get<2>(tuple);
1450 if (setsockopt(sockfd, std::get<0>(tuple), std::get<1>(tuple), &reset_val, sizeof(reset_val)) < 0) {
1451 BOOST_LOG(warning) << "Failed to reset option: "sv << errno;
1452 }
1453 }
1454 }
1455 }
1456
1457 private:
1458 int sockfd;
1459 std::vector<std::tuple<int, int, int>> options;
1460 };
1461
1470 std::unique_ptr<deinit_t> enable_socket_qos(uintptr_t native_socket, boost::asio::ip::address &address, uint16_t port, qos_data_type_e data_type, bool dscp_tagging) {
1471 int sockfd = (int) native_socket;
1472 std::vector<std::tuple<int, int, int>> reset_options;
1473
1474 if (dscp_tagging) {
1475 int level;
1476 int option;
1477
1478 // With dual-stack sockets, Linux uses IPV6_TCLASS for IPv6 traffic
1479 // and IP_TOS for IPv4 traffic.
1480 if (address.is_v6() && !address.to_v6().is_v4_mapped()) {
1481 level = SOL_IPV6;
1482 option = IPV6_TCLASS;
1483 } else {
1484 level = SOL_IP;
1485 option = IP_TOS;
1486 }
1487
1488 // The specific DSCP values here are chosen to be consistent with Windows,
1489 // except that we use CS6 instead of CS7 for audio traffic.
1490 int dscp = 0;
1491 switch (data_type) {
1493 dscp = 40;
1494 break;
1496 dscp = 48;
1497 break;
1498 default:
1499 BOOST_LOG(error) << "Unknown traffic type: "sv << (int) data_type;
1500 break;
1501 }
1502
1503 if (dscp) {
1504 // Shift to put the DSCP value in the correct position in the TOS field
1505 dscp <<= 2;
1506
1507 if (setsockopt(sockfd, level, option, &dscp, sizeof(dscp)) == 0) {
1508 // Reset TOS to -1 when QoS is disabled
1509 reset_options.emplace_back(std::make_tuple(level, option, -1));
1510 } else {
1511 BOOST_LOG(error) << "Failed to set TOS/TCLASS: "sv << errno;
1512 }
1513 }
1514 }
1515
1516 // We can use SO_PRIORITY to set outgoing traffic priority without DSCP tagging.
1517 //
1518 // NB: We set this after IP_TOS/IPV6_TCLASS since setting TOS value seems to
1519 // reset SO_PRIORITY back to 0.
1520 //
1521 // 6 is the highest priority that can be used without SYS_CAP_ADMIN.
1522 int priority = data_type == qos_data_type_e::audio ? 6 : 5;
1523 if (setsockopt(sockfd, SOL_SOCKET, SO_PRIORITY, &priority, sizeof(priority)) == 0) {
1524 // Reset SO_PRIORITY to 0 when QoS is disabled
1525 reset_options.emplace_back(std::make_tuple(SOL_SOCKET, SO_PRIORITY, 0));
1526 } else {
1527 BOOST_LOG(error) << "Failed to set SO_PRIORITY: "sv << errno;
1528 }
1529
1530 return std::make_unique<qos_t>(sockfd, reset_options);
1531 }
1532
1533 std::string get_host_name() {
1534 try {
1535 return boost::asio::ip::host_name();
1536 } catch (boost::system::system_error &err) {
1537 BOOST_LOG(error) << "Failed to get hostname: "sv << err.what();
1538 return "Hermes"s;
1539 }
1540 }
1541
1542 namespace source {
1543 enum source_e : std::size_t {
1544#ifdef HERMES_BUILD_CUDA
1545 NVFBC,
1546#endif
1547#ifdef HERMES_BUILD_WAYLAND
1549#endif
1550#ifdef HERMES_BUILD_DRM
1551 KMS,
1552#endif
1553#ifdef HERMES_BUILD_X11
1554 X11,
1555#endif
1557 };
1558 } // namespace source
1559
1560 static std::bitset<source::MAX_FLAGS> sources;
1561
1562#ifdef HERMES_BUILD_CUDA
1563 std::vector<std::string> nvfbc_display_names();
1564 std::shared_ptr<display_t> nvfbc_display(mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config);
1565
1566 bool verify_nvfbc() {
1567 return !nvfbc_display_names().empty();
1568 }
1569#endif
1570
1571#ifdef HERMES_BUILD_WAYLAND
1572 std::vector<std::string> wl_display_names();
1573 std::shared_ptr<display_t> wl_display(mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config);
1574
1575 bool verify_wl() {
1576 return window_system == window_system_e::WAYLAND && !wl_display_names().empty();
1577 }
1578#endif
1579
1580#ifdef HERMES_BUILD_DRM
1581 std::vector<std::string> kms_display_names(mem_type_e hwdevice_type);
1582 std::shared_ptr<display_t> kms_display(mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config);
1583
1584 bool verify_kms() {
1585 if (!kms_display_names(mem_type_e::unknown).empty()) {
1586 return true;
1587 }
1588
1589 // Hermes-KMS virtual displays are captured through the driver's render
1590 // node (no DRM master, no CAP_SYS_ADMIN), so a present driver makes the
1591 // KMS backend usable even when no physical framebuffer handle is
1592 // readable. Without this, running unprivileged with capture=kms would
1593 // abort platform init before the virtual-display bootstrap can run.
1594 if (config::video.virtual_display_backend == "hermes_kms" &&
1596 BOOST_LOG(info) << "KMS capture enabled through Hermes-KMS render-node path (no CAP_SYS_ADMIN)"sv;
1597 return true;
1598 }
1599
1600 return false;
1601 }
1602#endif
1603
1604#ifdef HERMES_BUILD_X11
1605 std::vector<std::string> x11_display_names();
1606 std::shared_ptr<display_t> x11_display(mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config);
1607
1608 bool verify_x11() {
1609 return window_system == window_system_e::X11 && !x11_display_names().empty();
1610 }
1611#endif
1612
1613 std::vector<std::string> display_names(mem_type_e hwdevice_type) {
1614#ifdef HERMES_BUILD_DRM
1615 // An EVDI display is a real DRM output, but its name is intentionally not
1616 // part of the generic monitor-index list. Keep the stable virtual name so
1617 // a capture reinitialization cannot switch the stream back to a physical
1618 // output (or a lower-latency-looking but wrong Wayland/NvFBC source).
1619 auto virtual_displays = VDISPLAY::matchDisplay("VIRTUAL-");
1620 if (!virtual_displays.empty()) {
1621 return virtual_displays;
1622 }
1623#endif
1624
1625#ifdef HERMES_BUILD_CUDA
1626 // display using NvFBC only supports mem_type_e::cuda
1627 if (sources[source::NVFBC] && hwdevice_type == mem_type_e::cuda) {
1628 return nvfbc_display_names();
1629 }
1630#endif
1631#ifdef HERMES_BUILD_WAYLAND
1632 if (sources[source::WAYLAND]) {
1633 return wl_display_names();
1634 }
1635#endif
1636#ifdef HERMES_BUILD_DRM
1637 if (sources[source::KMS]) {
1638 return kms_display_names(hwdevice_type);
1639 }
1640#endif
1641#ifdef HERMES_BUILD_X11
1642 if (sources[source::X11]) {
1643 return x11_display_names();
1644 }
1645#endif
1646 return {};
1647 }
1648
1654 // We don't track GPU state, so we will always reenumerate. Fortunately, it is fast on Linux.
1655 return true;
1656 }
1657
1658 std::shared_ptr<display_t> display(mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config) {
1659 if (!config.kwin_wayland_socket.empty() || !config.kwin_pipewire_socket.empty()) {
1660 if (config.kwin_wayland_socket.empty() || config.kwin_pipewire_socket.empty()) {
1661 BOOST_LOG(error) << "Incomplete private KWin endpoint; refusing host capture";
1662 return nullptr;
1663 }
1664#ifdef HERMES_BUILD_KWIN_TRANSPORT
1665 return kwin_display(hwdevice_type, config);
1666#else
1667 BOOST_LOG(error) << "Private KWin capture support was not built; refusing host capture";
1668 return nullptr;
1669#endif
1670 }
1671
1672#ifdef HERMES_BUILD_WAYLAND
1673 // A Hyprland headless output has no DRM device behind it, so the KMS
1674 // backend has nothing to open. Route it explicitly rather than letting it
1675 // fall through to the generic Wayland branch: with capture=kms configured,
1676 // falling through would reach kms_display() and fail on a display that
1677 // captures perfectly well over wlr-screencopy.
1678 if (!VDISPLAY::getHyprlandOutputName(display_name).empty()) {
1679 BOOST_LOG(info) << "Screencasting Hyprland headless output with Wayland's protocol"sv;
1680 return wl_display(hwdevice_type, display_name, config);
1681 }
1682#endif
1683#ifdef HERMES_BUILD_DRM
1684 if (VDISPLAY::isHermesKmsDisplay(display_name)) {
1685 BOOST_LOG(info) << "Screencasting Hermes-KMS virtual display with KMS"sv;
1686 return kms_display(hwdevice_type, display_name, config);
1687 }
1688 if (VDISPLAY::isEvdiDisplay(display_name)) {
1689 BOOST_LOG(info) << "Screencasting EVDI virtual display with KMS"sv;
1690 return kms_display(hwdevice_type, display_name, config);
1691 }
1692#endif
1693
1694#ifdef HERMES_BUILD_CUDA
1695 if (sources[source::NVFBC] && hwdevice_type == mem_type_e::cuda) {
1696 BOOST_LOG(info) << "Screencasting with NvFBC"sv;
1697 return nvfbc_display(hwdevice_type, display_name, config);
1698 }
1699#endif
1700#ifdef HERMES_BUILD_WAYLAND
1701 if (sources[source::WAYLAND]) {
1702 BOOST_LOG(info) << "Screencasting with Wayland's protocol"sv;
1703 return wl_display(hwdevice_type, display_name, config);
1704 }
1705#endif
1706#ifdef HERMES_BUILD_DRM
1707 if (sources[source::KMS]) {
1708 BOOST_LOG(info) << "Screencasting with KMS"sv;
1709 return kms_display(hwdevice_type, display_name, config);
1710 }
1711#endif
1712#ifdef HERMES_BUILD_X11
1713 if (sources[source::X11]) {
1714 BOOST_LOG(info) << "Screencasting with X11"sv;
1715 return x11_display(hwdevice_type, display_name, config);
1716 }
1717#endif
1718
1719 return nullptr;
1720 }
1721
1722 std::unique_ptr<deinit_t> init() {
1723 // Some existing Hermes-KMS configurations name the compositor here.
1724 // KWin is not a capture backend: leaving this value unresolved disables
1725 // every source and makes startup report all hardware encoders unavailable.
1726 if (config::video.capture == "kwin" && config::video.virtual_display_backend == "hermes_kms") {
1727 BOOST_LOG(warning) << "capture=kwin names a compositor, not a capture backend; using kms for Hermes-KMS. "
1728 "Select KMS under Force a Specific Capture Method to save this setting.";
1729 config::video.capture = "kms";
1730 }
1731
1732 // enable low latency mode for AMD
1733 // https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/30039
1734 set_env("AMD_DEBUG", "lowlatencyenc");
1735
1736 // These are allowed to fail.
1737 gbm::init();
1738
1739 window_system = window_system_e::NONE;
1740#ifdef HERMES_BUILD_WAYLAND
1741 if (std::getenv("WAYLAND_DISPLAY")) {
1742 window_system = window_system_e::WAYLAND;
1743 }
1744#endif
1745#if defined(HERMES_BUILD_X11) || defined(HERMES_BUILD_CUDA)
1746 if (std::getenv("DISPLAY") && window_system != window_system_e::WAYLAND) {
1747 if (std::getenv("WAYLAND_DISPLAY")) {
1748 BOOST_LOG(warning) << "Wayland detected, yet Hermes will use X11 for screencasting, screencasting will only work on XWayland applications"sv;
1749 }
1750
1751 window_system = window_system_e::X11;
1752 }
1753#endif
1754
1755#ifdef HERMES_BUILD_CUDA
1756 if ((config::video.capture.empty() && sources.none()) || config::video.capture == "nvfbc") {
1757 if (verify_nvfbc()) {
1758 sources[source::NVFBC] = true;
1759 }
1760 }
1761#endif
1762#ifdef HERMES_BUILD_WAYLAND
1763 if ((config::video.capture.empty() && sources.none()) || config::video.capture == "wlr") {
1764 if (verify_wl()) {
1765 sources[source::WAYLAND] = true;
1766 }
1767 }
1768#endif
1769#ifdef HERMES_BUILD_DRM
1770 if ((config::video.capture.empty() && sources.none()) || config::video.capture == "kms") {
1771 if (verify_kms()) {
1772 sources[source::KMS] = true;
1773 }
1774 }
1775#endif
1776#ifdef HERMES_BUILD_X11
1777 // We enumerate this capture backend regardless of other suitable sources,
1778 // since it may be needed as a NvFBC fallback for software encoding on X11.
1779 if (config::video.capture.empty() || config::video.capture == "x11") {
1780 if (verify_x11()) {
1781 sources[source::X11] = true;
1782 }
1783 }
1784#endif
1785
1786 if (sources.none()) {
1787 BOOST_LOG(error) << "Unable to initialize capture method [" << config::video.capture
1788 << "]. Linux capture values are auto (empty), kms, wlr, x11 or nvfbc; "
1789 "the selected backend must also be available. Encoder probing requires a working capture source.";
1790 return nullptr;
1791 }
1792
1793 if (!gladLoaderLoadEGL(EGL_NO_DISPLAY) || !eglGetPlatformDisplay) {
1794 BOOST_LOG(warning) << "Couldn't load EGL library"sv;
1795 }
1796
1797 return std::make_unique<deinit_t>();
1798 }
1799
1801 public:
1802 void sleep_for(const std::chrono::nanoseconds &duration) override {
1803 std::this_thread::sleep_for(duration);
1804 }
1805
1806 operator bool() override {
1807 return true;
1808 }
1809 };
1810
1811 std::unique_ptr<high_precision_timer> create_high_precision_timer() {
1812 return std::make_unique<linux_high_precision_timer>();
1813 }
1814
1815 std::string
1816 get_clipboard() {
1817 if (!clipboard_available()) {
1818 return "";
1819 }
1820
1821 const bool wayland = window_system == window_system_e::WAYLAND;
1822 const auto executable = bp::search_path(wayland ? "wl-paste" : "xclip").string();
1823 const char *wayland_arguments[] = {"wl-paste", "--no-newline", "--type", "text/plain", nullptr};
1824 const char *x11_arguments[] = {"xclip", "-selection", "clipboard", "-out", nullptr};
1825 clipboard::pipe_t helper(executable.c_str(), wayland ? wayland_arguments : x11_arguments, false);
1826 FILE *pipe = helper.get();
1827 if (pipe == nullptr) {
1828 BOOST_LOG(warning) << "Unable to read the clipboard";
1829 return "";
1830 }
1831
1832 constexpr size_t max_clipboard_bytes = 64 * 1024;
1833 std::string content;
1834 char buffer[4096];
1835 while (const size_t bytes_read = fread(buffer, 1, sizeof(buffer), pipe)) {
1836 if (content.size() + bytes_read > max_clipboard_bytes) {
1837 BOOST_LOG(warning) << "Clipboard exceeds the 64 KiB Hestia limit";
1838 return "";
1839 }
1840 content.append(buffer, bytes_read);
1841 }
1842
1843 const bool read_failed = ferror(pipe) != 0;
1844 if (!helper.finish() || read_failed) {
1845 BOOST_LOG(warning) << "Unable to read the clipboard";
1846 return "";
1847 }
1848
1849 return content;
1850 }
1851
1852 bool
1853 set_clipboard(const std::string& content) {
1854 if (!clipboard_available() || content.size() > 64 * 1024 || content.find('\0') != std::string::npos) {
1855 return false;
1856 }
1857
1858 const bool wayland = window_system == window_system_e::WAYLAND;
1859 const auto executable = bp::search_path(wayland ? "wl-copy" : "xclip").string();
1860 const char *wayland_arguments[] = {"wl-copy", "--type", "text/plain", nullptr};
1861 const char *x11_arguments[] = {"xclip", "-selection", "clipboard", "-in", nullptr};
1862 clipboard::pipe_t helper(executable.c_str(), wayland ? wayland_arguments : x11_arguments, true);
1863 const bool success = helper.write(content);
1864 if (!success) {
1865 BOOST_LOG(warning) << "Unable to write the " << (wayland ? "Wayland" : "X11") << " clipboard";
1866 }
1867 return success;
1868 }
1869
1870 bool
1871 clipboard_available() {
1872 if (window_system == window_system_e::WAYLAND) {
1873 return std::getenv("WAYLAND_DISPLAY") != nullptr &&
1874 !bp::search_path("wl-copy").empty() && !bp::search_path("wl-paste").empty();
1875 }
1876 if (window_system == window_system_e::X11) {
1877 return std::getenv("DISPLAY") != nullptr && !bp::search_path("xclip").empty();
1878 }
1879 return false;
1880 }
1881
1884
1885 const char *desktop = std::getenv("XDG_CURRENT_DESKTOP");
1886 if (desktop) {
1887 env.desktop = desktop;
1888 }
1889
1890 // Gamescope's nested Wayland socket is exported by gamescope-session and by
1891 // any running Gamescope compositor. When present, a Gamescope compositor is
1892 // available to capture/launch into.
1893 const char *gs_wl = std::getenv("GAMESCOPE_WAYLAND_DISPLAY");
1894 const bool desktop_is_gamescope =
1895 !env.desktop.empty() && boost::algorithm::to_lower_copy(env.desktop).find("gamescope") != std::string::npos;
1896 env.gamescope_running = (gs_wl != nullptr && gs_wl[0] != '\0') || desktop_is_gamescope;
1897
1898 // A standalone Gamescope session (SteamOS Game Mode) is the compositor
1899 // itself: it advertises itself via XDG_CURRENT_DESKTOP=gamescope, and there
1900 // is no separate desktop compositor underneath. Distinguish this from a
1901 // desktop that merely has Gamescope installed/nested.
1902 if (desktop_is_gamescope) {
1904 env.can_host_virtual_display = false;
1905 return env;
1906 }
1907
1908 switch (window_system) {
1911 // A desktop Wayland compositor can host a virtual display when it
1912 // exposes an output-management protocol (kscreen/wlr).
1913 env.can_host_virtual_display = true;
1914 break;
1917 env.can_host_virtual_display = true;
1918 break;
1920 default:
1922 env.can_host_virtual_display = false;
1923 break;
1924 }
1925
1926 return env;
1927 }
1928
1929 // Detect, read-only, whether a display-manager autologin drop-in exists. This
1930 // only inspects well-known config locations; it never enables autologin.
1931 static bool detect_autologin() {
1932 std::error_code ec;
1933
1934 // getty autologin override (used for tty/Gamescope-session appliance setups).
1935 for (const char *path : {"/etc/systemd/system/getty@tty1.service.d/autologin.conf",
1936 "/etc/systemd/system/getty@tty1.service.d/override.conf"}) {
1937 if (fs::exists(path, ec)) {
1938 std::ifstream in(path);
1939 std::string contents((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
1940 if (contents.find("--autologin") != std::string::npos || contents.find("autologin") != std::string::npos) {
1941 return true;
1942 }
1943 }
1944 }
1945
1946 // Display-manager autologin: SDDM and LightDM keep it in their config trees.
1947 for (const char *path : {"/etc/sddm.conf", "/etc/lightdm/lightdm.conf"}) {
1948 if (fs::exists(path, ec)) {
1949 std::ifstream in(path);
1950 std::string contents((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
1951 if (contents.find("Autologin") != std::string::npos || contents.find("autologin-user") != std::string::npos) {
1952 return true;
1953 }
1954 }
1955 }
1956 for (const char *dir : {"/etc/sddm.conf.d", "/etc/lightdm/lightdm.conf.d"}) {
1957 if (!fs::exists(dir, ec)) {
1958 continue;
1959 }
1960 for (fs::directory_iterator it(dir, fs::directory_options::skip_permission_denied, ec), end; !ec && it != end; it.increment(ec)) {
1961 std::ifstream in(it->path());
1962 std::string contents((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
1963 if (contents.find("Autologin") != std::string::npos || contents.find("autologin-user") != std::string::npos) {
1964 return true;
1965 }
1966 }
1967 }
1968
1969 return false;
1970 }
1971
1974 out.enabled = config::sunshine.appliance_mode;
1975
1976 const auto env = detect_session_environment();
1977 out.session_environment = env.describe();
1978 out.gamescope_available = env.gamescope_running || env.kind == session_environment_e::gamescope_session;
1979
1980 // A virtual display makes the host headless-capable: it can present without
1981 // a physical monitor attached. Reuse the existing driver readiness checks.
1982 const bool evdi_ready = VDISPLAY::getEvdiDiagnostic() == VDISPLAY::EVDI_DIAGNOSTIC::READY;
1983 const bool kms_ready = VDISPLAY::getHermesKmsDiagnostic() == VDISPLAY::HERMES_KMS_DIAGNOSTIC::READY;
1984 out.virtual_display_available = evdi_ready || kms_ready;
1986
1987 out.autologin_configured = detect_autologin();
1988
1989 // Aggregate diagnostic. The flag being off is reported first because the
1990 // whole feature is dormant; when enabled, report the first missing piece.
1991 if (!out.enabled) {
1992 out.diagnostic = "disabled";
1993 } else if (!out.virtual_display_available) {
1994 out.diagnostic = "no_virtual_display";
1995 } else if (!out.gamescope_available) {
1996 out.diagnostic = "no_gamescope";
1997 } else if (!out.autologin_configured) {
1998 out.diagnostic = "no_autologin";
1999 } else {
2000 out.diagnostic = "ready";
2001 }
2002
2003 return out;
2004 }
2005} // namespace platf
void sleep_for(const std::chrono::nanoseconds &duration) override
Sleep for the duration.
Definition misc.cpp:1802
Clipboard helper pipes with isolated descriptor ownership.
Declarations for common platform specific utilities.
mem_type_e
Definition common.h:211
bool process_group_running(std::uintptr_t native_handle)
Check if a process group still has running children.
Definition misc.cpp:1064
std::string get_mac_address(const std::string_view &address)
The MAC address of the interface that holds address.
Definition misc.cpp:412
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
@ gamescope_session
Standalone Gamescope compositor (SteamOS Game Mode).
Definition common.h:1025
@ desktop_wayland
Wayland desktop session (KDE/GNOME/wlroots).
Definition common.h:1024
@ desktop_x11
X11 desktop session.
Definition common.h:1023
@ headless
No window system / capture source available.
Definition common.h:1022
bool request_process_group_exit(std::uintptr_t native_handle)
Attempt to gracefully terminate a process group.
Definition misc.cpp:1054
qos_data_type_e
Definition common.h:797
std::unique_ptr< high_precision_timer > create_high_precision_timer()
Create platform-specific timer capable of high-precision sleep.
Definition misc.cpp:1811
std::unique_ptr< deinit_t > enable_socket_qos(uintptr_t native_socket, boost::asio::ip::address &address, uint16_t port, qos_data_type_e data_type, bool dscp_tagging)
Enable QoS on the given socket for traffic to the specified destination.
Definition misc.cpp:1470
void open_url(const std::string &url)
Open a url in the default web browser.
Definition misc.cpp:546
bool needs_encoder_reenumeration()
Check if GPUs/drivers have changed since the last call to this function.
Definition misc.cpp:1653
std::string get_host_name()
Returns the current computer name in UTF-8.
Definition misc.cpp:1533
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
bool touch_binds_to_output()
Whether the session binds a touchscreen or a pen to one output.
Definition misc.cpp:198
int set_env(const std::string &name, const std::string &value)
Set an environment variable.
Definition misc.cpp:1046
@ error
Error.
Definition common.h:440
appliance_readiness_t appliance_readiness()
Assess appliance-mode readiness without changing any state.
Definition misc.cpp:1972
int unset_env(const std::string &name)
Unset an environment variable.
Definition misc.cpp:1050
Declarations for the configuration of Sunshine.
Declarations for entry handling functions.
std::vector< std::pair< std::string, std::string > > environment(int fps, std::string_view existing_mangohud_config)
Declarations for graphics related functions.
Hermes capture adapter for an explicitly selected private KWin.
Declarations for logging related functions.
int open_drm_node(const char *path, int flags)
Open a DRM device node without becoming its DRM master.
Definition misc.cpp:138
@ WAYLAND
Wayland.
Definition misc.cpp:1548
@ MAX_FLAGS
The maximum number of flags.
Definition misc.cpp:1556
bool request_user_service_stop()
Definition misc.cpp:1068
Miscellaneous declarations for Linux.
window_system_e
Definition misc.h:20
@ WAYLAND
Wayland.
Definition misc.h:23
@ NONE
No window system.
Definition misc.h:21
@ X11
X11.
Definition misc.h:22
void exit_sunshine(int exit_code, bool async)
Terminates Sunshine gracefully with the provided exit code.
char ** get_argv()
Get the argv array passed to main().
raw_address_t to_raw_address(const boost::asio::ip::address &address)
The raw bytes of an address, IPv4-mapped IPv6 as IPv4, the IPv6 scope kept.
Definition network.cpp:92
Declarations for networking related functions.
Non-destructive process-group liveness checks and bounded cleanup helpers.
Recognize our installed user service without trusting inherited environment variables.
std::vector< std::string > restart_environment()
The environment the next restart must be given, as "NAME=value" strings for execve()....
Let a Hermes that started before the graphical session catch up with it.
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...
Read-only assessment of whether the host could run as a dedicated streaming appliance (boot straight ...
Definition common.h:1069
bool autologin_configured
A display-manager autologin drop-in was detected.
Definition common.h:1074
bool gamescope_available
A Gamescope compositor/session is present.
Definition common.h:1071
bool headless_capable
Can present without a physical monitor (virtual display present).
Definition common.h:1073
bool enabled
config appliance_mode flag state.
Definition common.h:1070
std::string session_environment
session_environment_t::describe() value.
Definition common.h:1075
bool virtual_display_available
An EVDI or Hermes-KMS virtual display is usable.
Definition common.h:1072
bool gamescope_running
A Gamescope compositor is present.
Definition common.h:1030
bool can_host_virtual_display
A desktop compositor can adopt a virtual display.
Definition common.h:1031
std::string desktop
Raw XDG_CURRENT_DESKTOP, for diagnostics.
Definition common.h:1032
Declarations for VA-API hardware accelerated capture.
Declarations for video.
bool isHermesKmsDriverPresent()
std::vector< std::string > matchDisplay(const std::string &sMatch)
Match displays by a given pattern.
HERMES_KMS_DIAGNOSTIC getHermesKmsDiagnostic()
bool isEvdiDisplay(const std::string &displayName)
Check if a display name is an EVDI virtual display.
compositor_e sessionCompositor()
Classify the compositor of the running session.
EVDI_DIAGNOSTIC getEvdiDiagnostic()
bool isHermesKmsDisplay(const std::string &displayName)
std::string systemdUserBusAddress(uint32_t uid)
The standard systemd user-bus address for uid.
std::string getHyprlandOutputName(const std::string &displayName)
The Hyprland output name backing a virtual display, or empty.
Virtual display declarations for Linux.