7#define BOOST_BIND_GLOBAL_PLACEHOLDERS
16#include <condition_variable>
28 #include <sys/utsname.h>
37#include <boost/algorithm/string.hpp>
38#include <boost/asio/ssl/context.hpp>
39#include <boost/filesystem.hpp>
40#include <boost/process/v1/search_path.hpp>
41#include <nlohmann/json.hpp>
42#include <Simple-Web-Server/crypto.hpp>
43#include <Simple-Web-Server/server_https.hpp>
70using namespace std::literals;
73 namespace fs = std::filesystem;
76 nlohmann::json hestia_runtime_status_json();
84 }
catch (
const std::exception &) {
91 class HestiaHTTPSServer:
public SimpleWeb::ServerBase<SimpleWeb::HTTPS> {
93 HestiaHTTPSServer(
const std::string &certification_file,
const std::string &private_key_file):
94 ServerBase<SimpleWeb::HTTPS>::ServerBase(443),
95 context(boost::asio::ssl::context::tls_server) {
96 context.set_options(boost::asio::ssl::context::no_tlsv1);
97 context.set_options(boost::asio::ssl::context::no_tlsv1_1);
98 context.use_certificate_chain_file(certification_file);
99 context.use_private_key_file(private_key_file, boost::asio::ssl::context::pem);
102 std::function<void(std::shared_ptr<Request>, SSL *)> authenticate_client;
105 boost::asio::ssl::context context;
107 void after_bind()
override {
110 context.set_verify_mode(boost::asio::ssl::verify_peer | boost::asio::ssl::verify_client_once);
111 context.set_verify_callback([](
int, boost::asio::ssl::verify_context &) {
123 if (X509 *certificate = SSL_CTX_get0_certificate(context.native_handle())) {
124 SSL_CTX_add_client_CA(context.native_handle(), certificate);
137 static const unsigned char session_id_context[] =
"hermes-confighttp";
138 SSL_CTX_set_session_id_context(
139 context.native_handle(),
141 sizeof(session_id_context) - 1
145 void accept()
override {
146 auto connection = create_connection(*io_service, context);
148 acceptor->async_accept(connection->socket->lowest_layer(), [
this, connection](
const SimpleWeb::error_code &ec) {
149 auto lock = connection->handler_runner->continue_lock();
154 if (ec != SimpleWeb::error::operation_aborted) {
158 auto session = std::make_shared<Session>(config.max_request_streambuf_size, connection);
160 boost::asio::ip::tcp::no_delay option(
true);
161 SimpleWeb::error_code socket_error;
162 session->connection->socket->lowest_layer().set_option(option, socket_error);
164 session->connection->set_timeout(config.timeout_request);
165 session->connection->socket->async_handshake(boost::asio::ssl::stream_base::server, [
this, session](
const SimpleWeb::error_code &handshake_error) {
166 session->connection->cancel_timeout();
167 auto lock = session->connection->handler_runner->continue_lock();
172 if (!handshake_error) {
173 if (authenticate_client) {
174 authenticate_client(session->request, session->connection->socket->native_handle());
177 }
else if (this->on_error) {
178 this->on_error(session->request, handshake_error);
181 }
else if (this->on_error) {
182 this->on_error(session->request, ec);
188 using https_server_t = HestiaHTTPSServer;
189 using args_t = SimpleWeb::CaseInsensitiveMultimap;
190 using resp_https_t = std::shared_ptr<typename SimpleWeb::ServerBase<SimpleWeb::HTTPS>::Response>;
191 using req_https_t = std::shared_ptr<typename SimpleWeb::ServerBase<SimpleWeb::HTTPS>::Request>;
200 std::string sessionCookie;
201 static std::chrono::time_point<std::chrono::steady_clock> cookie_creation_time;
222 std::filesystem::path localApiTokenPath;
224 std::filesystem::path local_api_token_path() {
225 const char *runtime_dir = std::getenv(
"XDG_RUNTIME_DIR");
226 if (!runtime_dir || !*runtime_dir) {
229 return std::filesystem::path {runtime_dir} /
"hermes" /
"local-api.token";
234 if (expected.empty() || presented.size() != expected.size()) {
237 unsigned char difference = 0;
238 for (
size_t index = 0; index < expected.size(); ++index) {
239 difference |=
static_cast<unsigned char>(presented[index] ^ expected[index]);
241 return difference == 0;
244 void write_local_api_token() {
245 localApiTokenPath = local_api_token_path();
246 if (localApiTokenPath.empty()) {
247 BOOST_LOG(debug) <<
"No XDG_RUNTIME_DIR; the local API token is not published."sv;
252 std::filesystem::create_directories(localApiTokenPath.parent_path(), ec);
254 BOOST_LOG(warning) <<
"Could not create "sv << localApiTokenPath.parent_path().string()
255 <<
": "sv << ec.message();
256 localApiTokenPath.clear();
264 const int fd = ::open(localApiTokenPath.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, S_IRUSR | S_IWUSR);
266 BOOST_LOG(warning) <<
"Could not write "sv << localApiTokenPath.string() <<
": "sv << std::strerror(errno);
268 localApiTokenPath.clear();
274 BOOST_LOG(warning) <<
"Short write publishing the local API token"sv;
275 std::filesystem::remove(localApiTokenPath, ec);
277 localApiTokenPath.clear();
281 BOOST_LOG(info) <<
"Local API token published at "sv << localApiTokenPath.string()
282 <<
" for the Game Mode console."sv;
285 void remove_local_api_token() {
286 if (localApiTokenPath.empty()) {
290 std::filesystem::remove(localApiTokenPath, ec);
292 localApiTokenPath.clear();
300 const auto header = request->header.find(
"authorization");
301 if (header == request->header.end()) {
304 constexpr std::string_view prefix =
"Bearer ";
305 std::string_view value {header->second};
306 if (value.size() <= prefix.size() ||
307 !boost::algorithm::iequals(value.substr(0, prefix.size()), prefix)) {
316 BOOST_LOG(warning) <<
"Web UI: ["sv << address
317 <<
"] -- rejected Game Mode token from WAN"sv;
324 static std::atomic<int> evdi_install_status {0};
326 static std::atomic<int> clipboard_install_status {0};
329 switch (diagnostic) {
330 case VDISPLAY::EVDI_DIAGNOSTIC::READY:
332 case VDISPLAY::EVDI_DIAGNOSTIC::INITIAL_DEVICE_CONFIGURATION_REQUIRED:
333 return "setup_required";
334 case VDISPLAY::EVDI_DIAGNOSTIC::LIBRARY_MISSING:
335 return "library_missing";
336 case VDISPLAY::EVDI_DIAGNOSTIC::MODULE_NOT_INSTALLED:
337 return "module_not_installed";
338 case VDISPLAY::EVDI_DIAGNOSTIC::MODULE_NOT_LOADED:
339 return "module_not_loaded";
340 case VDISPLAY::EVDI_DIAGNOSTIC::DKMS_BUILD_FAILED:
341 return "dkms_build_failed";
344 return "module_not_loaded";
358 static nlohmann::json stream_ports_json() {
359 nlohmann::json ports = nlohmann::json::array();
365 const std::pair<const char *, int> checks[] = {
366 {
"Video", stream::VIDEO_STREAM_PORT},
367 {
"Control", stream::CONTROL_PORT},
368 {
"Audio", stream::AUDIO_STREAM_PORT},
371 for (
const auto &[name, offset] : checks) {
383 static nlohmann::json evdi_status_json() {
385 nlohmann::json output {
386 {
"diagnostic", evdi_diagnostic_name(status.diagnostic)},
387 {
"libraryInstalled", status.library_installed},
388 {
"libraryLoaded", status.library_loaded},
389 {
"moduleLoaded", status.module_loaded},
390 {
"moduleInstalled", status.module_installed},
391 {
"deviceCount", status.device_count},
392 {
"sessionType", status.session_type},
393 {
"exclusiveLayoutSupported", status.exclusive_layout_supported},
394 {
"outputLayoutBackend", status.output_layout_backend},
395 {
"libraryVersion", status.library_version},
396 {
"runningKernel", status.running_kernel},
397 {
"dkmsKernels", status.dkms_kernels},
398 {
"activeDisplays", nlohmann::json::array()},
401 for (
const auto &display : status.active_displays) {
402 output[
"activeDisplays"].push_back({
404 {
"clientName",
display.client_name},
405 {
"deviceIndex",
display.device_index},
406 {
"drmCardIndex",
display.drm_card_index},
410 {
"frameUpdates",
display.frame_updates},
411 {
"capturePath",
"evdi_cpu_buffer"},
412 {
"zeroCopyCapture",
false},
413 {
"hardwareEncodingAvailable",
true},
421 switch (diagnostic) {
422 case VDISPLAY::HERMES_KMS_DIAGNOSTIC::READY:
424 case VDISPLAY::HERMES_KMS_DIAGNOSTIC::MODULE_NOT_LOADED:
425 return "module_not_loaded";
426 case VDISPLAY::HERMES_KMS_DIAGNOSTIC::MODULE_NOT_INSTALLED:
427 return "module_not_installed";
428 case VDISPLAY::HERMES_KMS_DIAGNOSTIC::DKMS_BUILD_FAILED:
429 return "dkms_build_failed";
430 case VDISPLAY::HERMES_KMS_DIAGNOSTIC::UAPI_TOO_OLD:
431 return "uapi_too_old";
432 case VDISPLAY::HERMES_KMS_DIAGNOSTIC::MISSING_CAPABILITIES:
433 return "missing_capabilities";
434 case VDISPLAY::HERMES_KMS_DIAGNOSTIC::DEVICE_NODE_MISSING:
435 return "device_node_missing";
440 return "module_not_loaded";
448 static nlohmann::json session_features_json() {
449 auto features = nlohmann::json::array();
453 {
"readiness", VDISPLAY::readinessName(
report.readiness)},
454 {
"detail",
report.detail},
455 {
"remediation",
report.remediation},
467 switch (status.diagnostic) {
470 case MODULE_NOT_INSTALLED:
471 return "The Hermes-KMS driver is not installed for the running kernel (" + status.running_kernel +
").";
472 case DKMS_BUILD_FAILED:
473 return "The Hermes-KMS driver failed to build for the running kernel (" + status.running_kernel +
474 "); DKMS's make.log for that kernel says why.";
475 case MODULE_NOT_LOADED:
476 return "The Hermes-KMS driver is installed but not loaded.";
478 return "The loaded Hermes-KMS driver (" + status.
driver_version +
", interface " +
479 std::to_string(status.
uapi_version) +
") is older than this Hermes needs (interface " +
481 case MISSING_CAPABILITIES:
483 ") lacks features this Hermes needs. Update the driver.";
484 case DEVICE_NODE_MISSING:
485 return "The Hermes-KMS driver is loaded but created no device.";
487 return "The Hermes-KMS driver is loaded, but Hermes may not open " + status.
inaccessible_node +
488 ". The driver's udev rules give that node to the user logged in at the PC: check that "
489 "they are installed and that Hermes runs as that user.";
500 " is still loaded. Restart the PC to use the installed driver.";
508 return "This driver (interface " + std::to_string(status.
uapi_version) +
510 "). That usually works; if virtual displays misbehave, update Hermes.";
513 static nlohmann::json hermes_kms_status_json() {
515 nlohmann::json output {
516 {
"diagnostic", hermes_kms_diagnostic_name(status.diagnostic)},
517 {
"moduleLoaded", status.module_loaded},
518 {
"moduleInstalled", status.module_installed},
523 {
"experimentalMultiOutputEnabled", status.experimental_multi_output_enabled},
524 {
"multiOutputCapable", status.multi_output_capable},
525 {
"experimentalIsolatedSessionsEnabled", status.experimental_isolated_sessions_enabled},
526 {
"multiDeviceCapable", status.multi_device_capable},
527 {
"deviceCount", status.device_count},
528 {
"outputCount", status.output_count},
529 {
"privateSeatBrokerCount", status.private_seat_broker_count},
530 {
"missingPrivateSeatBrokers", status.missing_private_seat_brokers},
532 {
"runningKernel", status.running_kernel},
533 {
"dkmsKernels", status.dkms_kernels},
534 {
"activeDisplays", nlohmann::json::array()},
539 {
"problem", hermes_kms_problem(status)},
540 {
"reloadNote", hermes_kms_reload_note(status)},
541 {
"newerNote", hermes_kms_newer_note(status)},
544 for (
const auto &display : status.active_displays) {
545 output[
"activeDisplays"].push_back({
547 {
"clientName",
display.client_name},
548 {
"deviceIndex",
display.device_index >= 0 ?
display.device_index + 1 : 0},
549 {
"outputIndex",
display.output_index >= 0 ?
display.output_index + 1 : 0},
550 {
"drmCardIndex",
display.drm_card_index},
554 {
"capturePath",
"hermes_kms_dmabuf"},
555 {
"zeroCopyCapture",
true},
556 {
"hardwareEncodingAvailable",
true},
567 static nlohmann::json prelogin_status_json() {
569 auto checks = nlohmann::json::array();
570 for (
const auto &check :
report.checks) {
573 {
"state", platf::prelogin::state_name(check.state)},
574 {
"title", check.title},
575 {
"detail", check.detail},
582 {
"checks", std::move(checks)},
586 static nlohmann::json clipboard_status_json() {
587 const bool wl_copy_available = !boost::process::v1::search_path(
"wl-copy").empty();
588 const bool wl_paste_available = !boost::process::v1::search_path(
"wl-paste").empty();
589 const bool xclip_available = !boost::process::v1::search_path(
"xclip").empty();
590 const bool wayland_display_available = std::getenv(
"WAYLAND_DISPLAY") !=
nullptr;
591 const bool x11_display_available = std::getenv(
"DISPLAY") !=
nullptr;
592 const char *diagnostic = platf::clipboard_available() ?
"ready" :
593 wayland_display_available && (!wl_copy_available || !wl_paste_available) ?
"wl_clipboard_missing" :
594 x11_display_available && !xclip_available ?
"xclip_missing" :
595 (!wayland_display_available && !x11_display_available) ?
"desktop_session_unavailable" :
"clipboard_unavailable";
597 {
"available", platf::clipboard_available()},
598 {
"diagnostic", diagnostic},
599 {
"wlCopyAvailable", wl_copy_available},
600 {
"wlPasteAvailable", wl_paste_available},
601 {
"xclipAvailable", xclip_available},
602 {
"waylandDisplayAvailable", wayland_display_available},
603 {
"x11DisplayAvailable", x11_display_available},
604 {
"manualInstall",
"Arch/CachyOS: sudo pacman -S --needed wl-clipboard xclip\nDebian/Ubuntu: sudo apt install wl-clipboard xclip\nFedora: sudo dnf install wl-clipboard xclip"},
613 BOOST_LOG(debug) <<
"METHOD :: "sv << request->method;
614 BOOST_LOG(debug) <<
"DESTINATION :: "sv << request->path;
615 for (
auto &[name, val] : request->header) {
616 BOOST_LOG(debug) << name <<
" -- " << (name ==
"Authorization" ?
"CREDENTIALS REDACTED" : val);
618 BOOST_LOG(debug) <<
" [--] "sv;
619 for (
auto &[name, val] : request->parse_query_string()) {
620 BOOST_LOG(debug) << name <<
" -- " << val;
622 BOOST_LOG(debug) <<
" [--] "sv;
630 void send_response(resp_https_t response,
const nlohmann::json &output_tree) {
631 SimpleWeb::CaseInsensitiveMultimap headers;
632 headers.emplace(
"Content-Type",
"application/json");
633 headers.emplace(
"X-Frame-Options",
"DENY");
634 headers.emplace(
"Content-Security-Policy",
"frame-ancestors 'none';");
635 response->write(output_tree.dump(), headers);
645 BOOST_LOG(info) <<
"Web UI: ["sv << address <<
"] -- not authorized"sv;
646 constexpr SimpleWeb::StatusCode code = SimpleWeb::StatusCode::client_error_unauthorized;
648 tree[
"status_code"] = code;
649 tree[
"status"] =
false;
650 tree[
"error"] =
"Unauthorized";
651 const SimpleWeb::CaseInsensitiveMultimap headers {
652 {
"Content-Type",
"application/json"},
653 {
"X-Frame-Options",
"DENY"},
654 {
"Content-Security-Policy",
"frame-ancestors 'none';"}
656 response->write(code, tree.dump(), headers);
665 void send_redirect(resp_https_t response, req_https_t request,
const char *path) {
667 BOOST_LOG(info) <<
"Web UI: ["sv << address <<
"] -- redirecting"sv;
668 const SimpleWeb::CaseInsensitiveMultimap headers {
670 {
"X-Frame-Options",
"DENY"},
671 {
"Content-Security-Policy",
"frame-ancestors 'none';"}
673 response->write(SimpleWeb::StatusCode::redirection_temporary_redirect, headers);
682 std::string
getCookieValue(
const std::string& cookieString,
const std::string& key) {
683 std::string keyWithEqual = key +
"=";
684 std::size_t startPos = cookieString.find(keyWithEqual);
685 if (startPos == std::string::npos)
687 startPos += keyWithEqual.length();
688 std::size_t endPos = cookieString.find(
";", startPos);
689 if (endPos == std::string::npos)
690 return cookieString.substr(startPos);
691 return cookieString.substr(startPos, endPos - startPos);
703 if (ip_type > http::origin_web_ui_allowed) {
704 BOOST_LOG(info) <<
"Web UI: ["sv << address <<
"] -- denied"sv;
705 response->write(SimpleWeb::StatusCode::client_error_forbidden);
720 bool authenticate(resp_https_t response, req_https_t request,
bool needsRedirect =
false) {
724 if (config::sunshine.username.empty()) {
729 auto fg = util::fail_guard([&]() {
731 std::string redir_path =
"/login?redir=.";
732 redir_path += request->path;
745 if (sessionCookie.empty())
748 if (std::chrono::steady_clock::now() - cookie_creation_time > SESSION_EXPIRE_DURATION) {
749 sessionCookie.clear();
752 auto cookies = request->header.find(
"cookie");
753 if (cookies == request->header.end())
756 if (authCookie.empty() ||
757 util::hex(
crypto::hash(authCookie + config::sunshine.salt)).to_string() != sessionCookie)
768 void not_found(resp_https_t response, [[maybe_unused]] req_https_t request) {
769 constexpr SimpleWeb::StatusCode code = SimpleWeb::StatusCode::client_error_not_found;
771 tree[
"status_code"] =
static_cast<int>(code);
772 tree[
"error"] =
"Not Found";
773 SimpleWeb::CaseInsensitiveMultimap headers;
774 headers.emplace(
"Content-Type",
"application/json");
775 headers.emplace(
"X-Frame-Options",
"DENY");
776 headers.emplace(
"Content-Security-Policy",
"frame-ancestors 'none';");
778 response->write(code, tree.dump(), headers);
787 void bad_request(resp_https_t response, [[maybe_unused]] req_https_t request,
const std::string &error_message =
"Bad Request") {
788 constexpr SimpleWeb::StatusCode code = SimpleWeb::StatusCode::client_error_bad_request;
790 tree[
"status_code"] =
static_cast<int>(code);
791 tree[
"status"] =
false;
792 tree[
"error"] = error_message;
793 SimpleWeb::CaseInsensitiveMultimap headers;
794 headers.emplace(
"Content-Type",
"application/json");
795 headers.emplace(
"X-Frame-Options",
"DENY");
796 headers.emplace(
"Content-Security-Policy",
"frame-ancestors 'none';");
798 response->write(code, tree.dump(), headers);
808 bool validateContentType(resp_https_t response, req_https_t request,
const std::string_view& contentType) {
809 auto requestContentType = request->header.find(
"content-type");
810 if (requestContentType == request->header.end()) {
811 bad_request(response, request,
"Content type not provided");
816 std::string actualContentType = requestContentType->second;
817 size_t semicolonPos = actualContentType.find(
';');
818 if (semicolonPos != std::string::npos) {
819 actualContentType = actualContentType.substr(0, semicolonPos);
823 boost::algorithm::trim(actualContentType);
824 boost::algorithm::to_lower(actualContentType);
826 std::string expectedContentType(contentType);
827 boost::algorithm::to_lower(expectedContentType);
829 if (actualContentType != expectedContentType) {
830 bad_request(response, request,
"Content type mismatch");
851 resp_https_t response,
853 const std::string &page,
854 const SimpleWeb::CaseInsensitiveMultimap &extra_headers = {}
856 const std::string path = WEB_DIR + page;
858 if (content.empty()) {
859 BOOST_LOG(error) <<
"Web UI asset missing or empty: ["sv << path <<
']';
860 BOOST_LOG(error) <<
"Hermes was built with assets in ["sv << HERMES_ASSETS_DIR
861 <<
"]; reinstall the package or rebuild with a matching HERMES_ASSETS_DIR."sv;
863 SimpleWeb::StatusCode::server_error_internal_server_error,
864 "Web UI assets are missing on the server. See the Hermes log for the expected path."
869 SimpleWeb::CaseInsensitiveMultimap headers;
870 headers.emplace(
"Content-Type",
"text/html; charset=utf-8");
871 headers.emplace(
"X-Frame-Options",
"DENY");
872 headers.emplace(
"Content-Security-Policy",
"frame-ancestors 'none';");
873 headers.insert(extra_headers.begin(), extra_headers.end());
874 response->write(content, headers);
897 void getPinPage(resp_https_t response, req_https_t request) {
919 send_web_page(response, request,
"apps.html", {{
"Access-Control-Allow-Origin",
"https://images.igdb.com/"}});
979 if (config::sunshine.username.empty()) {
995 if (!config::sunshine.username.empty()) {
1026 std::ifstream in(WEB_DIR
"images/hermes.ico", std::ios::binary);
1027 SimpleWeb::CaseInsensitiveMultimap headers;
1028 headers.emplace(
"Content-Type",
"image/x-icon");
1029 headers.emplace(
"X-Frame-Options",
"DENY");
1030 headers.emplace(
"Content-Security-Policy",
"frame-ancestors 'none';");
1031 response->write(SimpleWeb::StatusCode::success_ok, in, headers);
1045 std::ifstream in(WEB_DIR
"images/logo-hermes-45.png", std::ios::binary);
1046 SimpleWeb::CaseInsensitiveMultimap headers;
1047 headers.emplace(
"Content-Type",
"image/png");
1048 headers.emplace(
"X-Frame-Options",
"DENY");
1049 headers.emplace(
"Content-Security-Policy",
"frame-ancestors 'none';");
1050 response->write(SimpleWeb::StatusCode::success_ok, in, headers);
1060 auto relPath = fs::relative(base, query);
1061 return *(relPath.begin()) != fs::path(
"..");
1072 fs::path webDirPath(WEB_DIR);
1073 fs::path nodeModulesPath(webDirPath /
"assets");
1076 auto filePath = fs::weakly_canonical(webDirPath / fs::path(request->path).relative_path());
1080 BOOST_LOG(warning) <<
"Someone requested a path " << filePath <<
" that is outside the assets folder";
1085 if (!fs::exists(filePath)) {
1090 auto relPath = fs::relative(filePath, webDirPath);
1093 auto mimeType = mime_types.find(relPath.extension().string().substr(1));
1094 if (mimeType == mime_types.end()) {
1098 SimpleWeb::CaseInsensitiveMultimap headers;
1099 headers.emplace(
"Content-Type", mimeType->second);
1100 headers.emplace(
"X-Frame-Options",
"DENY");
1101 headers.emplace(
"Content-Security-Policy",
"frame-ancestors 'none';");
1102 std::ifstream in(filePath.string(), std::ios::binary);
1103 response->write(SimpleWeb::StatusCode::success_ok, in, headers);
1131 void getApps(resp_https_t response, req_https_t request) {
1140 nlohmann::json file_tree = nlohmann::json::parse(content);
1142 file_tree[
"current_app"] = proc::proc.get_running_app_uuid();
1143 file_tree[
"host_uuid"] = http::unique_id;
1144 file_tree[
"host_name"] = config::nvhttp.sunshine_name;
1147 }
catch (std::exception &e) {
1148 BOOST_LOG(warning) <<
"GetApps: "sv << e.what();
1172 nlohmann::json games = nlohmann::json::array();
1173 namespace library = platf::game_library;
1174 const char *home_env = std::getenv(
"HOME");
1175 const std::filesystem::path home {home_env ? home_env :
""};
1176 std::vector<library::game_t> found;
1177 const auto add = [&found](std::vector<library::game_t> more) {
1178 std::ranges::move(more, std::back_inserter(found));
1183 for (
const auto &root : {home /
".local/share/Steam", home /
".steam/steam"}) {
1185 if (std::filesystem::is_directory(root /
"steamapps", ec)) {
1186 add(library::steam_games(root,
"steam"));
1189 if (std::error_code ec; std::filesystem::is_directory(home /
".var/app/com.valvesoftware.Steam/.local/share/Steam/steamapps", ec)) {
1190 add(library::steam_games(home /
".var/app/com.valvesoftware.Steam/.local/share/Steam",
"flatpak run com.valvesoftware.Steam"));
1194 if (!boost::process::v1::search_path(
"lutris").empty()) {
1196 }
else if (std::error_code ec; std::filesystem::is_directory(home /
".var/app/net.lutris.Lutris", ec) &&
1197 !boost::process::v1::search_path(
"flatpak").empty()) {
1198 lutris =
"flatpak run net.lutris.Lutris";
1200 if (!lutris.empty()) {
1201 bool timed_out =
false;
1202 const auto output = platf::bounded_command::output(lutris +
" --list-games --installed --json </dev/null 2>/dev/null", std::chrono::seconds {30}, &timed_out);
1204 add(library::lutris_games(*output, lutris));
1206 BOOST_LOG(warning) <<
"Library: couldn't list Lutris' games"sv << (timed_out ?
" (no answer in 30 s)"sv :
""sv);
1210 for (
const auto &game : library::merge(std::move(found))) {
1211 games.push_back({{
"source", game.source}, {
"id", game.id}, {
"name", game.name}, {
"cmd", game.cmd}});
1214 nlohmann::json output_tree;
1215 output_tree[
"games"] = std::move(games);
1252 void saveApp(resp_https_t response, req_https_t request) {
1259 std::stringstream ss;
1260 ss << request->content.rdbuf();
1262 BOOST_LOG(info) << config::stream.file_apps;
1267 nlohmann::json inputTree = nlohmann::json::parse(ss.str());
1271 nlohmann::json fileTree = nlohmann::json::parse(content);
1278 proc::refresh(config::stream.file_apps);
1281 nlohmann::json outputTree;
1282 outputTree[
"status"] =
true;
1285 catch (std::exception &e) {
1286 BOOST_LOG(warning) <<
"SaveApp: "sv << e.what();
1298 void closeApp(resp_https_t response, req_https_t request) {
1305 proc::proc.terminate();
1306 nlohmann::json output_tree;
1307 output_tree[
"status"] =
true;
1326 std::stringstream ss;
1327 ss << request->content.rdbuf();
1329 nlohmann::json input_tree = nlohmann::json::parse(ss.str());
1330 nlohmann::json output_tree;
1334 nlohmann::json fileTree = nlohmann::json::parse(content);
1337 if (!input_tree.contains(
"order") || !input_tree[
"order"].is_array()) {
1338 throw std::runtime_error(
"Missing or invalid 'order' array in request body");
1340 const auto& order_uuids_json = input_tree[
"order"];
1344 nlohmann::json original_apps_list = nlohmann::json::array();
1345 if (fileTree.contains(
"apps")) {
1346 if (fileTree[
"apps"].is_array()) {
1347 original_apps_list = fileTree[
"apps"];
1350 BOOST_LOG(error) <<
"ReorderApps: 'apps' key in apps configuration file ('" << config::stream.file_apps
1351 <<
"') is present but not an array.";
1352 throw std::runtime_error(
"'apps' in file is not an array, cannot reorder.");
1356 BOOST_LOG(debug) <<
"ReorderApps: 'apps' key missing in apps configuration file ('" << config::stream.file_apps
1357 <<
"'). Treating as an empty list for reordering.";
1361 nlohmann::json reordered_apps_list = nlohmann::json::array();
1362 std::vector<bool> item_moved(original_apps_list.size(),
false);
1366 for (
const auto& uuid_json_value : order_uuids_json) {
1367 if (!uuid_json_value.is_string()) {
1368 BOOST_LOG(warning) <<
"ReorderApps: Encountered a non-string UUID in the 'order' array. Skipping this entry.";
1371 std::string target_uuid = uuid_json_value.get<std::string>();
1372 bool found_match_for_ordered_uuid =
false;
1375 for (
size_t i = 0; i < original_apps_list.size(); ++i) {
1376 if (item_moved[i]) {
1380 const auto& app_item = original_apps_list[i];
1382 if (app_item.is_object() && app_item.contains(
"uuid") && app_item[
"uuid"].is_string()) {
1383 if (app_item[
"uuid"].get<std::string>() == target_uuid) {
1384 reordered_apps_list.push_back(app_item);
1385 item_moved[i] =
true;
1386 found_match_for_ordered_uuid =
true;
1392 if (!found_match_for_ordered_uuid) {
1396 BOOST_LOG(debug) <<
"ReorderApps: UUID '" << target_uuid <<
"' from 'order' array not found in available apps list or its matching app was already processed. Omitting.";
1402 for (
size_t i = 0; i < original_apps_list.size(); ++i) {
1403 if (!item_moved[i]) {
1404 reordered_apps_list.push_back(original_apps_list[i]);
1409 fileTree[
"apps"] = reordered_apps_list;
1415 proc::refresh(config::stream.file_apps);
1417 output_tree[
"status"] =
true;
1419 }
catch (std::exception &e) {
1420 BOOST_LOG(warning) <<
"ReorderApps: "sv << e.what();
1432 void deleteApp(resp_https_t response, req_https_t request) {
1440 std::stringstream ss;
1441 ss << request->content.rdbuf();
1442 nlohmann::json input_tree = nlohmann::json::parse(ss.str());
1445 if (!input_tree.contains(
"uuid") || !input_tree[
"uuid"].is_string()) {
1446 bad_request(response, request,
"Missing or invalid uuid in request body");
1449 auto uuid = input_tree[
"uuid"].get<std::string>();
1453 nlohmann::json fileTree = nlohmann::json::parse(content);
1456 if (fileTree.contains(
"apps") && fileTree[
"apps"].is_array()) {
1457 auto& apps = fileTree[
"apps"];
1459 std::remove_if(apps.begin(), apps.end(), [&uuid](
const nlohmann::json& app) {
1460 return app.value(
"uuid",
"") == uuid;
1468 proc::refresh(config::stream.file_apps);
1471 nlohmann::json outputTree;
1472 outputTree[
"status"] =
true;
1475 catch (std::exception &e) {
1476 BOOST_LOG(warning) <<
"DeleteApp: "sv << e.what();
1496 nlohmann::json output_tree;
1497 output_tree[
"named_certs"] = named_certs;
1498 output_tree[
"status"] =
true;
1526 std::stringstream ss;
1527 ss << request->content.rdbuf();
1529 nlohmann::json input_tree = nlohmann::json::parse(ss.str());
1530 nlohmann::json output_tree;
1531 std::string uuid = input_tree.value(
"uuid",
"");
1532 std::string name = input_tree.value(
"name",
"");
1533 std::string display_mode = input_tree.value(
"display_mode",
"");
1534 bool enable_legacy_ordering = input_tree.value(
"enable_legacy_ordering",
true);
1535 bool allow_client_commands = input_tree.value(
"allow_client_commands",
true);
1536 bool always_use_virtual_display = input_tree.value(
"always_use_virtual_display",
false);
1537 auto do_cmds = nvhttp::extract_command_entries(input_tree,
"do");
1538 auto undo_cmds = nvhttp::extract_command_entries(input_tree,
"undo");
1539 auto perm =
static_cast<crypto::PERM>(input_tree.value(
"perm",
static_cast<uint32_t
>(crypto::PERM::_no)) &
static_cast<uint32_t
>(crypto::PERM::_all));
1547 enable_legacy_ordering,
1548 allow_client_commands,
1549 always_use_virtual_display
1552 }
catch (std::exception &e) {
1553 BOOST_LOG(warning) <<
"Update Client: "sv << e.what();
1572 void unpair(resp_https_t response, req_https_t request) {
1579 std::stringstream ss;
1580 ss << request->content.rdbuf();
1582 nlohmann::json input_tree = nlohmann::json::parse(ss.str());
1583 nlohmann::json output_tree;
1584 std::string uuid = input_tree.value(
"uuid",
"");
1587 }
catch (std::exception &e) {
1588 BOOST_LOG(warning) <<
"Unpair: "sv << e.what();
1600 void unpairAll(resp_https_t response, req_https_t request) {
1608 proc::proc.terminate();
1609 nlohmann::json output_tree;
1610 output_tree[
"status"] =
true;
1620 nlohmann::json output_tree;
1621 output_tree[
"status"] =
true;
1622 output_tree[
"platform"] =
"linux";
1623 output_tree[
"version"] = PROJECT_VERSION;
1624 output_tree[
"version_commit"] = PROJECT_VERSION_COMMIT;
1625 output_tree[
"vdisplayStatus"] = (int)proc::vDisplayDriverStatus;
1626 output_tree[
"streamPorts"] = stream_ports_json();
1628 output_tree[
"evdiInfo"] = evdi_status_json();
1629 output_tree[
"evdiDiagnostic"] = output_tree[
"evdiInfo"][
"diagnostic"];
1630 output_tree[
"hermesKmsInfo"] = hermes_kms_status_json();
1631 output_tree[
"hermesKmsDiagnostic"] = output_tree[
"hermesKmsInfo"][
"diagnostic"];
1632 output_tree[
"clipboardInfo"] = clipboard_status_json();
1633 output_tree[
"preloginInfo"] = prelogin_status_json();
1637 nlohmann::json &
overlay_config_file(nlohmann::json &response,
const std::unordered_map<std::string, std::string> &file_values) {
1638 for (
const auto &[name, value] : file_values) {
1643 if (response.contains(name)) {
1646 response[name] = value;
1659 void getConfig(resp_https_t response, req_https_t request) {
1685 nlohmann::json capabilities {
1687 {
"server_name",
"Hermes"},
1693 {
"hestia_protocol", 1},
1694 {
"min_client_protocol", 1},
1695 {
"max_client_protocol", 1},
1699 {
"server_version", PROJECT_VERSION},
1701 {
"gamestream",
true},
1702 {
"moonlight",
true},
1706 {
"virtual_display",
true},
1707 {
"virtual_display_backend", {
"evdi",
"hermes_kms"}},
1708 {
"hermes_kms_multi_output", {
1709 {
"supported",
true},
1710 {
"experimental",
true},
1713 {
"hermes_kms_isolated_sessions", {
1714 {
"status",
"prototype"},
1715 {
"experimental",
true},
1716 {
"profiles", {
"application",
"desktop"}},
1717 {
"max_sessions", 8},
1719 {
"kde_kscreen",
true},
1720 {
"display_recovery",
true},
1721 {
"client_resolution_matching",
true},
1722 {
"client_fps_matching",
true},
1723 {
"hdr_mode_control",
true},
1724 {
"scale_factor",
true},
1725 {
"gamescope_session", !boost::process::v1::search_path(
"gamescope").empty()},
1726 {
"server_commands",
true},
1727 {
"clipboard_sync", platf::clipboard_available()},
1728 {
"permission_system",
true},
1731 {
"max_width", 7680},
1732 {
"max_height", 4320},
1734 {
"supported_fps", {30, 40, 45, 60, 90, 120}},
1735 {
"supported_codecs", {
"h264",
"hevc",
"av1"}},
1739 if (config::video.pyrowave && video::pyrowave_available()) {
1740 capabilities[
"limits"][
"supported_codecs"].push_back(
"pyrowave");
1743 return capabilities;
1746 void send_hestia_error(resp_https_t response, SimpleWeb::StatusCode status,
const char *code,
const char *message) {
1747 const nlohmann::json output {
1751 {
"message", message},
1754 const SimpleWeb::CaseInsensitiveMultimap headers {
1755 {
"Content-Type",
"application/json"},
1756 {
"X-Frame-Options",
"DENY"},
1757 {
"Content-Security-Policy",
"frame-ancestors 'none';"},
1759 response->write(status, output.dump(), headers);
1762 bool authenticate_hestia_client(resp_https_t response, req_https_t request,
crypto::PERM permission,
const char *operation) {
1763 auto client = std::static_pointer_cast<crypto::named_cert_t>(request->userp);
1765 send_hestia_error(response, SimpleWeb::StatusCode::client_error_unauthorized,
"unauthorized",
"A paired client certificate is required");
1769 if (!(client->perm & permission)) {
1770 BOOST_LOG(info) <<
"[HestiaAPI] permission denied for " << operation <<
" client=" << client->uuid;
1771 send_hestia_error(response, SimpleWeb::StatusCode::client_error_forbidden,
"permission_denied",
"This client does not have the required permission");
1778 std::shared_ptr<crypto::named_cert_t> authenticate_hestia_paired_client(resp_https_t response, req_https_t request) {
1779 auto client = std::static_pointer_cast<crypto::named_cert_t>(request->userp);
1781 send_hestia_error(response, SimpleWeb::StatusCode::client_error_unauthorized,
"unauthorized",
"A paired client certificate is required");
1786 bool hestia_has_exact_keys(
const nlohmann::json &
object,
const std::set<std::string> &keys) {
1787 if (!
object.is_object() ||
object.size() != keys.size()) {
1791 for (
auto it =
object.begin(); it !=
object.end(); ++it) {
1792 if (!keys.contains(it.key())) {
1800 bool hestia_is_positive_integer(
const nlohmann::json &value) {
1801 return value.is_number_integer() && value.get<
int>() > 0;
1804 bool hestia_is_one_of(
const nlohmann::json &value,
const std::set<std::string> &values) {
1805 return value.is_string() && values.contains(value.get<std::string>());
1808 bool validate_hestia_session_prepare(
const nlohmann::json &request, std::string &error) {
1809 static const std::set<std::string> request_keys {
1810 "client",
"stream",
"virtual_display",
"app",
1812 static const std::set<std::string> client_keys {
1813 "name",
"version",
"platform",
"display_width",
"display_height",
"refresh_rate",
"hdr",
1815 static const std::set<std::string> stream_keys {
1816 "requested_width",
"requested_height",
"requested_fps",
"codec",
"bitrate_kbps",
"hdr_mode",
"scale_factor",
1818 static const std::set<std::string> virtual_display_keys {
1819 "enabled",
"backend",
"desktop_integration",
"recover_physical_monitor",
1821 static const std::set<std::string> app_keys {
1822 "id",
"launch_mode",
1825 if (!hestia_has_exact_keys(request, request_keys)) {
1826 error =
"Request must contain only client, stream, virtual_display, and app";
1830 const auto &client = request[
"client"];
1831 if (!hestia_has_exact_keys(client, client_keys) || !client[
"name"].is_string() ||
1832 !client[
"version"].is_string() || !hestia_is_one_of(client[
"platform"], {
"linux",
"windows",
"macos",
"steamdeck",
"unknown"}) ||
1833 !hestia_is_positive_integer(client[
"display_width"]) || !hestia_is_positive_integer(client[
"display_height"]) ||
1834 !hestia_is_positive_integer(client[
"refresh_rate"]) || !client[
"hdr"].is_boolean()) {
1835 error =
"Invalid client object";
1839 const auto &stream = request[
"stream"];
1840 if (!hestia_has_exact_keys(stream, stream_keys) || !hestia_is_positive_integer(stream[
"requested_width"]) ||
1841 !hestia_is_positive_integer(stream[
"requested_height"]) || !hestia_is_positive_integer(stream[
"requested_fps"]) ||
1842 !hestia_is_one_of(stream[
"codec"], {
"h264",
"hevc",
"av1",
"pyrowave"}) || !hestia_is_positive_integer(stream[
"bitrate_kbps"]) ||
1843 !hestia_is_one_of(stream[
"hdr_mode"], {
"sdr",
"hdr"}) || !hestia_is_positive_integer(stream[
"scale_factor"])) {
1844 error =
"Invalid stream object";
1848 const int requested_width = stream[
"requested_width"].get<
int>();
1849 const int requested_height = stream[
"requested_height"].get<
int>();
1850 const int requested_fps = stream[
"requested_fps"].get<
int>();
1851 const int scale_factor = stream[
"scale_factor"].get<
int>();
1852 static const std::set<int> supported_fps {30, 40, 45, 60, 90, 120};
1853 if (requested_width > 7680 || requested_height > 4320 || !supported_fps.contains(requested_fps) || scale_factor > 500) {
1854 error =
"Requested stream settings exceed host limits";
1859 if (!hestia_has_exact_keys(virtual_display, virtual_display_keys) || !virtual_display[
"enabled"].is_boolean() ||
1860 !hestia_is_one_of(virtual_display[
"backend"], {
"auto",
"evdi",
"hermes_kms",
"none"}) ||
1861 !hestia_is_one_of(virtual_display[
"desktop_integration"], {
"auto",
"kde_kscreen",
"none"}) ||
1862 !virtual_display[
"recover_physical_monitor"].is_boolean()) {
1863 error =
"Invalid virtual_display object";
1867 const auto &
app = request[
"app"];
1868 if (!hestia_has_exact_keys(app, app_keys) || !app[
"id"].is_string() ||
1869 !hestia_is_one_of(app[
"launch_mode"], {
"normal",
"desktop",
"steam_big_picture",
"gamescope",
"custom"})) {
1870 error =
"Invalid app object";
1893 if (!authenticate_hestia_client(response, request, crypto::PERM::launch,
"session prepare")) {
1897 auto content_type = request->header.find(
"content-type");
1898 if (content_type == request->header.end() || !boost::istarts_with(content_type->second,
"application/json")) {
1899 send_hestia_error(response, SimpleWeb::StatusCode::client_error_bad_request,
"invalid_request",
"Content-Type must be application/json");
1904 const nlohmann::json input = nlohmann::json::parse(request->content.string());
1905 std::string validation_error;
1906 if (!validate_hestia_session_prepare(input, validation_error)) {
1907 send_hestia_error(response, SimpleWeb::StatusCode::client_error_bad_request,
"invalid_request", validation_error.c_str());
1911 const auto &stream = input[
"stream"];
1912 const auto &virtual_display = input[
"virtual_display"];
1913 const auto &app = input[
"app"];
1914 if (stream[
"codec"] ==
"pyrowave" &&
1915 (!config::video.pyrowave || !video::pyrowave_available())) {
1916 send_hestia_error(response, SimpleWeb::StatusCode::client_error_bad_request,
"unsupported_codec",
"PyroWave is not enabled or unavailable on this host");
1919 if (stream[
"codec"] ==
"pyrowave" && stream[
"hdr_mode"] !=
"sdr") {
1920 send_hestia_error(response, SimpleWeb::StatusCode::client_error_bad_request,
"unsupported_codec_mode",
"PyroWave currently supports SDR streams only");
1923 if (app[
"launch_mode"] ==
"gamescope" && boost::process::v1::search_path(
"gamescope").empty()) {
1924 send_hestia_error(response, SimpleWeb::StatusCode::client_error_bad_request,
"unsupported_feature",
"Gamescope is not available on this host");
1927 const auto client = std::static_pointer_cast<crypto::named_cert_t>(request->userp);
1929 .virtual_display = virtual_display[
"enabled"].get<bool>(),
1930 .width = stream[
"requested_width"].get<int>(),
1931 .height = stream[
"requested_height"].get<int>(),
1932 .fps = stream[
"requested_fps"].get<int>(),
1933 .hdr = stream[
"hdr_mode"] ==
"hdr",
1934 .scale_factor = stream[
"scale_factor"].get<uint32_t>(),
1935 .launch_mode = app[
"launch_mode"].get<std::string>(),
1937 BOOST_LOG(debug) <<
"[HestiaAPI] session prepare requested: width=" << stream[
"requested_width"]
1938 <<
" height=" << stream[
"requested_height"] <<
" fps=" << stream[
"requested_fps"]
1939 <<
" virtual_display=" << virtual_display[
"enabled"]
1940 <<
" launch_mode=" << app[
"launch_mode"]
1941 <<
" client_name=" << input[
"client"][
"name"]
1942 <<
" client_version=" << input[
"client"][
"version"]
1943 <<
" client_platform=" << input[
"client"][
"platform"];
1945 const nlohmann::json output {
1947 {
"session_id",
"hestia-" + crypto::rand_alphabet(12)},
1948 {
"virtual_display", {
1951 {
"backend", virtual_display[
"backend"].get<std::string>()},
1952 {
"width", stream[
"requested_width"]},
1953 {
"height", stream[
"requested_height"]},
1954 {
"fps", stream[
"requested_fps"]},
1955 {
"hdr", stream[
"hdr_mode"] ==
"hdr"},
1956 {
"kscreen_enabled",
false},
1959 app[
"id"].get<std::string>(),
1960 virtual_display[
"enabled"].get<bool>(),
1961 stream[
"scale_factor"].get<int>()
1963 {
"warnings", {
"Prepared settings will be applied when the normal stream launches."}},
1966 }
catch (
const nlohmann::json::exception &) {
1967 send_hestia_error(response, SimpleWeb::StatusCode::client_error_bad_request,
"invalid_request",
"Request body must be valid JSON");
1968 }
catch (
const std::exception &e) {
1969 BOOST_LOG(error) <<
"[HestiaAPI] session prepare failed: " << e.what();
1970 send_hestia_error(response, SimpleWeb::StatusCode::server_error_internal_server_error,
"internal_error",
"Unable to prepare session");
1974 void stop_hestia_session(resp_https_t response, req_https_t request) {
1975 if (!authenticate_hestia_client(response, request, crypto::PERM::launch,
"session stop")) {
1979 const auto client = std::static_pointer_cast<crypto::named_cert_t>(request->userp);
1982 BOOST_LOG(debug) <<
"[HestiaAPI] session stop requested by client=" << client->uuid
1983 <<
" stopped=" << stopped;
1984 send_response(response, {{
"ok",
true}, {
"stopped", stopped}});
1987 nlohmann::json hestia_display_status_json() {
1989 const bool virtual_display_active = !evdi_status.active_displays.empty();
1990 const auto *
display = virtual_display_active ? &evdi_status.active_displays.front() :
nullptr;
1991 const bool exclusive_virtual_display = virtual_display_active && config::video.isolated_virtual_display_option;
1995 {
"active", virtual_display_active},
1996 {
"virtual_display", {
1997 {
"enabled", virtual_display_active},
1999 {
"backend", virtual_display_active ?
"evdi" :
"none"},
2005 {
"physical_display", {
2006 {
"disabled_during_stream", exclusive_virtual_display},
2007 {
"saved_primary", exclusive_virtual_display ? proc::proc.initial_display :
""},
2008 {
"recovery_state_exists", exclusive_virtual_display},
2011 {
"environment", evdi_status.session_type},
2012 {
"kscreen_available", evdi_status.output_layout_backend.rfind(
"kscreen", 0) == 0},
2018 void get_hestia_display_status(resp_https_t response, req_https_t request) {
2019 if (!authenticate_hestia_client(response, request, crypto::PERM::view,
"display status")) {
2026 void recover_hestia_display(resp_https_t response, req_https_t request) {
2027 if (!authenticate_hestia_client(response, request, crypto::PERM::launch,
"display recovery")) {
2031 auto content_type = request->header.find(
"content-type");
2032 if (content_type == request->header.end() || !boost::istarts_with(content_type->second,
"application/json")) {
2033 send_hestia_error(response, SimpleWeb::StatusCode::client_error_bad_request,
"invalid_request",
"Content-Type must be application/json");
2038 const nlohmann::json input = nlohmann::json::parse(request->content.string());
2039 if (!hestia_has_exact_keys(input, {
"force"}) || !input[
"force"].is_boolean()) {
2040 send_hestia_error(response, SimpleWeb::StatusCode::client_error_bad_request,
"invalid_request",
"Request must contain a boolean force field");
2044 const std::string restored_output = proc::proc.initial_display;
2045 if (proc::proc.running() > 0) {
2046 proc::proc.terminate();
2048 VDISPLAY::restoreExclusiveVirtualDisplay();
2056 const nlohmann::json output {
2058 {
"message",
"Physical display restored"},
2059 {
"restored_output", restored_output},
2062 }
catch (
const nlohmann::json::exception &) {
2063 send_hestia_error(response, SimpleWeb::StatusCode::client_error_bad_request,
"invalid_request",
"Request body must be valid JSON");
2064 }
catch (
const std::exception &e) {
2065 BOOST_LOG(error) <<
"[HestiaAPI] display recovery failed: " << e.what();
2066 send_hestia_error(response, SimpleWeb::StatusCode::server_error_internal_server_error,
"display_recovery_failed",
"Unable to recover the physical display");
2070 void get_hestia_commands(resp_https_t response, req_https_t request) {
2071 if (!authenticate_hestia_client(response, request, crypto::PERM::server_cmd,
"server command list")) {
2075 nlohmann::json commands = nlohmann::json::array();
2076 for (
size_t index = 0; index < config::sunshine.server_cmds.size(); ++index) {
2077 commands.push_back({
2079 {
"name", config::sunshine.server_cmds[index].cmd_name},
2080 {
"requires_confirmation",
true},
2084 send_response(response, {{
"ok",
true}, {
"commands", commands}});
2087 void get_hestia_client_permissions(resp_https_t response, req_https_t request) {
2088 auto client = authenticate_hestia_paired_client(response, request);
2093 const auto has_permission = [&client](
crypto::PERM permission) {
2094 return static_cast<bool>(client->perm & permission);
2098 {
"client_id", client->uuid},
2100 {
"view_streams", has_permission(crypto::PERM::view)},
2101 {
"list_apps", has_permission(crypto::PERM::list)},
2102 {
"launch_apps", has_permission(crypto::PERM::launch)},
2103 {
"keyboard_input", has_permission(crypto::PERM::input_kbd)},
2104 {
"mouse_input", has_permission(crypto::PERM::input_mouse)},
2105 {
"gamepad_input", has_permission(crypto::PERM::input_controller)},
2106 {
"virtual_display", has_permission(crypto::PERM::launch)},
2107 {
"server_commands", has_permission(crypto::PERM::server_cmd)},
2108 {
"clipboard_sync", platf::clipboard_available() && has_permission(crypto::PERM::clipboard_set) && has_permission(crypto::PERM::clipboard_read)},
2109 {
"display_recovery", has_permission(crypto::PERM::launch)},
2114 void get_hestia_clipboard(resp_https_t response, req_https_t request) {
2115 if (!authenticate_hestia_client(response, request, crypto::PERM::clipboard_read,
"clipboard read")) {
2118 if (!platf::clipboard_available()) {
2119 send_hestia_error(response, SimpleWeb::StatusCode::server_error_service_unavailable,
"clipboard_unavailable",
"Clipboard synchronization is unavailable on this host");
2123 send_response(response, {{
"ok",
true}, {
"text", platf::get_clipboard()}});
2129 nlohmann::json hestia_runtime_status_json() {
2130 nlohmann::json runtime;
2134 nlohmann::json codecs = nlohmann::json::array();
2136 codecs.push_back(
"h264");
2139 codecs.push_back(
"hevc");
2142 codecs.push_back(
"av1");
2144 if (config::video.pyrowave && video::pyrowave_available()) {
2145 codecs.push_back(
"pyrowave");
2147 nlohmann::json attempts = nlohmann::json::array();
2148 for (
const auto &attempt : enc.attempts) {
2149 attempts.push_back({
2150 {
"name", attempt.name},
2151 {
"selected", attempt.selected},
2152 {
"outcome", attempt.outcome},
2155 runtime[
"encoder"] = {
2156 {
"name", enc.encoder},
2157 {
"hardware", enc.hardware},
2158 {
"codecs", std::move(codecs)},
2161 {
"fell_back_to_software", enc.fell_back_to_software},
2162 {
"attempts", std::move(attempts)},
2165 runtime[
"encoder"] = {{
"name",
nullptr}, {
"hardware",
false}, {
"probed",
false}};
2171 const bool app_running = proc::proc.running() > 0;
2172 const bool awaiting_reconnect = sessions == 0 && app_running;
2175 runtime[
"sessions"] = {
2176 {
"active", sessions},
2177 {
"streaming", sessions > 0},
2182 {
"awaiting_reconnect", awaiting_reconnect},
2183 {
"ms_since_last_end", term.ms_since_last_end},
2184 {
"total_ended", term.total_ended},
2185 {
"client_lost_count", term.client_lost_count},
2192 if (pm.valid && sessions > 0) {
2193 runtime[
"pipeline"] = {
2195 {
"bitrate_kbps", pm.bitrate_kbps},
2196 {
"encode_ms", pm.encode_ms},
2197 {
"capture_to_encode_ms", pm.capture_to_encode_ms},
2198 {
"frames_encoded", pm.frames_encoded},
2199 {
"frames_dropped", pm.frames_dropped},
2200 {
"width", pm.width},
2201 {
"height", pm.height},
2204 runtime[
"pipeline"] =
nullptr;
2210 runtime[
"session"] = {
2211 {
"environment", session_env.describe()},
2212 {
"desktop", session_env.desktop},
2213 {
"gamescope_running", session_env.gamescope_running},
2214 {
"can_host_virtual_display", session_env.can_host_virtual_display},
2221 runtime[
"appliance"] = {
2222 {
"enabled", appliance.enabled},
2223 {
"diagnostic", appliance.diagnostic},
2224 {
"gamescope_available", appliance.gamescope_available},
2225 {
"virtual_display_available", appliance.virtual_display_available},
2226 {
"headless_capable", appliance.headless_capable},
2227 {
"autologin_configured", appliance.autologin_configured},
2228 {
"session_environment", appliance.session_environment},
2235 if (config::video.virtual_display_backend ==
"hermes_kms") {
2238 runtime[
"hermes_kms"] = {
2239 {
"output_index", km.output_index >= 0 ? km.output_index + 1 : 0},
2240 {
"output_name", km.output_name},
2241 {
"frame_sequence", km.frame_sequence},
2242 {
"frame_updates", km.frame_update_count},
2243 {
"frames_acquired", km.acquire_count},
2244 {
"acquires_no_frame", km.acquire_no_frame_count},
2245 {
"dmabuf_exports", km.dmabuf_export_count},
2246 {
"dmabuf_export_failures", km.dmabuf_export_fail_count},
2247 {
"frame_waits", km.wait_count},
2248 {
"frame_waits_ready", km.wait_ready_count},
2249 {
"frame_waits_timed_out", km.wait_timeout_count},
2250 {
"output_enables", km.output_enable_count},
2251 {
"output_disables", km.output_disable_count},
2252 {
"hotplug_events", km.hotplug_event_count},
2253 {
"last_update_ns", km.last_update_ns},
2254 {
"last_wait_duration_ns", km.last_wait_duration_ns},
2259 if (km.session_lifecycle) {
2260 runtime[
"hermes_kms"][
"session"] = {
2261 {
"bound_fds", km.bound_fd_count},
2262 {
"binds", km.bind_count},
2263 {
"binds_rejected", km.bind_reject_count},
2264 {
"unbinds", km.unbind_count},
2265 {
"bindings_revoked", km.binding_revoke_count},
2266 {
"cross_session_buffer_exports", km.cross_session_buffer_export_count},
2270 runtime[
"hermes_kms"] =
nullptr;
2284 nlohmann::json checks = nlohmann::json::array();
2287 auto add = [&](
const char *id,
const char *status, std::string message) {
2288 checks.push_back({{
"id",
id}, {
"status", status}, {
"message", std::move(message)}});
2289 if (std::string_view {status} ==
"fail") {
2297 add(
"encoder",
"warn",
"Encoder has not been probed yet; it is probed on the first session.");
2298 }
else if (enc.encoder.empty()) {
2299 add(
"encoder",
"fail",
"No usable video encoder was found.");
2300 }
else if (!enc.hardware) {
2301 add(
"encoder",
"warn",
2302 enc.fell_back_to_software ?
2303 "Using software encoding: hardware encoder(s) failed probing. Expect higher CPU use and latency." :
2304 "Using software encoding (no hardware encoder available). Expect higher CPU use and latency.");
2306 add(
"encoder",
"ok",
"Hardware encoder in use: " + enc.encoder +
".");
2312 add(
"display",
"ok",
"A capturable display is available.");
2314 add(
"display",
"warn",
2315 "No active display detected; a virtual display will be created for the session if configured.");
2320 const auto env = [](
const char *name) {
2321 const char *value = std::getenv(name);
2322 return std::string {value ? value :
""};
2330 if (session_present.has_value() &&
2332 add(
"virtual_display",
"warn",
2334 "A desktop session has started; Hermes joins it as soon as no client is connected. Until then the "
2335 "virtual-display layout cannot be managed." :
2336 "Nobody is logged in to a desktop yet, so the virtual-display layout cannot be managed. Hermes joins "
2337 "the desktop after login.");
2338 }
else if (evdi.session_type ==
"wayland" || evdi.session_type ==
"x11") {
2339 if (evdi.exclusive_layout_supported) {
2340 add(
"virtual_display",
"ok",
2341 "Virtual-display layout management available via " + evdi.output_layout_backend +
".");
2342 }
else if (evdi.output_layout_backend.rfind(
"mutter", 0) == 0) {
2343 add(
"virtual_display",
"warn",
2344 "GNOME/Mutter session: Hermes can only verify (not configure) the virtual output. "
2345 "Isolated virtual display is unavailable.");
2347 add(
"virtual_display",
"warn",
2348 "No output-management backend (kscreen/wlr/mutter) detected; virtual-display activation may fail.");
2351 add(
"virtual_display",
"warn",
2352 "Session type is '" + evdi.session_type +
"'; virtual-display support is limited.");
2358 if (config::video.virtual_display_backend ==
"hermes_kms") {
2360 std::string message;
2361 const char *status =
"ok";
2362 if (kms.diagnostic == VDISPLAY::HERMES_KMS_DIAGNOSTIC::READY) {
2363 message =
"Hermes-KMS " + kms.driver_version +
" is ready (interface " + std::to_string(kms.uapi_version) +
").";
2366 message = hermes_kms_problem(kms) +
2367 " Until it is fixed, no virtual display can be created, so apps set to create one will not "
2368 "start. Streaming a physical monitor still works, and the EVDI backend also gives virtual "
2369 "displays, without HDR10, a second virtual display or isolated sessions.";
2371 if (
const auto note = hermes_kms_reload_note(kms); !note.empty()) {
2373 message +=
' ' + note;
2375 if (
const auto note = hermes_kms_newer_note(kms); !note.empty()) {
2376 message +=
' ' + note;
2378 add(
"hermes_kms", status, std::move(message));
2379 }
else if (config::video.virtual_display_backend ==
"evdi") {
2381 add(
"hermes_kms",
"ok",
2382 std::string {
"Virtual displays use EVDI. HDR10, more than one virtual display, isolated sessions and "
2383 "zero-copy capture need the Hermes-KMS backend (virtual_display_backend = hermes_kms)."} +
2384 (kms.diagnostic == VDISPLAY::HERMES_KMS_DIAGNOSTIC::READY ?
2385 " Hermes-KMS " + kms.driver_version +
" is installed and ready if you switch." :
2391 add(
"session_environment",
"ok",
"Detected session environment: " + session_env.describe() +
".");
2393 return {{
"ready", ready}, {
"checks", std::move(checks)}};
2396 void get_hestia_diagnostics(resp_https_t response, req_https_t request) {
2397 if (!authenticate_hestia_client(response, request, crypto::PERM::view,
"diagnostics")) {
2401 send_response(response, {{
"ok",
true}, {
"runtime", hestia_runtime_status_json()}, {
"preflight",
hestia_preflight_json()}, {
"dependencies", {{
"clipboard", clipboard_status_json()}}}});
2413 if (!authenticate_hestia_client(response, request, crypto::PERM::view,
"stream info")) {
2416 const auto client = std::static_pointer_cast<crypto::named_cert_t>(request->userp);
2419 nlohmann::json body {{
"ok",
true}, {
"readiness",
nullptr}};
2420 if (readiness.checked && readiness.client == client->uuid) {
2421 body[
"readiness"] = {
2422 {
"ok", readiness.ok},
2423 {
"frame_seen", readiness.frame_seen},
2424 {
"capture", readiness.capture},
2425 {
"width", readiness.width},
2426 {
"height", readiness.height},
2427 {
"fps", readiness.framerate},
2428 {
"encoder", readiness.encoder},
2429 {
"gpu", readiness.gpu},
2430 {
"failure", readiness.failure},
2431 {
"checked_at", readiness.checked_at},
2446 double cpu_percent = -1;
2447 double cpu_celsius = -1;
2448 double cpu_watts = -1;
2449 double gpu_percent = -1;
2450 double gpu_celsius = -1;
2451 double gpu_watts = -1;
2452 double gpu_mhz = -1;
2453 double vram_used_mib = -1;
2454 double ram_available_mib = -1;
2460 std::chrono::system_clock::time_point at;
2466 namespace fs = std::filesystem;
2468 std::optional<long long> read_number(
const fs::path &path) {
2469 std::ifstream stream {path};
2471 if (stream >> value) {
2474 return std::nullopt;
2477 std::string read_word(
const fs::path &path) {
2478 std::ifstream stream {path};
2485 std::optional<fs::path> hwmon(std::initializer_list<std::string_view> names,
const fs::path &root =
"/sys/class/hwmon") {
2487 for (
const auto &entry : fs::directory_iterator {root, ec}) {
2488 const auto name = read_word(entry.path() /
"name");
2489 if (std::ranges::find(names, name) != names.end()) {
2490 return entry.path();
2493 return std::nullopt;
2497 double temperature(
const fs::path &dir, std::string_view label) {
2499 for (
const auto &entry : fs::directory_iterator {dir, ec}) {
2500 const auto file = entry.path().filename().string();
2501 if (file.starts_with(
"temp") && file.ends_with(
"_label") && read_word(entry.path()) == label) {
2502 const auto input = dir / (file.substr(0, file.size() - 6) +
"_input");
2503 if (
const auto value = read_number(input)) {
2504 return *value / 1000.0;
2508 const auto value = read_number(dir /
"temp1_input");
2509 return value ? *value / 1000.0 : -1;
2513 long long cpu_busy = -1, cpu_total = -1;
2514 long long cpu_energy_uj = -1;
2515 std::chrono::steady_clock::time_point cpu_energy_at;
2516 long long net_errors = -1, udp_dropped = -1;
2517 long long gpu_energy_uj = -1;
2518 std::chrono::steady_clock::time_point gpu_energy_at;
2523 double current_amdgpu_clock(
const fs::path &path) {
2524 std::ifstream stream {path};
2525 for (std::string line; std::getline(stream, line);) {
2526 if (line.find(
'*') != std::string::npos) {
2527 const auto colon = line.find(
':');
2528 return colon == std::string::npos ? -1 : std::atof(line.c_str() + colon + 1);
2535 void read_nvidia(
const std::string &pci_address, system_t &s) {
2536 const auto command =
"nvidia-smi -i " + pci_address +
2537 " --query-gpu=utilization.gpu,temperature.gpu,power.draw,memory.used,clocks.gr"
2538 " --format=csv,noheader,nounits 2>/dev/null";
2539 FILE *smi = ::popen(
command.c_str(),
"r");
2544 const bool read = std::fgets(line,
sizeof(line), smi) !=
nullptr;
2549 std::array<double *, 5> fields {&s.gpu_percent, &s.gpu_celsius, &s.gpu_watts, &s.vram_used_mib, &s.gpu_mhz};
2550 std::istringstream values {line};
2552 for (
auto *field : fields) {
2553 if (!std::getline(values, value,
',')) {
2556 char *end =
nullptr;
2557 const double number = std::strtod(value.c_str(), &end);
2558 if (end != value.c_str()) {
2574 std::ifstream stat {
"/proc/stat"};
2576 long long user, nice, system, idle, iowait, irq, softirq, steal;
2577 if (stat >> cpu >> user >> nice >> system >> idle >> iowait >> irq >> softirq >> steal) {
2578 const long long busy = user + nice + system + irq + softirq + steal;
2579 const long long total = busy + idle + iowait;
2580 if (previous.cpu_total >= 0 && total > previous.cpu_total) {
2581 s.cpu_percent = 100.0 * (busy - previous.cpu_busy) / (total - previous.cpu_total);
2583 previous.cpu_busy = busy;
2584 previous.cpu_total = total;
2587 if (
const auto cpu = hwmon({
"k10temp",
"zenpower",
"coretemp"})) {
2588 s.cpu_celsius = temperature(*cpu, read_word(*cpu /
"name") ==
"coretemp" ?
"Package id 0" :
"Tctl");
2591 if (
const auto energy = read_number(
"/sys/class/powercap/intel-rapl:0/energy_uj")) {
2592 const auto now = std::chrono::steady_clock::now();
2593 if (previous.cpu_energy_uj >= 0 && *energy >= previous.cpu_energy_uj) {
2594 const double seconds = std::chrono::duration<double>(now - previous.cpu_energy_at).count();
2596 s.cpu_watts = (*energy - previous.cpu_energy_uj) / 1e6 / seconds;
2599 previous.cpu_energy_uj = *energy;
2600 previous.cpu_energy_at = now;
2606 if (
const auto space = description.find(
' '); description.starts_with(
"/dev/dri/")) {
2607 encode_card =
"/sys/class/drm/" + fs::path {description.substr(0, space)}.filename().string() +
"/device";
2613 const auto driver = fs::read_symlink(card /
"driver", ec).filename().string();
2614 if (driver ==
"amdgpu") {
2615 if (
const auto busy = read_number(card /
"gpu_busy_percent")) {
2616 s.gpu_percent =
static_cast<double>(*busy);
2618 if (
const auto vram = read_number(card /
"mem_info_vram_used")) {
2619 s.vram_used_mib = *vram / 1048576.0;
2621 s.gpu_mhz = current_amdgpu_clock(card /
"pp_dpm_sclk");
2622 if (
const auto gpu = hwmon({
"amdgpu"}, card /
"hwmon")) {
2623 s.gpu_celsius = temperature(*gpu,
"junction");
2624 if (
const auto power = read_number(*gpu /
"power1_average").or_else([&]() {
2625 return read_number(*gpu /
"power1_input");
2627 s.gpu_watts = *power / 1e6;
2630 }
else if (driver ==
"nvidia") {
2631 read_nvidia(fs::canonical(card, ec).filename().
string(), s);
2632 }
else if (driver ==
"i915" || driver ==
"xe") {
2634 for (
const auto &entry : fs::directory_iterator {card /
"drm", ec}) {
2635 if (
const auto mhz = read_number(entry.path() /
"gt_act_freq_mhz")) {
2636 s.gpu_mhz =
static_cast<double>(*mhz);
2639 if (
const auto mhz = read_number(card /
"tile0/gt0/freq0/act_freq")) {
2640 s.gpu_mhz =
static_cast<double>(*mhz);
2643 if (
const auto gpu = hwmon({
"i915",
"xe"}, card /
"hwmon")) {
2644 s.gpu_celsius = temperature(*gpu,
"pkg");
2645 if (
const auto energy = read_number(*gpu /
"energy1_input")) {
2646 const auto now = std::chrono::steady_clock::now();
2647 if (previous.gpu_energy_uj >= 0 && *energy >= previous.gpu_energy_uj) {
2648 const double seconds = std::chrono::duration<double>(now - previous.gpu_energy_at).count();
2650 if (seconds > 0 && seconds < 10) {
2651 s.gpu_watts = (*energy - previous.gpu_energy_uj) / 1e6 / seconds;
2654 previous.gpu_energy_uj = *energy;
2655 previous.gpu_energy_at = now;
2663 std::ifstream meminfo {
"/proc/meminfo"};
2664 for (std::string key; meminfo >> key;) {
2667 if (key ==
"MemAvailable:") {
2668 s.ram_available_mib = kib / 1024.0;
2671 meminfo.ignore(std::numeric_limits<std::streamsize>::max(),
'\n');
2677 std::ifstream dev {
"/proc/net/dev"};
2679 long long errors = 0;
2681 for (
int n = 0; std::getline(dev, line); ++n) {
2682 const auto colon = line.find(
':');
2683 if (n < 2 || colon == std::string::npos || boost::algorithm::trim_copy(line.substr(0, colon)) ==
"lo") {
2686 std::istringstream fields {line.substr(colon + 1)};
2687 std::array<long long, 16> v {};
2688 for (
auto &field : v) {
2691 errors += v[2] + v[3] + v[10] + v[11];
2695 if (previous.net_errors >= 0) {
2698 previous.net_errors = errors;
2703 std::ifstream snmp {
"/proc/net/snmp"};
2704 std::string header, values;
2705 while (std::getline(snmp, header) && std::getline(snmp, values)) {
2706 if (!header.starts_with(
"Udp:")) {
2709 std::istringstream names {header}, numbers {values};
2710 std::string name, number;
2711 long long dropped = 0;
2712 while (names >> name && numbers >> number) {
2713 if (name ==
"RcvbufErrors" || name ==
"SndbufErrors") {
2714 dropped += std::stoll(number);
2717 if (previous.udp_dropped >= 0) {
2720 previous.udp_dropped = dropped;
2728 std::deque<sample_t> samples;
2729 constexpr std::size_t max_samples = 720;
2732 using namespace std::literals;
2733 static auto last_streaming = std::chrono::steady_clock::time_point {};
2735 const auto now = std::chrono::steady_clock::now();
2737 last_streaming = now;
2739 const bool sampling = last_streaming != std::chrono::steady_clock::time_point {} && now - last_streaming <= 60s;
2742 auto system = read_system(sampling);
2747 std::lock_guard lock {mutex};
2748 samples.push_back(std::move(sample));
2749 if (samples.size() > max_samples) {
2750 samples.pop_front();
2754 std::vector<sample_t> snapshot() {
2755 std::lock_guard lock {mutex};
2756 return {samples.begin(), samples.end()};
2761 std::string local_time(std::chrono::system_clock::time_point at,
const char *format) {
2762 const auto t = std::chrono::system_clock::to_time_t(at);
2764 localtime_r(&t, &tm);
2766 std::strftime(text,
sizeof(text), format, &tm);
2770 std::vector<std::string> tail_lines(
const std::filesystem::path &path, std::size_t count) {
2771 std::ifstream stream {path};
2772 std::deque<std::string> lines;
2773 for (std::string line; std::getline(stream, line);) {
2774 lines.push_back(std::move(line));
2775 if (lines.size() > count) {
2779 return {lines.begin(), lines.end()};
2783 std::string redacted_settings() {
2784 static const std::array<std::string_view, 8> secret {
"pass",
"secret",
"token",
"key",
"cert",
"salt",
"credential",
"pin"};
2785 std::ifstream stream {config::sunshine.config_file};
2787 for (std::string line; std::getline(stream, line);) {
2788 const auto equals = line.find(
'=');
2789 if (equals != std::string::npos) {
2790 auto key = boost::algorithm::to_lower_copy(boost::algorithm::trim_copy(line.substr(0, equals)));
2791 if (std::ranges::any_of(secret, [&](std::string_view word) {
return key.find(word) != std::string::npos; })) {
2792 line = line.substr(0, equals + 1) +
" <removed>";
2795 output += line +
'\n';
2797 return output.empty() ?
"(no settings file, or all defaults)\n" : output;
2808 namespace fs = std::filesystem;
2809 using report_timeline::read_number;
2810 using report_timeline::read_word;
2812 const auto read_line = [](
const fs::path &path) {
2813 std::ifstream stream {path};
2815 std::getline(stream, line);
2819 out <<
"\n== USB devices ==\n";
2820 std::vector<std::string> usb;
2821 for (
const auto &entry : fs::directory_iterator {
"/sys/bus/usb/devices", ec}) {
2822 const auto vendor = read_word(entry.path() /
"idVendor");
2824 if (vendor.empty() || entry.path().filename().string().starts_with(
"usb")) {
2827 const auto product = read_line(entry.path() /
"product");
2828 const auto maker = read_line(entry.path() /
"manufacturer");
2829 const auto speed = read_word(entry.path() /
"speed");
2830 usb.push_back(std::format(
"{:<10} {}:{} {}{}{} ({} Mbps)", entry.path().filename().string(), vendor, read_word(entry.path() /
"idProduct"),
2831 maker, maker.empty() || product.empty() ?
"" :
" ", product.empty() ?
"(no name)" : product, speed.empty() ?
"?" : speed));
2833 std::ranges::sort(usb);
2834 for (
const auto &line : usb) {
2835 out <<
" " << line <<
'\n';
2838 out <<
" None readable.\n";
2841 out <<
"\n== Input devices ==\n";
2843 std::ifstream devices {
"/proc/bus/input/devices"};
2844 std::string name, phys;
2845 for (std::string line; std::getline(devices, line);) {
2846 if (line.starts_with(
"N: Name=")) {
2847 name = line.substr(8);
2848 }
else if (line.starts_with(
"P: Phys=")) {
2849 phys = line.substr(8);
2850 }
else if (line.starts_with(
"H: Handlers=")) {
2851 out <<
" " << name << (phys.empty() ?
"" :
" [" + phys +
"]") <<
" -> " << line.substr(12) <<
'\n';
2858 out <<
"\n== Display outputs ==\n";
2859 std::vector<fs::path> connectors;
2860 for (
const auto &entry : fs::directory_iterator {
"/sys/class/drm", ec}) {
2861 const auto name = entry.path().filename().string();
2862 if (name.starts_with(
"card") && name.find(
'-') != std::string::npos) {
2863 connectors.push_back(entry.path());
2866 std::ranges::sort(connectors);
2867 for (
const auto &connector : connectors) {
2868 const auto status = read_word(connector /
"status");
2869 const auto driver = fs::read_symlink(connector.parent_path() / connector.filename().string().substr(0, connector.filename().string().find(
'-')) /
"device/driver", ec).filename().string();
2870 out <<
" " << std::format(
"{:<26}", connector.filename().string()) <<
' ' << std::format(
"{:<12}", status)
2871 <<
" enabled=" << read_word(connector /
"enabled") <<
" power=" << read_word(connector /
"dpms")
2872 <<
" preferred=" << (status ==
"connected" ? read_line(connector /
"modes") :
"-") <<
" driver=" << driver <<
'\n';
2874 if (connectors.empty()) {
2878 out <<
"\n== Hermes sessions ==\n";
2879 const auto sessions = proc::proc.list_isolated();
2880 for (
const auto &session : sessions) {
2881 std::string details = session.profile;
2882 for (
const auto &detail : {session.compositor, session.display.empty() ?
""s :
"display " + session.display, session.unit}) {
2883 if (!detail.empty()) {
2884 details +=
", " + detail;
2887 out <<
" " << session.client_name <<
": " << session.app_name <<
" (" << details <<
") "
2888 << (session.running ?
"running" :
"NOT RUNNING") <<
'\n';
2890 if (sessions.empty()) {
2891 out <<
" No isolated or detached sessions.\n";
2894 out <<
" App running on the host desktop: " << (proc::proc.running() > 0 ? proc::proc.get_last_run_app_name() :
"none"s) <<
'\n';
2896 out <<
"\n== Network links ==\n";
2897 for (
const auto &entry : fs::directory_iterator {
"/sys/class/net", ec}) {
2898 const auto name = entry.path().filename().string();
2902 const auto speed = read_number(entry.path() /
"speed");
2903 const bool wireless = fs::exists(entry.path() /
"wireless");
2904 out <<
" " << std::format(
"{:<16}", name) <<
' ' << std::format(
"{:<8}", read_word(entry.path() /
"operstate"))
2905 << (wireless ?
" Wi-Fi" : speed && *speed > 0 ? std::format(
" {} Mbps", *speed) :
" speed unknown")
2906 <<
" mtu=" << read_word(entry.path() /
"mtu") <<
'\n';
2909 out <<
"\n== Sound cards ==\n";
2911 std::ifstream cards {
"/proc/asound/cards"};
2914 while (std::getline(cards, line)) {
2915 if (!line.empty() && line.find(
'[') != std::string::npos) {
2916 out <<
" " << boost::algorithm::trim_copy(line) <<
'\n';
2928 long long rss_kib = 0;
2929 double cpu_seconds = 0;
2931 std::vector<program_t> programs;
2932 const double ticks =
static_cast<double>(::sysconf(_SC_CLK_TCK));
2933 const long long page_kib = ::sysconf(_SC_PAGESIZE) / 1024;
2934 for (
const auto &entry : fs::directory_iterator {
"/proc", ec}) {
2935 const auto pid = entry.path().filename().string();
2936 if (pid.empty() || !std::isdigit(
static_cast<unsigned char>(pid[0]))) {
2939 const auto stat = read_line(entry.path() /
"stat");
2940 const auto open = stat.find(
'('), close = stat.rfind(
')');
2941 if (open == std::string::npos || close == std::string::npos) {
2944 std::istringstream fields {stat.substr(close + 2)};
2945 std::vector<std::string> v {std::istream_iterator<std::string> {fields}, {}};
2946 if (v.size() < 22) {
2950 programs.push_back({stat.substr(open + 1, close - open - 1), std::stoll(v[21]) * page_kib,
2951 (std::stod(v[11]) + std::stod(v[12])) / ticks});
2953 const auto list = [&](
const char *title,
auto key,
auto show) {
2954 std::ranges::sort(programs, [&](
const auto &a,
const auto &b) {
2955 return key(a) > key(b);
2957 out <<
'\n' << title <<
'\n';
2958 for (std::size_t n = 0; n < std::min<std::size_t>(20, programs.size()); ++n) {
2959 out <<
" " << std::format(
"{:<20}", programs[n].name) <<
' ' << show(programs[n]) <<
'\n';
2962 list(
"== Programs using the most memory ==", [](
const program_t &p) {
return static_cast<double>(p.rss_kib); }, [](
const program_t &p) {
2963 return std::format(
"{:>8.0f} MiB", p.rss_kib / 1024.0);
2965 list(
"== Programs that used the most CPU time ==", [](
const program_t &p) {
return p.cpu_seconds; }, [](
const program_t &p) {
2966 return std::format(
"{:>10.0f} s", p.cpu_seconds);
2977 std::ostringstream out;
2978 const auto now = std::chrono::system_clock::now();
2979 out <<
"Hermes diagnostic report\n"
2980 <<
"Generated: " << local_time(now,
"%Y-%m-%d %H:%M:%S %Z") <<
'\n'
2981 <<
"Hermes " << PROJECT_VERSION <<
" (" << PROJECT_VERSION_COMMIT <<
")\n"
2982 <<
"Review before posting publicly: the log names clients and their addresses.\n";
2984 out <<
"\n== Machine ==\n";
2985 std::string os =
"unknown";
2986 for (
const auto &line : tail_lines(
"/etc/os-release", 100)) {
2987 if (line.starts_with(
"PRETTY_NAME=")) {
2988 os = boost::algorithm::trim_copy_if(line.substr(12), boost::algorithm::is_any_of(
"\""));
2991 out <<
"OS: " << os <<
'\n';
2994 out <<
"Kernel: " << system.release <<
' ' << system.machine <<
'\n';
2996 out <<
"Session: " << session_env.describe() <<
'\n';
2998 std::string kms = std::filesystem::exists(
"/sys/module/hermes_kms") ?
"loaded" :
"not loaded";
2999 for (
const auto &gpu : gpus) {
3000 if (
const auto at = gpu.find(
"(hermes-kms "); at != std::string::npos) {
3001 kms =
"loaded, version " + gpu.substr(at + 12, gpu.find(
')', at) - at - 12);
3005 out <<
"Hermes-KMS: " << kms <<
'\n';
3006 out <<
"Virtual display backend: " << config::video.virtual_display_backend <<
'\n';
3008 for (
const auto &gpu : gpus) {
3009 out <<
" " << gpu <<
'\n';
3012 out <<
"Encodes on: " << (encoding.empty() ?
"no GPU qualifies"s : encoding) <<
'\n';
3016 out <<
"\n== Last capture-path check ==\n";
3018 if (!readiness.checked) {
3019 out <<
"None since Hermes started.\n";
3021 out <<
"When: " << local_time(std::chrono::system_clock::from_time_t(readiness.checked_at),
"%Y-%m-%d %H:%M:%S") <<
'\n'
3022 <<
"Result: " << (readiness.ok ? readiness.frame_seen ?
"passed" :
"passed; no new frame in time" :
"FAILED: " + readiness.failure) <<
'\n'
3023 <<
"Capture: " << readiness.capture <<
" (" << readiness.width <<
'x' << readiness.height <<
" at " << readiness.framerate <<
" fps)\n"
3024 <<
"Encoder: " << readiness.encoder << (readiness.gpu.empty() ?
"" :
" on " + readiness.gpu) <<
'\n';
3027 const auto log = tail_lines(config::sunshine.log_file, 3000);
3028 out <<
"\n== Problems: warnings and errors in the recent log ==\n";
3029 std::size_t problems = 0;
3030 for (
const auto &line : log) {
3031 if (line.find(
"]: Warning: ") != std::string::npos || line.find(
"]: Error: ") != std::string::npos ||
3032 line.find(
"]: Fatal: ") != std::string::npos) {
3033 out << line <<
'\n';
3041 out <<
"\n== Stream timeline (every 5 s while streaming, and for a minute after) ==\n";
3042 const auto samples = report_timeline::snapshot();
3043 if (samples.empty()) {
3044 out <<
"No stream since Hermes started.\n";
3046 const auto value = [](
double v,
const char *format) -> std::string {
3047 return v < 0 ?
"-"s : std::vformat(format, std::make_format_args(v));
3049 const auto count = [](
long long v) -> std::string {
3050 return v < 0 ?
"-"s : std::to_string(v);
3052 out <<
"time streams size fps Mbps enc ms cap->enc dropped | CPU % CPU °C CPU W | GPU % GPU °C GPU W GPU MHz VRAM MiB | RAM free MiB | net errors UDP dropped\n";
3053 for (
const auto &sample : samples) {
3054 const auto &p = sample.pipeline;
3055 const auto &m = sample.system;
3057 const bool streaming = sample.sessions > 0 && p.valid;
3058 out << std::format(
"{} {:>7} {:>10} {:>5} {:>6} {:>7} {:>8} {:>7} | {:>5} {:>6} {:>5} | {:>5} {:>6} {:>5} {:>7} {:>8} | {:>12} | {:>10} {:>11}\n",
3059 local_time(sample.at,
"%H:%M:%S"), sample.sessions,
3060 streaming ? std::format(
"{}x{}", p.width, p.height) :
"-"s,
3061 streaming ? std::format(
"{:.1f}", p.fps) :
"-"s,
3062 streaming ? std::format(
"{:.1f}", p.bitrate_kbps / 1000.0) :
"-"s,
3063 streaming ? std::format(
"{:.2f}", p.encode_ms) :
"-"s,
3064 streaming ? std::format(
"{:.2f}", p.capture_to_encode_ms) :
"-"s,
3065 streaming ? std::to_string(p.frames_dropped) :
"-"s,
3066 value(m.cpu_percent,
"{:.0f}"), value(m.cpu_celsius,
"{:.0f}"), value(m.cpu_watts,
"{:.0f}"),
3067 value(m.gpu_percent,
"{:.0f}"), value(m.gpu_celsius,
"{:.0f}"), value(m.gpu_watts,
"{:.0f}"), value(m.gpu_mhz,
"{:.0f}"),
3068 value(m.vram_used_mib,
"{:.0f}"), value(m.ram_available_mib,
"{:.0f}"),
3069 count(m.net_errors), count(m.udp_dropped));
3071 out <<
"\"-\" means the value could not be read without root: CPU W on recent kernels, and an Intel GPU's usage.\n"
3072 "GPU figures are for the encoding GPU: amdgpu and Intel from sysfs, NVIDIA from nvidia-smi.\n";
3077 out <<
"\n== Kernel warnings and errors (last 2 hours) ==\n";
3078 if (FILE *kernel = ::popen(
"journalctl -k -p warning --since -2h -q --no-pager -n 200 2>&1",
"r")) {
3081 while (
const auto n = std::fread(buffer, 1,
sizeof(buffer), kernel)) {
3082 text.append(buffer, n);
3088 std::string example, last_time;
3089 std::size_t count = 0;
3090 std::size_t order = 0;
3092 std::map<std::string, message_t> messages;
3093 std::istringstream lines {text};
3094 for (std::string line; std::getline(lines, line);) {
3096 const auto kernel_at = line.find(
" kernel: ");
3097 const auto message = kernel_at == std::string::npos ? line : line.substr(kernel_at + 9);
3100 for (std::size_t i = 0; i < message.size();) {
3101 if (std::isdigit(
static_cast<unsigned char>(message[i]))) {
3102 while (i < message.size() && (std::isxdigit(
static_cast<unsigned char>(message[i])) || message[i] ==
'x' || message[i] ==
':' || message[i] ==
'.')) {
3107 key += message[i++];
3110 auto &entry = messages[key];
3111 if (!entry.count++) {
3112 entry.example = message;
3113 entry.order = messages.size();
3115 entry.last_time = line.substr(0, std::min<std::size_t>(15, line.size()));
3117 std::vector<const message_t *> sorted;
3118 for (
const auto &[key, entry] : messages) {
3119 sorted.push_back(&entry);
3121 std::ranges::sort(sorted, [](
const auto *a,
const auto *b) {
3122 return a->count != b->count ? a->count > b->count : a->order < b->order;
3124 for (
const auto *entry : sorted) {
3125 out << std::format(
"{:>5}x last {} {}\n", entry->count, entry->last_time, entry->example);
3127 if (sorted.empty()) {
3131 out <<
"\n== What this session can do ==\n";
3132 for (
const auto &feature : session_features_json()) {
3133 out << feature[
"feature"].get<std::string>() <<
": " << feature[
"readiness"].get<std::string>() <<
" - "
3134 << feature[
"detail"].get<std::string>();
3135 if (
const auto fix = feature[
"remediation"].get<std::string>(); !fix.empty()) {
3136 out <<
" Fix: " << fix;
3142 for (
const auto ¬e : {hermes_kms_problem(kms), hermes_kms_reload_note(kms), hermes_kms_newer_note(kms)}) {
3143 if (!note.empty()) {
3144 out <<
"Hermes-KMS: " << note <<
'\n';
3148 out <<
"\n== Runtime state ==\n" << hestia_runtime_status_json().dump(2) <<
'\n';
3150 out <<
"\n== Settings (secrets removed) ==\n" << redacted_settings();
3151 out <<
"\n== Recent log ==\n";
3152 for (
const auto &line : log) {
3153 out << line <<
'\n';
3158 void send_diagnostic_report(resp_https_t response) {
3159 SimpleWeb::CaseInsensitiveMultimap headers;
3160 headers.emplace(
"Content-Type",
"text/plain; charset=utf-8");
3161 headers.emplace(
"Content-Disposition",
"attachment; filename=\"hermes-report-" +
3162 local_time(std::chrono::system_clock::now(),
"%Y%m%d-%H%M%S") +
".txt\"");
3163 headers.emplace(
"X-Frame-Options",
"DENY");
3164 response->write(SimpleWeb::StatusCode::success_ok, diagnostic_report(), headers);
3176 send_diagnostic_report(response);
3179 void get_hestia_diagnostic_report(resp_https_t response, req_https_t request) {
3180 if (!authenticate_hestia_client(response, request, crypto::PERM::view,
"diagnostic report")) {
3183 send_diagnostic_report(response);
3186 void set_hestia_clipboard(resp_https_t response, req_https_t request) {
3187 if (!authenticate_hestia_client(response, request, crypto::PERM::clipboard_set,
"clipboard write")) {
3190 if (!platf::clipboard_available()) {
3191 send_hestia_error(response, SimpleWeb::StatusCode::server_error_service_unavailable,
"clipboard_unavailable",
"Clipboard synchronization is unavailable on this host");
3195 auto content_type = request->header.find(
"content-type");
3196 if (content_type == request->header.end() || !boost::istarts_with(content_type->second,
"application/json")) {
3197 send_hestia_error(response, SimpleWeb::StatusCode::client_error_bad_request,
"invalid_request",
"Content-Type must be application/json");
3202 const nlohmann::json input = nlohmann::json::parse(request->content.string());
3203 if (!hestia_has_exact_keys(input, {
"text"}) || !input[
"text"].is_string()) {
3204 send_hestia_error(response, SimpleWeb::StatusCode::client_error_bad_request,
"invalid_request",
"Request must contain only a text field");
3207 const std::string text = input[
"text"].get<std::string>();
3208 if (text.size() > 64 * 1024 || text.find(
'\0') != std::string::npos || !platf::set_clipboard(text)) {
3209 send_hestia_error(response, SimpleWeb::StatusCode::client_error_bad_request,
"invalid_request",
"Clipboard text is invalid, too large, or unavailable");
3213 }
catch (
const nlohmann::json::exception &) {
3214 send_hestia_error(response, SimpleWeb::StatusCode::client_error_bad_request,
"invalid_request",
"Request body must be valid JSON");
3218 void run_hestia_command(resp_https_t response, req_https_t request) {
3219 if (!authenticate_hestia_client(response, request, crypto::PERM::server_cmd,
"server command execution")) {
3223 auto content_type = request->header.find(
"content-type");
3224 if (content_type == request->header.end() || !boost::istarts_with(content_type->second,
"application/json")) {
3225 send_hestia_error(response, SimpleWeb::StatusCode::client_error_bad_request,
"invalid_request",
"Content-Type must be application/json");
3230 const nlohmann::json input = nlohmann::json::parse(request->content.string());
3231 if (!hestia_has_exact_keys(input, {
"id"}) || !input[
"id"].is_number_integer()) {
3232 send_hestia_error(response, SimpleWeb::StatusCode::client_error_bad_request,
"invalid_request",
"Request must contain an integer id field");
3236 const int command_id = input[
"id"].get<
int>();
3237 if (command_id < 0 ||
static_cast<size_t>(command_id) >= config::sunshine.server_cmds.size()) {
3238 send_hestia_error(response, SimpleWeb::StatusCode::client_error_bad_request,
"invalid_request",
"Unknown server command id");
3242 const auto &configured_command = config::sunshine.server_cmds[command_id];
3243 const std::string
command = configured_command.cmd_val;
3244 const bool elevated = configured_command.elevated;
3245 BOOST_LOG(info) <<
"[HestiaAPI] executing configured server command id=" << command_id;
3246 std::thread([command, elevated] {
3248 auto env = proc::proc.get_env();
3249 auto working_dir = proc::find_working_directory(command, env);
3250 auto child = platf::run_command(elevated,
true, command, working_dir, env,
nullptr, ec,
nullptr);
3252 BOOST_LOG(error) <<
"[HestiaAPI] server command failed to start: " << ec.message();
3259 }
catch (
const nlohmann::json::exception &) {
3260 send_hestia_error(response, SimpleWeb::StatusCode::client_error_bad_request,
"invalid_request",
"Request body must be valid JSON");
3271 void getLocale(resp_https_t response, req_https_t request) {
3274 nlohmann::json output_tree;
3275 output_tree[
"status"] =
true;
3276 output_tree[
"locale"] = config::sunshine.locale;
3302 std::stringstream ss;
3303 ss << request->content.rdbuf();
3306 std::stringstream config_stream;
3307 nlohmann::json output_tree;
3308 nlohmann::json input_tree = nlohmann::json::parse(ss);
3309 for (
const auto &[k, v] : input_tree.items()) {
3310 if (v.is_null() || (v.is_string() && v.get<std::string>().empty())) {
3316 config_stream << k <<
" = " << (v.is_string() ? v.get<std::string>() : v.dump()) << std::endl;
3319 output_tree[
"status"] =
true;
3321 }
catch (std::exception &e) {
3322 BOOST_LOG(warning) <<
"SaveConfig: "sv << e.what();
3335 if (
const char *marker = std::getenv(
"container"); marker && marker[0]) {
3339 return std::filesystem::exists(
"/run/.containerenv", ec) || std::filesystem::exists(
"/.dockerenv", ec);
3352 nlohmann::json output_tree;
3355 std::stringstream ss;
3356 ss << request->content.rdbuf();
3357 if (!nlohmann::json::parse(ss).value(
"confirm",
false)) {
3358 bad_request(response, request,
"EVDI installation requires explicit confirmation");
3365 if (config::video.virtual_display_backend !=
"evdi") {
3366 bad_request(response, request,
"EVDI is not the configured virtual-display backend; installing it would change nothing.");
3376 bad_request(response, request,
"Hermes is running in a container. Install EVDI on the host - a module installed in the container matches no kernel and drives no display.");
3381 constexpr auto install_command = R
"EVDI(pkexec sh -c 'set -eu
3382if command -v pacman >/dev/null 2>&1; then
3383 pacman -S --needed --noconfirm evdi
3384elif command -v apt-get >/dev/null 2>&1; then
3386 apt-get install -y evdi-dkms libevdi1
3387elif command -v dnf >/dev/null 2>&1; then
3388 dnf install -y evdi akmod-evdi
3390 echo "Unsupported package manager. Install EVDI manually." >&2
3393if command -v dkms >/dev/null 2>&1; then
3394 dkms autoinstall -k "$(uname -r)"
3396printf "options evdi initial_device_count=1\n" > /etc/modprobe.d/apollo-evdi.conf
3397modprobe -r evdi 2>/dev/null || true
3399printf "evdi\\n" > /etc/modules-load.d/evdi.conf')EVDI";
3401 if (evdi_install_status.load() == 1) {
3402 output_tree[
"status"] =
true;
3403 output_tree[
"installStatus"] =
"running";
3408 evdi_install_status.store(1);
3409 std::thread([install_command] {
3410 auto working_dir = boost::filesystem::path(std::getenv(
"HOME") ?:
"/tmp");
3411 auto env = boost::this_process::environment();
3413 auto child = platf::run_command(
false,
true, install_command, working_dir, env,
nullptr, ec,
nullptr);
3415 BOOST_LOG(warning) <<
"Unable to launch EVDI installer: " << ec.message();
3416 evdi_install_status.store(3);
3421 if (child.exit_code() != 0) {
3422 BOOST_LOG(warning) <<
"EVDI installer exited with code " << child.exit_code();
3423 evdi_install_status.store(3);
3431 output_tree[
"status"] =
true;
3432 output_tree[
"installStatus"] =
"running";
3433 }
catch (
const std::exception &e) {
3434 BOOST_LOG(warning) <<
"InstallEvdi: " << e.what();
3448 nlohmann::json output_tree;
3449 output_tree[
"status"] =
true;
3450 output_tree[
"installStatus"] = evdi_install_status.load();
3451 output_tree[
"vdisplayStatus"] = (int)proc::vDisplayDriverStatus;
3452 output_tree[
"evdiInfo"] = evdi_status_json();
3453 output_tree[
"evdiDiagnostic"] = output_tree[
"evdiInfo"][
"diagnostic"];
3454 output_tree[
"hermesKmsInfo"] = hermes_kms_status_json();
3455 output_tree[
"hermesKmsDiagnostic"] = output_tree[
"hermesKmsInfo"][
"diagnostic"];
3460 void getEvdiStatus(resp_https_t response, req_https_t request) {
3461 if (!authenticate(response, request)) {
3465 nlohmann::json output_tree;
3466 output_tree[
"status"] =
true;
3467 output_tree[
"evdiInfo"] = evdi_status_json();
3477 nlohmann::json output_tree;
3478 output_tree[
"status"] =
true;
3479 output_tree[
"hermesKmsInfo"] = hermes_kms_status_json();
3482 output_tree[
"sessionFeatures"] = session_features_json();
3497 void getSessions(resp_https_t response, req_https_t request) {
3498 if (!authenticate(response, request)) {
3504 nlohmann::json output_tree;
3505 nlohmann::json sessions = nlohmann::json::array();
3506 for (
const auto &session : proc::proc.list_isolated()) {
3507 nlohmann::json entry;
3508 entry[
"id"] = session.launch_session_id;
3509 entry[
"uuid"] = session.client_uuid;
3510 entry[
"client_name"] = session.client_name;
3511 entry[
"app_id"] = session.app_id;
3512 entry[
"app_name"] = session.app_name;
3513 entry[
"profile"] = session.profile;
3514 entry[
"compositor"] = session.compositor;
3515 entry[
"seat"] = session.seat;
3516 entry[
"display"] = session.display;
3517 entry[
"running"] = session.running;
3518 entry[
"uptime_seconds"] = session.uptime_seconds;
3522 if (!session.account_user.empty()) {
3523 entry[
"account_user"] = session.account_user;
3524 entry[
"account_uid"] = session.account_uid;
3526 if (!session.unit.empty()) {
3527 entry[
"unit"] = session.unit;
3529 if (!session.audio_sink.empty()) {
3530 entry[
"audio_sink"] = session.audio_sink;
3534 entry[
"streaming"] = rtsp_stream::find_session(session.client_uuid) !=
nullptr;
3535 sessions.push_back(std::move(entry));
3538 output_tree[
"sessions"] = std::move(sessions);
3542 output_tree[
"supported"] =
true;
3543 output_tree[
"status"] =
true;
3563 void getGameModeStatus(resp_https_t response, req_https_t request) {
3564 if (!authenticate(response, request)) {
3570 nlohmann::json output_tree;
3571 output_tree[
"version"] = PROJECT_VERSION;
3572 output_tree[
"version_commit"] = PROJECT_VERSION_COMMIT;
3573 output_tree[
"hostname"] = config::nvhttp.sunshine_name;
3576 output_tree[
"paired_clients"] = clients.is_array() ? clients.size() : 0;
3579 output_tree[
"pending_pair"] =
true;
3580 output_tree[
"pending_pair_name"] = *pending;
3582 output_tree[
"pending_pair"] =
false;
3586 output_tree[
"isolated_sessions"] = proc::proc.list_isolated().size();
3588 output_tree[
"status"] =
true;
3618 std::stringstream ss;
3619 ss << request->content.rdbuf();
3620 nlohmann::json input_tree = nlohmann::json::parse(ss.str());
3621 nlohmann::json output_tree;
3623 const std::string uuid = input_tree.value(
"uuid",
"");
3625 bad_request(response, request,
"A client uuid is required.");
3629 const auto sessions = proc::proc.list_isolated();
3630 const bool known = std::ranges::any_of(sessions, [&](
const auto &session) {
3631 return session.client_uuid == uuid;
3634 output_tree[
"status"] =
false;
3635 output_tree[
"error"] =
"No isolated session belongs to that client.";
3641 proc::proc.terminate_isolated_client(uuid);
3643 BOOST_LOG(info) <<
"Isolated session for client ["sv << uuid <<
"] was ended from the web UI."sv;
3644 output_tree[
"status"] =
true;
3646 }
catch (std::exception &e) {
3647 BOOST_LOG(warning) <<
"Terminate session: "sv << e.what();
3652 void getClipboardStatus(resp_https_t response, req_https_t request) {
3653 if (!authenticate(response, request)) {
3657 nlohmann::json output_tree;
3658 output_tree[
"status"] =
true;
3659 output_tree[
"clipboardInfo"] = clipboard_status_json();
3660 output_tree[
"installStatus"] = clipboard_install_status.load();
3664 void installClipboard(resp_https_t response, req_https_t request) {
3669 nlohmann::json output_tree;
3671 std::stringstream ss;
3672 ss << request->content.rdbuf();
3673 if (!nlohmann::json::parse(ss).value(
"confirm",
false)) {
3674 bad_request(response, request,
"Clipboard installation requires explicit confirmation");
3677 if (clipboard_install_status.load() == 1) {
3678 output_tree[
"status"] =
true;
3679 output_tree[
"installStatus"] =
"running";
3685 constexpr auto install_command = R
"CLIP(pkexec sh -c 'set -eu
3686if command -v pacman >/dev/null 2>&1; then
3687 pacman -S --needed --noconfirm wl-clipboard xclip
3688elif command -v apt-get >/dev/null 2>&1; then
3690 apt-get install -y wl-clipboard xclip
3691elif command -v dnf >/dev/null 2>&1; then
3692 dnf install -y wl-clipboard xclip
3694 echo "Unsupported package manager. Install wl-clipboard and xclip manually." >&2
3697 clipboard_install_status.store(1);
3698 std::thread([install_command] {
3699 auto working_dir = boost::filesystem::path(std::getenv(
"HOME") ?:
"/tmp");
3700 auto env = boost::this_process::environment();
3702 auto child = platf::run_command(
false,
true, install_command, working_dir, env,
nullptr, ec,
nullptr);
3704 BOOST_LOG(warning) <<
"Unable to launch clipboard installer: " << ec.message();
3705 clipboard_install_status.store(3);
3709 clipboard_install_status.store(child.exit_code() == 0 ? 2 : 3);
3711 output_tree[
"status"] =
true;
3712 output_tree[
"installStatus"] =
"running";
3713 }
catch (
const std::exception &e) {
3714 BOOST_LOG(warning) <<
"InstallClipboard: " << e.what();
3728 void uploadCover(resp_https_t response, req_https_t request) {
3733 std::stringstream ss;
3735 ss << request->content.rdbuf();
3737 nlohmann::json input_tree = nlohmann::json::parse(ss.str());
3738 nlohmann::json output_tree;
3739 std::string key = input_tree.value(
"key",
"");
3741 bad_request(response, request,
"Cover key is required");
3744 std::string url = input_tree.value(
"url",
"");
3745 const std::string coverdir =
platf::appdata().string() +
"/covers/";
3747 std::string path = coverdir + http::url_escape(key) +
".png";
3749 if (http::url_get_host(url) !=
"images.igdb.com") {
3750 bad_request(response, request,
"Only images.igdb.com is allowed");
3753 if (!http::download_file(url, path)) {
3754 bad_request(response, request,
"Failed to download cover");
3758 auto data = SimpleWeb::Crypto::Base64::decode(input_tree.value(
"data",
""));
3759 std::ofstream imgfile(path);
3760 imgfile.write(data.data(),
static_cast<int>(data.size()));
3762 output_tree[
"status"] =
true;
3763 output_tree[
"path"] = path;
3765 }
catch (std::exception &e) {
3766 BOOST_LOG(warning) <<
"UploadCover: "sv << e.what();
3778 void getLogs(resp_https_t response, req_https_t request) {
3785 SimpleWeb::CaseInsensitiveMultimap headers;
3786 std::string contentType =
"text/plain";
3787 headers.emplace(
"Content-Type", contentType);
3788 headers.emplace(
"X-Frame-Options",
"DENY");
3789 headers.emplace(
"Content-Security-Policy",
"frame-ancestors 'none';");
3790 response->write(SimpleWeb::StatusCode::success_ok, content, headers);
3811 void savePassword(resp_https_t response, req_https_t request) {
3812 if ((!config::sunshine.username.empty() && !authenticate(response, request)) || !validateContentType(response, request,
"application/json"))
3815 std::vector<std::string> errors;
3816 std::stringstream ss;
3817 ss << request->content.rdbuf();
3819 nlohmann::json input_tree = nlohmann::json::parse(ss.str());
3820 nlohmann::json output_tree;
3821 std::string username = input_tree.value(
"currentUsername",
"");
3822 std::string newUsername = input_tree.value(
"newUsername",
"");
3823 std::string password = input_tree.value(
"currentPassword",
"");
3824 std::string newPassword = input_tree.value(
"newPassword",
"");
3825 std::string confirmPassword = input_tree.value(
"confirmNewPassword",
"");
3826 if (newUsername.empty())
3827 newUsername = username;
3828 if (newUsername.empty()) {
3829 errors.push_back(
"Invalid Username");
3831 auto hash = util::hex(
crypto::hash(password + config::sunshine.salt)).to_string();
3832 if (config::sunshine.username.empty() ||
3833 (boost::iequals(username, config::sunshine.username) && hash == config::sunshine.password)) {
3834 if (newPassword.empty() || newPassword != confirmPassword)
3835 errors.push_back(
"Password Mismatch");
3837 http::save_user_creds(config::sunshine.credentials_file, newUsername, newPassword);
3838 http::reload_user_creds(config::sunshine.credentials_file);
3839 sessionCookie.clear();
3840 output_tree[
"status"] =
true;
3843 errors.push_back(
"Invalid Current Credentials");
3846 if (!errors.empty()) {
3847 std::string error = std::accumulate(errors.begin(), errors.end(), std::string(),
3848 [](
const std::string &a,
const std::string &b) {
3849 return a.empty() ? b : a +
", " + b;
3855 }
catch (std::exception &e) {
3856 BOOST_LOG(warning) <<
"SavePassword: "sv << e.what();
3868 void getOTP(resp_https_t response, req_https_t request) {
3875 nlohmann::json output_tree;
3877 std::stringstream ss;
3878 ss << request->content.rdbuf();
3879 nlohmann::json input_tree = nlohmann::json::parse(ss.str());
3881 std::string passphrase = input_tree.value(
"passphrase",
"");
3882 if (passphrase.empty())
3883 throw std::runtime_error(
"Passphrase not provided!");
3884 if (passphrase.size() < 4)
3885 throw std::runtime_error(
"Passphrase too short!");
3887 std::string deviceName = input_tree.value(
"deviceName",
"");
3888 output_tree[
"otp"] = nvhttp::request_otp(passphrase, deviceName);
3889 output_tree[
"ip"] = platf::get_local_ip_for_gateway();
3890 output_tree[
"name"] = config::nvhttp.sunshine_name;
3891 output_tree[
"status"] =
true;
3892 output_tree[
"message"] =
"OTP created, effective within 3 minutes.";
3894 }
catch (std::exception &e) {
3895 BOOST_LOG(warning) <<
"OTP creation failed: "sv << e.what();
3896 bad_request(response, request, e.what());
3915 void savePin(resp_https_t response, req_https_t request) {
3923 std::stringstream ss;
3924 ss << request->content.rdbuf();
3925 nlohmann::json input_tree = nlohmann::json::parse(ss.str());
3926 nlohmann::json output_tree;
3927 std::string pin = input_tree.value(
"pin",
"");
3928 std::string name = input_tree.value(
"name",
"");
3931 }
catch (std::exception &e) {
3932 BOOST_LOG(warning) <<
"SavePin: "sv << e.what();
3951 nlohmann::json output_tree;
3963 void restart(resp_https_t response, req_https_t request) {
3970 proc::proc.terminate();
3982 std::mutex quit_mutex;
3983 std::condition_variable quit_cv;
3984 bool server_stopping =
false;
3985 int quit_waiters = 0;
3993 void quit(resp_https_t response, req_https_t request) {
4000 BOOST_LOG(warning) <<
"Requested quit from config page!"sv;
4002 proc::proc.terminate();
4009 std::lock_guard<std::mutex> lock(quit_mutex);
4010 if (server_stopping) {
4015 std::thread write_resp([response]()
mutable {
4016 std::unique_lock<std::mutex> lock(quit_mutex);
4017 if (!quit_cv.wait_for(lock, 5s, [] { return server_stopping; })) {
4022 quit_cv.notify_all();
4024 write_resp.detach();
4032 void launchApp(resp_https_t response, req_https_t request) {
4040 std::stringstream ss;
4041 ss << request->content.rdbuf();
4042 nlohmann::json input_tree = nlohmann::json::parse(ss.str());
4045 if (!input_tree.contains(
"uuid") || !input_tree[
"uuid"].is_string()) {
4046 bad_request(response, request,
"Missing or invalid uuid in request body");
4049 std::string uuid = input_tree[
"uuid"].get<std::string>();
4051 nlohmann::json output_tree;
4052 const auto &apps = proc::proc.get_apps();
4053 for (
auto &app : apps) {
4054 if (
app.uuid == uuid) {
4057 .uuid = http::unique_id,
4058 .perm = crypto::PERM::_all,
4060 BOOST_LOG(info) <<
"Launching app ["sv <<
app.name <<
"] from web UI"sv;
4061 auto launch_session = nvhttp::make_launch_session(
true,
false, request->parse_query_string(), &named_cert);
4062 auto err = proc::proc.execute(app, launch_session);
4066 if (!launch_session->launch_error_message.empty()) {
4067 bad_request(response, request, launch_session->launch_error_message);
4069 bad_request(response, request, err == 503 ?
4070 "Failed to initialize video capture/encoding. Is a display connected and turned on?" :
4071 "Failed to start the specified application");
4074 output_tree[
"status"] =
true;
4080 BOOST_LOG(error) <<
"Couldn't find app with uuid ["sv << uuid <<
']';
4081 bad_request(response, request,
"Cannot find requested application");
4083 catch (std::exception &e) {
4084 BOOST_LOG(warning) <<
"LaunchApp: "sv << e.what();
4094 void disconnect(resp_https_t response, req_https_t request) {
4102 std::stringstream ss;
4103 ss << request->content.rdbuf();
4104 nlohmann::json output_tree;
4105 nlohmann::json input_tree = nlohmann::json::parse(ss.str());
4106 std::string uuid = input_tree.value(
"uuid",
"");
4109 }
catch (std::exception &e) {
4110 BOOST_LOG(warning) <<
"Disconnect: "sv << e.what();
4111 bad_request(response, request, e.what());
4128 void login(resp_https_t response, req_https_t request) {
4133 auto fg = util::fail_guard([&]{
4134 response->write(SimpleWeb::StatusCode::client_error_unauthorized);
4138 std::stringstream ss;
4139 ss << request->content.rdbuf();
4140 nlohmann::json input_tree = nlohmann::json::parse(ss.str());
4141 std::string username = input_tree.value(
"username",
"");
4142 std::string password = input_tree.value(
"password",
"");
4143 std::string hash = util::hex(
crypto::hash(password + config::sunshine.salt)).to_string();
4144 if (!boost::iequals(username, config::sunshine.username) || hash != config::sunshine.password)
4146 std::string sessionCookieRaw = crypto::rand_alphabet(64);
4147 sessionCookie = util::hex(
crypto::hash(sessionCookieRaw + config::sunshine.salt)).to_string();
4148 cookie_creation_time = std::chrono::steady_clock::now();
4149 const SimpleWeb::CaseInsensitiveMultimap headers {
4150 {
"Set-Cookie",
"auth=" + sessionCookieRaw +
"; Secure; SameSite=Strict; Max-Age=2592000; Path=/" }
4152 response->write(headers);
4154 }
catch (std::exception &e) {
4156 <<
"]: "sv << e.what();
4157 response->write(SimpleWeb::StatusCode::server_error_internal_server_error);
4167 auto shutdown_event =
mail::man->event<
bool>(mail::shutdown);
4168 write_local_api_token();
4169 auto token_guard = util::fail_guard(remove_local_api_token);
4172 https_server_t server { config::nvhttp.cert, config::nvhttp.pkey };
4173 server.authenticate_client = [](
const req_https_t &request, SSL *ssl) {
4174 crypto::x509_t certificate {
4175#if OPENSSL_VERSION_MAJOR >= 3
4176 SSL_get1_peer_certificate(ssl)
4178 SSL_get_peer_certificate(ssl)
4185 crypto::p_named_cert_t client;
4187 request->userp = std::move(client);
4189 BOOST_LOG(info) <<
"[HestiaAPI] unpaired client certificate rejected";
4192 server.default_resource[
"DELETE"] = [](resp_https_t response, req_https_t request) {
4195 server.default_resource[
"PATCH"] = [](resp_https_t response, req_https_t request) {
4198 server.default_resource[
"POST"] = [](resp_https_t response, req_https_t request) {
4201 server.default_resource[
"PUT"] = [](resp_https_t response, req_https_t request) {
4204 server.default_resource[
"GET"] =
not_found;
4206 server.resource[
"^/pin/?$"][
"GET"] =
getPinPage;
4207 server.resource[
"^/apps/?$"][
"GET"] =
getAppsPage;
4213 server.resource[
"^/api/login"][
"POST"] =
login;
4214 server.resource[
"^/api/pin$"][
"POST"] =
savePin;
4215 server.resource[
"^/api/otp$"][
"POST"] =
getOTP;
4216 server.resource[
"^/api/apps$"][
"GET"] =
getApps;
4217 server.resource[
"^/api/apps$"][
"POST"] =
saveApp;
4218 server.resource[
"^/api/apps/reorder$"][
"POST"] =
reorderApps;
4219 server.resource[
"^/api/library$"][
"GET"] =
getLibrary;
4220 server.resource[
"^/api/apps/delete$"][
"POST"] =
deleteApp;
4221 server.resource[
"^/api/apps/launch$"][
"POST"] =
launchApp;
4222 server.resource[
"^/api/apps/close$"][
"POST"] =
closeApp;
4223 server.resource[
"^/api/logs$"][
"GET"] =
getLogs;
4224 server.resource[
"^/api/metrics$"][
"GET"] =
getMetrics;
4225 server.resource[
"^/api/config$"][
"GET"] =
getConfig;
4226 server.resource[
"^/api/config$"][
"POST"] =
saveConfig;
4227 server.resource[
"^/api/evdi/install$"][
"POST"] =
installEvdi;
4229 server.resource[
"^/api/evdi/status$"][
"GET"] =
getEvdiStatus;
4231 server.resource[
"^/api/clipboard/status$"][
"GET"] = getClipboardStatus;
4232 server.resource[
"^/api/clipboard/install$"][
"POST"] = installClipboard;
4236 server.resource[
"^/api/hestia/v1/session/stop$"][
"POST"] = stop_hestia_session;
4237 server.resource[
"^/api/hestia/v1/display/status$"][
"GET"] = get_hestia_display_status;
4238 server.resource[
"^/api/hestia/v1/display/recover$"][
"POST"] = recover_hestia_display;
4239 server.resource[
"^/api/hestia/v1/client/permissions$"][
"GET"] = get_hestia_client_permissions;
4240 server.resource[
"^/api/hestia/v1/diagnostics$"][
"GET"] = get_hestia_diagnostics;
4242 server.resource[
"^/api/hestia/v1/diagnostics/report$"][
"GET"] = get_hestia_diagnostic_report;
4244 server.resource[
"^/api/hestia/v1/clipboard$"][
"GET"] = get_hestia_clipboard;
4245 server.resource[
"^/api/hestia/v1/clipboard$"][
"POST"] = set_hestia_clipboard;
4246 server.resource[
"^/api/hestia/v1/commands$"][
"GET"] = get_hestia_commands;
4247 server.resource[
"^/api/hestia/v1/commands/run$"][
"POST"] = run_hestia_command;
4248 server.resource[
"^/api/configLocale$"][
"GET"] =
getLocale;
4249 server.resource[
"^/api/restart$"][
"POST"] =
restart;
4250 server.resource[
"^/api/quit$"][
"POST"] =
quit;
4252 server.resource[
"^/api/password$"][
"POST"] =
savePassword;
4253 server.resource[
"^/api/clients/unpair-all$"][
"POST"] =
unpairAll;
4254 server.resource[
"^/api/clients/list$"][
"GET"] =
getClients;
4255 server.resource[
"^/api/clients/update$"][
"POST"] =
updateClient;
4256 server.resource[
"^/api/clients/unpair$"][
"POST"] =
unpair;
4257 server.resource[
"^/api/clients/disconnect$"][
"POST"] =
disconnect;
4259 server.resource[
"^/api/sessions/list$"][
"GET"] =
getSessions;
4261 server.resource[
"^/api/covers/upload$"][
"POST"] =
uploadCover;
4268 server.config.reuse_address =
true;
4270 server.config.port = port_https;
4276 if (!fs::exists(WEB_DIR
"index.html")) {
4277 BOOST_LOG(error) <<
"Web UI assets not found in ["sv << WEB_DIR <<
']';
4278 BOOST_LOG(error) <<
"The configuration UI will not render. This binary was built with "sv
4279 "HERMES_ASSETS_DIR=["sv << HERMES_ASSETS_DIR <<
"]."sv;
4282 auto accept_and_run = [&](
auto *server) {
4284 server->start([port_https](
unsigned short port) {
4285 BOOST_LOG(info) <<
"Configuration UI available at [https://localhost:"sv << port <<
"]";
4287 }
catch (boost::system::system_error &err) {
4289 if (shutdown_event->peek())
4291 BOOST_LOG(fatal) <<
"Couldn't start Configuration HTTPS server on port ["sv << port_https <<
"]: "sv << err.what();
4292 BOOST_LOG(fatal) <<
"Another host is most likely already bound to it. Hermes, Apollo and Sunshine all use this port, so only one of them can run at a time."sv;
4293 shutdown_event->raise(
true);
4297 std::thread tcp { accept_and_run, &server };
4300 std::atomic_bool stop_timeline {
false};
4301 std::thread timeline {[&stop_timeline]() {
4302 using namespace std::literals;
4303 while (!stop_timeline) {
4304 for (
int tick = 0; tick < 50 && !stop_timeline; ++tick) {
4305 std::this_thread::sleep_for(100ms);
4307 report_timeline::record();
4310 auto stop_timeline_guard = util::fail_guard([&]() {
4311 stop_timeline =
true;
4316 shutdown_event->view();
4320 std::unique_lock<std::mutex> lock(quit_mutex);
4321 server_stopping =
true;
4322 quit_cv.notify_all();
4323 quit_cv.wait(lock, [] {
return quit_waiters == 0; });
void release_host_sink()
Let go of a hold_host_sink() hold and restore the sink it recorded.
Declarations for audio capture and encoding.
Capture a shell helper's output without an unbounded shutdown wait.
void stop()
Stop the RTSP server.
Declarations for common platform specific utilities.
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...
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.
appliance_readiness_t appliance_readiness()
Assess appliance-mode readiness without changing any state.
Declarations for the configuration of Sunshine.
bool has_local_api_token(req_https_t request)
std::string localApiToken
A bearer token any local process of this user may present.
void disconnect(resp_https_t response, req_https_t request)
Disconnect a client.
void getLoginPage(resp_https_t response, req_https_t request)
Get the login page.
void getConfig(resp_https_t response, req_https_t request)
Get the current configuration: the computed values Hermes is running with, overlaid with what the con...
void getWelcomePage(resp_https_t response, req_https_t request)
Get the welcome page.
void saveConfig(resp_https_t response, req_https_t request)
Save the configuration settings.
void unpairAll(resp_https_t response, req_https_t request)
Unpair all clients.
void updateClient(resp_https_t response, req_https_t request)
Update client information.
void savePassword(resp_https_t response, req_https_t request)
Update existing credentials.
void getConfigPage(resp_https_t response, req_https_t request)
Get the configuration page.
bool local_api_token_origin_allowed(std::string_view address)
Whether an address may authenticate with the Game Mode local token.
void getHermesLogoImage(resp_https_t response, req_https_t request)
Get the Hermes logo image.
void getPinPage(resp_https_t response, req_https_t request)
Get the PIN page.
void getEvdiStatus(resp_https_t response, req_https_t request)
bool authenticate(resp_https_t response, req_https_t request, bool needsRedirect=false)
Authenticate the request.
void launchApp(resp_https_t response, req_https_t request)
Launch an application.
nlohmann::json hestia_capabilities_json()
The Hestia extension capabilities document.
void getLibrary(resp_https_t response, req_https_t request)
List the games installed in Steam and Lutris, to add as apps.
void getHestiaCapabilities(resp_https_t response, req_https_t request)
Return the static Hestia extension capabilities.
nlohmann::json computed_config_json()
Get the configuration settings.
bool checkIPOrigin(resp_https_t response, req_https_t request)
Check if the IP origin is allowed.
void closeApp(resp_https_t response, req_https_t request)
Close the currently running application.
void print_req(const req_https_t &request)
Log the request details.
bool token_matches(std::string_view presented, std::string_view expected)
void getEvdiInstallStatus(resp_https_t response, req_https_t request)
void getSessions(resp_https_t response, req_https_t request)
List the isolated sessions this server is holding.
void get_hestia_stream_info(resp_https_t response, req_https_t request)
void getGameModeStatus(resp_https_t response, req_https_t request)
Everything the Game Mode console shows on one screen, in one call.
void send_response(resp_https_t response, const nlohmann::json &output_tree)
Send a response.
void getOTP(resp_https_t response, req_https_t request)
Get a one-time password (OTP).
void savePin(resp_https_t response, req_https_t request)
Send a PIN code to the host.
void login(resp_https_t response, req_https_t request)
Login the user.
std::string getCookieValue(const std::string &cookieString, const std::string &key)
Retrieve the value of a key from a cookie string.
void not_found(resp_https_t response, req_https_t request)
Send a 404 Not Found response.
bool running_in_container()
Whether Hermes is running inside a container.
void saveApp(resp_https_t response, req_https_t request)
Save an application. To save a new application the UUID must be empty. To update an existing applicat...
std::string diagnostic_report()
void getLogs(resp_https_t response, req_https_t request)
Get the logs from the log file.
void reorderApps(resp_https_t response, req_https_t request)
Reorder applications.
void getIndexPage(resp_https_t response, req_https_t request)
Get the index page.
void bad_request(resp_https_t response, req_https_t request, const std::string &error_message="Bad Request")
Send a 400 Bad Request response.
void unpair(resp_https_t response, req_https_t request)
Unpair a client.
void terminateSession(resp_https_t response, req_https_t request)
End one isolated session.
void uploadCover(resp_https_t response, req_https_t request)
Upload a cover image.
void getClientsPage(resp_https_t response, req_https_t request)
Get the clients page.
void getLocale(resp_https_t response, req_https_t request)
Get the locale setting.
void quit(resp_https_t response, req_https_t request)
Quit Hermes.
void getFaviconImage(resp_https_t response, req_https_t request)
Get the favicon image.
bool validateContentType(resp_https_t response, req_https_t request, const std::string_view &contentType)
Validate the request content type and send bad request when mismatch.
void getTroubleshootingPage(resp_https_t response, req_https_t request)
Get the troubleshooting page.
void send_redirect(resp_https_t response, req_https_t request, const char *path)
Send a redirect response.
void getClients(resp_https_t response, req_https_t request)
Get the list of paired clients.
void getHermesKmsStatus(resp_https_t response, req_https_t request)
bool isChildPath(fs::path const &base, fs::path const &query)
Check if a path is a child of another path.
void getNodeModules(resp_https_t response, req_https_t request)
Get an asset from the node_modules directory.
nlohmann::json & overlay_config_file(nlohmann::json &response, const std::unordered_map< std::string, std::string > &file_values)
Overlay a parsed hermes.conf onto response, in place.
void getAppsPage(resp_https_t response, req_https_t request)
Get the apps page.
void installEvdi(resp_https_t response, req_https_t request)
void getDiagnosticReport(resp_https_t response, req_https_t request)
Download a diagnostic report of this host.
void resetDisplayDevicePersistence(resp_https_t response, req_https_t request)
Reset the display device persistence.
void machine_snapshot(std::ostream &out)
void start()
Start the HTTPS server.
void prepare_hestia_session(resp_https_t response, req_https_t request)
Store settings for a paired Hestia client's next stream launch.
void getMetrics(resp_https_t response, req_https_t request)
Get the live runtime status: encoder, session, and pipeline counters. The same view the Hestia diagno...
void deleteApp(resp_https_t response, req_https_t request)
Delete an application.
void send_web_page(resp_https_t response, req_https_t request, const std::string &page, const SimpleWeb::CaseInsensitiveMultimap &extra_headers={})
Serve a page from the packaged web assets.
void send_unauthorized(resp_https_t response, req_https_t request)
Send a 401 Unauthorized response.
nlohmann::json hestia_preflight_json()
Aggregate "is the host ready to stream?" checks.
void getPasswordPage(resp_https_t response, req_https_t request)
Get the password page.
void getApps(resp_https_t response, req_https_t request)
Get the list of available applications.
void restart(resp_https_t response, req_https_t request)
Restart Hermes.
Declarations for the Web UI Config HTTP server.
sha256_t hash(const std::string_view &plaintext)
Hashes the given plaintext using SHA-256.
Declarations for cryptography functions.
PERM
The permissions of a client.
void revert_configuration()
Revert the display configuration and restore the previous state.
bool reset_persistence()
Reset the persistence and currently held initial display state.
Declarations for display device handling.
std::vector< std::string > render_node_descriptions()
Describe every GPU render node, as encode_gpu_description() does, the capture-only Hermes-KMS node in...
std::string encode_gpu_description(bool nvenc)
Describe the GPU a stream encodes on, for logs and diagnostics: its render node, driver and the name ...
Declarations for file handling functions.
The games installed in Steam and Lutris, for adding them as apps.
Declarations for globally accessible variables and functions.
Declarations for common HTTP.
Declarations for logging related functions.
Miscellaneous declarations for Linux.
std::string encode_card
The encoding GPU's sysfs device directory.
std::string read_file(const char *path)
Read a file to string.
int write_file(const char *path, const std::string_view &contents)
Writes a file.
bool make_directory(const std::string &path)
Make a directory.
void exit_sunshine(int exit_code, bool async)
Terminates Sunshine gracefully with the provided exit code.
safe::mail_t man
A process-wide communication mechanism.
void store_hestia_session_prepare(const std::string &client_uuid, hestia_session_prepare_t prepare)
bool pin(std::string pin, std::string name)
Compare the user supplied pin to the Moonlight pin.
bool unpair_client(const std::string_view uuid)
Remove single client.
std::optional< std::string > pending_pair_client()
The client whose pairing request is waiting for a PIN, if any.
void erase_all_clients()
Remove all paired clients.
bool verify_paired_client_certificate(X509 *certificate, crypto::p_named_cert_t &named_cert_out)
Verify a TLS client certificate against the paired-client store.
nlohmann::json describe_applied_settings(const std::string &app_id, bool virtual_display, int scale_factor)
bool update_device_info(const std::string &uuid, const std::string &name, const std::string &display_mode, const cmd_list_t &do_cmds, const cmd_list_t &undo_cmds, const crypto::PERM newPerm, const bool enable_legacy_ordering, const bool allow_client_commands, const bool always_use_virtual_display)
Update device info.
void clear_hestia_session_prepare(const std::string &client_uuid)
bool find_and_stop_session(const std::string &uuid, bool graceful)
Finds and stop session.
nlohmann::json get_all_clients()
Get all paired clients.
std::uint16_t map_port(int port)
Map a specified port based on the base port.
bool udp_port_available(af_e af, std::uint16_t port)
Whether a UDP port can still be bound on this host.
net_e from_address(const std::string_view &view, std::span< const interface_address_t > links)
Classify an address against the given interface subnets.
std::string_view af_to_any_address_string(af_e af)
Get the wildcard binding address for a given address family.
std::string addr_to_normalized_string(boost::asio::ip::address address)
Get the given address in normalized string form.
af_e af_from_enum_string(const std::string_view &view)
Get the address family enum value from a string.
net_e from_address_ranges(const std::string_view &view)
Classify an address by the fixed ranges alone.
Declarations for networking related functions.
Declarations for the nvhttp (GameStream) server.
report_t report()
assess(collect_facts()).
int command(const char *name, int argc, char *argv[])
hermes --prelogin status|enable|disable.
Set up and check what it takes for Hermes to be reachable before login.
void migrate_apps(nlohmann::json *fileTree_p, nlohmann::json *inputTree_p)
Migrate the applications stored in the file tree by merging in a new app.
void initVDisplayDriver()
Initialize the virtual display driver. This should be called early in startup to enable virtual displ...
Declarations for the startup and shutdown of the apps started by a streaming Session.
@ app
The client sent none; the app's own scale.
std::string_view last_termination_reason()
Get a short identifier for why the most recent session ended.
int session_count()
Get the number of active sessions.
Declarations for RTSP streaming.
termination_stats_t termination_stats()
Snapshot of the termination/reconnection stats.
Declarations for the streaming protocols.
uint32_t required_uapi_version
Minimum UAPI version Hermes needs.
std::string inaccessible_node
bool device_present
A hermes-kms DRM card node was found and opened.
std::string installed_version
uint32_t uapi_version
UAPI version reported by the device, or 0.
int card_index
DRM card index of the Hermes-KMS device, or -1.
uint32_t newest_known_uapi_version
std::string driver_version
"major.minor.patch" from the device, if present.
The machine around the stream. A value nobody may read here stays negative.
long long udp_dropped
UDP packets the kernel dropped for full buffers since the last sample.
long long net_errors
Dropped or errored packets on the network cards since the last sample.
bool enabled
Hermes' unit is set to start at boot.
bool ready
Every requirement is known to be in place.
Live per-frame pipeline metrics, for diagnostics/metrics.
Declarations for utility functions.
Declarations for UUID generation.
bool display_present()
Whether the host has a display to capture without creating one.
encoder_status_t get_encoder_status()
Snapshot of the last encoder probe result (thread-safe copy).
capture_readiness_t last_capture_readiness()
The result of the last check_capture_path().
pipeline_metrics_t get_pipeline_metrics()
Snapshot of the live pipeline metrics (thread-safe copy).
EvdiStatus getEvdiStatus()
bool needsInitialDeviceConfiguration()
Whether EVDI needs a device pre-created at module load time.
HermesKmsMetrics getHermesKmsMetrics()
Read the Hermes-KMS device metrics, if a metrics-capable device is present. It opens a short-lived re...
std::vector< FeatureReport > assessSession(const SessionFacts &facts)
Turn observations into a per-feature verdict with remediation.
SessionFacts probeSessionFacts()
std::string featureName(feature_e feature)
HermesKmsStatus getHermesKmsStatus()
bool displayServerReachable(const std::string &wayland_display, const std::string &x_display, const std::string &runtime_dir)
Whether a display server is listening where these variables point.
std::optional< bool > graphicalSessionPresent()
Whether this user has a session of their own, as logind sees it - graphical or not,...
@ virtual_display
Create a virtual display and have it composited onto.
@ OK
Driver is operational.
EVDI_DIAGNOSTIC
Actionable EVDI state exposed to the Web UI.
HERMES_KMS_DIAGNOSTIC
Actionable Hermes-KMS state exposed to the Web UI.
@ NO_ACCESS
The driver's desktop render node exists but this user may not open it.