33#include <netinet/udp.h>
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>
70#ifdef HERMES_BUILD_KWIN_TRANSPORT
74#include <linux/rtnetlink.h>
76#ifdef HERMES_BUILD_SDBUS
78 #include <sys/eventfd.h>
79 #include <systemd/sd-bus.h>
83 #define HERMES_GNUC_EXTENSION __extension__
85 #define HERMES_GNUC_EXTENSION
88using namespace std::literals;
89namespace fs = std::filesystem;
90namespace bp = boost::process::v1;
95 void *handle(
const std::vector<const char *> &libs) {
98 for (
auto lib : libs) {
99 handle = dlopen(lib, RTLD_LAZY | RTLD_LOCAL);
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) {
113 BOOST_LOG(error) << ss.str();
118 int load(
void *handle,
const std::vector<std::tuple<apiproc *, const char *>> &funcs,
bool strict) {
120 for (
auto &func : funcs) {
121 TUPLE_2D_REF(fn, name, func);
123 *fn = HERMES_GNUC_EXTENSION(apiproc) dlsym(handle, name);
125 if (!*fn && strict) {
126 BOOST_LOG(error) <<
"Couldn't find function: "sv << name;
139 const int fd = ::open(path, flags | O_CLOEXEC);
143 const int saved_errno = errno;
144 (void) drmDropMaster(fd);
150#ifdef HERMES_BUILD_SDBUS
151 int open_user_bus(sd_bus **result) {
157 const int discovered = sd_bus_open_user(result);
158 if (discovered >= 0) {
162 sd_bus_unref(*result);
165 if (discovered != -ENOMEDIUM) {
169 sd_bus *bus =
nullptr;
170 int status = sd_bus_new(&bus);
174 const auto fail = [&bus](
int error) {
180 status = sd_bus_set_address(bus, address.c_str());
184 status = sd_bus_set_bus_client(bus, 1);
188 status = sd_bus_start(bus);
208 using ifaddr_t = util::safe_ptr<ifaddrs, freeifaddrs>;
210 ifaddr_t get_ifaddrs() {
211 ifaddrs *p {
nullptr};
224 constexpr auto CONFIG_DIR_NAME =
"hermes"sv;
225 constexpr auto SHARED_CONFIG_DIR_NAME =
"sunshine"sv;
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},
240 void rename_shared_config_files(
const fs::path &config_path) {
241 for (
const auto &[shared_name, name] : RENAMED_CONFIG_FILES) {
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);
248 std::cerr <<
"Failed to rename "sv << shared_file <<
" to "sv << file <<
": "sv << ec.message() << std::endl;
262 void seed_from_shared_config(
const fs::path &config_path,
const fs::path &shared_path) {
264 if (!fs::is_directory(shared_path, ec)) {
270 if (fs::is_directory(config_path, ec) && !fs::is_empty(config_path, ec)) {
274 std::cout <<
"Seeding "sv << config_path <<
" from "sv << shared_path << std::endl;
275 fs::create_directories(config_path, ec);
277 fs::copy(shared_path, config_path, fs::copy_options::recursive | fs::copy_options::copy_symlinks, 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;
287 for (
const auto &name : {
"sunshine.log"sv,
"sunshine.log.backup"sv}) {
288 fs::remove(config_path / name, ec);
292 std::cout << shared_path <<
" was left untouched; Apollo and Sunshine keep using it."sv << std::endl;
302 static std::once_flag migration_flag;
303 static fs::path config_path;
306 std::call_once(migration_flag, []() {
308 bool migrate_config =
true;
311 const char *migrate_envvar;
314 if ((homedir = getenv(
"HOME")) ==
nullptr || strlen(homedir) == 0) {
316 homedir = getpwuid(geteuid())->pw_dir;
320 if ((dir = getenv(
"CONFIGURATION_DIRECTORY")) !=
nullptr && strlen(dir) > 0) {
322 config_path = fs::path(dir) / CONFIG_DIR_NAME;
326 if (!found && (dir = getenv(
"XDG_CONFIG_HOME")) !=
nullptr && strlen(dir) > 0) {
328 config_path = fs::path(dir) / CONFIG_DIR_NAME;
332 migrate_config =
false;
333 config_path = fs::path(homedir) /
".config" / CONFIG_DIR_NAME;
337 migrate_envvar = getenv(
"SUNSHINE_MIGRATE_CONFIG");
338 if (migrate_config && found && migrate_envvar && strcmp(migrate_envvar,
"1") == 0) {
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;
346 fs::create_directories(config_path, ec);
351 fs::copy(old_config_path, config_path, fs::copy_options::recursive | fs::copy_options::copy_symlinks, ec);
355 fs::remove_all(old_config_path, ec);
357 std::cerr <<
"Failed to clean up old config directory: " << ec.message() << std::endl;
364 std::cerr <<
"Migration failed: " << ec.message() << std::endl;
365 config_path = old_config_path;
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;
376 seed_from_shared_config(config_path, config_path.parent_path() / SHARED_CONFIG_DIR_NAME);
377 rename_shared_config_files(config_path);
383 std::string from_sockaddr(
const sockaddr *
const ip_addr) {
384 char data[INET6_ADDRSTRLEN] = {};
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);
393 return std::string {data};
396 std::pair<std::uint16_t, std::string> from_sockaddr_ex(
const sockaddr *
const ip_addr) {
397 char data[INET6_ADDRSTRLEN] = {};
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;
409 return {port, std::string {data}};
416 boost::system::error_code ec;
417 const auto parsed = boost::asio::ip::make_address(std::string {address}, 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;
424 auto ifaddrs = get_ifaddrs();
425 for (
auto pos = ifaddrs.get(); pos !=
nullptr; pos = pos->ifa_next) {
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);
437 BOOST_LOG(warning) <<
"Unable to find MAC address for "sv << address;
438 return "00:00:00:00:00:00"s;
441std::string get_local_ip_for_gateway() {
442 int fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
444 BOOST_LOG(warning) <<
"Socket creation failed: " << strerror(errno);
449 struct nlmsghdr *nlMsg = (
struct nlmsghdr *)buffer;
450 struct rtmsg *rtMsg = (
struct rtmsg *)NLMSG_DATA(nlMsg);
451 struct rtattr *rtAttr;
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();
461 if (send(fd, nlMsg, nlMsg->nlmsg_len, 0) < 0) {
462 BOOST_LOG(warning) <<
"Send message failed: " << strerror(errno);
467 std::string local_ip;
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) {
477 rtMsg = (
struct rtmsg *)NLMSG_DATA(nlMsg);
478 if (rtMsg->rtm_family != AF_INET || rtMsg->rtm_table != RT_TABLE_MAIN)
481 rtAttr = (
struct rtattr *)RTM_RTA(rtMsg);
482 int rtLen = RTM_PAYLOAD(nlMsg);
486 memset(&gateway, 0,
sizeof(gateway));
487 memset(&local, 0,
sizeof(local));
489 for (; RTA_OK(rtAttr, rtLen); rtAttr = RTA_NEXT(rtAttr, rtLen)) {
490 switch(rtAttr->rta_type) {
492 gateway.s_addr = *
reinterpret_cast<uint32_t *
>(RTA_DATA(rtAttr));
495 local.s_addr = *
reinterpret_cast<uint32_t *
>(RTA_DATA(rtAttr));
502 if (gateway.s_addr != 0 && local.s_addr != 0) {
503 local_ip = inet_ntoa(local);
514 if (local_ip.empty()) {
515 BOOST_LOG(warning) <<
"No associated IP address found for the default gateway";
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) {
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);
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);
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);
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);
548 auto working_dir = boost::filesystem::path(std::getenv(
"HOME"));
549 std::string cmd = R
"(xdg-open ")" + url + R"(")";
551 boost::process::v1::environment _env = boost::this_process::environment();
553 auto child = run_command(
false,
false, cmd, working_dir, _env,
nullptr, ec,
nullptr);
555 BOOST_LOG(warning) <<
"Couldn't open url ["sv << url <<
"]: System: "sv << ec.message();
557 BOOST_LOG(info) <<
"Opened url ["sv << url <<
"]"sv;
562 void adjust_thread_priority(thread_priority_e priority) {
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;
576 struct screen_lock_bus_t {
577 using clock = std::chrono::steady_clock;
579 sd_bus *bus {
nullptr};
580 sd_bus_slot *owner_watch {
nullptr};
581 std::uint32_t cookie {0};
585 std::string cookie_owner;
586 bool inhibited {
false};
587 bool failure_logged {
false};
590 clock::time_point retry_at {};
592 clock::duration retry_delay {};
595 std::string bus_error_message(
const sd_bus_error &error,
int status) {
597 return error.message;
599 return std::strerror(-status);
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);
607 class screen_lock_inhibitor_t {
609 screen_lock_inhibitor_t():
610 wake_fd_ {::eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK)},
611 wake_errno_ {wake_fd_ < 0 ? errno : 0} {
614 screen_lock_inhibitor_t(
const screen_lock_inhibitor_t &) =
delete;
615 screen_lock_inhibitor_t &operator=(
const screen_lock_inhibitor_t &) =
delete;
617 ~screen_lock_inhibitor_t() {
621 worker_.request_stop();
623 if (worker_.joinable()) {
631 void set_streaming(
bool streaming) {
633 std::lock_guard lock {mutex_};
634 streaming_ = streaming;
635 if (streaming && !worker_.joinable()) {
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;
644 worker_ = std::jthread {[
this](std::stop_token
stop) {
653 using clock = screen_lock_bus_t::clock;
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();
660 bool streaming_ {
false};
661 bool wake_failure_logged_ {
false};
663 const int wake_errno_;
664 std::jthread worker_;
670 const std::uint64_t one = 1;
671 while (::write(wake_fd_, &one,
sizeof(one)) < 0 && errno == EINTR) {
675 void consume_wakeups() {
676 std::uint64_t count = 0;
677 while (::read(wake_fd_, &count,
sizeof(count)) < 0 && errno == EINTR) {
681 bool wants_inhibition() {
682 std::lock_guard lock {mutex_};
690 bool wait_for_event(
const screen_lock_bus_t &state, clock::time_point deadline) {
691 std::array<pollfd, 2> fds {};
693 fds[count++] = pollfd {wake_fd_, POLLIN, 0};
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) {
703 fds[count++] = pollfd {fd,
static_cast<short>(events), 0};
707 if (has_bus_deadline > 0 && bus_deadline_usec != UINT64_MAX) {
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
715 deadline = std::min(deadline, clock::now() + remaining);
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));
725 if (::poll(fds.data(), count, timeout_ms) < 0 && errno != EINTR) {
727 std::this_thread::sleep_for(std::chrono::milliseconds {100});
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;
740 static void retry_now(screen_lock_bus_t &state) {
741 state.retry_at = clock::now();
742 state.retry_delay = {};
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);
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) {
759 if (std::strcmp(name, screen_saver_service.data()) != 0 ||
760 std::strcmp(old_owner, new_owner) == 0) {
767 if (state->inhibited && state->cookie_owner == old_owner) {
768 state->inhibited =
false;
770 state->cookie_owner.clear();
771 if (new_owner[0] !=
'\0') {
776 state->retry_delay = {};
777 schedule_retry(*state);
779 }
else if (!state->inhibited && new_owner[0] !=
'\0') {
786 static bool dispatch(screen_lock_bus_t &state) {
788 while ((processed = sd_bus_process(state.bus,
nullptr)) > 0) {
790 return processed >= 0;
793 static void close_bus(screen_lock_bus_t &state,
bool release_inhibition) {
797 if (release_inhibition && state.inhibited) {
802 if (release_inhibition && state.inhibited) {
803 sd_bus_error error = SD_BUS_ERROR_NULL;
806 const int status = sd_bus_call_method(
808 state.cookie_owner.c_str(),
809 screen_saver_path.data(),
810 screen_saver_interface.data(),
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;
822 BOOST_LOG(warning) <<
"Could not release screen-lock inhibition: "sv
823 << bus_error_message(error, status);
825 sd_bus_error_free(&error);
829 sd_bus_slot_unref(state.owner_watch);
830 state.owner_watch =
nullptr;
831 sd_bus_unref(state.bus);
833 state.inhibited =
false;
835 state.cookie_owner.clear();
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.");
848 sd_bus_set_method_call_timeout(bus, 2'000'000);
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);
858 warn_once(state,
"Could not watch org.freedesktop.ScreenSaver ownership changes.");
859 close_bus(state,
false);
863 state.retry_at = clock::now();
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(
872 screen_saver_service.data(),
873 screen_saver_path.data(),
874 screen_saver_interface.data(),
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) {
888 warn_once(state,
"Could not inhibit screen locking through org.freedesktop.ScreenSaver: " + bus_error_message(error, status));
890 warn_once(state,
"The screensaver returned an unexpected Inhibit reply.");
892 if (status < 0 && screen_saver_has_no_owner(error)) {
895 state.retry_at = never;
897 schedule_retry(state);
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);
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;
911 sd_bus_error_free(&error);
912 sd_bus_message_unref(reply);
915 void run(std::stop_token stop) {
916 screen_lock_bus_t state;
922 if (
stop.stop_requested()) {
926 if (!wants_inhibition()) {
927 close_bus(state,
true);
928 state.retry_delay = {};
929 wait_for_event(state, never);
934 if (clock::now() < state.retry_at) {
935 wait_for_event(state, state.retry_at);
938 if (!connect_bus(state)) {
939 schedule_retry(state);
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);
953 if (!state.inhibited && clock::now() >= state.retry_at) {
954 acquire_inhibition(state);
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);
965 close_bus(state,
true);
969 screen_lock_inhibitor_t &screen_lock() {
970 static screen_lock_inhibitor_t inhibitor;
974 void inhibit_screen_lock() {
975 screen_lock().set_streaming(
true);
978 void uninhibit_screen_lock() {
979 screen_lock().set_streaming(
false);
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;
990 void uninhibit_screen_lock() {}
994 void streaming_will_start() {
995 if (config::sunshine.inhibit_screen_lock) {
996 inhibit_screen_lock();
1000 void streaming_will_stop() {
1003 uninhibit_screen_lock();
1006 void restart_on_exit() {
1007 char executable[PATH_MAX];
1008 ssize_t len = readlink(
"/proc/self/exe", executable, PATH_MAX - 1);
1010 BOOST_LOG(fatal) <<
"readlink() failed: "sv << errno;
1013 executable[len] =
'\0';
1016 int openmax = (int) sysconf(_SC_OPEN_MAX);
1017 for (
int fd = STDERR_FILENO + 1; fd < openmax; fd++) {
1027 std::vector<char *> envp;
1029 for (
const auto &assignment : environment) {
1030 envp.push_back(
const_cast<char *
>(assignment.c_str()));
1032 envp.push_back(
nullptr);
1037 BOOST_LOG(fatal) <<
"execv() failed: "sv << errno;
1042 atexit(restart_on_exit);
1046 int set_env(
const std::string &name,
const std::string &value) {
1047 return setenv(name.c_str(), value.c_str(), 1);
1051 return unsetenv(name.c_str());
1055 if (process_group::signal(native_handle, SIGTERM)) {
1056 BOOST_LOG(debug) <<
"Successfully sent SIGTERM to process group: "sv << native_handle;
1059 BOOST_LOG(warning) <<
"Unable to send SIGTERM to process group ["sv << native_handle <<
"]: "sv << errno;
1065 return process_group::running(native_handle);
1069 std::ifstream cgroups {
"/proc/self/cgroup"};
1071 bool managed =
false;
1072 while (std::getline(cgroups, entry)) {
1073 if (is_hermes_user_service_cgroup(entry)) {
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";
1094 child.terminate(ec);
1097 BOOST_LOG(warning) <<
"Unable to request user-service stop; continuing normal shutdown";
1101 struct sockaddr_in to_sockaddr(boost::asio::ip::address_v4 address, uint16_t port) {
1102 struct sockaddr_in saddr_v4 = {};
1104 saddr_v4.sin_family = AF_INET;
1105 saddr_v4.sin_port = htons(port);
1107 auto addr_bytes = address.to_bytes();
1108 memcpy(&saddr_v4.sin_addr, addr_bytes.data(),
sizeof(saddr_v4.sin_addr));
1113 struct sockaddr_in6 to_sockaddr(boost::asio::ip::address_v6 address, uint16_t port) {
1114 struct sockaddr_in6 saddr_v6 = {};
1116 saddr_v6.sin6_family = AF_INET6;
1117 saddr_v6.sin6_port = htons(port);
1118 saddr_v6.sin6_scope_id = address.scope_id();
1120 auto addr_bytes = address.to_bytes();
1121 memcpy(&saddr_v6.sin6_addr, addr_bytes.data(),
sizeof(saddr_v6.sin6_addr));
1127 auto sockfd = (int) send_info.native_socket;
1128 struct msghdr msg = {};
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);
1136 msg.msg_name = (
struct sockaddr *) &taddr_v6;
1137 msg.msg_namelen =
sizeof(taddr_v6);
1139 taddr_v4 = to_sockaddr(send_info.target_address.to_v4(), send_info.target_port);
1141 msg.msg_name = (
struct sockaddr *) &taddr_v4;
1142 msg.msg_namelen =
sizeof(taddr_v4);
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;
1150 socklen_t cmbuflen = 0;
1152 msg.msg_control = cmbuf.buf;
1153 msg.msg_controllen =
sizeof(cmbuf.buf);
1157 auto pktinfo_cm = CMSG_FIRSTHDR(&msg);
1158 if (send_info.source_address.is_v6()) {
1159 struct in6_pktinfo pktInfo;
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;
1165 cmbuflen += CMSG_SPACE(
sizeof(pktInfo));
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));
1172 struct in_pktinfo pktInfo;
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;
1178 cmbuflen += CMSG_SPACE(
sizeof(pktInfo));
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));
1186 auto const max_iovs_per_msg = send_info.payload_buffers.size() + (send_info.headers ? 1 : 0);
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) {
1197 auto segs_in_batch = std::min(send_info.block_count - seg_index, seg_max);
1198 if (send_info.headers) {
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;
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;
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;
1223 msg.msg_iovlen = iovlen;
1226 if (segs_in_batch > 1) {
1227 msg.msg_controllen = cmbuflen + CMSG_SPACE(sizeof(uint16_t));
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;
1236 msg.msg_controllen = cmbuflen;
1242 auto bytes_sent = sendmsg(sockfd, &msg, 0);
1243 if (bytes_sent < 0) {
1245 if (errno == EAGAIN) {
1249 pfd.events = POLLOUT;
1251 if (poll(&pfd, 1, -1) != 1) {
1252 BOOST_LOG(warning) <<
"poll() failed: "sv << errno;
1260 BOOST_LOG(verbose) <<
"sendmsg() failed: "sv << errno;
1264 seg_index += bytes_sent / msg_size;
1268 if (seg_index != 0) {
1269 return seg_index >= send_info.block_count;
1276 struct mmsghdr msgs[send_info.block_count];
1277 struct iovec iovs[send_info.block_count * (send_info.headers ? 2 : 1)];
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;
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;
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;
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;
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) {
1307 if (errno == EAGAIN) {
1311 pfd.events = POLLOUT;
1313 if (poll(&pfd, 1, -1) != 1) {
1314 BOOST_LOG(warning) <<
"poll() failed: "sv << errno;
1322 BOOST_LOG(warning) <<
"sendmmsg() failed: "sv << errno;
1326 blocks_sent += msgs_sent;
1333 bool send(send_info_t &send_info) {
1334 auto sockfd = (int) send_info.native_socket;
1335 struct msghdr msg = {};
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);
1343 msg.msg_name = (
struct sockaddr *) &taddr_v6;
1344 msg.msg_namelen =
sizeof(taddr_v6);
1346 taddr_v4 = to_sockaddr(send_info.target_address.to_v4(), send_info.target_port);
1348 msg.msg_name = (
struct sockaddr *) &taddr_v4;
1349 msg.msg_namelen =
sizeof(taddr_v4);
1353 char buf[std::max(CMSG_SPACE(
sizeof(
struct in_pktinfo)), CMSG_SPACE(
sizeof(
struct in6_pktinfo)))];
1354 struct cmsghdr alignment;
1357 socklen_t cmbuflen = 0;
1359 msg.msg_control = cmbuf.buf;
1360 msg.msg_controllen =
sizeof(cmbuf.buf);
1362 auto pktinfo_cm = CMSG_FIRSTHDR(&msg);
1363 if (send_info.source_address.is_v6()) {
1364 struct in6_pktinfo pktInfo;
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;
1370 cmbuflen += CMSG_SPACE(
sizeof(pktInfo));
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));
1377 struct in_pktinfo pktInfo;
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;
1383 cmbuflen += CMSG_SPACE(
sizeof(pktInfo));
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));
1391 struct iovec iovs[2];
1393 if (send_info.header) {
1394 iovs[iovlen].iov_base = (
void *) send_info.header;
1395 iovs[iovlen].iov_len = send_info.header_size;
1398 iovs[iovlen].iov_base = (
void *) send_info.payload;
1399 iovs[iovlen].iov_len = send_info.payload_size;
1403 msg.msg_iovlen = iovlen;
1405 msg.msg_controllen = cmbuflen;
1407 auto bytes_sent = sendmsg(sockfd, &msg, 0);
1410 while (bytes_sent < 0 && errno == EAGAIN) {
1414 pfd.events = POLLOUT;
1416 if (poll(&pfd, 1, -1) != 1) {
1417 BOOST_LOG(warning) <<
"poll() failed: "sv << errno;
1422 bytes_sent = sendmsg(sockfd, &msg, 0);
1425 if (bytes_sent < 0) {
1426 BOOST_LOG(warning) <<
"sendmsg() failed: "sv << errno;
1436 static std::atomic<int> qos_ref_count = 0;
1440 qos_t(
int sockfd, std::vector<std::tuple<int, int, int>> options):
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;
1459 std::vector<std::tuple<int, int, int>> options;
1471 int sockfd = (int) native_socket;
1472 std::vector<std::tuple<int, int, int>> reset_options;
1480 if (address.is_v6() && !address.to_v6().is_v4_mapped()) {
1482 option = IPV6_TCLASS;
1491 switch (data_type) {
1499 BOOST_LOG(error) <<
"Unknown traffic type: "sv << (int) data_type;
1507 if (setsockopt(sockfd, level, option, &dscp,
sizeof(dscp)) == 0) {
1509 reset_options.emplace_back(std::make_tuple(level, option, -1));
1511 BOOST_LOG(error) <<
"Failed to set TOS/TCLASS: "sv << errno;
1523 if (setsockopt(sockfd, SOL_SOCKET, SO_PRIORITY, &priority,
sizeof(priority)) == 0) {
1525 reset_options.emplace_back(std::make_tuple(SOL_SOCKET, SO_PRIORITY, 0));
1527 BOOST_LOG(error) <<
"Failed to set SO_PRIORITY: "sv << errno;
1530 return std::make_unique<qos_t>(sockfd, reset_options);
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();
1544#ifdef HERMES_BUILD_CUDA
1547#ifdef HERMES_BUILD_WAYLAND
1550#ifdef HERMES_BUILD_DRM
1553#ifdef HERMES_BUILD_X11
1560 static std::bitset<source::MAX_FLAGS> sources;
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);
1566 bool verify_nvfbc() {
1567 return !nvfbc_display_names().empty();
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);
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);
1585 if (!kms_display_names(mem_type_e::unknown).empty()) {
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;
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);
1613 std::vector<std::string> display_names(mem_type_e hwdevice_type) {
1614#ifdef HERMES_BUILD_DRM
1620 if (!virtual_displays.empty()) {
1621 return virtual_displays;
1625#ifdef HERMES_BUILD_CUDA
1627 if (sources[source::NVFBC] && hwdevice_type == mem_type_e::cuda) {
1628 return nvfbc_display_names();
1631#ifdef HERMES_BUILD_WAYLAND
1632 if (sources[source::WAYLAND]) {
1633 return wl_display_names();
1636#ifdef HERMES_BUILD_DRM
1637 if (sources[source::KMS]) {
1638 return kms_display_names(hwdevice_type);
1641#ifdef HERMES_BUILD_X11
1642 if (sources[source::X11]) {
1643 return x11_display_names();
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";
1664#ifdef HERMES_BUILD_KWIN_TRANSPORT
1665 return kwin_display(hwdevice_type, config);
1667 BOOST_LOG(error) <<
"Private KWin capture support was not built; refusing host capture";
1672#ifdef HERMES_BUILD_WAYLAND
1679 BOOST_LOG(info) <<
"Screencasting Hyprland headless output with Wayland's protocol"sv;
1680 return wl_display(hwdevice_type, display_name, config);
1683#ifdef HERMES_BUILD_DRM
1685 BOOST_LOG(info) <<
"Screencasting Hermes-KMS virtual display with KMS"sv;
1686 return kms_display(hwdevice_type, display_name, config);
1689 BOOST_LOG(info) <<
"Screencasting EVDI virtual display with KMS"sv;
1690 return kms_display(hwdevice_type, display_name, config);
1694#ifdef HERMES_BUILD_CUDA
1696 BOOST_LOG(info) <<
"Screencasting with NvFBC"sv;
1697 return nvfbc_display(hwdevice_type, display_name, config);
1700#ifdef HERMES_BUILD_WAYLAND
1702 BOOST_LOG(info) <<
"Screencasting with Wayland's protocol"sv;
1703 return wl_display(hwdevice_type, display_name, config);
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);
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);
1722 std::unique_ptr<deinit_t> init() {
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";
1734 set_env(
"AMD_DEBUG",
"lowlatencyenc");
1740#ifdef HERMES_BUILD_WAYLAND
1741 if (std::getenv(
"WAYLAND_DISPLAY")) {
1745#if defined(HERMES_BUILD_X11) || defined(HERMES_BUILD_CUDA)
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;
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;
1762#ifdef HERMES_BUILD_WAYLAND
1763 if ((config::video.capture.empty() && sources.none()) || config::video.capture ==
"wlr") {
1765 sources[source::WAYLAND] =
true;
1769#ifdef HERMES_BUILD_DRM
1770 if ((config::video.capture.empty() && sources.none()) || config::video.capture ==
"kms") {
1772 sources[source::KMS] =
true;
1776#ifdef HERMES_BUILD_X11
1779 if (config::video.capture.empty() || config::video.capture ==
"x11") {
1781 sources[source::X11] =
true;
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.";
1793 if (!gladLoaderLoadEGL(EGL_NO_DISPLAY) || !eglGetPlatformDisplay) {
1794 BOOST_LOG(warning) <<
"Couldn't load EGL library"sv;
1797 return std::make_unique<deinit_t>();
1802 void sleep_for(
const std::chrono::nanoseconds &duration)
override {
1803 std::this_thread::sleep_for(duration);
1806 operator bool()
override {
1812 return std::make_unique<linux_high_precision_timer>();
1817 if (!clipboard_available()) {
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";
1832 constexpr size_t max_clipboard_bytes = 64 * 1024;
1833 std::string content;
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";
1840 content.append(buffer, bytes_read);
1843 const bool read_failed = ferror(pipe) != 0;
1844 if (!helper.finish() || read_failed) {
1845 BOOST_LOG(warning) <<
"Unable to read the clipboard";
1853 set_clipboard(
const std::string& content) {
1854 if (!clipboard_available() || content.size() > 64 * 1024 || content.find(
'\0') != std::string::npos) {
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);
1865 BOOST_LOG(warning) <<
"Unable to write the " << (wayland ?
"Wayland" :
"X11") <<
" clipboard";
1871 clipboard_available() {
1873 return std::getenv(
"WAYLAND_DISPLAY") !=
nullptr &&
1874 !bp::search_path(
"wl-copy").empty() && !bp::search_path(
"wl-paste").empty();
1877 return std::getenv(
"DISPLAY") !=
nullptr && !bp::search_path(
"xclip").empty();
1885 const char *desktop = std::getenv(
"XDG_CURRENT_DESKTOP");
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;
1902 if (desktop_is_gamescope) {
1908 switch (window_system) {
1931 static bool detect_autologin() {
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) {
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) {
1956 for (
const char *dir : {
"/etc/sddm.conf.d",
"/etc/lightdm/lightdm.conf.d"}) {
1957 if (!fs::exists(dir, ec)) {
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) {
1974 out.
enabled = config::sunshine.appliance_mode;
void sleep_for(const std::chrono::nanoseconds &duration) override
Sleep for the duration.
Clipboard helper pipes with isolated descriptor ownership.
Declarations for common platform specific utilities.
bool process_group_running(std::uintptr_t native_handle)
Check if a process group still has running children.
std::string get_mac_address(const std::string_view &address)
The MAC address of the interface that holds address.
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...
@ gamescope_session
Standalone Gamescope compositor (SteamOS Game Mode).
@ desktop_wayland
Wayland desktop session (KDE/GNOME/wlroots).
@ desktop_x11
X11 desktop session.
@ headless
No window system / capture source available.
bool request_process_group_exit(std::uintptr_t native_handle)
Attempt to gracefully terminate a process group.
std::unique_ptr< high_precision_timer > create_high_precision_timer()
Create platform-specific timer capable of high-precision sleep.
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.
void open_url(const std::string &url)
Open a url in the default web browser.
bool needs_encoder_reenumeration()
Check if GPUs/drivers have changed since the last call to this function.
std::string get_host_name()
Returns the current computer name in UTF-8.
session_environment_t detect_session_environment()
Detect the current session/compositor environment.
std::filesystem::path appdata()
Performs migration if necessary, then returns the appdata directory.
bool touch_binds_to_output()
Whether the session binds a touchscreen or a pen to one output.
int set_env(const std::string &name, const std::string &value)
Set an environment variable.
appliance_readiness_t appliance_readiness()
Assess appliance-mode readiness without changing any state.
int unset_env(const std::string &name)
Unset an environment variable.
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.
@ MAX_FLAGS
The maximum number of flags.
bool request_user_service_stop()
Miscellaneous declarations for Linux.
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.
Declarations for networking related functions.
std::optional< raw_address_t > raw_from_sockaddr(const sockaddr *addr)
The address a sockaddr holds.
bool same_address(const raw_address_t &interface_address, const raw_address_t &wanted)
Whether an interface address is the address the host was reached on.
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 ...
bool autologin_configured
A display-manager autologin drop-in was detected.
bool gamescope_available
A Gamescope compositor/session is present.
bool headless_capable
Can present without a physical monitor (virtual display present).
bool enabled
config appliance_mode flag state.
std::string session_environment
session_environment_t::describe() value.
bool virtual_display_available
An EVDI or Hermes-KMS virtual display is usable.
bool gamescope_running
A Gamescope compositor is present.
bool can_host_virtual_display
A desktop compositor can adopt a virtual display.
std::string desktop
Raw XDG_CURRENT_DESKTOP, for diagnostics.
Declarations for VA-API hardware accelerated capture.
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.