Hermes 0.7.0
Linux game streaming host
Loading...
Searching...
No Matches
confighttp.cpp
Go to the documentation of this file.
1
7#define BOOST_BIND_GLOBAL_PLACEHOLDERS
8
9// standard includes
10#include <filesystem>
11#include <format>
12#include <fstream>
13#include <set>
14#include <sstream>
15#include <thread>
16#include <condition_variable>
17#include <mutex>
18#include <numeric>
19#include <algorithm>
20#include <atomic>
21#include <deque>
22#include <map>
23#include <limits>
24#include <optional>
25#include <iterator>
26#include <cctype>
27#include <mutex>
28 #include <sys/utsname.h>
29 #include <unistd.h>
30 #include <cerrno>
31 #include <cstring>
32 #include <fcntl.h>
33 #include <sys/stat.h>
34 #include <unistd.h>
35
36// lib includes
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>
44
45// local includes
46#include "audio.h"
47#include "config.h"
48#include "confighttp.h"
49#include "crypto.h"
50#include "display_device.h"
51#include "file_handler.h"
52#include "globals.h"
53#include "httpcommon.h"
54#include "logging.h"
55#include "network.h"
56#include "nvhttp.h"
57#include "platform/common.h"
58#include "process.h"
59#include "rtsp.h"
60#include "stream.h"
61#include "utility.h"
62#include "uuid.h"
63#include "video.h"
66 #include "platform/linux/misc.h"
67
69
70using namespace std::literals;
71
72namespace confighttp {
73 namespace fs = std::filesystem;
74
75 // Defined later; declared here so the web-UI metrics handler can reuse it.
76 nlohmann::json hestia_runtime_status_json();
77
78 bool local_api_token_origin_allowed(std::string_view address) {
79 try {
80 // The fixed ranges only: sharing a subnet with this host does not make a
81 // public address private (a PC on a cable modem shares a public /22 with
82 // its neighbours), and the console the token is for never runs there.
83 return net::from_address_ranges(address) <= net::LAN;
84 } catch (const std::exception &) {
85 // Authentication policy must fail closed if it is ever handed an address
86 // that the network classifier cannot parse.
87 return false;
88 }
89 }
90
91 class HestiaHTTPSServer: public SimpleWeb::ServerBase<SimpleWeb::HTTPS> {
92 public:
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);
100 }
101
102 std::function<void(std::shared_ptr<Request>, SSL *)> authenticate_client;
103
104 protected:
105 boost::asio::ssl::context context;
106
107 void after_bind() override {
108 // Request a client certificate but permit clients that do not have one so
109 // the read-only capabilities probe remains available before pairing.
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 &) {
112 return true;
113 });
114
115 // This listener serves both the Hestia API, which identifies callers by their paired
116 // certificate, and the config UI, which browsers load. Advertising no acceptable CAs
117 // means "any certificate will do", so a browser holding any client certificate at all
118 // opens a selection dialog on the config UI — and dismissing it aborts the connection,
119 // which surfaces as "Failed to fetch" on the login page. Advertising our own
120 // certificate instead gives browsers something to filter their store against; nothing
121 // matches, so they send an empty certificate without prompting. Paired Hestia clients
122 // present their certificate regardless of what is advertised.
123 if (X509 *certificate = SSL_CTX_get0_certificate(context.native_handle())) {
124 SSL_CTX_add_client_CA(context.native_handle(), certificate);
125 }
126
127 // OpenSSL requires a session id context on any server that authenticates
128 // clients and also allows resumption. Without one, resuming a session is a
129 // fatal error — "session id context uninitialized" — instead of falling
130 // back to a full handshake, and the connection dies mid-request.
131 //
132 // The first request of a page load negotiates a fresh session and works,
133 // so the page renders. The next request tries to resume and is killed,
134 // which Chromium reports as ERR_SSL_PROTOCOL_ERROR and fetch() as a bare
135 // "Failed to fetch". That is why logging in worked in Firefox but not in
136 // Brave, and why only requests made after the page had loaded ever broke.
137 static const unsigned char session_id_context[] = "hermes-confighttp";
138 SSL_CTX_set_session_id_context(
139 context.native_handle(),
140 session_id_context,
141 sizeof(session_id_context) - 1
142 );
143 }
144
145 void accept() override {
146 auto connection = create_connection(*io_service, context);
147
148 acceptor->async_accept(connection->socket->lowest_layer(), [this, connection](const SimpleWeb::error_code &ec) {
149 auto lock = connection->handler_runner->continue_lock();
150 if (!lock) {
151 return;
152 }
153
154 if (ec != SimpleWeb::error::operation_aborted) {
155 this->accept();
156 }
157
158 auto session = std::make_shared<Session>(config.max_request_streambuf_size, connection);
159 if (!ec) {
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);
163
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();
168 if (!lock) {
169 return;
170 }
171
172 if (!handshake_error) {
173 if (authenticate_client) {
174 authenticate_client(session->request, session->connection->socket->native_handle());
175 }
176 this->read(session);
177 } else if (this->on_error) {
178 this->on_error(session->request, handshake_error);
179 }
180 });
181 } else if (this->on_error) {
182 this->on_error(session->request, ec);
183 }
184 });
185 }
186 };
187
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>;
192
193 // Keep the base enum for client operations.
194 enum class op_e {
197 };
198
199 // SESSION COOKIE
200 std::string sessionCookie;
201 static std::chrono::time_point<std::chrono::steady_clock> cookie_creation_time;
202
221 std::string localApiToken;
222 std::filesystem::path localApiTokenPath;
223
224 std::filesystem::path local_api_token_path() {
225 const char *runtime_dir = std::getenv("XDG_RUNTIME_DIR");
226 if (!runtime_dir || !*runtime_dir) {
227 return {};
228 }
229 return std::filesystem::path {runtime_dir} / "hermes" / "local-api.token";
230 }
231
233 bool token_matches(std::string_view presented, std::string_view expected) {
234 if (expected.empty() || presented.size() != expected.size()) {
235 return false;
236 }
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]);
240 }
241 return difference == 0;
242 }
243
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;
248 return;
249 }
250
251 std::error_code ec;
252 std::filesystem::create_directories(localApiTokenPath.parent_path(), ec);
253 if (ec) {
254 BOOST_LOG(warning) << "Could not create "sv << localApiTokenPath.parent_path().string()
255 << ": "sv << ec.message();
256 localApiTokenPath.clear();
257 return;
258 }
259
260 localApiToken = crypto::rand_alphabet(64);
261
262 // Created private and only then written: a token that is briefly
263 // world-readable is a token that leaked, however short the window.
264 const int fd = ::open(localApiTokenPath.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, S_IRUSR | S_IWUSR);
265 if (fd < 0) {
266 BOOST_LOG(warning) << "Could not write "sv << localApiTokenPath.string() << ": "sv << std::strerror(errno);
267 localApiToken.clear();
268 localApiTokenPath.clear();
269 return;
270 }
271 const auto written = ::write(fd, localApiToken.data(), localApiToken.size());
272 ::close(fd);
273 if (written != static_cast<ssize_t>(localApiToken.size())) {
274 BOOST_LOG(warning) << "Short write publishing the local API token"sv;
275 std::filesystem::remove(localApiTokenPath, ec);
276 localApiToken.clear();
277 localApiTokenPath.clear();
278 return;
279 }
280
281 BOOST_LOG(info) << "Local API token published at "sv << localApiTokenPath.string()
282 << " for the Game Mode console."sv;
283 }
284
285 void remove_local_api_token() {
286 if (localApiTokenPath.empty()) {
287 return;
288 }
289 std::error_code ec;
290 std::filesystem::remove(localApiTokenPath, ec);
291 localApiToken.clear();
292 localApiTokenPath.clear();
293 }
294
296 bool has_local_api_token(req_https_t request) {
297 if (localApiToken.empty()) {
298 return false;
299 }
300 const auto header = request->header.find("authorization");
301 if (header == request->header.end()) {
302 return false;
303 }
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)) {
308 return false;
309 }
310 if (!token_matches(value.substr(prefix.size()), localApiToken)) {
311 return false;
312 }
313
314 const auto address = net::addr_to_normalized_string(request->remote_endpoint().address());
315 if (!local_api_token_origin_allowed(address)) {
316 BOOST_LOG(warning) << "Web UI: ["sv << address
317 << "] -- rejected Game Mode token from WAN"sv;
318 return false;
319 }
320 return true;
321 }
322
323 // 0 = idle, 1 = running, 2 = succeeded, 3 = failed/cancelled.
324 static std::atomic<int> evdi_install_status {0};
325 // 0 = idle, 1 = running, 2 = succeeded, 3 = failed/cancelled.
326 static std::atomic<int> clipboard_install_status {0};
327
328 static const char *evdi_diagnostic_name(VDISPLAY::EVDI_DIAGNOSTIC diagnostic) {
329 switch (diagnostic) {
330 case VDISPLAY::EVDI_DIAGNOSTIC::READY:
331 return "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";
342 }
343
344 return "module_not_loaded";
345 }
346
358 static nlohmann::json stream_ports_json() {
359 nlohmann::json ports = nlohmann::json::array();
360 if (rtsp_stream::session_count() > 0) {
361 return ports;
362 }
363
364 const auto address_family = net::af_from_enum_string(config::sunshine.address_family);
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},
369 };
370
371 for (const auto &[name, offset] : checks) {
372 const auto port = net::map_port(offset);
373 ports.push_back({
374 {"name", name},
375 {"port", port},
376 {"available", net::udp_port_available(address_family, port)},
377 });
378 }
379 return ports;
380 }
381
382
383 static nlohmann::json evdi_status_json() {
384 const auto status = VDISPLAY::getEvdiStatus();
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()},
399 };
400
401 for (const auto &display : status.active_displays) {
402 output["activeDisplays"].push_back({
403 {"name", display.name},
404 {"clientName", display.client_name},
405 {"deviceIndex", display.device_index},
406 {"drmCardIndex", display.drm_card_index},
407 {"width", display.width},
408 {"height", display.height},
409 {"fps", display.fps},
410 {"frameUpdates", display.frame_updates},
411 {"capturePath", "evdi_cpu_buffer"},
412 {"zeroCopyCapture", false},
413 {"hardwareEncodingAvailable", true},
414 });
415 }
416
417 return output;
418 }
419
420 static const char *hermes_kms_diagnostic_name(VDISPLAY::HERMES_KMS_DIAGNOSTIC diagnostic) {
421 switch (diagnostic) {
422 case VDISPLAY::HERMES_KMS_DIAGNOSTIC::READY:
423 return "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";
437 return "no_access";
438 }
439
440 return "module_not_loaded";
441 }
442
448 static nlohmann::json session_features_json() {
449 auto features = nlohmann::json::array();
450 for (const auto &report : VDISPLAY::assessSession(VDISPLAY::probeSessionFacts())) {
451 features.push_back({
452 {"feature", VDISPLAY::featureName(report.feature)},
453 {"readiness", VDISPLAY::readinessName(report.readiness)},
454 {"detail", report.detail},
455 {"remediation", report.remediation},
456 });
457 }
458 return features;
459 }
460
465 static std::string hermes_kms_problem(const VDISPLAY::HermesKmsStatus &status) {
467 switch (status.diagnostic) {
468 case READY:
469 return {};
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.";
477 case UAPI_TOO_OLD:
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 " +
480 std::to_string(status.required_uapi_version) + "). Update the driver.";
481 case MISSING_CAPABILITIES:
482 return "The loaded Hermes-KMS driver (" + status.driver_version +
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.";
486 case NO_ACCESS:
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.";
490 }
491 return {};
492 }
493
495 static std::string hermes_kms_reload_note(const VDISPLAY::HermesKmsStatus &status) {
496 if (!status.reload_needed) {
497 return {};
498 }
499 return "Hermes-KMS " + status.installed_version + " is installed, but " + status.driver_version +
500 " is still loaded. Restart the PC to use the installed driver.";
501 }
502
504 static std::string hermes_kms_newer_note(const VDISPLAY::HermesKmsStatus &status) {
505 if (status.uapi_version <= status.newest_known_uapi_version) {
506 return {};
507 }
508 return "This driver (interface " + std::to_string(status.uapi_version) +
509 ") is newer than this Hermes (interface " + std::to_string(status.newest_known_uapi_version) +
510 "). That usually works; if virtual displays misbehave, update Hermes.";
511 }
512
513 static nlohmann::json hermes_kms_status_json() {
514 const auto status = VDISPLAY::getHermesKmsStatus();
515 nlohmann::json output {
516 {"diagnostic", hermes_kms_diagnostic_name(status.diagnostic)},
517 {"moduleLoaded", status.module_loaded},
518 {"moduleInstalled", status.module_installed},
519 {"devicePresent", status.device_present},
520 {"cardIndex", status.card_index},
521 {"uapiVersion", status.uapi_version},
522 {"requiredUapiVersion", status.required_uapi_version},
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},
531 {"driverVersion", status.driver_version},
532 {"runningKernel", status.running_kernel},
533 {"dkmsKernels", status.dkms_kernels},
534 {"activeDisplays", nlohmann::json::array()},
535 {"inaccessibleNode", status.inaccessible_node},
536 {"installedVersion", status.installed_version},
537 {"reloadNeeded", status.reload_needed},
538 {"newestKnownUapiVersion", status.newest_known_uapi_version},
539 {"problem", hermes_kms_problem(status)},
540 {"reloadNote", hermes_kms_reload_note(status)},
541 {"newerNote", hermes_kms_newer_note(status)},
542 };
543
544 for (const auto &display : status.active_displays) {
545 output["activeDisplays"].push_back({
546 {"name", display.name},
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},
551 {"width", display.width},
552 {"height", display.height},
553 {"fps", display.fps},
554 {"capturePath", "hermes_kms_dmabuf"},
555 {"zeroCopyCapture", true},
556 {"hardwareEncodingAvailable", true},
557 });
558 }
559
560 return output;
561 }
562
567 static nlohmann::json prelogin_status_json() {
568 const auto report = platf::prelogin::report();
569 auto checks = nlohmann::json::array();
570 for (const auto &check : report.checks) {
571 checks.push_back({
572 {"id", check.id},
573 {"state", platf::prelogin::state_name(check.state)},
574 {"title", check.title},
575 {"detail", check.detail},
576 {"fix", check.fix},
577 });
578 }
579 return {
580 {"enabled", report.enabled},
581 {"ready", report.ready},
582 {"checks", std::move(checks)},
583 };
584 }
585
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";
596 return {
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"},
605 };
606 }
607
612 void print_req(const req_https_t &request) {
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);
617 }
618 BOOST_LOG(debug) << " [--] "sv;
619 for (auto &[name, val] : request->parse_query_string()) {
620 BOOST_LOG(debug) << name << " -- " << val;
621 }
622 BOOST_LOG(debug) << " [--] "sv;
623 }
624
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);
636 }
637
643 void send_unauthorized(resp_https_t response, req_https_t request) {
644 auto address = net::addr_to_normalized_string(request->remote_endpoint().address());
645 BOOST_LOG(info) << "Web UI: ["sv << address << "] -- not authorized"sv;
646 constexpr SimpleWeb::StatusCode code = SimpleWeb::StatusCode::client_error_unauthorized;
647 nlohmann::json tree;
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';"}
655 };
656 response->write(code, tree.dump(), headers);
657 }
658
665 void send_redirect(resp_https_t response, req_https_t request, const char *path) {
666 auto address = net::addr_to_normalized_string(request->remote_endpoint().address());
667 BOOST_LOG(info) << "Web UI: ["sv << address << "] -- redirecting"sv;
668 const SimpleWeb::CaseInsensitiveMultimap headers {
669 {"Location", path},
670 {"X-Frame-Options", "DENY"},
671 {"Content-Security-Policy", "frame-ancestors 'none';"}
672 };
673 response->write(SimpleWeb::StatusCode::redirection_temporary_redirect, headers);
674 }
675
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)
686 return "";
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);
692 }
693
700 bool checkIPOrigin(resp_https_t response, req_https_t request) {
701 auto address = net::addr_to_normalized_string(request->remote_endpoint().address());
702 auto ip_type = net::from_address(address);
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);
706 return false;
707 }
708 return true;
709 }
710
720 bool authenticate(resp_https_t response, req_https_t request, bool needsRedirect = false) {
721 if (!checkIPOrigin(response, request))
722 return false;
723 // If credentials not set, redirect to welcome.
724 if (config::sunshine.username.empty()) {
725 send_redirect(response, request, "/welcome");
726 return false;
727 }
728 // Guard: on failure, redirect if requested.
729 auto fg = util::fail_guard([&]() {
730 if (needsRedirect) {
731 std::string redir_path = "/login?redir=.";
732 redir_path += request->path;
733 send_redirect(response, request, redir_path.c_str());
734 } else {
735 send_unauthorized(response, request);
736 }
737 });
738 // Checked after the origin and the first-run redirect, never before: the
739 // token is a way for a local process to skip typing a password it already
740 // effectively holds, not a way around either of those.
741 if (has_local_api_token(request)) {
742 fg.disable();
743 return true;
744 }
745 if (sessionCookie.empty())
746 return false;
747 // Check for expiry
748 if (std::chrono::steady_clock::now() - cookie_creation_time > SESSION_EXPIRE_DURATION) {
749 sessionCookie.clear();
750 return false;
751 }
752 auto cookies = request->header.find("cookie");
753 if (cookies == request->header.end())
754 return false;
755 auto authCookie = getCookieValue(cookies->second, "auth");
756 if (authCookie.empty() ||
757 util::hex(crypto::hash(authCookie + config::sunshine.salt)).to_string() != sessionCookie)
758 return false;
759 fg.disable();
760 return true;
761 }
762
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;
770 nlohmann::json tree;
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';");
777
778 response->write(code, tree.dump(), headers);
779 }
780
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;
789 nlohmann::json tree;
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';");
797
798 response->write(code, tree.dump(), headers);
799 }
800
801
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");
812 return false;
813 }
814
815 // Extract the media type part before any parameters (e.g., charset)
816 std::string actualContentType = requestContentType->second;
817 size_t semicolonPos = actualContentType.find(';');
818 if (semicolonPos != std::string::npos) {
819 actualContentType = actualContentType.substr(0, semicolonPos);
820 }
821
822 // Trim whitespace and convert to lowercase for case-insensitive comparison
823 boost::algorithm::trim(actualContentType);
824 boost::algorithm::to_lower(actualContentType);
825
826 std::string expectedContentType(contentType);
827 boost::algorithm::to_lower(expectedContentType);
828
829 if (actualContentType != expectedContentType) {
830 bad_request(response, request, "Content type mismatch");
831 return false;
832 }
833 return true;
834 }
835
851 resp_https_t response,
852 req_https_t request,
853 const std::string &page,
854 const SimpleWeb::CaseInsensitiveMultimap &extra_headers = {}
855 ) {
856 const std::string path = WEB_DIR + page;
857 const std::string content = file_handler::read_file(path.c_str());
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;
862 response->write(
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."
865 );
866 return;
867 }
868
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);
875 }
876
882 void getIndexPage(resp_https_t response, req_https_t request) {
883 if (!authenticate(response, request, true)) {
884 return;
885 }
886
887 print_req(request);
888
889 send_web_page(response, request, "index.html");
890 }
891
897 void getPinPage(resp_https_t response, req_https_t request) {
898 if (!authenticate(response, request, true)) {
899 return;
900 }
901
902 print_req(request);
903
904 send_web_page(response, request, "pin.html");
905 }
906
912 void getAppsPage(resp_https_t response, req_https_t request) {
913 if (!authenticate(response, request, true)) {
914 return;
915 }
916
917 print_req(request);
918
919 send_web_page(response, request, "apps.html", {{"Access-Control-Allow-Origin", "https://images.igdb.com/"}});
920 }
921
927 void getClientsPage(resp_https_t response, req_https_t request) {
928 if (!authenticate(response, request, true)) {
929 return;
930 }
931
932 print_req(request);
933
934 send_web_page(response, request, "clients.html");
935 }
936
942 void getConfigPage(resp_https_t response, req_https_t request) {
943 if (!authenticate(response, request, true)) {
944 return;
945 }
946
947 print_req(request);
948
949 send_web_page(response, request, "config.html");
950 }
951
957 void getPasswordPage(resp_https_t response, req_https_t request) {
958 if (!authenticate(response, request, true)) {
959 return;
960 }
961
962 print_req(request);
963
964 send_web_page(response, request, "password.html");
965 }
966
974 void getLoginPage(resp_https_t response, req_https_t request) {
975 if (!checkIPOrigin(response, request)) {
976 return;
977 }
978
979 if (config::sunshine.username.empty()) {
980 send_redirect(response, request, "/welcome");
981 return;
982 }
983
984 send_web_page(response, request, "login.html");
985 }
986
992 void getWelcomePage(resp_https_t response, req_https_t request) {
993 print_req(request);
994
995 if (!config::sunshine.username.empty()) {
996 send_redirect(response, request, "/");
997 return;
998 }
999
1000 send_web_page(response, request, "welcome.html");
1001 }
1002
1008 void getTroubleshootingPage(resp_https_t response, req_https_t request) {
1009 if (!authenticate(response, request, true)) {
1010 return;
1011 }
1012
1013 print_req(request);
1014
1015 send_web_page(response, request, "troubleshooting.html");
1016 }
1017
1023 void getFaviconImage(resp_https_t response, req_https_t request) {
1024 print_req(request);
1025
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);
1032 }
1033
1042 void getHermesLogoImage(resp_https_t response, req_https_t request) {
1043 print_req(request);
1044
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);
1051 }
1052
1059 bool isChildPath(fs::path const &base, fs::path const &query) {
1060 auto relPath = fs::relative(base, query);
1061 return *(relPath.begin()) != fs::path("..");
1062 }
1063
1069 void getNodeModules(resp_https_t response, req_https_t request) {
1070 print_req(request);
1071
1072 fs::path webDirPath(WEB_DIR);
1073 fs::path nodeModulesPath(webDirPath / "assets");
1074
1075 // .relative_path is needed to shed any leading slash that might exist in the request path
1076 auto filePath = fs::weakly_canonical(webDirPath / fs::path(request->path).relative_path());
1077
1078 // Don't do anything if file does not exist or is outside the assets directory
1079 if (!isChildPath(filePath, nodeModulesPath)) {
1080 BOOST_LOG(warning) << "Someone requested a path " << filePath << " that is outside the assets folder";
1081 bad_request(response, request);
1082 return;
1083 }
1084
1085 if (!fs::exists(filePath)) {
1086 not_found(response, request);
1087 return;
1088 }
1089
1090 auto relPath = fs::relative(filePath, webDirPath);
1091 // get the mime type from the file extension mime_types map
1092 // remove the leading period from the extension
1093 auto mimeType = mime_types.find(relPath.extension().string().substr(1));
1094 if (mimeType == mime_types.end()) {
1095 bad_request(response, request);
1096 return;
1097 }
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);
1104 }
1105
1115 void getMetrics(resp_https_t response, req_https_t request) {
1116 if (!authenticate(response, request)) {
1117 return;
1118 }
1119
1120 print_req(request);
1121 send_response(response, hestia_runtime_status_json());
1122 }
1123
1131 void getApps(resp_https_t response, req_https_t request) {
1132 if (!authenticate(response, request)) {
1133 return;
1134 }
1135
1136 print_req(request);
1137
1138 try {
1139 std::string content = file_handler::read_file(config::stream.file_apps.c_str());
1140 nlohmann::json file_tree = nlohmann::json::parse(content);
1141
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;
1145
1146 send_response(response, file_tree);
1147 } catch (std::exception &e) {
1148 BOOST_LOG(warning) << "GetApps: "sv << e.what();
1149 bad_request(response, request, e.what());
1150 }
1151 }
1152
1165 void getLibrary(resp_https_t response, req_https_t request) {
1166 if (!authenticate(response, request)) {
1167 return;
1168 }
1169
1170 print_req(request);
1171
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));
1179 };
1180
1181 // ~/.steam/steam is usually a link to ~/.local/share/Steam; a game seen
1182 // twice is listed once.
1183 for (const auto &root : {home / ".local/share/Steam", home / ".steam/steam"}) {
1184 std::error_code ec;
1185 if (std::filesystem::is_directory(root / "steamapps", ec)) {
1186 add(library::steam_games(root, "steam"));
1187 }
1188 }
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"));
1191 }
1192
1193 std::string lutris;
1194 if (!boost::process::v1::search_path("lutris").empty()) {
1195 lutris = "lutris";
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";
1199 }
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);
1203 if (output) {
1204 add(library::lutris_games(*output, lutris));
1205 } else {
1206 BOOST_LOG(warning) << "Library: couldn't list Lutris' games"sv << (timed_out ? " (no answer in 30 s)"sv : ""sv);
1207 }
1208 }
1209
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}});
1212 }
1213
1214 nlohmann::json output_tree;
1215 output_tree["games"] = std::move(games);
1216 send_response(response, output_tree);
1217 }
1218
1252 void saveApp(resp_https_t response, req_https_t request) {
1253 if (!validateContentType(response, request, "application/json") || !authenticate(response, request)) {
1254 return;
1255 }
1256
1257 print_req(request);
1258
1259 std::stringstream ss;
1260 ss << request->content.rdbuf();
1261
1262 BOOST_LOG(info) << config::stream.file_apps;
1263 try {
1264 // TODO: Input Validation
1265
1266 // Read the input JSON from the request body.
1267 nlohmann::json inputTree = nlohmann::json::parse(ss.str());
1268
1269 // Read the existing apps file.
1270 std::string content = file_handler::read_file(config::stream.file_apps.c_str());
1271 nlohmann::json fileTree = nlohmann::json::parse(content);
1272
1273 // Migrate/merge the new app into the file tree.
1274 proc::migrate_apps(&fileTree, &inputTree);
1275
1276 // Write the updated file tree back to disk.
1277 file_handler::write_file(config::stream.file_apps.c_str(), fileTree.dump(4));
1278 proc::refresh(config::stream.file_apps);
1279
1280 // Prepare and send the output response.
1281 nlohmann::json outputTree;
1282 outputTree["status"] = true;
1283 send_response(response, outputTree);
1284 }
1285 catch (std::exception &e) {
1286 BOOST_LOG(warning) << "SaveApp: "sv << e.what();
1287 bad_request(response, request, e.what());
1288 }
1289 }
1290
1298 void closeApp(resp_https_t response, req_https_t request) {
1299 if (!validateContentType(response, request, "application/json") || !authenticate(response, request)) {
1300 return;
1301 }
1302
1303 print_req(request);
1304
1305 proc::proc.terminate();
1306 nlohmann::json output_tree;
1307 output_tree["status"] = true;
1308 send_response(response, output_tree);
1309 }
1310
1318 void reorderApps(resp_https_t response, req_https_t request) {
1319 if (!validateContentType(response, request, "application/json") || !authenticate(response, request)) {
1320 return;
1321 }
1322
1323 print_req(request);
1324
1325 try {
1326 std::stringstream ss;
1327 ss << request->content.rdbuf();
1328
1329 nlohmann::json input_tree = nlohmann::json::parse(ss.str());
1330 nlohmann::json output_tree;
1331
1332 // Read the existing apps file.
1333 std::string content = file_handler::read_file(config::stream.file_apps.c_str());
1334 nlohmann::json fileTree = nlohmann::json::parse(content);
1335
1336 // Get the desired order of UUIDs from the request.
1337 if (!input_tree.contains("order") || !input_tree["order"].is_array()) {
1338 throw std::runtime_error("Missing or invalid 'order' array in request body");
1339 }
1340 const auto& order_uuids_json = input_tree["order"];
1341
1342 // Get the original apps array from the fileTree.
1343 // Default to an empty array if "apps" key is missing or if it's present but not an array (after logging an error).
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"];
1348 } else {
1349 // "apps" key exists but is not an array. This is a malformed state.
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.");
1353 }
1354 } else {
1355 // "apps" key is missing. Treat as an empty list. Reordering an empty list is valid.
1356 BOOST_LOG(debug) << "ReorderApps: 'apps' key missing in apps configuration file ('" << config::stream.file_apps
1357 << "'). Treating as an empty list for reordering.";
1358 // original_apps_list is already an empty array, so no specific action needed here.
1359 }
1360
1361 nlohmann::json reordered_apps_list = nlohmann::json::array();
1362 std::vector<bool> item_moved(original_apps_list.size(), false);
1363
1364 // Phase 1: Place apps according to the 'order' array from the request.
1365 // Iterate through the desired order of UUIDs.
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.";
1369 continue;
1370 }
1371 std::string target_uuid = uuid_json_value.get<std::string>();
1372 bool found_match_for_ordered_uuid = false;
1373
1374 // Find the first unmoved app in the original list that matches the current target_uuid.
1375 for (size_t i = 0; i < original_apps_list.size(); ++i) {
1376 if (item_moved[i]) {
1377 continue; // This specific app object has already been placed.
1378 }
1379
1380 const auto& app_item = original_apps_list[i];
1381 // Ensure the app item is an object and has a UUID to match against.
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); // Add the found app object to the new list.
1385 item_moved[i] = true; // Mark this specific object as moved.
1386 found_match_for_ordered_uuid = true;
1387 break; // Found an app for this UUID, move to the next UUID in the 'order' array.
1388 }
1389 }
1390 }
1391
1392 if (!found_match_for_ordered_uuid) {
1393 // This means a UUID specified in the 'order' array was not found in the original_apps_list
1394 // among the currently available (unmoved) app objects.
1395 // Per instruction "If the uuid is missing from the original json file, omit it."
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.";
1397 }
1398 }
1399
1400 // Phase 2: Append any remaining apps from the original list that were not explicitly ordered.
1401 // These are app objects that were not marked 'item_moved' in Phase 1.
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]);
1405 }
1406 }
1407
1408 // Update the fileTree with the new, reordered list of apps.
1409 fileTree["apps"] = reordered_apps_list;
1410
1411 // Write the modified fileTree back to the apps configuration file.
1412 file_handler::write_file(config::stream.file_apps.c_str(), fileTree.dump(4));
1413
1414 // Notify relevant parts of the system that the apps configuration has changed.
1415 proc::refresh(config::stream.file_apps);
1416
1417 output_tree["status"] = true;
1418 send_response(response, output_tree);
1419 } catch (std::exception &e) {
1420 BOOST_LOG(warning) << "ReorderApps: "sv << e.what();
1421 bad_request(response, request, e.what());
1422 }
1423 }
1424
1432 void deleteApp(resp_https_t response, req_https_t request) {
1433 if (!validateContentType(response, request, "application/json") || !authenticate(response, request)) {
1434 return;
1435 }
1436
1437 print_req(request);
1438
1439 try {
1440 std::stringstream ss;
1441 ss << request->content.rdbuf();
1442 nlohmann::json input_tree = nlohmann::json::parse(ss.str());
1443
1444 // Check for required uuid field in body
1445 if (!input_tree.contains("uuid") || !input_tree["uuid"].is_string()) {
1446 bad_request(response, request, "Missing or invalid uuid in request body");
1447 return;
1448 }
1449 auto uuid = input_tree["uuid"].get<std::string>();
1450
1451 // Read the apps file into a nlohmann::json object.
1452 std::string content = file_handler::read_file(config::stream.file_apps.c_str());
1453 nlohmann::json fileTree = nlohmann::json::parse(content);
1454
1455 // Remove any app with the matching uuid directly from the "apps" array.
1456 if (fileTree.contains("apps") && fileTree["apps"].is_array()) {
1457 auto& apps = fileTree["apps"];
1458 apps.erase(
1459 std::remove_if(apps.begin(), apps.end(), [&uuid](const nlohmann::json& app) {
1460 return app.value("uuid", "") == uuid;
1461 }),
1462 apps.end()
1463 );
1464 }
1465
1466 // Write the updated JSON back to the file.
1467 file_handler::write_file(config::stream.file_apps.c_str(), fileTree.dump(4));
1468 proc::refresh(config::stream.file_apps);
1469
1470 // Prepare and send the response.
1471 nlohmann::json outputTree;
1472 outputTree["status"] = true;
1473 send_response(response, outputTree);
1474 }
1475 catch (std::exception &e) {
1476 BOOST_LOG(warning) << "DeleteApp: "sv << e.what();
1477 bad_request(response, request, e.what());
1478 }
1479 }
1480
1488 void getClients(resp_https_t response, req_https_t request) {
1489 if (!authenticate(response, request)) {
1490 return;
1491 }
1492
1493 print_req(request);
1494
1495 nlohmann::json named_certs = nvhttp::get_all_clients();
1496 nlohmann::json output_tree;
1497 output_tree["named_certs"] = named_certs;
1498 output_tree["status"] = true;
1499 send_response(response, output_tree);
1500 }
1501
1519 void updateClient(resp_https_t response, req_https_t request) {
1520 if (!validateContentType(response, request, "application/json") || !authenticate(response, request)) {
1521 return;
1522 }
1523
1524 print_req(request);
1525
1526 std::stringstream ss;
1527 ss << request->content.rdbuf();
1528 try {
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));
1540 output_tree["status"] = nvhttp::update_device_info(
1541 uuid,
1542 name,
1543 display_mode,
1544 do_cmds,
1545 undo_cmds,
1546 perm,
1547 enable_legacy_ordering,
1548 allow_client_commands,
1549 always_use_virtual_display
1550 );
1551 send_response(response, output_tree);
1552 } catch (std::exception &e) {
1553 BOOST_LOG(warning) << "Update Client: "sv << e.what();
1554 bad_request(response, request, e.what());
1555 }
1556 }
1557
1572 void unpair(resp_https_t response, req_https_t request) {
1573 if (!validateContentType(response, request, "application/json") || !authenticate(response, request)) {
1574 return;
1575 }
1576
1577 print_req(request);
1578
1579 std::stringstream ss;
1580 ss << request->content.rdbuf();
1581 try {
1582 nlohmann::json input_tree = nlohmann::json::parse(ss.str());
1583 nlohmann::json output_tree;
1584 std::string uuid = input_tree.value("uuid", "");
1585 output_tree["status"] = nvhttp::unpair_client(uuid);
1586 send_response(response, output_tree);
1587 } catch (std::exception &e) {
1588 BOOST_LOG(warning) << "Unpair: "sv << e.what();
1589 bad_request(response, request, e.what());
1590 }
1591 }
1592
1600 void unpairAll(resp_https_t response, req_https_t request) {
1601 if (!validateContentType(response, request, "application/json") || !authenticate(response, request)) {
1602 return;
1603 }
1604
1605 print_req(request);
1606
1608 proc::proc.terminate();
1609 nlohmann::json output_tree;
1610 output_tree["status"] = true;
1611 send_response(response, output_tree);
1612 }
1613
1619 nlohmann::json computed_config_json() {
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();
1627 output_tree["evdiSetupRequired"] = VDISPLAY::needsInitialDeviceConfiguration();
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();
1634 return output_tree;
1635 }
1636
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) {
1639 // The response is authoritative for what it computed. config::parse_config
1640 // yields strings and nothing else, so letting one of these through does
1641 // not merely report a stale value - it changes the field's type, and the
1642 // home page reads streamPorts as an array.
1643 if (response.contains(name)) {
1644 continue;
1645 }
1646 response[name] = value;
1647 }
1648 return response;
1649 }
1650
1659 void getConfig(resp_https_t response, req_https_t request) {
1660 if (!authenticate(response, request)) {
1661 return;
1662 }
1663
1664 print_req(request);
1665
1666 auto output_tree = computed_config_json();
1667 const auto vars = config::parse_config(file_handler::read_file(config::sunshine.config_file.c_str()));
1668 send_response(response, overlay_config_file(output_tree, vars));
1669 }
1670
1678 void getHestiaCapabilities(resp_https_t response, req_https_t request) {
1679 print_req(request);
1680
1682 }
1683
1684 nlohmann::json hestia_capabilities_json() {
1685 nlohmann::json capabilities {
1686 {"ok", true},
1687 {"server_name", "Hermes"},
1688 // "base" is a protocol-compatibility identifier the Hestia client checks
1689 // against a fixed value ("Apollo"); it is NOT visible branding. Renaming
1690 // it breaks the Hestia handshake (client reports "base is incompatible"
1691 // and falls back to legacy mode), so it must stay "Apollo".
1692 {"base", "Apollo"},
1693 {"hestia_protocol", 1},
1694 {"min_client_protocol", 1},
1695 {"max_client_protocol", 1},
1696 // Same version the web UI and the log report (the VERSION file, plus
1697 // the commit suffix on non-release branches), so clients show the
1698 // Hermes version the user actually installed.
1699 {"server_version", PROJECT_VERSION},
1700 {"compatibility", {
1701 {"gamestream", true},
1702 {"moonlight", true},
1703 {"sunshine", true},
1704 }},
1705 {"features", {
1706 {"virtual_display", true},
1707 {"virtual_display_backend", {"evdi", "hermes_kms"}},
1708 {"hermes_kms_multi_output", {
1709 {"supported", true},
1710 {"experimental", true},
1711 {"max_outputs", 8},
1712 }},
1713 {"hermes_kms_isolated_sessions", {
1714 {"status", "prototype"},
1715 {"experimental", true},
1716 {"profiles", {"application", "desktop"}},
1717 {"max_sessions", 8},
1718 }},
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},
1729 }},
1730 {"limits", {
1731 {"max_width", 7680},
1732 {"max_height", 4320},
1733 {"max_fps", 120},
1734 {"supported_fps", {30, 40, 45, 60, 90, 120}},
1735 {"supported_codecs", {"h264", "hevc", "av1"}},
1736 }},
1737 };
1738
1739 if (config::video.pyrowave && video::pyrowave_available()) {
1740 capabilities["limits"]["supported_codecs"].push_back("pyrowave");
1741 }
1742
1743 return capabilities;
1744 }
1745
1746 void send_hestia_error(resp_https_t response, SimpleWeb::StatusCode status, const char *code, const char *message) {
1747 const nlohmann::json output {
1748 {"ok", false},
1749 {"error", {
1750 {"code", code},
1751 {"message", message},
1752 }},
1753 };
1754 const SimpleWeb::CaseInsensitiveMultimap headers {
1755 {"Content-Type", "application/json"},
1756 {"X-Frame-Options", "DENY"},
1757 {"Content-Security-Policy", "frame-ancestors 'none';"},
1758 };
1759 response->write(status, output.dump(), headers);
1760 }
1761
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);
1764 if (!client) {
1765 send_hestia_error(response, SimpleWeb::StatusCode::client_error_unauthorized, "unauthorized", "A paired client certificate is required");
1766 return false;
1767 }
1768
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");
1772 return false;
1773 }
1774
1775 return true;
1776 }
1777
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);
1780 if (!client) {
1781 send_hestia_error(response, SimpleWeb::StatusCode::client_error_unauthorized, "unauthorized", "A paired client certificate is required");
1782 }
1783 return client;
1784 }
1785
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()) {
1788 return false;
1789 }
1790
1791 for (auto it = object.begin(); it != object.end(); ++it) {
1792 if (!keys.contains(it.key())) {
1793 return false;
1794 }
1795 }
1796
1797 return true;
1798 }
1799
1800 bool hestia_is_positive_integer(const nlohmann::json &value) {
1801 return value.is_number_integer() && value.get<int>() > 0;
1802 }
1803
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>());
1806 }
1807
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",
1811 };
1812 static const std::set<std::string> client_keys {
1813 "name", "version", "platform", "display_width", "display_height", "refresh_rate", "hdr",
1814 };
1815 static const std::set<std::string> stream_keys {
1816 "requested_width", "requested_height", "requested_fps", "codec", "bitrate_kbps", "hdr_mode", "scale_factor",
1817 };
1818 static const std::set<std::string> virtual_display_keys {
1819 "enabled", "backend", "desktop_integration", "recover_physical_monitor",
1820 };
1821 static const std::set<std::string> app_keys {
1822 "id", "launch_mode",
1823 };
1824
1825 if (!hestia_has_exact_keys(request, request_keys)) {
1826 error = "Request must contain only client, stream, virtual_display, and app";
1827 return false;
1828 }
1829
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";
1836 return false;
1837 }
1838
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";
1845 return false;
1846 }
1847
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";
1855 return false;
1856 }
1857
1858 const auto &virtual_display = request["virtual_display"];
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";
1864 return false;
1865 }
1866
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";
1871 return false;
1872 }
1873
1874 return true;
1875 }
1876
1892 void prepare_hestia_session(resp_https_t response, req_https_t request) {
1893 if (!authenticate_hestia_client(response, request, crypto::PERM::launch, "session prepare")) {
1894 return;
1895 }
1896
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");
1900 return;
1901 }
1902
1903 try {
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());
1908 return;
1909 }
1910
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");
1917 return;
1918 }
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");
1921 return;
1922 }
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");
1925 return;
1926 }
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>(),
1936 });
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"];
1944
1945 const nlohmann::json output {
1946 {"ok", true},
1947 {"session_id", "hestia-" + crypto::rand_alphabet(12)},
1948 {"virtual_display", {
1949 {"created", false},
1950 {"name", ""},
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},
1957 }},
1959 app["id"].get<std::string>(),
1960 virtual_display["enabled"].get<bool>(),
1961 stream["scale_factor"].get<int>()
1962 )},
1963 {"warnings", {"Prepared settings will be applied when the normal stream launches."}},
1964 };
1965 send_response(response, output);
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");
1971 }
1972 }
1973
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")) {
1976 return;
1977 }
1978
1979 const auto client = std::static_pointer_cast<crypto::named_cert_t>(request->userp);
1981 const bool stopped = nvhttp::find_and_stop_session(client->uuid, true);
1982 BOOST_LOG(debug) << "[HestiaAPI] session stop requested by client=" << client->uuid
1983 << " stopped=" << stopped;
1984 send_response(response, {{"ok", true}, {"stopped", stopped}});
1985 }
1986
1987 nlohmann::json hestia_display_status_json() {
1988 const auto evdi_status = VDISPLAY::getEvdiStatus();
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;
1992
1993 return {
1994 {"ok", true},
1995 {"active", virtual_display_active},
1996 {"virtual_display", {
1997 {"enabled", virtual_display_active},
1998 {"name", display ? display->name : ""},
1999 {"backend", virtual_display_active ? "evdi" : "none"},
2000 {"width", display ? display->width : 0},
2001 {"height", display ? display->height : 0},
2002 {"fps", display ? display->fps : 0},
2003 {"hdr", false},
2004 }},
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},
2009 }},
2010 {"desktop", {
2011 {"environment", evdi_status.session_type},
2012 {"kscreen_available", evdi_status.output_layout_backend.rfind("kscreen", 0) == 0},
2013 {"kscreen_output", display ? display->name : ""},
2014 }},
2015 };
2016 }
2017
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")) {
2020 return;
2021 }
2022
2023 send_response(response, hestia_display_status_json());
2024 }
2025
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")) {
2028 return;
2029 }
2030
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");
2034 return;
2035 }
2036
2037 try {
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");
2041 return;
2042 }
2043
2044 const std::string restored_output = proc::proc.initial_display;
2045 if (proc::proc.running() > 0) {
2046 proc::proc.terminate();
2047 } else {
2048 VDISPLAY::restoreExclusiveVirtualDisplay();
2049 // The monitors are coming back, so whatever sink left with them can be
2050 // waited for and put back as the default. terminate() does this for the
2051 // branch above.
2054 }
2055
2056 const nlohmann::json output {
2057 {"ok", true},
2058 {"message", "Physical display restored"},
2059 {"restored_output", restored_output},
2060 };
2061 send_response(response, 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");
2067 }
2068 }
2069
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")) {
2072 return;
2073 }
2074
2075 nlohmann::json commands = nlohmann::json::array();
2076 for (size_t index = 0; index < config::sunshine.server_cmds.size(); ++index) {
2077 commands.push_back({
2078 {"id", index},
2079 {"name", config::sunshine.server_cmds[index].cmd_name},
2080 {"requires_confirmation", true},
2081 });
2082 }
2083
2084 send_response(response, {{"ok", true}, {"commands", commands}});
2085 }
2086
2087 void get_hestia_client_permissions(resp_https_t response, req_https_t request) {
2088 auto client = authenticate_hestia_paired_client(response, request);
2089 if (!client) {
2090 return;
2091 }
2092
2093 const auto has_permission = [&client](crypto::PERM permission) {
2094 return static_cast<bool>(client->perm & permission);
2095 };
2096 send_response(response, {
2097 {"ok", true},
2098 {"client_id", client->uuid},
2099 {"permissions", {
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)},
2110 }},
2111 });
2112 }
2113
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")) {
2116 return;
2117 }
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");
2120 return;
2121 }
2122
2123 send_response(response, {{"ok", true}, {"text", platf::get_clipboard()}});
2124 }
2125
2126 // Build the live encoder/session view shared by the diagnostics endpoint, so
2127 // users can see the real encoder (hardware vs software) and who is connected
2128 // instead of guessing from logs.
2129 nlohmann::json hestia_runtime_status_json() {
2130 nlohmann::json runtime;
2131
2132 const auto enc = video::get_encoder_status();
2133 if (enc.probed) {
2134 nlohmann::json codecs = nlohmann::json::array();
2135 if (enc.h264) {
2136 codecs.push_back("h264");
2137 }
2138 if (enc.hevc) {
2139 codecs.push_back("hevc");
2140 }
2141 if (enc.av1) {
2142 codecs.push_back("av1");
2143 }
2144 if (config::video.pyrowave && video::pyrowave_available()) {
2145 codecs.push_back("pyrowave");
2146 }
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},
2153 });
2154 }
2155 runtime["encoder"] = {
2156 {"name", enc.encoder},
2157 {"hardware", enc.hardware},
2158 {"codecs", std::move(codecs)},
2159 // Why this encoder was chosen: the encoders tried (and rejected) during
2160 // probing, and whether we fell back to software because hardware failed.
2161 {"fell_back_to_software", enc.fell_back_to_software},
2162 {"attempts", std::move(attempts)},
2163 };
2164 } else {
2165 runtime["encoder"] = {{"name", nullptr}, {"hardware", false}, {"probed", false}};
2166 }
2167
2168 const int sessions = rtsp_stream::session_count();
2169 // An app still running with no active session means the host is holding it
2170 // paused for a client to reconnect (resume), rather than having torn down.
2171 const bool app_running = proc::proc.running() > 0;
2172 const bool awaiting_reconnect = sessions == 0 && app_running;
2173
2174 const auto term = stream::session::termination_stats();
2175 runtime["sessions"] = {
2176 {"active", sessions},
2177 {"streaming", sessions > 0},
2178 {"last_termination", std::string(rtsp_stream::last_termination_reason())},
2179 // Reconnection observability: when/why the last session ended and how
2180 // often clients have been dropping, plus whether an app is parked for a
2181 // reconnect right now.
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},
2186 };
2187
2188 // Live per-frame pipeline metrics (only meaningful while streaming).
2189 const auto pm = video::get_pipeline_metrics();
2190 // The last stream's figures stay published after it ends; they describe
2191 // nothing running now.
2192 if (pm.valid && sessions > 0) {
2193 runtime["pipeline"] = {
2194 {"fps", pm.fps},
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},
2202 };
2203 } else {
2204 runtime["pipeline"] = nullptr;
2205 }
2206
2207 // Session/compositor environment, used to decide virtual-display and
2208 // Gamescope behavior (e.g. SteamOS Game Mode vs a desktop session).
2209 const auto session_env = platf::detect_session_environment();
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},
2215 };
2216
2217 // Appliance-mode readiness (dormant): reports whether the host could boot
2218 // straight into a headless/Gamescope streaming session. Detection only —
2219 // no boot/login orchestration exists yet, and the flag is off by default.
2220 const auto appliance = platf::appliance_readiness();
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},
2229 };
2230
2231 // Hermes-KMS device counters: the zero-copy capture path's own view of how
2232 // many frames were updated, acquired, exported, and waited on. Only present
2233 // when the hermes_kms backend is selected and a metrics-capable device is
2234 // found; null otherwise so the field's absence is unambiguous.
2235 if (config::video.virtual_display_backend == "hermes_kms") {
2236 const auto km = VDISPLAY::getHermesKmsMetrics();
2237 if (km.available) {
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},
2255 };
2256 // Session-capability lifecycle, only from a driver that reports it
2257 // (UAPI 13+); omitted rather than zeroed on older ones so absence is
2258 // unambiguous. `bound_fds` counts the descriptor this read binds.
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},
2267 };
2268 }
2269 } else {
2270 runtime["hermes_kms"] = nullptr;
2271 }
2272 }
2273
2274 return runtime;
2275 }
2276
2277 // Aggregate "is the host ready to stream?" checks from signals Hermes already
2278 // collects, so a client (or the user) can see at a glance what's ready and
2279 // what needs attention, instead of discovering problems mid-session.
2280 //
2281 // Each check is {id, status: ok|warn|fail, message}. `ready` is true when no
2282 // check is `fail` (warnings are non-blocking, e.g. software-encoding fallback).
2283 nlohmann::json hestia_preflight_json() {
2284 nlohmann::json checks = nlohmann::json::array();
2285 bool ready = true;
2286
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") {
2290 ready = false;
2291 }
2292 };
2293
2294 // Encoder readiness.
2295 const auto enc = video::get_encoder_status();
2296 if (!enc.probed) {
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.");
2305 } else {
2306 add("encoder", "ok", "Hardware encoder in use: " + enc.encoder + ".");
2307 }
2308
2309 // A capturable display must be present (unless a virtual display will be
2310 // created on demand).
2311 if (video::display_present()) {
2312 add("display", "ok", "A capturable display is available.");
2313 } else {
2314 add("display", "warn",
2315 "No active display detected; a virtual display will be created for the session if configured.");
2316 }
2317
2318 // Virtual-display backend readiness (Linux only).
2319 const auto evdi = VDISPLAY::getEvdiStatus();
2320 const auto env = [](const char *name) {
2321 const char *value = std::getenv(name);
2322 return std::string {value ? value : ""};
2323 };
2324 // Started before anyone logged in, or left behind by a session that has
2325 // ended, Hermes has no desktop to talk to: the variables can be missing,
2326 // empty, or point at nothing. Say so, rather than blaming the session type
2327 // or a missing layout backend. Only when logind can tell; a deliberately
2328 // headless host keeps the checks below.
2329 const auto session_present = VDISPLAY::graphicalSessionPresent();
2330 if (session_present.has_value() &&
2331 !VDISPLAY::displayServerReachable(env("WAYLAND_DISPLAY"), env("DISPLAY"), env("XDG_RUNTIME_DIR"))) {
2332 add("virtual_display", "warn",
2333 *session_present ?
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.");
2346 } else {
2347 add("virtual_display", "warn",
2348 "No output-management backend (kscreen/wlr/mutter) detected; virtual-display activation may fail.");
2349 }
2350 } else {
2351 add("virtual_display", "warn",
2352 "Session type is '" + evdi.session_type + "'; virtual-display support is limited.");
2353 }
2354
2355 // Hermes-KMS: whether the driver is there, whether it pairs with this
2356 // Hermes, and what that means for streaming. Never a failure: without it
2357 // a physical monitor still streams.
2358 if (config::video.virtual_display_backend == "hermes_kms") {
2359 const auto kms = VDISPLAY::getHermesKmsStatus();
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) + ").";
2364 } else {
2365 status = "warn";
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.";
2370 }
2371 if (const auto note = hermes_kms_reload_note(kms); !note.empty()) {
2372 status = "warn";
2373 message += ' ' + note;
2374 }
2375 if (const auto note = hermes_kms_newer_note(kms); !note.empty()) {
2376 message += ' ' + note;
2377 }
2378 add("hermes_kms", status, std::move(message));
2379 } else if (config::video.virtual_display_backend == "evdi") {
2380 const auto kms = VDISPLAY::getHermesKmsStatus();
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." :
2386 std::string {}));
2387 }
2388
2389 // Session/compositor environment (informational).
2390 const auto session_env = platf::detect_session_environment();
2391 add("session_environment", "ok", "Detected session environment: " + session_env.describe() + ".");
2392
2393 return {{"ready", ready}, {"checks", std::move(checks)}};
2394 }
2395
2396 void get_hestia_diagnostics(resp_https_t response, req_https_t request) {
2397 if (!authenticate_hestia_client(response, request, crypto::PERM::view, "diagnostics")) {
2398 return;
2399 }
2400
2401 send_response(response, {{"ok", true}, {"runtime", hestia_runtime_status_json()}, {"preflight", hestia_preflight_json()}, {"dependencies", {{"clipboard", clipboard_status_json()}}}});
2402 }
2403
2412 void get_hestia_stream_info(resp_https_t response, req_https_t request) {
2413 if (!authenticate_hestia_client(response, request, crypto::PERM::view, "stream info")) {
2414 return;
2415 }
2416 const auto client = std::static_pointer_cast<crypto::named_cert_t>(request->userp);
2417
2418 const auto readiness = video::last_capture_readiness();
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},
2432 };
2433 }
2434 send_response(response, body);
2435 }
2436
2437
2445 struct system_t {
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;
2455 long long net_errors = -1;
2456 long long udp_dropped = -1;
2457 };
2458
2459 struct sample_t {
2460 std::chrono::system_clock::time_point at;
2461 int sessions;
2463 system_t system;
2464 };
2465
2466 namespace fs = std::filesystem;
2467
2468 std::optional<long long> read_number(const fs::path &path) {
2469 std::ifstream stream {path};
2470 long long value;
2471 if (stream >> value) {
2472 return value;
2473 }
2474 return std::nullopt;
2475 }
2476
2477 std::string read_word(const fs::path &path) {
2478 std::ifstream stream {path};
2479 std::string value;
2480 stream >> value;
2481 return value;
2482 }
2483
2484 // The hwmon directory a driver registered under a name, such as k10temp.
2485 std::optional<fs::path> hwmon(std::initializer_list<std::string_view> names, const fs::path &root = "/sys/class/hwmon") {
2486 std::error_code ec;
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();
2491 }
2492 }
2493 return std::nullopt;
2494 }
2495
2496 // A temperature in °C: the input labelled `label` if there is one, else temp1.
2497 double temperature(const fs::path &dir, std::string_view label) {
2498 std::error_code ec;
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;
2505 }
2506 }
2507 }
2508 const auto value = read_number(dir / "temp1_input");
2509 return value ? *value / 1000.0 : -1;
2510 }
2511
2512 struct previous_t {
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;
2519 } previous;
2520
2521 // The first number in a file of several: amdgpu's clock list marks the
2522 // current one with '*', "1: 2450Mhz *".
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);
2529 }
2530 }
2531 return -1;
2532 }
2533
2534 // nvidia-smi ships with the driver and needs no privileges.
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");
2540 if (!smi) {
2541 return;
2542 }
2543 char line[256] {};
2544 const bool read = std::fgets(line, sizeof(line), smi) != nullptr;
2545 ::pclose(smi);
2546 if (!read) {
2547 return;
2548 }
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};
2551 std::string value;
2552 for (auto *field : fields) {
2553 if (!std::getline(values, value, ',')) {
2554 break;
2555 }
2556 char *end = nullptr;
2557 const double number = std::strtod(value.c_str(), &end);
2558 if (end != value.c_str()) {
2559 *field = number;
2560 }
2561 }
2562 }
2563
2564 std::string encode_card;
2565
2566 // gpu: also read the encoding GPU. Only while a stream is sampled: its
2567 // sysfs files and nvidia-smi wake a GPU that runtime PM has suspended,
2568 // which an idle host must never do every five seconds.
2569 system_t read_system(bool gpu) {
2570 system_t s;
2571
2572 // CPU usage, from the change in /proc/stat since the last sample.
2573 {
2574 std::ifstream stat {"/proc/stat"};
2575 std::string cpu;
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);
2582 }
2583 previous.cpu_busy = busy;
2584 previous.cpu_total = total;
2585 }
2586 }
2587 if (const auto cpu = hwmon({"k10temp", "zenpower", "coretemp"})) {
2588 s.cpu_celsius = temperature(*cpu, read_word(*cpu / "name") == "coretemp" ? "Package id 0" : "Tctl");
2589 }
2590 // Package energy. Recent kernels let only root read it.
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();
2595 if (seconds > 0) {
2596 s.cpu_watts = (*energy - previous.cpu_energy_uj) / 1e6 / seconds;
2597 }
2598 }
2599 previous.cpu_energy_uj = *energy;
2600 previous.cpu_energy_at = now;
2601 }
2602
2603 // The encoding GPU, where its driver reports on it (amdgpu does).
2604 if (gpu && encode_card.empty()) {
2605 const auto description = platf::encode_gpu_description();
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";
2608 }
2609 }
2610 if (gpu && !encode_card.empty()) {
2611 const fs::path card {encode_card};
2612 std::error_code ec;
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);
2617 }
2618 if (const auto vram = read_number(card / "mem_info_vram_used")) {
2619 s.vram_used_mib = *vram / 1048576.0;
2620 }
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");
2626 })) {
2627 s.gpu_watts = *power / 1e6;
2628 }
2629 }
2630 } else if (driver == "nvidia") {
2631 read_nvidia(fs::canonical(card, ec).filename().string(), s);
2632 } else if (driver == "i915" || driver == "xe") {
2633 // The current clock: i915 reports it under its card, xe per GT.
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);
2637 }
2638 }
2639 if (const auto mhz = read_number(card / "tile0/gt0/freq0/act_freq")) {
2640 s.gpu_mhz = static_cast<double>(*mhz);
2641 }
2642 // Arc cards report temperature and energy; most integrated ones do not.
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();
2649 // Not across a gap with no reading, as after an idle spell.
2650 if (seconds > 0 && seconds < 10) {
2651 s.gpu_watts = (*energy - previous.gpu_energy_uj) / 1e6 / seconds;
2652 }
2653 }
2654 previous.gpu_energy_uj = *energy;
2655 previous.gpu_energy_at = now;
2656 }
2657 }
2658 }
2659 }
2660
2661 // Memory still available to programs.
2662 {
2663 std::ifstream meminfo {"/proc/meminfo"};
2664 for (std::string key; meminfo >> key;) {
2665 long long kib;
2666 meminfo >> kib;
2667 if (key == "MemAvailable:") {
2668 s.ram_available_mib = kib / 1024.0;
2669 break;
2670 }
2671 meminfo.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
2672 }
2673 }
2674
2675 // Network cards: errors and drops, both directions, all but loopback.
2676 {
2677 std::ifstream dev {"/proc/net/dev"};
2678 std::string line;
2679 long long errors = 0;
2680 bool any = false;
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") {
2684 continue;
2685 }
2686 std::istringstream fields {line.substr(colon + 1)};
2687 std::array<long long, 16> v {};
2688 for (auto &field : v) {
2689 fields >> field;
2690 }
2691 errors += v[2] + v[3] + v[10] + v[11];
2692 any = true;
2693 }
2694 if (any) {
2695 if (previous.net_errors >= 0) {
2696 s.net_errors = errors - previous.net_errors;
2697 }
2698 previous.net_errors = errors;
2699 }
2700 }
2701 // UDP: datagrams dropped because a receive or send buffer was full.
2702 {
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:")) {
2707 continue;
2708 }
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);
2715 }
2716 }
2717 if (previous.udp_dropped >= 0) {
2718 s.udp_dropped = dropped - previous.udp_dropped;
2719 }
2720 previous.udp_dropped = dropped;
2721 break;
2722 }
2723 }
2724 return s;
2725 }
2726
2727 std::mutex mutex;
2728 std::deque<sample_t> samples;
2729 constexpr std::size_t max_samples = 720;
2730
2731 void record() {
2732 using namespace std::literals;
2733 static auto last_streaming = std::chrono::steady_clock::time_point {};
2734 const int sessions = rtsp_stream::session_count();
2735 const auto now = std::chrono::steady_clock::now();
2736 if (sessions > 0) {
2737 last_streaming = now;
2738 }
2739 const bool sampling = last_streaming != std::chrono::steady_clock::time_point {} && now - last_streaming <= 60s;
2740 // The /proc counters every time, so the changes they report span five
2741 // seconds even for the first sample of a stream; the GPU only while sampling.
2742 auto system = read_system(sampling);
2743 if (!sampling) {
2744 return;
2745 }
2746 sample_t sample {std::chrono::system_clock::now(), sessions, video::get_pipeline_metrics(), system};
2747 std::lock_guard lock {mutex};
2748 samples.push_back(std::move(sample));
2749 if (samples.size() > max_samples) {
2750 samples.pop_front();
2751 }
2752 }
2753
2754 std::vector<sample_t> snapshot() {
2755 std::lock_guard lock {mutex};
2756 return {samples.begin(), samples.end()};
2757 }
2758 } // namespace report_timeline
2759
2760 namespace {
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);
2763 std::tm tm {};
2764 localtime_r(&t, &tm);
2765 char text[64];
2766 std::strftime(text, sizeof(text), format, &tm);
2767 return text;
2768 }
2769
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) {
2776 lines.pop_front();
2777 }
2778 }
2779 return {lines.begin(), lines.end()};
2780 }
2781
2782 // Settings as the user wrote them, without anything secret in them.
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};
2786 std::string output;
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>";
2793 }
2794 }
2795 output += line + '\n';
2796 }
2797 return output.empty() ? "(no settings file, or all defaults)\n" : output;
2798 }
2799 } // namespace
2800
2807 void machine_snapshot(std::ostream &out) {
2808 namespace fs = std::filesystem;
2809 using report_timeline::read_number;
2810 using report_timeline::read_word;
2811 std::error_code ec;
2812 const auto read_line = [](const fs::path &path) {
2813 std::ifstream stream {path};
2814 std::string line;
2815 std::getline(stream, line);
2816 return line;
2817 };
2818
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");
2823 // usbN are the controllers' own root hubs, not devices.
2824 if (vendor.empty() || entry.path().filename().string().starts_with("usb")) {
2825 continue;
2826 }
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));
2832 }
2833 std::ranges::sort(usb);
2834 for (const auto &line : usb) {
2835 out << " " << line << '\n';
2836 }
2837 if (usb.empty()) {
2838 out << " None readable.\n";
2839 }
2840
2841 out << "\n== Input devices ==\n";
2842 {
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';
2852 name.clear();
2853 phys.clear();
2854 }
2855 }
2856 }
2857
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());
2864 }
2865 }
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';
2873 }
2874 if (connectors.empty()) {
2875 out << " None.\n";
2876 }
2877
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;
2885 }
2886 }
2887 out << " " << session.client_name << ": " << session.app_name << " (" << details << ") "
2888 << (session.running ? "running" : "NOT RUNNING") << '\n';
2889 }
2890 if (sessions.empty()) {
2891 out << " No isolated or detached sessions.\n";
2892 }
2893 out << " Streams now: " << rtsp_stream::session_count() << '\n';
2894 out << " App running on the host desktop: " << (proc::proc.running() > 0 ? proc::proc.get_last_run_app_name() : "none"s) << '\n';
2895
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();
2899 if (name == "lo") {
2900 continue;
2901 }
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';
2907 }
2908
2909 out << "\n== Sound cards ==\n";
2910 {
2911 std::ifstream cards {"/proc/asound/cards"};
2912 std::string line;
2913 bool any = false;
2914 while (std::getline(cards, line)) {
2915 if (!line.empty() && line.find('[') != std::string::npos) {
2916 out << " " << boost::algorithm::trim_copy(line) << '\n';
2917 any = true;
2918 }
2919 }
2920 if (!any) {
2921 out << " None.\n";
2922 }
2923 }
2924
2925 // Names only: arguments can hold anything.
2926 struct program_t {
2927 std::string name;
2928 long long rss_kib = 0;
2929 double cpu_seconds = 0;
2930 };
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]))) {
2937 continue;
2938 }
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) {
2942 continue;
2943 }
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) {
2947 continue;
2948 }
2949 // v[0] is field 3 (state), so utime (14) is v[11], stime (15) v[12], rss (24) v[21].
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});
2952 }
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);
2956 });
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';
2960 }
2961 };
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);
2964 });
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);
2967 });
2968 }
2969
2976 std::string diagnostic_report() {
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";
2983
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("\""));
2989 }
2990 }
2991 out << "OS: " << os << '\n';
2992 utsname system {};
2993 ::uname(&system);
2994 out << "Kernel: " << system.release << ' ' << system.machine << '\n';
2995 const auto session_env = platf::detect_session_environment();
2996 out << "Session: " << session_env.describe() << '\n';
2997 const auto gpus = platf::render_node_descriptions();
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);
3002 break;
3003 }
3004 }
3005 out << "Hermes-KMS: " << kms << '\n';
3006 out << "Virtual display backend: " << config::video.virtual_display_backend << '\n';
3007 out << "GPUs:\n";
3008 for (const auto &gpu : gpus) {
3009 out << " " << gpu << '\n';
3010 }
3011 const auto encoding = platf::encode_gpu_description();
3012 out << "Encodes on: " << (encoding.empty() ? "no GPU qualifies"s : encoding) << '\n';
3013
3014 machine_snapshot(out);
3015
3016 out << "\n== Last capture-path check ==\n";
3017 const auto readiness = video::last_capture_readiness();
3018 if (!readiness.checked) {
3019 out << "None since Hermes started.\n";
3020 } else {
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';
3025 }
3026
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';
3034 ++problems;
3035 }
3036 }
3037 if (!problems) {
3038 out << "None.\n";
3039 }
3040
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";
3045 } else {
3046 const auto value = [](double v, const char *format) -> std::string {
3047 return v < 0 ? "-"s : std::vformat(format, std::make_format_args(v));
3048 };
3049 const auto count = [](long long v) -> std::string {
3050 return v < 0 ? "-"s : std::to_string(v);
3051 };
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;
3056 // The pipeline's last figures stay published once a stream ends.
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));
3070 }
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";
3073 }
3074
3075 // Drivers and hardware: what the kernel warned about lately, where the
3076 // user may read it (journal access).
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")) {
3079 std::string text;
3080 char buffer[4096];
3081 while (const auto n = std::fread(buffer, 1, sizeof(buffer), kernel)) {
3082 text.append(buffer, n);
3083 }
3084 ::pclose(kernel);
3085 // The same message, differing only in numbers, can repeat hundreds of
3086 // times; one line each, with a count, lets the rare ones show.
3087 struct message_t {
3088 std::string example, last_time;
3089 std::size_t count = 0;
3090 std::size_t order = 0;
3091 };
3092 std::map<std::string, message_t> messages;
3093 std::istringstream lines {text};
3094 for (std::string line; std::getline(lines, line);) {
3095 // "Oct 31 11:52:30 Haven kernel: message"
3096 const auto kernel_at = line.find(" kernel: ");
3097 const auto message = kernel_at == std::string::npos ? line : line.substr(kernel_at + 9);
3098 // Numbers, hex addresses included, become '#'.
3099 std::string key;
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] == '.')) {
3103 ++i;
3104 }
3105 key += '#';
3106 } else {
3107 key += message[i++];
3108 }
3109 }
3110 auto &entry = messages[key];
3111 if (!entry.count++) {
3112 entry.example = message;
3113 entry.order = messages.size();
3114 }
3115 entry.last_time = line.substr(0, std::min<std::size_t>(15, line.size()));
3116 }
3117 std::vector<const message_t *> sorted;
3118 for (const auto &[key, entry] : messages) {
3119 sorted.push_back(&entry);
3120 }
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;
3123 });
3124 for (const auto *entry : sorted) {
3125 out << std::format("{:>5}x last {} {}\n", entry->count, entry->last_time, entry->example);
3126 }
3127 if (sorted.empty()) {
3128 out << "None.\n";
3129 }
3130 }
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;
3137 }
3138 out << '\n';
3139 }
3140 {
3141 const auto kms = VDISPLAY::getHermesKmsStatus();
3142 for (const auto &note : {hermes_kms_problem(kms), hermes_kms_reload_note(kms), hermes_kms_newer_note(kms)}) {
3143 if (!note.empty()) {
3144 out << "Hermes-KMS: " << note << '\n';
3145 }
3146 }
3147 }
3148 out << "\n== Runtime state ==\n" << hestia_runtime_status_json().dump(2) << '\n';
3149 out << "\n== Streaming preflight ==\n" << hestia_preflight_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';
3154 }
3155 return out.str();
3156 }
3157
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);
3165 }
3166
3171 void getDiagnosticReport(resp_https_t response, req_https_t request) {
3172 if (!authenticate(response, request)) {
3173 return;
3174 }
3175 print_req(request);
3176 send_diagnostic_report(response);
3177 }
3178
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")) {
3181 return;
3182 }
3183 send_diagnostic_report(response);
3184 }
3185
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")) {
3188 return;
3189 }
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");
3192 return;
3193 }
3194
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");
3198 return;
3199 }
3200
3201 try {
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");
3205 return;
3206 }
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");
3210 return;
3211 }
3212 send_response(response, {{"ok", true}});
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");
3215 }
3216 }
3217
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")) {
3220 return;
3221 }
3222
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");
3226 return;
3227 }
3228
3229 try {
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");
3233 return;
3234 }
3235
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");
3239 return;
3240 }
3241
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] {
3247 std::error_code ec;
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);
3251 if (ec) {
3252 BOOST_LOG(error) << "[HestiaAPI] server command failed to start: " << ec.message();
3253 } else {
3254 child.detach();
3255 }
3256 }).detach();
3257
3258 send_response(response, {{"ok", true}});
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");
3261 }
3262 }
3263
3271 void getLocale(resp_https_t response, req_https_t request) {
3272 print_req(request);
3273
3274 nlohmann::json output_tree;
3275 output_tree["status"] = true;
3276 output_tree["locale"] = config::sunshine.locale;
3277 send_response(response, output_tree);
3278 }
3279
3295 void saveConfig(resp_https_t response, req_https_t request) {
3296 if (!validateContentType(response, request, "application/json") || !authenticate(response, request)) {
3297 return;
3298 }
3299
3300 print_req(request);
3301
3302 std::stringstream ss;
3303 ss << request->content.rdbuf();
3304 try {
3305 // TODO: Input Validation
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())) {
3311 continue;
3312 }
3313
3314 // v.dump() will dump valid json, which we do not want for strings in the config right now
3315 // we should migrate the config file to straight json and get rid of all this nonsense
3316 config_stream << k << " = " << (v.is_string() ? v.get<std::string>() : v.dump()) << std::endl;
3317 }
3318 file_handler::write_file(config::sunshine.config_file.c_str(), config_stream.str());
3319 output_tree["status"] = true;
3320 send_response(response, output_tree);
3321 } catch (std::exception &e) {
3322 BOOST_LOG(warning) << "SaveConfig: "sv << e.what();
3323 bad_request(response, request, e.what());
3324 }
3325 }
3326
3335 if (const char *marker = std::getenv("container"); marker && marker[0]) {
3336 return true;
3337 }
3338 std::error_code ec;
3339 return std::filesystem::exists("/run/.containerenv", ec) || std::filesystem::exists("/.dockerenv", ec);
3340 }
3341
3346 void installEvdi(resp_https_t response, req_https_t request) {
3347 if (!validateContentType(response, request, "application/json") || !authenticate(response, request)) {
3348 return;
3349 }
3350
3351 print_req(request);
3352 nlohmann::json output_tree;
3353
3354 try {
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");
3359 return;
3360 }
3361
3362 // Installing EVDI can only help a host that is going to use EVDI. Under
3363 // any other backend the package is installed, the module is loaded, and
3364 // nothing that follows reads either of them.
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.");
3367 return;
3368 }
3369
3370 // A container has no polkit authority to ask, so pkexec exits non-zero and
3371 // the user is told the installation "failed or was cancelled" - for a
3372 // command that could not have worked. Even granted the privilege it would
3373 // install the module into the container, where it would match no kernel
3374 // and drive no display: the module belongs to the host.
3375 if (running_in_container()) {
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.");
3377 return;
3378 }
3379
3380 // Fixed command only: no request data is passed to a privileged shell.
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
3385 apt-get update
3386 apt-get install -y evdi-dkms libevdi1
3387elif command -v dnf >/dev/null 2>&1; then
3388 dnf install -y evdi akmod-evdi
3389else
3390 echo "Unsupported package manager. Install EVDI manually." >&2
3391 exit 2
3392fi
3393if command -v dkms >/dev/null 2>&1; then
3394 dkms autoinstall -k "$(uname -r)"
3395fi
3396printf "options evdi initial_device_count=1\n" > /etc/modprobe.d/apollo-evdi.conf
3397modprobe -r evdi 2>/dev/null || true
3398modprobe evdi
3399printf "evdi\\n" > /etc/modules-load.d/evdi.conf')EVDI";
3400
3401 if (evdi_install_status.load() == 1) {
3402 output_tree["status"] = true;
3403 output_tree["installStatus"] = "running";
3404 send_response(response, output_tree);
3405 return;
3406 }
3407
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();
3412 std::error_code ec;
3413 auto child = platf::run_command(false, true, install_command, working_dir, env, nullptr, ec, nullptr);
3414 if (ec) {
3415 BOOST_LOG(warning) << "Unable to launch EVDI installer: " << ec.message();
3416 evdi_install_status.store(3);
3417 return;
3418 }
3419
3420 child.wait();
3421 if (child.exit_code() != 0) {
3422 BOOST_LOG(warning) << "EVDI installer exited with code " << child.exit_code();
3423 evdi_install_status.store(3);
3424 return;
3426
3428 evdi_install_status.store(proc::vDisplayDriverStatus == VDISPLAY::DRIVER_STATUS::OK ? 2 : 3);
3429 }).detach();
3430
3431 output_tree["status"] = true;
3432 output_tree["installStatus"] = "running";
3433 } catch (const std::exception &e) {
3434 BOOST_LOG(warning) << "InstallEvdi: " << e.what();
3435 bad_request(response, request, e.what());
3436 return;
3437 }
3438
3439 send_response(response, output_tree);
3440 }
3441
3442 /** Return the state of the EVDI installation started by this Web UI. */
3443 void getEvdiInstallStatus(resp_https_t response, req_https_t request) {
3444 if (!authenticate(response, request)) {
3445 return;
3446 }
3447
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"];
3456 send_response(response, output_tree);
3457 }
3458
3460 void getEvdiStatus(resp_https_t response, req_https_t request) {
3461 if (!authenticate(response, request)) {
3462 return;
3463 }
3464
3465 nlohmann::json output_tree;
3466 output_tree["status"] = true;
3467 output_tree["evdiInfo"] = evdi_status_json();
3468 send_response(response, output_tree);
3469 }
3470
3472 void getHermesKmsStatus(resp_https_t response, req_https_t request) {
3473 if (!authenticate(response, request)) {
3474 return;
3475 }
3476
3477 nlohmann::json output_tree;
3478 output_tree["status"] = true;
3479 output_tree["hermesKmsInfo"] = hermes_kms_status_json();
3480 // Only here, not in every config response: it asks the compositor and
3481 // kscreen-doctor, which is worth it when the user opens this panel.
3482 output_tree["sessionFeatures"] = session_features_json();
3483 send_response(response, output_tree);
3484 }
3485
3497 void getSessions(resp_https_t response, req_https_t request) {
3498 if (!authenticate(response, request)) {
3499 return;
3500 }
3501
3502 print_req(request);
3503
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;
3519 // Absent rather than empty where the session has none, so the UI can tell
3520 // "runs as the Hermes user" from "runs as hermes-s01" without comparing
3521 // against a magic empty string.
3522 if (!session.account_user.empty()) {
3523 entry["account_user"] = session.account_user;
3524 entry["account_uid"] = session.account_uid;
3525 }
3526 if (!session.unit.empty()) {
3527 entry["unit"] = session.unit;
3528 }
3529 if (!session.audio_sink.empty()) {
3530 entry["audio_sink"] = session.audio_sink;
3531 }
3532 // Whether anybody is attached right now, which is the difference between
3533 // ending somebody's session and reclaiming an abandoned one.
3534 entry["streaming"] = rtsp_stream::find_session(session.client_uuid) != nullptr;
3535 sessions.push_back(std::move(entry));
3536 }
3537
3538 output_tree["sessions"] = std::move(sessions);
3539 // So the UI can tell "nothing is running" from "this platform never runs
3540 // one", and hide the panel entirely in the second case rather than showing
3541 // an empty list forever.
3542 output_tree["supported"] = true;
3543 output_tree["status"] = true;
3544 send_response(response, output_tree);
3546
3563 void getGameModeStatus(resp_https_t response, req_https_t request) {
3564 if (!authenticate(response, request)) {
3565 return;
3566 }
3567
3568 print_req(request);
3569
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;
3574
3575 const auto clients = nvhttp::get_all_clients();
3576 output_tree["paired_clients"] = clients.is_array() ? clients.size() : 0;
3577
3578 if (const auto pending = nvhttp::pending_pair_client(); pending) {
3579 output_tree["pending_pair"] = true;
3580 output_tree["pending_pair_name"] = *pending;
3581 } else {
3582 output_tree["pending_pair"] = false;
3583 }
3584
3585 output_tree["streaming_sessions"] = rtsp_stream::session_count();
3586 output_tree["isolated_sessions"] = proc::proc.list_isolated().size();
3587
3588 output_tree["status"] = true;
3589 send_response(response, output_tree);
3590 }
3591
3592 /**
3593 * @brief End one isolated session.
3594 * @param response The HTTP response object.
3595 * @param request The HTTP request object.
3596 *
3597 * The body for the POST request should be JSON serialized in the following format:
3598 * @code{.json}
3599 * {
3600 * "uuid": "<client uuid>"
3601 * }
3602 * @endcode
3603 *
3604 * The stream is stopped first where there is one, so the client is told the
3605 * session ended rather than being left holding a stream into a desktop that
3606 * is being torn down underneath it. Ending a session does not unpair the
3607 * client and does not remove its account or its files: it may connect again
3608 * and get the same session back.
3609 */
3610 void terminateSession(resp_https_t response, req_https_t request) {
3611 if (!validateContentType(response, request, "application/json") || !authenticate(response, request)) {
3612 return;
3613 }
3614
3615 print_req(request);
3616
3617 try {
3618 std::stringstream ss;
3619 ss << request->content.rdbuf();
3620 nlohmann::json input_tree = nlohmann::json::parse(ss.str());
3621 nlohmann::json output_tree;
3622
3623 const std::string uuid = input_tree.value("uuid", "");
3624 if (uuid.empty()) {
3625 bad_request(response, request, "A client uuid is required.");
3626 return;
3627 }
3628
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;
3632 });
3633 if (!known) {
3634 output_tree["status"] = false;
3635 output_tree["error"] = "No isolated session belongs to that client.";
3636 send_response(response, output_tree);
3637 return;
3638 }
3639
3641 proc::proc.terminate_isolated_client(uuid);
3642
3643 BOOST_LOG(info) << "Isolated session for client ["sv << uuid << "] was ended from the web UI."sv;
3644 output_tree["status"] = true;
3645 send_response(response, output_tree);
3646 } catch (std::exception &e) {
3647 BOOST_LOG(warning) << "Terminate session: "sv << e.what();
3648 bad_request(response, request, e.what());
3649 }
3650 }
3651
3652 void getClipboardStatus(resp_https_t response, req_https_t request) {
3653 if (!authenticate(response, request)) {
3654 return;
3655 }
3656
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();
3661 send_response(response, output_tree);
3662 }
3663
3664 void installClipboard(resp_https_t response, req_https_t request) {
3665 if (!validateContentType(response, request, "application/json") || !authenticate(response, request)) {
3666 return;
3667 }
3668
3669 nlohmann::json output_tree;
3670 try {
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");
3675 return;
3676 }
3677 if (clipboard_install_status.load() == 1) {
3678 output_tree["status"] = true;
3679 output_tree["installStatus"] = "running";
3680 send_response(response, output_tree);
3681 return;
3682 }
3683
3684 // Fixed package-manager commands only. No request value reaches the shell.
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
3689 apt-get update
3690 apt-get install -y wl-clipboard xclip
3691elif command -v dnf >/dev/null 2>&1; then
3692 dnf install -y wl-clipboard xclip
3693else
3694 echo "Unsupported package manager. Install wl-clipboard and xclip manually." >&2
3695 exit 2
3696fi')CLIP";
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();
3701 std::error_code ec;
3702 auto child = platf::run_command(false, true, install_command, working_dir, env, nullptr, ec, nullptr);
3703 if (ec) {
3704 BOOST_LOG(warning) << "Unable to launch clipboard installer: " << ec.message();
3705 clipboard_install_status.store(3);
3706 return;
3707 }
3708 child.wait();
3709 clipboard_install_status.store(child.exit_code() == 0 ? 2 : 3);
3710 }).detach();
3711 output_tree["status"] = true;
3712 output_tree["installStatus"] = "running";
3713 } catch (const std::exception &e) {
3714 BOOST_LOG(warning) << "InstallClipboard: " << e.what();
3715 bad_request(response, request, e.what());
3716 return;
3717 }
3718 send_response(response, output_tree);
3719 }
3720
3728 void uploadCover(resp_https_t response, req_https_t request) {
3729 if (!validateContentType(response, request, "application/json") || !authenticate(response, request)) {
3730 return;
3731 }
3732
3733 std::stringstream ss;
3734
3735 ss << request->content.rdbuf();
3736 try {
3737 nlohmann::json input_tree = nlohmann::json::parse(ss.str());
3738 nlohmann::json output_tree;
3739 std::string key = input_tree.value("key", "");
3740 if (key.empty()) {
3741 bad_request(response, request, "Cover key is required");
3742 return;
3743 }
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";
3748 if (!url.empty()) {
3749 if (http::url_get_host(url) != "images.igdb.com") {
3750 bad_request(response, request, "Only images.igdb.com is allowed");
3751 return;
3752 }
3753 if (!http::download_file(url, path)) {
3754 bad_request(response, request, "Failed to download cover");
3755 return;
3756 }
3757 } else {
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()));
3761 }
3762 output_tree["status"] = true;
3763 output_tree["path"] = path;
3764 send_response(response, output_tree);
3765 } catch (std::exception &e) {
3766 BOOST_LOG(warning) << "UploadCover: "sv << e.what();
3767 bad_request(response, request, e.what());
3768 }
3769 }
3770
3778 void getLogs(resp_https_t response, req_https_t request) {
3779 if (!authenticate(response, request)) {
3780 return;
3781 }
3783 print_req(request);
3784 std::string content = file_handler::read_file(config::sunshine.log_file.c_str());
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);
3791 }
3792
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"))
3813 return;
3814 print_req(request);
3815 std::vector<std::string> errors;
3816 std::stringstream ss;
3817 ss << request->content.rdbuf();
3818 try {
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");
3830 } else {
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");
3836 else {
3837 http::save_user_creds(config::sunshine.credentials_file, newUsername, newPassword);
3838 http::reload_user_creds(config::sunshine.credentials_file);
3839 sessionCookie.clear(); // force re-login
3840 output_tree["status"] = true;
3841 }
3842 } else {
3843 errors.push_back("Invalid Current Credentials");
3844 }
3845 }
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;
3850 });
3851 bad_request(response, request, error);
3852 return;
3853 }
3854 send_response(response, output_tree);
3855 } catch (std::exception &e) {
3856 BOOST_LOG(warning) << "SavePassword: "sv << e.what();
3857 bad_request(response, request, e.what());
3858 }
3859 }
3860
3868 void getOTP(resp_https_t response, req_https_t request) {
3869 if (!validateContentType(response, request, "application/json") || !authenticate(response, request)) {
3870 return;
3871 }
3872
3873 print_req(request);
3874
3875 nlohmann::json output_tree;
3876 try {
3877 std::stringstream ss;
3878 ss << request->content.rdbuf();
3879 nlohmann::json input_tree = nlohmann::json::parse(ss.str());
3880
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.";
3893 send_response(response, output_tree);
3894 } catch (std::exception &e) {
3895 BOOST_LOG(warning) << "OTP creation failed: "sv << e.what();
3896 bad_request(response, request, e.what());
3897 }
3898 }
3899
3907
3915 void savePin(resp_https_t response, req_https_t request) {
3916 if (!validateContentType(response, request, "application/json") || !authenticate(response, request)) {
3917 return;
3918 }
3919
3920 print_req(request);
3921
3922 try {
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", "");
3929 output_tree["status"] = nvhttp::pin(pin, name);
3930 send_response(response, output_tree);
3931 } catch (std::exception &e) {
3932 BOOST_LOG(warning) << "SavePin: "sv << e.what();
3933 bad_request(response, request, e.what());
3935 }
3936
3944 void resetDisplayDevicePersistence(resp_https_t response, req_https_t request) {
3945 if (!validateContentType(response, request, "application/json") || !authenticate(response, request)) {
3946 return;
3947 }
3948
3949 print_req(request);
3950
3951 nlohmann::json output_tree;
3952 output_tree["status"] = display_device::reset_persistence();
3953 send_response(response, output_tree);
3954 }
3955
3963 void restart(resp_https_t response, req_https_t request) {
3964 if (!validateContentType(response, request, "application/json") || !authenticate(response, request)) {
3965 return;
3966 }
3967
3968 print_req(request);
3969
3970 proc::proc.terminate();
3971
3972 // We may not return from this call
3973 platf::restart();
3974 }
3975
3976 // A quit request answers only if Hermes is still running 5 s later. The
3977 // thread that waits for that must let go of the response before the server
3978 // is destroyed: a response that outlives it crashes Hermes when the thread
3979 // writes or releases it, which happens whenever shutting down takes longer
3980 // than 5 s (closing an EVDI display can).
3981 namespace {
3982 std::mutex quit_mutex;
3983 std::condition_variable quit_cv;
3984 bool server_stopping = false;
3985 int quit_waiters = 0;
3986 } // namespace
3987
3993 void quit(resp_https_t response, req_https_t request) {
3994 if (!authenticate(response, request)) {
3995 return;
3996 }
3997
3998 print_req(request);
3999
4000 BOOST_LOG(warning) << "Requested quit from config page!"sv;
4001
4002 proc::proc.terminate();
4004 {
4005 lifetime::exit_sunshine(0, true);
4006 }
4007 // If exit fails, write a response after 5 seconds.
4008 {
4009 std::lock_guard<std::mutex> lock(quit_mutex);
4010 if (server_stopping) {
4011 return;
4012 }
4013 ++quit_waiters;
4014 }
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; })) {
4018 response->write();
4019 }
4020 response.reset();
4021 --quit_waiters;
4022 quit_cv.notify_all();
4023 });
4024 write_resp.detach();
4025 }
4026
4032 void launchApp(resp_https_t response, req_https_t request) {
4033 if (!validateContentType(response, request, "application/json") || !authenticate(response, request)) {
4034 return;
4035 }
4036
4037 print_req(request);
4038
4039 try {
4040 std::stringstream ss;
4041 ss << request->content.rdbuf();
4042 nlohmann::json input_tree = nlohmann::json::parse(ss.str());
4043
4044 // Check for required uuid field in body
4045 if (!input_tree.contains("uuid") || !input_tree["uuid"].is_string()) {
4046 bad_request(response, request, "Missing or invalid uuid in request body");
4047 return;
4048 }
4049 std::string uuid = input_tree["uuid"].get<std::string>();
4050
4051 nlohmann::json output_tree;
4052 const auto &apps = proc::proc.get_apps();
4053 for (auto &app : apps) {
4054 if (app.uuid == uuid) {
4055 crypto::named_cert_t named_cert {
4056 .name = "",
4057 .uuid = http::unique_id,
4058 .perm = crypto::PERM::_all,
4059 };
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);
4063 if (err) {
4064 // Same precedence as the client launch in nvhttp: a reason the
4065 // launch recorded beats the guess made from the status code.
4066 if (!launch_session->launch_error_message.empty()) {
4067 bad_request(response, request, launch_session->launch_error_message);
4068 } else {
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");
4072 }
4073 } else {
4074 output_tree["status"] = true;
4075 send_response(response, output_tree);
4076 }
4077 return;
4078 }
4079 }
4080 BOOST_LOG(error) << "Couldn't find app with uuid ["sv << uuid << ']';
4081 bad_request(response, request, "Cannot find requested application");
4082 }
4083 catch (std::exception &e) {
4084 BOOST_LOG(warning) << "LaunchApp: "sv << e.what();
4085 bad_request(response, request, e.what());
4086 }
4087 }
4088
4094 void disconnect(resp_https_t response, req_https_t request) {
4095 if (!validateContentType(response, request, "application/json") || !authenticate(response, request)) {
4096 return;
4097 }
4098
4099 print_req(request);
4100
4101 try {
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", "");
4107 output_tree["status"] = nvhttp::find_and_stop_session(uuid, true);
4108 send_response(response, output_tree);
4109 } catch (std::exception &e) {
4110 BOOST_LOG(warning) << "Disconnect: "sv << e.what();
4111 bad_request(response, request, e.what());
4112 }
4113 }
4114
4128 void login(resp_https_t response, req_https_t request) {
4129 if (!checkIPOrigin(response, request) || !validateContentType(response, request, "application/json")) {
4130 return;
4131 }
4132
4133 auto fg = util::fail_guard([&]{
4134 response->write(SimpleWeb::StatusCode::client_error_unauthorized);
4135 });
4136
4137 try {
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)
4145 return;
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=/" }
4151 };
4152 response->write(headers);
4153 fg.disable();
4154 } catch (std::exception &e) {
4155 BOOST_LOG(warning) << "Web UI Login failed: ["sv << net::addr_to_normalized_string(request->remote_endpoint().address())
4156 << "]: "sv << e.what();
4157 response->write(SimpleWeb::StatusCode::server_error_internal_server_error);
4158 fg.disable();
4159 return;
4160 }
4161 }
4162
4166 void start() {
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);
4170 auto port_https = net::map_port(PORT_HTTPS);
4171 auto address_family = net::af_from_enum_string(config::sunshine.address_family);
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)
4177#else
4178 SSL_get_peer_certificate(ssl)
4179#endif
4180 };
4181 if (!certificate) {
4182 return;
4183 }
4184
4185 crypto::p_named_cert_t client;
4186 if (nvhttp::verify_paired_client_certificate(certificate.get(), client)) {
4187 request->userp = std::move(client);
4188 } else {
4189 BOOST_LOG(info) << "[HestiaAPI] unpaired client certificate rejected";
4190 }
4191 };
4192 server.default_resource["DELETE"] = [](resp_https_t response, req_https_t request) {
4193 bad_request(response, request);
4194 };
4195 server.default_resource["PATCH"] = [](resp_https_t response, req_https_t request) {
4196 bad_request(response, request);
4197 };
4198 server.default_resource["POST"] = [](resp_https_t response, req_https_t request) {
4199 bad_request(response, request);
4200 };
4201 server.default_resource["PUT"] = [](resp_https_t response, req_https_t request) {
4202 bad_request(response, request);
4203 };
4204 server.default_resource["GET"] = not_found;
4205 server.resource["^/$"]["GET"] = getIndexPage;
4206 server.resource["^/pin/?$"]["GET"] = getPinPage;
4207 server.resource["^/apps/?$"]["GET"] = getAppsPage;
4208 server.resource["^/config/?$"]["GET"] = getConfigPage;
4209 server.resource["^/password/?$"]["GET"] = getPasswordPage;
4210 server.resource["^/welcome/?$"]["GET"] = getWelcomePage;
4211 server.resource["^/login/?$"]["GET"] = getLoginPage;
4212 server.resource["^/troubleshooting/?$"]["GET"] = getTroubleshootingPage;
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;
4228 server.resource["^/api/evdi/install/status$"]["GET"] = getEvdiInstallStatus;
4229 server.resource["^/api/evdi/status$"]["GET"] = getEvdiStatus;
4230 server.resource["^/api/hermes-kms/status$"]["GET"] = getHermesKmsStatus;
4231 server.resource["^/api/clipboard/status$"]["GET"] = getClipboardStatus;
4232 server.resource["^/api/clipboard/install$"]["POST"] = installClipboard;
4233 server.resource["^/api/hestia/v1/?$"]["GET"] = getHestiaCapabilities;
4234 server.resource["^/api/hestia/v1/capabilities$"]["GET"] = getHestiaCapabilities;
4235 server.resource["^/api/hestia/v1/session/prepare$"]["POST"] = prepare_hestia_session;
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;
4241 server.resource["^/api/hestia/v1/stream/info$"]["GET"] = get_hestia_stream_info;
4242 server.resource["^/api/hestia/v1/diagnostics/report$"]["GET"] = get_hestia_diagnostic_report;
4243 server.resource["^/api/diagnostics/report$"]["GET"] = getDiagnosticReport;
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;
4251 server.resource["^/api/reset-display-device-persistence$"]["POST"] = resetDisplayDevicePersistence;
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;
4258 server.resource["^/api/gamemode/status$"]["GET"] = getGameModeStatus;
4259 server.resource["^/api/sessions/list$"]["GET"] = getSessions;
4260 server.resource["^/api/sessions/terminate$"]["POST"] = terminateSession;
4261 server.resource["^/api/covers/upload$"]["POST"] = uploadCover;
4262 // Cached pages from earlier releases may still request these URLs.
4263 server.resource["^/images/apollo.ico$"]["GET"] = getFaviconImage;
4264 server.resource["^/images/logo-apollo-45.png$"]["GET"] = getHermesLogoImage;
4265 server.resource["^/images/hermes.ico$"]["GET"] = getFaviconImage;
4266 server.resource["^/images/logo-hermes-45.png$"]["GET"] = getHermesLogoImage;
4267 server.resource["^/assets\\/.+$"]["GET"] = getNodeModules;
4268 server.config.reuse_address = true;
4269 server.config.address = net::af_to_any_address_string(address_family);
4270 server.config.port = port_https;
4271
4272 // Say this at startup rather than leaving the first visitor to discover a
4273 // broken UI. A packaging or build mismatch puts the assets somewhere other
4274 // than where this binary was told to look, and the symptom — a blank page —
4275 // gives no hint of that.
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;
4280 }
4281
4282 auto accept_and_run = [&](auto *server) {
4283 try {
4284 server->start([port_https](unsigned short port) {
4285 BOOST_LOG(info) << "Configuration UI available at [https://localhost:"sv << port << "]";
4286 });
4287 } catch (boost::system::system_error &err) {
4288 // It's possible the exception gets thrown after calling server->stop() from a different thread
4289 if (shutdown_event->peek())
4290 return;
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);
4294 return;
4295 }
4296 };
4297 std::thread tcp { accept_and_run, &server };
4298
4299 // The diagnostic report's stream timeline.
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);
4306 }
4307 report_timeline::record();
4308 }
4309 }};
4310 auto stop_timeline_guard = util::fail_guard([&]() {
4311 stop_timeline = true;
4312 timeline.join();
4313 });
4314
4315 // Wait for any event
4316 shutdown_event->view();
4317
4318 // Let a pending quit request drop its response while the server still exists.
4319 {
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; });
4324 }
4325
4326 server.stop();
4327
4328 tcp.join();
4329 }
4330} // namespace confighttp
void release_host_sink()
Let go of a hold_host_sink() hold and restore the sink it recorded.
Definition audio.cpp:461
Declarations for audio capture and encoding.
Capture a shell helper's output without an unbounded shutdown wait.
void stop()
Stop the RTSP server.
Definition rtsp.cpp:687
Declarations for common platform specific utilities.
@ system
System memory.
Definition common.h:212
std::shared_ptr< display_t > display(mem_type_e hwdevice_type, const std::string &display_name, const video::config_t &config)
Get the display_t instance for the given hwdevice_type. If display_name is empty, use the first monit...
Definition misc.cpp:1658
session_environment_t detect_session_environment()
Detect the current session/compositor environment.
Definition misc.cpp:1882
std::filesystem::path appdata()
Performs migration if necessary, then returns the appdata directory.
Definition misc.cpp:301
appliance_readiness_t appliance_readiness()
Assess appliance-mode readiness without changing any state.
Definition misc.cpp:1972
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.
@ REMOVE
Remove client.
@ ADD
Add client.
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.
Definition crypto.cpp:364
Declarations for cryptography functions.
PERM
The permissions of a client.
Definition crypto.h:45
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.
Definition globals.cpp:8
void store_hestia_session_prepare(const std::string &client_uuid, hestia_session_prepare_t prepare)
Definition nvhttp.cpp:2211
bool pin(std::string pin, std::string name)
Compare the user supplied pin to the Moonlight pin.
Definition nvhttp.cpp:1026
bool unpair_client(const std::string_view uuid)
Remove single client.
Definition nvhttp.cpp:2470
std::optional< std::string > pending_pair_client()
The client whose pairing request is waiting for a PIN, if any.
Definition nvhttp.cpp:1018
void erase_all_clients()
Remove all paired clients.
Definition nvhttp.cpp:2398
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.
Definition nvhttp.cpp:2207
nlohmann::json describe_applied_settings(const std::string &app_id, bool virtual_display, int scale_factor)
Definition nvhttp.cpp:94
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.
Definition nvhttp.cpp:2436
void clear_hestia_session_prepare(const std::string &client_uuid)
Definition nvhttp.cpp:2236
bool find_and_stop_session(const std::string &uuid, bool graceful)
Finds and stop session.
Definition nvhttp.cpp:2414
nlohmann::json get_all_clients()
Get all paired clients.
Definition nvhttp.cpp:1236
std::uint16_t map_port(int port)
Map a specified port based on the base port.
Definition network.cpp:350
bool udp_port_available(af_e af, std::uint16_t port)
Whether a UDP port can still be bound on this host.
Definition network.cpp:316
net_e from_address(const std::string_view &view, std::span< const interface_address_t > links)
Classify an address against the given interface subnets.
Definition network.cpp:112
std::string_view af_to_any_address_string(af_e af)
Get the wildcard binding address for a given address family.
Definition network.cpp:178
std::string addr_to_normalized_string(boost::asio::ip::address address)
Get the given address in normalized string form.
Definition network.cpp:202
af_e af_from_enum_string(const std::string_view &view)
Get the address family enum value from a string.
Definition network.cpp:166
net_e from_address_ranges(const std::string_view &view)
Classify an address by the fixed ranges alone.
Definition network.cpp:108
Declarations for networking related functions.
@ LAN
LAN.
Definition network.h:41
Declarations for the nvhttp (GameStream) server.
report_t report()
assess(collect_facts()).
Definition prelogin.cpp:609
int command(const char *name, int argc, char *argv[])
hermes --prelogin status|enable|disable.
Definition prelogin.cpp:632
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.
Definition process.cpp:4521
void initVDisplayDriver()
Initialize the virtual display driver. This should be called early in startup to enable virtual displ...
Definition process.cpp:1580
Declarations for the startup and shutdown of the apps started by a streaming Session.
@ app
The client sent none; the app's own scale.
Definition process.h:201
std::string_view last_termination_reason()
Get a short identifier for why the most recent session ended.
Definition rtsp.cpp:785
int session_count()
Get the number of active sessions.
Definition rtsp.cpp:773
Declarations for RTSP streaming.
termination_stats_t termination_stats()
Snapshot of the termination/reconnection stats.
Definition stream.cpp:2326
Declarations for the streaming protocols.
uint32_t required_uapi_version
Minimum UAPI version Hermes needs.
bool device_present
A hermes-kms DRM card node was found and opened.
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.
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.
Definition prelogin.h:39
bool ready
Every requirement is known to be in place.
Definition prelogin.h:40
Live per-frame pipeline metrics, for diagnostics/metrics.
Definition video.h:514
Declarations for utility functions.
Declarations for UUID generation.
bool display_present()
Whether the host has a display to capture without creating one.
Definition video.cpp:52
encoder_status_t get_encoder_status()
Snapshot of the last encoder probe result (thread-safe copy).
Definition video.cpp:852
capture_readiness_t last_capture_readiness()
The result of the last check_capture_path().
Definition video.cpp:3212
pipeline_metrics_t get_pipeline_metrics()
Snapshot of the live pipeline metrics (thread-safe copy).
Definition video.cpp:926
Declarations for video.
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.