Hermes 0.7.0
Linux game streaming host
Loading...
Searching...
No Matches
nvhttp.cpp
Go to the documentation of this file.
1
5// macros
6#define BOOST_BIND_GLOBAL_PLACEHOLDERS
7
8// standard includes
9#include <filesystem>
10#include <format>
11#include <mutex>
12#include <string>
13#include <unordered_map>
14#include <utility>
15#include <string>
16
17// lib includes
18#include <boost/asio/ssl/context.hpp>
19#include <boost/asio/ssl/context_base.hpp>
20#include <boost/property_tree/json_parser.hpp>
21#include <boost/property_tree/ptree.hpp>
22#include <boost/property_tree/xml_parser.hpp>
23#include <Simple-Web-Server/server_http.hpp>
24
25// local includes
26#include "config.h"
27#include "display_device.h"
28#include "file_handler.h"
29#include "globals.h"
30#include "httpcommon.h"
31#include "logging.h"
32#include "network.h"
33#include "nvhttp.h"
34#include "platform/common.h"
35#include "process.h"
36#include "rtsp.h"
37#include "stream.h"
38#include "system_tray.h"
39#include "utility.h"
40#include "uuid.h"
41#include "video.h"
42#include "zwpad.h"
43
44
45using namespace std::literals;
46
47namespace nvhttp {
48
49 namespace fs = std::filesystem;
50 namespace pt = boost::property_tree;
51
52 using p_named_cert_t = crypto::p_named_cert_t;
53 using PERM = crypto::PERM;
54
55 bool experimental_isolated_sessions_enabled() {
56 return config::video.virtual_display_backend == "hermes_kms" &&
57 config::video.hermes_kms_isolated_sessions;
58 }
59
60 struct client_t {
61 std::vector<p_named_cert_t> named_devices;
62 };
63
64 namespace {
65 const char *source_name(proc::virtual_display_source_e source) {
66 switch (source) {
68 return "headless";
70 return "app_forced";
72 return "client";
74 break;
75 }
76 return "app";
77 }
78
79 const char *source_name(proc::scale_factor_source_e source) {
80 switch (source) {
81 case proc::scale_factor_source_e::app_forced:
82 return "app_forced";
83 case proc::scale_factor_source_e::client:
84 return "client";
85 case proc::scale_factor_source_e::app:
86 return "app";
87 case proc::scale_factor_source_e::host_default:
88 break;
89 }
90 return "host_default";
91 }
92 } // namespace
93
94 nlohmann::json describe_applied_settings(const std::string &app_id, bool virtual_display, int scale_factor) {
95 const auto apps = proc::proc.get_apps();
96 const auto app = std::find_if(apps.begin(), apps.end(), [&](const proc::ctx_t &candidate) {
97 return candidate.id == app_id;
98 });
99 if (app == apps.end()) {
100 return nullptr;
101 }
102
104 probe.virtual_display = virtual_display;
105 probe.client_virtual_display = virtual_display;
106 probe.scale_factor = scale_factor;
107 probe.client_scale_factor = scale_factor;
108
109 const auto display = proc::decide_virtual_display(*app, probe, config::video.headless_mode);
110 bool display_effective = display.use;
111 std::string display_source = source_name(display.source);
112 // An isolated app runs on a display of its own whatever was asked.
113 if (proc::resolve_session_route(*app, experimental_isolated_sessions_enabled(), display.use,
114 config::video.isolation_method) != proc::session_route_e::shared) {
115 display_effective = true;
116 display_source = "isolated_session";
117 }
118 const auto scale = proc::decide_scale_factor(*app, probe, config::video.default_scale_factor);
119
120 return {
121 {"virtual_display", {
122 {"requested", virtual_display},
123 {"effective", display_effective},
124 {"source", display_source},
125 }},
126 {"scale_factor", {
127 {"requested", scale_factor},
128 {"effective", scale.percent},
129 {"source", source_name(scale.source)},
130 }},
131 };
132 }
133
134 struct pair_session_t;
135
136 crypto::cert_chain_t cert_chain;
137 static std::string one_time_pin;
138 static std::string otp_passphrase;
139 static std::string otp_device_name;
140 static std::chrono::time_point<std::chrono::steady_clock> otp_creation_time;
141
142 class SunshineHTTPSServer: public SimpleWeb::ServerBase<SunshineHTTPS> {
143 public:
144 SunshineHTTPSServer(const std::string &certification_file, const std::string &private_key_file):
145 ServerBase<SunshineHTTPS>::ServerBase(443),
146 context(boost::asio::ssl::context::tls_server) {
147 // Disabling TLS 1.0 and 1.1 (see RFC 8996)
148 context.set_options(boost::asio::ssl::context::no_tlsv1);
149 context.set_options(boost::asio::ssl::context::no_tlsv1_1);
150 context.use_certificate_chain_file(certification_file);
151 context.use_private_key_file(private_key_file, boost::asio::ssl::context::pem);
152 }
153
154 std::function<bool(std::shared_ptr<Request>, SSL*)> verify;
155 std::function<void(std::shared_ptr<Response>, std::shared_ptr<Request>)> on_verify_failed;
156
157 protected:
158 boost::asio::ssl::context context;
159
160 void after_bind() override {
161 if (verify) {
162 context.set_verify_mode(boost::asio::ssl::verify_peer | boost::asio::ssl::verify_fail_if_no_peer_cert | boost::asio::ssl::verify_client_once);
163 context.set_verify_callback([](int verified, boost::asio::ssl::verify_context &ctx) {
164 // To respond with an error message, a connection must be established
165 return 1;
166 });
167 }
168 }
169
170 // This is Server<HTTPS>::accept() with SSL validation support added
171 void accept() override {
172 auto connection = create_connection(*io_service, context);
173
174 acceptor->async_accept(connection->socket->lowest_layer(), [this, connection](const SimpleWeb::error_code &ec) {
175 auto lock = connection->handler_runner->continue_lock();
176 if (!lock) {
177 return;
178 }
179
180 if (ec != SimpleWeb::error::operation_aborted) {
181 this->accept();
182 }
183
184 auto session = std::make_shared<Session>(config.max_request_streambuf_size, connection);
185
186 if (!ec) {
187 boost::asio::ip::tcp::no_delay option(true);
188 SimpleWeb::error_code ec;
189 session->connection->socket->lowest_layer().set_option(option, ec);
190
191 session->connection->set_timeout(config.timeout_request);
192 session->connection->socket->async_handshake(boost::asio::ssl::stream_base::server, [this, session](const SimpleWeb::error_code &ec) {
193 session->connection->cancel_timeout();
194 auto lock = session->connection->handler_runner->continue_lock();
195 if (!lock) {
196 return;
197 }
198 if (!ec) {
199 if (verify && !verify(session->request, session->connection->socket->native_handle())) {
200 this->write(session, on_verify_failed);
201 } else {
202 this->read(session);
203 }
204 } else if (this->on_error) {
205 this->on_error(session->request, ec);
206 }
207 });
208 } else if (this->on_error) {
209 this->on_error(session->request, ec);
210 }
211 });
212 }
213 };
214
215 using https_server_t = SunshineHTTPSServer;
216 using http_server_t = SimpleWeb::Server<SimpleWeb::HTTP>;
217
219 std::string servercert;
220 std::string pkey;
221 } conf_intern;
222
223 // uniqueID, session
224 std::unordered_map<std::string, pair_session_t> map_id_sess;
225 // HTTP pairing, HTTPS pairing and Web UI PIN submission run on different
226 // server threads. Helpers can remove a session while the caller holds this.
227 std::recursive_mutex pair_session_mutex;
228 client_t client_root;
229 std::atomic<uint32_t> session_id_counter;
230
231 uint32_t launch_count() {
232 return session_id_counter.load();
233 }
234
254 std::unordered_map<std::string, std::string> pending_pairs;
255
256 void set_pending_pair(const std::string &unique_id, const std::string &name) {
257 std::lock_guard lock {pending_pair_mutex};
258 pending_pairs[unique_id] = name;
259 }
260
261 void clear_pending_pair(const std::string &unique_id) {
262 std::lock_guard lock {pending_pair_mutex};
263 pending_pairs.erase(unique_id);
264 }
265
266 void clear_pending_pairs() {
267 std::lock_guard lock {pending_pair_mutex};
268 pending_pairs.clear();
269 }
270
273 std::chrono::steady_clock::time_point expires_at;
274 };
275 static std::mutex pending_hestia_session_prepares_mutex;
276 static std::unordered_map<std::string, pending_hestia_session_prepare_t> pending_hestia_session_prepares;
277
278 using resp_https_t = std::shared_ptr<typename SimpleWeb::ServerBase<SunshineHTTPS>::Response>;
279 using req_https_t = std::shared_ptr<typename SimpleWeb::ServerBase<SunshineHTTPS>::Request>;
280 using resp_http_t = std::shared_ptr<typename SimpleWeb::ServerBase<SimpleWeb::HTTP>::Response>;
281 using req_http_t = std::shared_ptr<typename SimpleWeb::ServerBase<SimpleWeb::HTTP>::Request>;
282
283 enum class op_e {
284 ADD,
285 REMOVE
286 };
287
288 std::string get_arg(const args_t &args, const char *name, const char *default_value) {
289 auto it = args.find(name);
290 if (it == std::end(args)) {
291 if (default_value != nullptr) {
292 return std::string(default_value);
293 }
294
295 throw std::out_of_range(name);
296 }
297 return it->second;
298 }
299
300 // Helper function to extract command entries from a JSON object.
301 cmd_list_t extract_command_entries(const nlohmann::json& j, const std::string& key) {
302 cmd_list_t commands;
303
304 // Check if the key exists in the JSON.
305 if (j.contains(key)) {
306 // Ensure that the value for the key is an array.
307 try {
308 for (const auto& item : j.at(key)) {
309 try {
310 // Extract "cmd" and "elevated" fields from the JSON object.
311 std::string cmd = item.at("cmd").get<std::string>();
312 bool elevated = util::get_non_string_json_value<bool>(item, "elevated", false);
313
314 // Add the command entry to the list.
315 commands.push_back({cmd, elevated});
316 } catch (const std::exception& e) {
317 BOOST_LOG(warning) << "Error parsing command entry: " << e.what();
318 }
319 }
320 } catch (const std::exception &e) {
321 BOOST_LOG(warning) << "Error retrieving key \"" << key << "\": " << e.what();
322 }
323 } else {
324 BOOST_LOG(debug) << "Key \"" << key << "\" not found in the JSON.";
325 }
326
327 return commands;
328 }
329
330 void save_state() {
331 nlohmann::json root = nlohmann::json::object();
332 // If the state file exists, try to read it.
333 if (fs::exists(config::nvhttp.file_state)) {
334 try {
335 std::ifstream in(config::nvhttp.file_state);
336 in >> root;
337 } catch (std::exception &e) {
338 BOOST_LOG(error) << "Couldn't read "sv << config::nvhttp.file_state << ": "sv << e.what();
339 return;
340 }
341 }
342
343 // Erase any previous "root" key.
344 root.erase("root");
345
346 // Create a new "root" object and set the unique id.
347 root["root"] = nlohmann::json::object();
348 root["root"]["uniqueid"] = http::unique_id;
349
350 client_t &client = client_root;
351 nlohmann::json named_cert_nodes = nlohmann::json::array();
352
353 std::unordered_set<std::string> unique_certs;
354 std::unordered_map<std::string, int> name_counts;
355
356 for (auto &named_cert_p : client.named_devices) {
357 // Only add each unique certificate once.
358 if (unique_certs.insert(named_cert_p->cert).second) {
359 nlohmann::json named_cert_node = nlohmann::json::object();
360 std::string base_name = named_cert_p->name;
361 // Remove any pending id suffix (e.g., " (2)") if present.
362 size_t pos = base_name.find(" (");
363 if (pos != std::string::npos) {
364 base_name = base_name.substr(0, pos);
365 }
366 int count = name_counts[base_name]++;
367 std::string final_name = base_name;
368 if (count > 0) {
369 final_name += " (" + std::to_string(count + 1) + ")";
370 }
371 named_cert_node["name"] = final_name;
372 named_cert_node["cert"] = named_cert_p->cert;
373 named_cert_node["uuid"] = named_cert_p->uuid;
374 named_cert_node["display_mode"] = named_cert_p->display_mode;
375 named_cert_node["perm"] = static_cast<uint32_t>(named_cert_p->perm);
376 named_cert_node["enable_legacy_ordering"] = named_cert_p->enable_legacy_ordering;
377 named_cert_node["allow_client_commands"] = named_cert_p->allow_client_commands;
378 named_cert_node["always_use_virtual_display"] = named_cert_p->always_use_virtual_display;
379
380 // Add "do" commands if available.
381 if (!named_cert_p->do_cmds.empty()) {
382 nlohmann::json do_cmds_node = nlohmann::json::array();
383 for (const auto &cmd : named_cert_p->do_cmds) {
384 do_cmds_node.push_back(crypto::command_entry_t::serialize(cmd));
385 }
386 named_cert_node["do"] = do_cmds_node;
387 }
388
389 // Add "undo" commands if available.
390 if (!named_cert_p->undo_cmds.empty()) {
391 nlohmann::json undo_cmds_node = nlohmann::json::array();
392 for (const auto &cmd : named_cert_p->undo_cmds) {
393 undo_cmds_node.push_back(crypto::command_entry_t::serialize(cmd));
394 }
395 named_cert_node["undo"] = undo_cmds_node;
396 }
397
398 named_cert_nodes.push_back(named_cert_node);
399 }
400 }
401
402 root["root"]["named_devices"] = named_cert_nodes;
403
404 try {
405 std::ofstream out(config::nvhttp.file_state);
406 out << root.dump(4); // Pretty-print with an indent of 4 spaces.
407 } catch (std::exception &e) {
408 BOOST_LOG(error) << "Couldn't write "sv << config::nvhttp.file_state << ": "sv << e.what();
409 return;
410 }
411 }
412
413 void load_state() {
414 if (!fs::exists(config::nvhttp.file_state)) {
415 BOOST_LOG(info) << "File "sv << config::nvhttp.file_state << " doesn't exist"sv;
416 http::unique_id = uuid_util::uuid_t::generate().string();
417 return;
418 }
419
420 nlohmann::json tree;
421 try {
422 std::ifstream in(config::nvhttp.file_state);
423 in >> tree;
424 } catch (std::exception &e) {
425 BOOST_LOG(error) << "Couldn't read "sv << config::nvhttp.file_state << ": "sv << e.what();
426 return;
427 }
428
429 // Check that the file contains a usable "root.uniqueid" value. Accept it
430 // only if it parses as a UUID; a missing, empty, or malformed value
431 // (e.g. a truncated/corrupted state file) regenerates a fresh id instead
432 // of throwing and taking down the host.
433 std::string uid = (tree.contains("root") && tree["root"].contains("uniqueid")) ?
434 tree["root"]["uniqueid"].get<std::string>() :
435 std::string {};
436 try {
437 http::uuid = uuid_util::uuid_t::parse(uid);
438 http::unique_id = uid;
439 } catch (const std::invalid_argument &) {
440 BOOST_LOG(warning) << "State file has an invalid uniqueid; regenerating"sv;
441 http::uuid = uuid_util::uuid_t::generate();
442 http::unique_id = http::uuid.string();
443 }
444
445 nlohmann::json root = tree["root"];
446 client_t client; // Local client to load into
447
448 // Import from the old format if available.
449 if (root.contains("devices")) {
450 for (auto &device_node : root["devices"]) {
451 // For each device, if there is a "certs" array, add a named certificate.
452 if (device_node.contains("certs")) {
453 for (auto &el : device_node["certs"]) {
454 auto named_cert_p = std::make_shared<crypto::named_cert_t>();
455 named_cert_p->name = "";
456 named_cert_p->cert = el.get<std::string>();
457 named_cert_p->uuid = uuid_util::uuid_t::generate().string();
458 named_cert_p->display_mode = "";
459 named_cert_p->perm = PERM::_all;
460 named_cert_p->enable_legacy_ordering = true;
461 named_cert_p->allow_client_commands = true;
462 named_cert_p->always_use_virtual_display = false;
463 client.named_devices.emplace_back(named_cert_p);
464 }
465 }
466 }
467 }
468
469 // Import from the new format.
470 if (root.contains("named_devices")) {
471 for (auto &el : root["named_devices"]) {
472 auto named_cert_p = std::make_shared<crypto::named_cert_t>();
473 named_cert_p->name = el.value("name", "");
474 named_cert_p->cert = el.value("cert", "");
475 named_cert_p->uuid = el.value("uuid", "");
476 named_cert_p->display_mode = el.value("display_mode", "");
477 named_cert_p->perm = (PERM)(util::get_non_string_json_value<uint32_t>(el, "perm", (uint32_t)PERM::_all)) & PERM::_all;
478 named_cert_p->enable_legacy_ordering = el.value("enable_legacy_ordering", true);
479 named_cert_p->allow_client_commands = el.value("allow_client_commands", true);
480 named_cert_p->always_use_virtual_display = el.value("always_use_virtual_display", false);
481 // Load command entries for "do" and "undo" keys.
482 named_cert_p->do_cmds = extract_command_entries(el, "do");
483 named_cert_p->undo_cmds = extract_command_entries(el, "undo");
484 client.named_devices.emplace_back(named_cert_p);
485 }
486 }
487
488 // Clear any existing certificate chain and add the imported certificates.
489 cert_chain.clear();
490 for (auto &named_cert : client.named_devices) {
491 cert_chain.add(named_cert);
492 }
493
494 client_root = client;
495 }
496
497 void add_authorized_client(const p_named_cert_t& named_cert_p) {
498 client_t &client = client_root;
499 client.named_devices.push_back(named_cert_p);
500
501#if defined HERMES_TRAY && HERMES_TRAY >= 1
502 system_tray::update_tray_paired(named_cert_p->name);
503#endif
504
505 if (!config::sunshine.flags[config::flag::FRESH_STATE]) {
506 save_state();
507 load_state();
508 }
509 }
510
511 std::shared_ptr<rtsp_stream::launch_session_t> make_launch_session(bool host_audio, bool input_only, const args_t &args, const crypto::named_cert_t* named_cert_p) {
512 auto launch_session = std::make_shared<rtsp_stream::launch_session_t>();
513
514 launch_session->id = ++session_id_counter;
515
516 // If launched from client
517 if (named_cert_p->uuid != http::unique_id) {
518 auto rikey = util::from_hex_vec(get_arg(args, "rikey"), true);
519 std::copy(rikey.cbegin(), rikey.cend(), std::back_inserter(launch_session->gcm_key));
520
521 launch_session->host_audio = host_audio;
522
523 // Encrypted RTSP is enabled with client reported corever >= 1
524 auto corever = util::from_view(get_arg(args, "corever", "0"));
525 if (corever >= 1) {
526 launch_session->rtsp_cipher = crypto::cipher::gcm_t {
527 launch_session->gcm_key, false
528 };
529 launch_session->rtsp_iv_counter = 0;
530 }
531 launch_session->rtsp_url_scheme = launch_session->rtsp_cipher ? "rtspenc://"s : "rtsp://"s;
532
533 // Generate the unique identifiers for this connection that we will send later during RTSP handshake
534 unsigned char raw_payload[8];
535 RAND_bytes(raw_payload, sizeof(raw_payload));
536 launch_session->av_ping_payload = util::hex_vec(raw_payload);
537 RAND_bytes((unsigned char *) &launch_session->control_connect_data, sizeof(launch_session->control_connect_data));
538
539 launch_session->iv.resize(16);
540 uint32_t prepend_iv = util::endian::big<uint32_t>(util::from_view(get_arg(args, "rikeyid")));
541 auto prepend_iv_p = (uint8_t *) &prepend_iv;
542 std::copy(prepend_iv_p, prepend_iv_p + sizeof(prepend_iv), std::begin(launch_session->iv));
543 }
544
545 std::stringstream mode;
546 if (named_cert_p->display_mode.empty()) {
547 auto mode_str = get_arg(args, "mode", config::video.fallback_mode.c_str());
548 mode = std::stringstream(mode_str);
549 BOOST_LOG(info) << "Display mode for client ["sv << named_cert_p->name <<"] requested to ["sv << mode_str << ']';
550 } else {
551 mode = std::stringstream(named_cert_p->display_mode);
552 BOOST_LOG(info) << "Display mode for client ["sv << named_cert_p->name <<"] overriden to ["sv << named_cert_p->display_mode << ']';
553 }
554
555 // Split mode by the char "x", to populate width/height/fps
556 int x = 0;
557 std::string segment;
558 while (std::getline(mode, segment, 'x')) {
559 if (x == 0) {
560 launch_session->width = atoi(segment.c_str());
561 }
562 if (x == 1) {
563 launch_session->height = atoi(segment.c_str());
564 }
565 if (x == 2) {
566 auto fps = atof(segment.c_str());
567 if (fps < 1000) {
568 fps *= 1000;
569 };
570 launch_session->fps = (int)fps;
571 break;
572 }
573 x++;
574 }
575
576 // Parsing have failed or missing components
577 if (x != 2) {
578 launch_session->width = 1920;
579 launch_session->height = 1080;
580 launch_session->fps = 60000; // 60fps * 1000 denominator
581 }
582
583 launch_session->device_name = named_cert_p->name.empty() ? "HermesDisplay"s : named_cert_p->name;
584 launch_session->unique_id = named_cert_p->uuid;
585 launch_session->perm = named_cert_p->perm;
586 launch_session->enable_sops = util::from_view(get_arg(args, "sops", "0"));
587 launch_session->surround_info = util::from_view(get_arg(args, "surroundAudioInfo", "196610"));
588 launch_session->surround_params = (get_arg(args, "surroundParams", ""));
589 launch_session->gcmap = util::from_view(get_arg(args, "gcmap", "0"));
590 launch_session->enable_hdr = util::from_view(get_arg(args, "hdrMode", "0"));
591 launch_session->virtual_display = util::from_view(get_arg(args, "virtualDisplay", "0")) || named_cert_p->always_use_virtual_display;
592 launch_session->scale_factor = util::from_view(get_arg(args, "scaleFactor", "100"));
593 if (args.find("scaleFactor") != args.end()) {
594 launch_session->client_scale_factor = launch_session->scale_factor;
595 }
596 launch_session->launch_mode = "normal";
597
598 launch_session->client_do_cmds = named_cert_p->do_cmds;
599 launch_session->client_undo_cmds = named_cert_p->undo_cmds;
600
601 launch_session->input_only = input_only;
602
603 return launch_session;
604 }
605
606 void remove_session(const pair_session_t &sess) {
607 std::lock_guard lock {pair_session_mutex};
608 // The argument can itself be owned by map_id_sess. Do not keep a reference
609 // to its identifier while destroying that map element.
610 const std::string unique_id = sess.client.uniqueID;
611 clear_pending_pair(unique_id);
612 map_id_sess.erase(unique_id);
613 }
614
615 bool cancel_pending_pairing(const std::string &unique_id) {
616 std::lock_guard lock {pair_session_mutex};
617 auto it = map_id_sess.find(unique_id);
618 if (it == map_id_sess.end()) {
619 return false;
620 }
621 const std::string id = unique_id;
622 // Release an old request parked waiting for a PIN before replacing it.
623 auto &response = it->second.async_insert_pin.response;
624 const std::string cancelled = "<root status_code=\"409\" status_message=\"Pairing cancelled\"><paired>0</paired></root>";
625 if (response.has_left() && response.left()) {
626 response.left()->close_connection_after_response = true;
627 response.left()->write(cancelled);
628 } else if (response.has_right() && response.right()) {
629 response.right()->close_connection_after_response = true;
630 response.right()->write(cancelled);
631 }
632 clear_pending_pair(id);
633 map_id_sess.erase(it);
634 return true;
635 }
636
638 std::lock_guard lock {pair_session_mutex};
639 const std::string id = session.client.uniqueID;
641 return map_id_sess.emplace(id, std::move(session)).first->second;
642 }
643
644 void fail_pair(pair_session_t &sess, pt::ptree &tree, const std::string status_msg) {
645 tree.put("root.paired", 0);
646 tree.put("root.<xmlattr>.status_code", 400);
647 tree.put("root.<xmlattr>.status_message", status_msg);
648 remove_session(sess); // Security measure, delete the session when something went wrong and force a re-pair
649 BOOST_LOG(warning) << "Pair attempt failed due to " << status_msg;
650 }
651
652 void getservercert(pair_session_t &sess, pt::ptree &tree, const std::string &pin) {
653 if (sess.last_phase != PAIR_PHASE::NONE) {
654 fail_pair(sess, tree, "Out of order call to getservercert");
655 return;
656 }
657 sess.last_phase = PAIR_PHASE::GETSERVERCERT;
658
659 if (sess.async_insert_pin.salt.size() < 32) {
660 fail_pair(sess, tree, "Salt too short");
661 return;
662 }
663
664 std::string_view salt_view {sess.async_insert_pin.salt.data(), 32};
665
666 auto salt = util::from_hex<std::array<uint8_t, 16>>(salt_view, true);
667
668 auto key = crypto::gen_aes_key(salt, pin);
669 sess.cipher_key = std::make_unique<crypto::aes_t>(key);
670
671 tree.put("root.paired", 1);
672 tree.put("root.plaincert", util::hex_vec(conf_intern.servercert, true));
673 tree.put("root.<xmlattr>.status_code", 200);
674 }
675
676 void clientchallenge(pair_session_t &sess, pt::ptree &tree, const std::string &challenge) {
677 if (sess.last_phase != PAIR_PHASE::GETSERVERCERT) {
678 fail_pair(sess, tree, "Out of order call to clientchallenge");
679 return;
680 }
681 sess.last_phase = PAIR_PHASE::CLIENTCHALLENGE;
682
683 if (!sess.cipher_key) {
684 fail_pair(sess, tree, "Cipher key not set");
685 return;
686 }
687 crypto::cipher::ecb_t cipher(*sess.cipher_key, false);
688
689 std::vector<uint8_t> decrypted;
690 cipher.decrypt(challenge, decrypted);
691
692 auto x509 = crypto::x509(conf_intern.servercert);
693 auto sign = crypto::signature(x509);
694 auto serversecret = crypto::rand(16);
695
696 decrypted.insert(std::end(decrypted), std::begin(sign), std::end(sign));
697 decrypted.insert(std::end(decrypted), std::begin(serversecret), std::end(serversecret));
698
699 auto hash = crypto::hash({(char *) decrypted.data(), decrypted.size()});
700 auto serverchallenge = crypto::rand(16);
701
702 std::string plaintext;
703 plaintext.reserve(hash.size() + serverchallenge.size());
704
705 plaintext.insert(std::end(plaintext), std::begin(hash), std::end(hash));
706 plaintext.insert(std::end(plaintext), std::begin(serverchallenge), std::end(serverchallenge));
707
708 std::vector<uint8_t> encrypted;
709 cipher.encrypt(plaintext, encrypted);
710
711 sess.serversecret = std::move(serversecret);
712 sess.serverchallenge = std::move(serverchallenge);
713
714 tree.put("root.paired", 1);
715 tree.put("root.challengeresponse", util::hex_vec(encrypted, true));
716 tree.put("root.<xmlattr>.status_code", 200);
717 }
718
719 void serverchallengeresp(pair_session_t &sess, pt::ptree &tree, const std::string &encrypted_response) {
720 if (sess.last_phase != PAIR_PHASE::CLIENTCHALLENGE) {
721 fail_pair(sess, tree, "Out of order call to serverchallengeresp");
722 return;
723 }
724 sess.last_phase = PAIR_PHASE::SERVERCHALLENGERESP;
725
726 if (!sess.cipher_key || sess.serversecret.empty()) {
727 fail_pair(sess, tree, "Cipher key or serversecret not set");
728 return;
729 }
730
731 std::vector<uint8_t> decrypted;
732 crypto::cipher::ecb_t cipher(*sess.cipher_key, false);
733
734 cipher.decrypt(encrypted_response, decrypted);
735
736 sess.clienthash = std::move(decrypted);
737
738 auto serversecret = sess.serversecret;
739 auto sign = crypto::sign256(crypto::pkey(conf_intern.pkey), serversecret);
740
741 serversecret.insert(std::end(serversecret), std::begin(sign), std::end(sign));
742
743 tree.put("root.pairingsecret", util::hex_vec(serversecret, true));
744 tree.put("root.paired", 1);
745 tree.put("root.<xmlattr>.status_code", 200);
746 }
747
748 void clientpairingsecret(pair_session_t &sess, pt::ptree &tree, const std::string &client_pairing_secret) {
749 if (sess.last_phase != PAIR_PHASE::SERVERCHALLENGERESP) {
750 fail_pair(sess, tree, "Out of order call to clientpairingsecret");
751 return;
752 }
753 sess.last_phase = PAIR_PHASE::CLIENTPAIRINGSECRET;
754
755 auto &client = sess.client;
756
757 if (client_pairing_secret.size() <= 16) {
758 fail_pair(sess, tree, "Client pairing secret too short");
759 return;
760 }
761
762 std::string_view secret {client_pairing_secret.data(), 16};
763 std::string_view sign {client_pairing_secret.data() + secret.size(), client_pairing_secret.size() - secret.size()};
764
765 auto x509 = crypto::x509(client.cert);
766 if (!x509) {
767 fail_pair(sess, tree, "Invalid client certificate");
768 return;
769 }
770 auto x509_sign = crypto::signature(x509);
771
772 std::string data;
773 data.reserve(sess.serverchallenge.size() + x509_sign.size() + secret.size());
774
775 data.insert(std::end(data), std::begin(sess.serverchallenge), std::end(sess.serverchallenge));
776 data.insert(std::end(data), std::begin(x509_sign), std::end(x509_sign));
777 data.insert(std::end(data), std::begin(secret), std::end(secret));
778
779 auto hash = crypto::hash(data);
780
781 // if hash not correct, probably MITM
782 bool same_hash = hash.size() == sess.clienthash.size() && std::equal(hash.begin(), hash.end(), sess.clienthash.begin());
783 auto verify = crypto::verify256(crypto::x509(client.cert), secret, sign);
784 if (same_hash && verify) {
785 tree.put("root.paired", 1);
786
787 auto named_cert_p = std::make_shared<crypto::named_cert_t>();
788 named_cert_p->name = client.name;
789 for (char& c : named_cert_p->name) {
790 if (c == '(') c = '[';
791 else if (c == ')') c = ']';
792 }
793 named_cert_p->cert = std::move(client.cert);
794 named_cert_p->uuid = uuid_util::uuid_t::generate().string();
795 // If the device is the first one paired with the server, assign full permission.
796 if (client_root.named_devices.empty()) {
797 named_cert_p->perm = PERM::_all;
798 } else {
799 named_cert_p->perm = PERM::_default;
800 }
801
802 named_cert_p->enable_legacy_ordering = true;
803 named_cert_p->allow_client_commands = true;
804 named_cert_p->always_use_virtual_display = false;
805
806 // Keep sess alive until the single remove_session() below. Erasing it
807 // here made that later cleanup dereference a destroyed map value.
808 add_authorized_client(named_cert_p);
809 } else {
810 tree.put("root.paired", 0);
811 BOOST_LOG(warning) << "Pair attempt failed due to same_hash: " << same_hash << ", verify: " << verify;
812 }
813
814 remove_session(sess);
815 tree.put("root.<xmlattr>.status_code", 200);
816 }
817
818 template<class T>
819 struct tunnel;
820
821 template<>
823 static auto constexpr to_string = "HTTPS"sv;
824 };
825
826 template<>
827 struct tunnel<SimpleWeb::HTTP> {
828 static auto constexpr to_string = "NONE"sv;
829 };
830
831 inline crypto::named_cert_t* get_verified_cert(req_https_t request) {
832 return (crypto::named_cert_t*)request->userp.get();
833 }
834
835 template <class T>
836 void print_req(std::shared_ptr<typename SimpleWeb::ServerBase<T>::Request> request) {
837 BOOST_LOG(debug) << "TUNNEL :: "sv << tunnel<T>::to_string;
838
839 BOOST_LOG(debug) << "METHOD :: "sv << request->method;
840 BOOST_LOG(debug) << "DESTINATION :: "sv << request->path;
841
842 for (auto &[name, val] : request->header) {
843 BOOST_LOG(debug) << name << " -- " << val;
844 }
845
846 BOOST_LOG(debug) << " [--] "sv;
847
848 for (auto &[name, val] : request->parse_query_string()) {
849 BOOST_LOG(debug) << name << " -- " << val;
850 }
851
852 BOOST_LOG(debug) << " [--] "sv;
853 }
854
855 template<class T>
856 void not_found(std::shared_ptr<typename SimpleWeb::ServerBase<T>::Response> response, std::shared_ptr<typename SimpleWeb::ServerBase<T>::Request> request) {
857 print_req<T>(request);
858
859 pt::ptree tree;
860 tree.put("root.<xmlattr>.status_code", 404);
861
862 std::ostringstream data;
863
864 pt::write_xml(data, tree);
865 response->write(SimpleWeb::StatusCode::client_error_not_found, data.str());
866 response->close_connection_after_response = true;
867 }
868
869 template <class T>
870 void pair(std::shared_ptr<typename SimpleWeb::ServerBase<T>::Response> response, std::shared_ptr<typename SimpleWeb::ServerBase<T>::Request> request) {
871 std::lock_guard lock {pair_session_mutex};
872
873 pt::ptree tree;
874
875 auto fg = util::fail_guard([&]() {
876 std::ostringstream data;
877
878 pt::write_xml(data, tree);
879 response->write(data.str());
880 response->close_connection_after_response = true;
881 });
882
883 if (!config::sunshine.enable_pairing) {
884 tree.put("root.<xmlattr>.status_code", 403);
885 tree.put("root.<xmlattr>.status_message", "Pairing is disabled for this instance");
886
887 return;
888 }
889
890 auto args = request->parse_query_string();
891 if (args.find("uniqueid"s) == std::end(args)) {
892 tree.put("root.<xmlattr>.status_code", 400);
893 tree.put("root.<xmlattr>.status_message", "Missing uniqueid parameter");
894
895 return;
896 }
897
898 auto uniqID {get_arg(args, "uniqueid")};
899
900 args_t::const_iterator it;
901 if (it = args.find("phrase"); it != std::end(args)) {
902 if (it->second == "getservercert"sv) {
903 pair_session_t sess;
904
905 auto deviceName { get_arg(args, "devicename") };
906
907 if (deviceName == "roth"sv) {
908 deviceName = "Legacy Moonlight Client";
909 }
910
911 sess.client.uniqueID = std::move(uniqID);
912 sess.client.name = std::move(deviceName);
913 sess.client.cert = util::from_hex_vec(get_arg(args, "clientcert"), true);
914
915 auto &new_session = begin_pairing_session(std::move(sess));
916
917 new_session.async_insert_pin.salt = std::move(get_arg(args, "salt"));
918
919 auto it = args.find("otpauth");
920 if (it != std::end(args)) {
921 if (one_time_pin.empty() || (std::chrono::steady_clock::now() - otp_creation_time > OTP_EXPIRE_DURATION)) {
922 one_time_pin.clear();
923 otp_passphrase.clear();
924 otp_device_name.clear();
925 tree.put("root.<xmlattr>.status_code", 503);
926 tree.put("root.<xmlattr>.status_message", "OTP auth not available.");
927 } else {
928 auto hash = util::hex(crypto::hash(one_time_pin + new_session.async_insert_pin.salt + otp_passphrase), true);
929
930 if (hash.to_string_view() == it->second) {
931
932 if (!otp_device_name.empty()) {
933 new_session.client.name = std::move(otp_device_name);
934 }
935
936 getservercert(new_session, tree, one_time_pin);
937
938 one_time_pin.clear();
939 otp_passphrase.clear();
940 otp_device_name.clear();
941 return;
942 }
943 }
944
945 // Always return positive, attackers will fail in the next steps.
946 getservercert(new_session, tree, crypto::rand(16));
947 return;
948 }
949
950 if (config::sunshine.flags[config::flag::PIN_STDIN]) {
951 std::string pin;
952
953 std::cout << "Please insert pin: "sv;
954 std::getline(std::cin, pin);
955
956 getservercert(new_session, tree, pin);
957 } else {
958#if defined HERMES_TRAY && HERMES_TRAY >= 1
960#endif
961 set_pending_pair(new_session.client.uniqueID, new_session.client.name);
962 new_session.async_insert_pin.response = std::move(response);
963
964 fg.disable();
965 return;
966 }
967 } else if (it->second == "pairchallenge"sv) {
968 tree.put("root.paired", 1);
969 tree.put("root.<xmlattr>.status_code", 200);
970 return;
971 }
972 }
973
974 auto sess_it = map_id_sess.find(uniqID);
975 if (sess_it == std::end(map_id_sess)) {
976 tree.put("root.<xmlattr>.status_code", 400);
977 tree.put("root.<xmlattr>.status_message", "Invalid uniqueid");
978
979 return;
980 }
981
982 if (it = args.find("clientchallenge"); it != std::end(args)) {
983 auto challenge = util::from_hex_vec(it->second, true);
984 clientchallenge(sess_it->second, tree, challenge);
985 } else if (it = args.find("serverchallengeresp"); it != std::end(args)) {
986 auto encrypted_response = util::from_hex_vec(it->second, true);
987 serverchallengeresp(sess_it->second, tree, encrypted_response);
988 } else if (it = args.find("clientpairingsecret"); it != std::end(args)) {
989 auto pairingsecret = util::from_hex_vec(it->second, true);
990 clientpairingsecret(sess_it->second, tree, pairingsecret);
991 } else {
992 tree.put("root.<xmlattr>.status_code", 404);
993 tree.put("root.<xmlattr>.status_message", "Invalid pairing request");
994 }
995 }
996
997 void cancel_pairing_request(std::shared_ptr<SimpleWeb::ServerBase<SimpleWeb::HTTP>::Response> response,
998 std::shared_ptr<SimpleWeb::ServerBase<SimpleWeb::HTTP>::Request> request) {
999 auto args = request->parse_query_string();
1000 pt::ptree tree;
1001 auto id = args.find("uniqueid");
1002 if (id == args.end() || id->second.empty()) {
1003 tree.put("root.<xmlattr>.status_code", 400);
1004 tree.put("root.<xmlattr>.status_message", "Missing uniqueid parameter");
1005 } else {
1006 // Unauthenticated legacy /unpair cancels only the pending handshake.
1007 // Revoking a trusted certificate still requires the authenticated Web UI.
1008 cancel_pending_pairing(id->second);
1009 tree.put("root.<xmlattr>.status_code", 200);
1010 tree.put("root.paired", 0);
1011 }
1012 std::ostringstream data;
1013 pt::write_xml(data, tree);
1014 response->write(data.str());
1015 response->close_connection_after_response = true;
1016 }
1017
1018 std::optional<std::string> pending_pair_client() {
1019 std::lock_guard lock {pending_pair_mutex};
1020 if (pending_pairs.empty()) {
1021 return std::nullopt;
1022 }
1023 return pending_pairs.begin()->second;
1024 }
1025
1026 bool pin(std::string pin, std::string name) {
1027 std::lock_guard lock {pair_session_mutex};
1028 pt::ptree tree;
1029 if (map_id_sess.empty()) {
1030 return false;
1031 }
1032
1033 // ensure pin is 4 digits
1034 if (pin.size() != 4) {
1035 tree.put("root.paired", 0);
1036 tree.put("root.<xmlattr>.status_code", 400);
1037 tree.put(
1038 "root.<xmlattr>.status_message",
1039 std::format("Pin must be 4 digits, {} provided", pin.size())
1040 );
1041 return false;
1042 }
1043
1044 // ensure all pin characters are numeric
1045 if (!std::all_of(pin.begin(), pin.end(), ::isdigit)) {
1046 tree.put("root.paired", 0);
1047 tree.put("root.<xmlattr>.status_code", 400);
1048 tree.put("root.<xmlattr>.status_message", "Pin must be numeric");
1049 return false;
1050 }
1051
1052 // A previous client can still be exchanging challenges. Submit the PIN
1053 // only to a request actually waiting for it, not an arbitrary map entry.
1054 auto pending = std::find_if(map_id_sess.begin(), map_id_sess.end(), [](const auto &entry) {
1055 const auto &session = entry.second;
1056 const auto &response = session.async_insert_pin.response;
1057 return session.last_phase == PAIR_PHASE::NONE &&
1058 ((response.has_left() && response.left()) || (response.has_right() && response.right()));
1059 });
1060 if (pending == map_id_sess.end()) {
1061 return false;
1062 }
1063 auto &sess = pending->second;
1064 clear_pending_pair(sess.client.uniqueID);
1065 if (!name.empty()) {
1066 sess.client.name = name;
1067 }
1068 // getservercert() can reject and erase sess. Keep the waiting response
1069 // independently so both the success and rejection paths can reply safely.
1070 auto async_response = std::move(sess.async_insert_pin.response);
1071 sess.async_insert_pin.response = std::decay_t<decltype(async_response.left())>();
1072 getservercert(sess, tree, pin);
1073
1074 // response to the request for pin
1075 std::ostringstream data;
1076 pt::write_xml(data, tree);
1077
1078 if (async_response.has_left() && async_response.left()) {
1079 async_response.left()->write(data.str());
1080 } else if (async_response.has_right() && async_response.right()) {
1081 async_response.right()->write(data.str());
1082 } else {
1083 return false;
1084 }
1085
1086 // response to the current request
1087 return true;
1088 }
1089
1090 template<class T>
1091 void serverinfo(std::shared_ptr<typename SimpleWeb::ServerBase<T>::Response> response, std::shared_ptr<typename SimpleWeb::ServerBase<T>::Request> request) {
1092 print_req<T>(request);
1093
1094 int pair_status = 0;
1095 if constexpr (std::is_same_v<SunshineHTTPS, T>) {
1096 auto args = request->parse_query_string();
1097 auto clientID = args.find("uniqueid"s);
1098
1099 if (clientID != std::end(args)) {
1100 pair_status = 1;
1101 }
1102 }
1103
1104 auto local_endpoint = request->local_endpoint();
1105
1106 pt::ptree tree;
1107
1108 tree.put("root.<xmlattr>.status_code", 200);
1109 tree.put("root.hostname", config::nvhttp.sunshine_name);
1110
1111 tree.put("root.appversion", VERSION);
1112 tree.put("root.GfeVersion", GFE_VERSION);
1113 tree.put("root.uniqueid", http::unique_id);
1114 tree.put("root.HttpsPort", net::map_port(PORT_HTTPS));
1115 tree.put("root.ExternalPort", net::map_port(PORT_HTTP));
1116 tree.put("root.MaxLumaPixelsHEVC", video::active_hevc_mode > 1 ? "1869449984" : "0");
1117
1118 // Only include the MAC address for requests sent from paired clients over HTTPS.
1119 // For HTTP requests, use a placeholder MAC address that Moonlight knows to ignore.
1120 if constexpr (std::is_same_v<SunshineHTTPS, T>) {
1121 tree.put("root.mac", platf::get_mac_address(net::addr_to_normalized_string(local_endpoint.address())));
1122
1123 auto named_cert_p = get_verified_cert(request);
1124 if (!!(named_cert_p->perm & PERM::server_cmd)) {
1125 pt::ptree& root_node = tree.get_child("root");
1126
1127 if (config::sunshine.server_cmds.size() > 0) {
1128 // Broadcast server_cmds
1129 for (const auto& cmd : config::sunshine.server_cmds) {
1130 pt::ptree cmd_node;
1131 cmd_node.put_value(cmd.cmd_name);
1132 root_node.push_back(std::make_pair("ServerCommand", cmd_node));
1133 }
1134 }
1135 } else {
1136 BOOST_LOG(debug) << "Permission Get ServerCommand denied for [" << named_cert_p->name << "] (" << (uint32_t)named_cert_p->perm << ")";
1137 }
1138
1139 tree.put("root.Permission", std::to_string((uint32_t)named_cert_p->perm));
1140
1141 tree.put("root.VirtualDisplayCapable", true);
1142 if (!!(named_cert_p->perm & PERM::_all_actions)) {
1143 tree.put("root.VirtualDisplayDriverReady", proc::vDisplayDriverStatus == VDISPLAY::DRIVER_STATUS::OK);
1144 } else {
1145 tree.put("root.VirtualDisplayDriverReady", true);
1146 }
1147 } else {
1148 tree.put("root.mac", "00:00:00:00:00:00");
1149 tree.put("root.Permission", "0");
1150 }
1151
1152 // Moonlight clients track LAN IPv6 addresses separately from LocalIP which is expected to
1153 // always be an IPv4 address. If we return that same IPv6 address here, it will clobber the
1154 // stored LAN IPv4 address. To avoid this, we need to return an IPv4 address in this field
1155 // when we get a request over IPv6.
1156 //
1157 // HACK: We should return the IPv4 address of local interface here, but we don't currently
1158 // have that implemented. For now, we will emulate the behavior of GFE+GS-IPv6-Forwarder,
1159 // which returns 127.0.0.1 as LocalIP for IPv6 connections. Moonlight clients with IPv6
1160 // support know to ignore this bogus address.
1161 if (local_endpoint.address().is_v6() && !local_endpoint.address().to_v6().is_v4_mapped()) {
1162 tree.put("root.LocalIP", "127.0.0.1");
1163 } else {
1164 tree.put("root.LocalIP", net::addr_to_normalized_string(local_endpoint.address()));
1165 }
1166
1167 uint32_t codec_mode_flags = SCM_H264;
1168 if (video::last_encoder_probe_supported_yuv444_for_codec[0]) {
1169 codec_mode_flags |= SCM_H264_HIGH8_444;
1170 }
1171 if (video::active_hevc_mode >= 2) {
1172 codec_mode_flags |= SCM_HEVC;
1173 if (video::last_encoder_probe_supported_yuv444_for_codec[1]) {
1174 codec_mode_flags |= SCM_HEVC_REXT8_444;
1175 }
1176 }
1177 if (video::active_hevc_mode >= 3) {
1178 codec_mode_flags |= SCM_HEVC_MAIN10;
1179 if (video::last_encoder_probe_supported_yuv444_for_codec[1]) {
1180 codec_mode_flags |= SCM_HEVC_REXT10_444;
1181 }
1182 }
1183 if (video::active_av1_mode >= 2) {
1184 codec_mode_flags |= SCM_AV1_MAIN8;
1185 if (video::last_encoder_probe_supported_yuv444_for_codec[2]) {
1186 codec_mode_flags |= SCM_AV1_HIGH8_444;
1187 }
1188 }
1189 if (video::active_av1_mode >= 3) {
1190 codec_mode_flags |= SCM_AV1_MAIN10;
1191 if (video::last_encoder_probe_supported_yuv444_for_codec[2]) {
1192 codec_mode_flags |= SCM_AV1_HIGH10_444;
1193 }
1194 }
1195 if (config::video.pyrowave && video::pyrowave_available()) {
1196 codec_mode_flags |= video::PYROWAVE_SERVER_CODEC_MODE;
1197 }
1198 tree.put("root.ServerCodecModeSupport", codec_mode_flags);
1199
1200 tree.put("root.PairStatus", pair_status);
1201
1202 if constexpr (std::is_same_v<SunshineHTTPS, T>) {
1203 auto named_cert_p = get_verified_cert(request);
1204 const bool isolated_sessions = experimental_isolated_sessions_enabled();
1205 const auto isolated_appid = isolated_sessions ?
1206 proc::proc.running_for_client(named_cert_p->uuid) :
1207 0;
1208 int current_appid = isolated_appid > 0 ?
1209 isolated_appid :
1210 proc::proc.running();
1211 // When input only mode is enabled, the only resume method should be launching the same app again.
1212 if (config::input.enable_input_only_mode && current_appid != proc::input_only_app_id) {
1213 current_appid = 0;
1214 }
1215 tree.put("root.currentgame", current_appid);
1216 tree.put(
1217 "root.currentgameuuid",
1218 isolated_appid > 0 ?
1219 proc::proc.running_app_uuid_for_client(named_cert_p->uuid) :
1220 proc::proc.get_running_app_uuid()
1221 );
1222 tree.put("root.state", current_appid > 0 ? "SUNSHINE_SERVER_BUSY" : "SUNSHINE_SERVER_FREE");
1223 } else {
1224 tree.put("root.currentgame", 0);
1225 tree.put("root.currentgameuuid", "");
1226 tree.put("root.state", "SUNSHINE_SERVER_FREE");
1227 }
1228
1229 std::ostringstream data;
1230
1231 pt::write_xml(data, tree);
1232 response->write(data.str());
1233 response->close_connection_after_response = true;
1234 }
1235
1236 nlohmann::json get_all_clients() {
1237 nlohmann::json named_cert_nodes = nlohmann::json::array();
1238 client_t &client = client_root;
1239 std::list<std::string> connected_uuids = rtsp_stream::get_all_session_uuids();
1240
1241 for (auto &named_cert : client.named_devices) {
1242 nlohmann::json named_cert_node;
1243 named_cert_node["name"] = named_cert->name;
1244 named_cert_node["uuid"] = named_cert->uuid;
1245 named_cert_node["display_mode"] = named_cert->display_mode;
1246 named_cert_node["perm"] = static_cast<uint32_t>(named_cert->perm);
1247 named_cert_node["enable_legacy_ordering"] = named_cert->enable_legacy_ordering;
1248 named_cert_node["allow_client_commands"] = named_cert->allow_client_commands;
1249 named_cert_node["always_use_virtual_display"] = named_cert->always_use_virtual_display;
1250
1251 // Add "do" commands if available
1252 if (!named_cert->do_cmds.empty()) {
1253 nlohmann::json do_cmds_node = nlohmann::json::array();
1254 for (const auto &cmd : named_cert->do_cmds) {
1255 do_cmds_node.push_back(crypto::command_entry_t::serialize(cmd));
1256 }
1257 named_cert_node["do"] = do_cmds_node;
1258 }
1259
1260 // Add "undo" commands if available
1261 if (!named_cert->undo_cmds.empty()) {
1262 nlohmann::json undo_cmds_node = nlohmann::json::array();
1263 for (const auto &cmd : named_cert->undo_cmds) {
1264 undo_cmds_node.push_back(crypto::command_entry_t::serialize(cmd));
1265 }
1266 named_cert_node["undo"] = undo_cmds_node;
1267 }
1268
1269 // Determine connection status
1270 bool connected = false;
1271 if (connected_uuids.empty()) {
1272 connected = false;
1273 } else {
1274 for (auto it = connected_uuids.begin(); it != connected_uuids.end(); ++it) {
1275 if (*it == named_cert->uuid) {
1276 connected = true;
1277 connected_uuids.erase(it);
1278 break;
1279 }
1280 }
1281 }
1282 named_cert_node["connected"] = connected;
1283
1284 named_cert_nodes.push_back(named_cert_node);
1285 }
1286
1287 return named_cert_nodes;
1288 }
1289
1290 void applist(resp_https_t response, req_https_t request) {
1291 print_req<SunshineHTTPS>(request);
1292
1293 pt::ptree tree;
1294
1295 auto g = util::fail_guard([&]() {
1296 std::ostringstream data;
1297
1298 pt::write_xml(data, tree);
1299 response->write(data.str());
1300 response->close_connection_after_response = true;
1301 });
1302
1303 auto &apps = tree.add_child("root", pt::ptree {});
1304
1305 apps.put("<xmlattr>.status_code", 200);
1306
1307 auto named_cert_p = get_verified_cert(request);
1308 if (!!(named_cert_p->perm & PERM::_all_actions)) {
1309 const auto isolated_appid = experimental_isolated_sessions_enabled() ?
1310 proc::proc.running_for_client(named_cert_p->uuid) :
1311 0;
1312 auto current_appid = isolated_appid > 0 ?
1313 isolated_appid :
1314 proc::proc.running();
1315 auto should_hide_inactive_apps = config::input.enable_input_only_mode && current_appid > 0 && current_appid != proc::input_only_app_id;
1316
1317 auto app_list = proc::proc.get_apps();
1318
1319 bool enable_legacy_ordering = config::sunshine.legacy_ordering && named_cert_p->enable_legacy_ordering;
1320 size_t bits;
1321 if (enable_legacy_ordering) {
1322 bits = zwpad::pad_width_for_count(app_list.size());
1323 }
1324
1325 for (size_t i = 0; i < app_list.size(); i++) {
1326 auto& app = app_list[i];
1327 auto appid = util::from_view(app.id);
1328 if (should_hide_inactive_apps) {
1329 if (
1330 appid != current_appid
1331 && appid != proc::input_only_app_id
1332 && appid != proc::terminate_app_id
1333 ) {
1334 continue;
1335 }
1336 } else {
1337 if (appid == proc::terminate_app_id) {
1338 continue;
1339 }
1340 }
1341
1342 std::string app_name;
1343 if (enable_legacy_ordering) {
1344 app_name = zwpad::pad_for_ordering(app.name, bits, i);
1345 } else {
1346 app_name = app.name;
1347 }
1348
1349 pt::ptree app_node;
1350
1351 app_node.put("IsHdrSupported"s, video::active_hevc_mode == 3 ? 1 : 0);
1352 app_node.put("AppTitle"s, app_name);
1353 app_node.put("UUID", app.uuid);
1354 app_node.put("IDX", app.idx);
1355 app_node.put("ID", app.id);
1356
1357 apps.push_back(std::make_pair("App", std::move(app_node)));
1358 }
1359 } else {
1360 BOOST_LOG(debug) << "Permission ListApp denied for [" << named_cert_p->name << "] (" << (uint32_t)named_cert_p->perm << ")";
1361
1362 pt::ptree app_node;
1363
1364 app_node.put("IsHdrSupported"s, 0);
1365 app_node.put("AppTitle"s, "Permission Denied");
1366 app_node.put("UUID", "");
1367 app_node.put("IDX", "0");
1368 app_node.put("ID", "114514");
1369
1370 apps.push_back(std::make_pair("App", std::move(app_node)));
1371
1372 return;
1373 }
1374
1375 }
1376
1377 void launch(bool &host_audio, resp_https_t response, req_https_t request) {
1378 print_req<SunshineHTTPS>(request);
1379
1380 pt::ptree tree;
1381 auto g = util::fail_guard([&]() {
1382 std::ostringstream data;
1383
1384 pt::write_xml(data, tree);
1385 response->write(data.str());
1386 response->close_connection_after_response = true;
1387 });
1388
1389 auto args = request->parse_query_string();
1390
1391 auto appid_str = get_arg(args, "appid", "0");
1392 auto appuuid_str = get_arg(args, "appuuid", "");
1393 auto appid = util::from_view(appid_str);
1394 auto named_cert_p = get_verified_cert(request);
1395 const bool isolated_sessions = experimental_isolated_sessions_enabled();
1396
1397 const auto host_current_appid = proc::proc.running();
1398 const auto host_current_app_uuid = proc::proc.get_running_app_uuid();
1399 const auto isolated_current_appid = isolated_sessions ?
1400 proc::proc.running_for_client(named_cert_p->uuid) :
1401 0;
1402 const auto isolated_current_app_uuid = isolated_sessions ?
1403 proc::proc.running_app_uuid_for_client(named_cert_p->uuid) :
1404 std::string {};
1405
1406 bool is_input_only =
1407 config::input.enable_input_only_mode &&
1408 (appid == proc::input_only_app_id || appuuid_str == REMOTE_INPUT_UUID);
1409
1410 const proc::ctx_t *requested_app = nullptr;
1411 if (!is_input_only && (appid > 0 || !appuuid_str.empty())) {
1412 const auto &apps = proc::proc.get_apps();
1413 const auto app_iter = std::find_if(
1414 apps.begin(),
1415 apps.end(),
1416 [&appid_str, &appuuid_str](const auto &app) {
1417 return app.id == appid_str || app.uuid == appuuid_str;
1418 }
1419 );
1420 if (app_iter != apps.end()) {
1421 requested_app = &*app_iter;
1422 }
1423 }
1424
1425 auto perm = PERM::launch;
1426
1427 BOOST_LOG(verbose) << "Launching app [" << appid_str << "] with UUID [" << appuuid_str << "]";
1428 // BOOST_LOG(verbose) << "QS: " << request->query_string;
1429
1430 // Before Hestia one-shot state is consumed, only relax launch permission
1431 // when this app cannot become isolated. Assume a virtual display, because
1432 // Hestia may still request one.
1433 bool permission_isolated = false;
1434 if (requested_app) {
1435 permission_isolated =
1437 *requested_app,
1438 isolated_sessions,
1439 true,
1440 config::video.isolation_method
1441 ) != proc::session_route_e::shared;
1442 }
1443
1444 const auto permission_current_appid =
1445 permission_isolated ? isolated_current_appid : host_current_appid;
1446 const auto &permission_current_app_uuid =
1447 permission_isolated ? isolated_current_app_uuid : host_current_app_uuid;
1448
1449 if (
1450 !permission_isolated
1451 && permission_current_appid > 0
1452 && (appuuid_str != TERMINATE_APP_UUID || appid != proc::terminate_app_id)
1453 && (
1454 is_input_only
1455 || appid == permission_current_appid
1456 || (!appuuid_str.empty() && appuuid_str == permission_current_app_uuid)
1457 )
1458 ) {
1459 perm = PERM::_allow_view;
1460 }
1461
1462 if (!(named_cert_p->perm & perm)) {
1463 BOOST_LOG(debug) << "Permission LaunchApp denied for [" << named_cert_p->name << "] (" << (uint32_t)named_cert_p->perm << ")";
1464
1465 tree.put("root.resume", 0);
1466 tree.put("root.<xmlattr>.status_code", 403);
1467 tree.put("root.<xmlattr>.status_message", "Permission denied");
1468
1469 return;
1470 }
1471 if (
1472 args.find("rikey"s) == std::end(args) ||
1473 args.find("rikeyid"s) == std::end(args) ||
1474 args.find("localAudioPlayMode"s) == std::end(args) ||
1475 (args.find("appid"s) == std::end(args) && args.find("appuuid"s) == std::end(args))
1476 ) {
1477 tree.put("root.resume", 0);
1478 tree.put("root.<xmlattr>.status_code", 400);
1479 tree.put("root.<xmlattr>.status_message", "Missing a required launch parameter");
1480
1481 return;
1482 }
1483
1484 if (!is_input_only) {
1485 // Special handling for the "terminate" app
1486 if (
1487 (config::input.enable_input_only_mode && appid == proc::terminate_app_id)
1488 || appuuid_str == TERMINATE_APP_UUID
1489 ) {
1490 const auto stream_route =
1491 rtsp_stream::session_is_isolated(named_cert_p->uuid);
1492 const bool terminate_isolated =
1493 stream_route.value_or(
1494 isolated_sessions &&
1495 proc::proc.isolated_client_present(named_cert_p->uuid)
1496 );
1497
1498 rtsp_stream::cancel_pending_launch(named_cert_p->uuid);
1499 BOOST_LOG(info) << "Client " << named_cert_p->name << " launched Terminate" << (terminate_isolated ? " for its isolated session." : ".");
1500 if (terminate_isolated) {
1501 rtsp_stream::terminate_session(named_cert_p->uuid);
1502 proc::proc.terminate_isolated_client(named_cert_p->uuid);
1503 } else {
1504 proc::proc.terminate();
1505 }
1506
1507 tree.put("root.resume", 0);
1508 tree.put("root.<xmlattr>.status_code", 410);
1509 tree.put("root.<xmlattr>.status_message", "App terminated.");
1510
1511 return;
1512 }
1513
1514 }
1515
1516 host_audio = util::from_view(get_arg(args, "localAudioPlayMode"));
1517 auto launch_session = make_launch_session(host_audio, is_input_only, args, named_cert_p);
1518 if (!is_input_only) {
1519 if (const auto hestia_prepare = take_hestia_session_prepare(named_cert_p->uuid)) {
1520 launch_session->width = hestia_prepare->width;
1521 launch_session->height = hestia_prepare->height;
1522 launch_session->fps = hestia_prepare->fps * 1000;
1523 launch_session->enable_hdr = hestia_prepare->hdr;
1524 launch_session->virtual_display = hestia_prepare->virtual_display;
1525 launch_session->client_virtual_display = hestia_prepare->virtual_display;
1526 launch_session->scale_factor = hestia_prepare->scale_factor;
1527 launch_session->client_scale_factor = static_cast<int>(hestia_prepare->scale_factor);
1528 launch_session->launch_mode = hestia_prepare->launch_mode;
1529 BOOST_LOG(info) << "[HestiaAPI] applying prepared session for client " << named_cert_p->uuid
1530 << ": " << launch_session->width << 'x' << launch_session->height
1531 << '@' << hestia_prepare->fps << "Hz virtual_display=" << launch_session->virtual_display
1532 << " launch_mode=" << launch_session->launch_mode;
1533 }
1534 }
1535
1536 auto session_route = proc::session_route_e::shared;
1537 if (requested_app) {
1538 const auto decision = proc::decide_virtual_display(
1539 *requested_app,
1540 *launch_session,
1541 config::video.headless_mode
1542 );
1543 if (launch_session->client_virtual_display && decision.use != *launch_session->client_virtual_display) {
1544 BOOST_LOG(info) << "[Settings] Virtual display " << (decision.use ? "on" : "off") << " for ["
1545 << requested_app->name << "]: the client asked for "
1546 << (*launch_session->client_virtual_display ? "on" : "off") << ", but "
1547 << proc::describe(decision.source) << '.';
1548 } else {
1549 BOOST_LOG(info) << "[Settings] Virtual display " << (decision.use ? "on" : "off") << " for ["
1550 << requested_app->name << "]: " << proc::describe(decision.source) << '.';
1551 }
1552 launch_session->virtual_display = decision.use;
1553 launch_session->virtual_display_decided = true;
1554 const auto scale = proc::decide_scale_factor(*requested_app, *launch_session, config::video.default_scale_factor);
1555 if (launch_session->client_scale_factor && scale.percent != *launch_session->client_scale_factor) {
1556 BOOST_LOG(info) << "[Settings] Resolution scale " << scale.percent << "% for [" << requested_app->name
1557 << "]: the client asked for " << *launch_session->client_scale_factor << "%, but "
1558 << proc::describe(scale.source) << '.';
1559 } else {
1560 BOOST_LOG(info) << "[Settings] Resolution scale " << scale.percent << "% for [" << requested_app->name
1561 << "]: " << proc::describe(scale.source) << '.';
1562 }
1563 const bool virtual_display_requested = decision.use;
1564 session_route = proc::resolve_session_route(
1565 *requested_app,
1566 isolated_sessions,
1567 virtual_display_requested,
1568 config::video.isolation_method
1569 );
1570 }
1571
1572 const bool isolated_launch =
1573 session_route != proc::session_route_e::shared;
1574
1575 const auto current_appid =
1576 isolated_launch ? isolated_current_appid : host_current_appid;
1577 const auto &current_app_uuid =
1578 isolated_launch ? isolated_current_app_uuid : host_current_app_uuid;
1579
1580 if (
1581 !is_input_only
1582 && !isolated_launch
1583 && host_current_appid > 0
1584 && host_current_appid != proc::input_only_app_id
1585 && (
1586 (appid > 0 && appid != host_current_appid)
1587 || (!appuuid_str.empty() && appuuid_str != host_current_app_uuid)
1588 )
1589 ) {
1590 tree.put("root.resume", 0);
1591 tree.put("root.<xmlattr>.status_code", 400);
1592 tree.put("root.<xmlattr>.status_message", "An app is already running on this host");
1593 return;
1594 }
1595
1596 auto encryption_mode = net::encryption_mode_for_address(request->remote_endpoint().address());
1597 if (!launch_session->rtsp_cipher && encryption_mode == config::ENCRYPTION_MODE_MANDATORY) {
1598 BOOST_LOG(error) << "Rejecting client that cannot comply with mandatory encryption requirement"sv;
1599
1600 tree.put("root.<xmlattr>.status_code", 403);
1601 tree.put("root.<xmlattr>.status_message", "Encryption is mandatory for this host but unsupported by the client");
1602 tree.put("root.gamesession", 0);
1603
1604 return;
1605 }
1606
1607 bool no_active_sessions = rtsp_stream::shared_session_count() == 0;
1608 // Whether this request started the app or the isolated session, as
1609 // opposed to finding it already running.
1610 bool started_here = false;
1611
1612 if (is_input_only) {
1613 BOOST_LOG(info) << "Launching input only session..."sv;
1614
1615 launch_session->client_do_cmds.clear();
1616 launch_session->client_undo_cmds.clear();
1617
1618 // Still probe encoders once, if input only session is launched first
1619 // But we're ignoring if it's successful or not
1620 if (no_active_sessions && !proc::proc.virtual_display) {
1622 if (current_appid == 0) {
1623 proc::proc.launch_input_only();
1624 }
1625 }
1626 } else if (appid > 0 || !appuuid_str.empty()) {
1627 if (isolated_launch) {
1628 const auto &apps = proc::proc.get_apps();
1629 const auto app_iter = std::find_if(
1630 apps.begin(),
1631 apps.end(),
1632 [&appid_str, &appuuid_str](const auto &app) {
1633 return app.id == appid_str || app.uuid == appuuid_str;
1634 }
1635 );
1636 if (app_iter == apps.end()) {
1637 BOOST_LOG(error) << "Couldn't find app with ID [" << appid_str
1638 << "] or UUID [" << appuuid_str << ']';
1639 tree.put("root.<xmlattr>.status_code", 404);
1640 tree.put("root.<xmlattr>.status_message", "Cannot find requested application");
1641 tree.put("root.gamesession", 0);
1642 return;
1643 }
1644 if (!app_iter->allow_client_commands) {
1645 launch_session->client_do_cmds.clear();
1646 launch_session->client_undo_cmds.clear();
1647 }
1648
1649 const auto err = proc::proc.execute_isolated(*app_iter, launch_session);
1650 if (err) {
1651 tree.put("root.<xmlattr>.status_code", err);
1652 if (!launch_session->launch_error_message.empty()) {
1653 tree.put("root.<xmlattr>.status_message", launch_session->launch_error_message);
1654 } else {
1655 tree.put(
1656 "root.<xmlattr>.status_message",
1657 err == 409 ?
1658 "This client already owns an isolated session." :
1659 err == 503 ?
1660 "Failed to start the isolated compositor/capture session." :
1661 "Failed to start the specified application"
1662 );
1663 }
1664 tree.put("root.gamesession", 0);
1665 return;
1666 }
1667 started_here = true;
1668 } else if (appid == current_appid || (!appuuid_str.empty() && appuuid_str == current_app_uuid)) {
1669 // We're basically resuming the same app
1670
1671 BOOST_LOG(debug) << "Resuming app [" << proc::proc.get_last_run_app_name() << "] from launch app path...";
1672
1673 if (!proc::proc.allow_client_commands || !named_cert_p->allow_client_commands) {
1674 launch_session->client_do_cmds.clear();
1675 launch_session->client_undo_cmds.clear();
1676 }
1677
1678 if (current_appid == proc::input_only_app_id) {
1679 launch_session->input_only = true;
1680 }
1681
1682 if (no_active_sessions && !proc::proc.virtual_display) {
1683 display_device::configure_display(config::video, *launch_session);
1684 if (video::probe_encoders()) {
1685 tree.put("root.resume", 0);
1686 tree.put("root.<xmlattr>.status_code", 503);
1687 tree.put("root.<xmlattr>.status_message", "Failed to initialize video capture/encoding. Is a display connected and turned on?");
1688
1689 return;
1690 }
1691 }
1692 } else {
1693 const auto& apps = proc::proc.get_apps();
1694 auto app_iter = std::find_if(apps.begin(), apps.end(), [&appid_str, &appuuid_str](const auto _app) {
1695 return _app.id == appid_str || _app.uuid == appuuid_str;
1696 });
1697
1698 if (app_iter == apps.end()) {
1699 BOOST_LOG(error) << "Couldn't find app with ID ["sv << appid_str << "] or UUID ["sv << appuuid_str << ']';
1700 tree.put("root.<xmlattr>.status_code", 404);
1701 tree.put("root.<xmlattr>.status_message", "Cannot find requested application");
1702 tree.put("root.gamesession", 0);
1703 return;
1704 }
1705
1706 if (!app_iter->allow_client_commands) {
1707 launch_session->client_do_cmds.clear();
1708 launch_session->client_undo_cmds.clear();
1709 }
1710
1711 auto err = proc::proc.execute(*app_iter, launch_session);
1712 if (err) {
1713 tree.put("root.<xmlattr>.status_code", err);
1714 if (!launch_session->launch_error_message.empty()) {
1715 tree.put("root.<xmlattr>.status_message", launch_session->launch_error_message);
1716 } else {
1717 tree.put(
1718 "root.<xmlattr>.status_message",
1719 err == 503
1720 ? "Failed to initialize video capture/encoding. Is a display connected and turned on?"
1721 : "Failed to start the specified application");
1722 }
1723 tree.put("root.gamesession", 0);
1724
1725 return;
1726 }
1727 started_here = true;
1728 }
1729 } else {
1730 tree.put("root.<xmlattr>.status_code", 403);
1731 tree.put("root.<xmlattr>.status_message", "How did you get here?");
1732 tree.put("root.gamesession", 0);
1733 }
1734
1735 if (!is_input_only &&
1736 !isolated_launch &&
1737 config::video.virtual_display_backend == "hermes_kms" &&
1738 config::video.hermes_kms_multi_output &&
1739 (proc::proc.virtual_display || launch_session->virtual_display || config::video.headless_mode) &&
1740 !launch_session->session_scoped_virtual_display) {
1741 if (const int result = proc::proc.prepare_session_virtual_display(launch_session); result != 0) {
1742 tree.put("root.<xmlattr>.status_code", result);
1743 tree.put("root.<xmlattr>.status_message", "No independent Hermes-KMS output is available for this client.");
1744 tree.put("root.gamesession", 0);
1745 return;
1746 }
1747 }
1748
1749 // One real frame through capture, conversion and encoding, before the
1750 // client is told the stream is ready, while no stream holds the encoder.
1751 if (!is_input_only && rtsp_stream::session_count() == 0) {
1752 video::config_t stream {};
1753 stream.display_name = launch_session->display_name;
1754 stream.kwin_wayland_socket = launch_session->kwin_wayland_socket;
1755 stream.kwin_pipewire_socket = launch_session->kwin_pipewire_socket;
1756 // The preflight must know that the client asked for HDR; an HDR output
1757 // cannot be validated by trying to capture it as an SDR-only stream.
1758 stream.dynamicRange = launch_session->enable_hdr ? 1 : 0;
1759 stream.framerate = launch_session->fps / 1000;
1760 std::string failure;
1761 if (video::check_capture_path(stream, failure, named_cert_p->uuid)) {
1762 if (config::video.ignore_encoder_probe_failure) {
1763 // The same escape hatch the encoder probe honours.
1764 BOOST_LOG(warning) << "Capture readiness: " << failure << "; continuing due to user configuration."sv;
1765 } else {
1766 BOOST_LOG(error) << "Capture readiness: " << failure;
1767 // Undo what this launch started. Left running, the app would be
1768 // resumed by the client's retry, which skips this check.
1769 if (started_here) {
1770 if (isolated_launch) {
1771 proc::proc.terminate_isolated(
1772 launch_session->isolated_runtime_owner_id ? launch_session->isolated_runtime_owner_id : launch_session->id
1773 );
1774 } else {
1775 proc::proc.terminate();
1777 }
1778 }
1779 // An output prepared above for this launch alone has no stream to release it.
1780 if (!isolated_launch && launch_session->session_virtual_display_cleanup_pending) {
1781 VDISPLAY::removeVirtualDisplay(launch_session->display_guid);
1782 launch_session->session_virtual_display_cleanup_pending = false;
1783 launch_session->session_scoped_virtual_display = false;
1784 launch_session->display_name.clear();
1785 }
1786 tree.put("root.<xmlattr>.status_code", 503);
1787 tree.put("root.<xmlattr>.status_message", failure + ".");
1788 tree.put("root.gamesession", 0);
1789 return;
1790 }
1791 }
1792 } else if (!is_input_only) {
1793 // Another stream holds the encoder, so this launch ran no check: an
1794 // earlier one of this client's would describe a stream it no longer has.
1795 video::forget_capture_readiness(named_cert_p->uuid);
1796 }
1797
1798 if (!rtsp_stream::launch_session_raise(launch_session)) {
1799 tree.put("root.<xmlattr>.status_code", 503);
1800 tree.put("root.<xmlattr>.status_message", "Another client is still completing its RTSP handshake. Please retry.");
1801 tree.put("root.gamesession", 0);
1802 return;
1803 }
1804
1805 tree.put("root.<xmlattr>.status_code", 200);
1806 tree.put(
1807 "root.sessionUrl0",
1808 std::format(
1809 "{}{}:{}",
1810 launch_session->rtsp_url_scheme,
1811 net::addr_to_url_escaped_string(request->local_endpoint().address()),
1812 static_cast<int>(net::map_port(rtsp_stream::RTSP_SETUP_PORT))
1813 )
1814 );
1815 tree.put("root.gamesession", 1);
1816 }
1817
1818 void resume(bool &host_audio, resp_https_t response, req_https_t request) {
1819 print_req<SunshineHTTPS>(request);
1820
1821 pt::ptree tree;
1822 auto g = util::fail_guard([&]() {
1823 std::ostringstream data;
1824
1825 pt::write_xml(data, tree);
1826 response->write(data.str());
1827 response->close_connection_after_response = true;
1828 });
1829
1830 auto named_cert_p = get_verified_cert(request);
1831 const bool isolated_sessions_enabled = experimental_isolated_sessions_enabled();
1832 if (!(named_cert_p->perm & PERM::_allow_view)) {
1833 BOOST_LOG(debug) << "Permission ViewApp denied for [" << named_cert_p->name << "] (" << (uint32_t)named_cert_p->perm << ")";
1834
1835 tree.put("root.resume", 0);
1836 tree.put("root.<xmlattr>.status_code", 403);
1837 tree.put("root.<xmlattr>.status_message", "Permission denied");
1838
1839 return;
1840 }
1841
1842 const auto isolated_current_appid = isolated_sessions_enabled ?
1843 proc::proc.running_for_client(named_cert_p->uuid) :
1844 0;
1845 const bool isolated_resume = isolated_current_appid > 0;
1846 const auto current_appid = isolated_resume ?
1847 isolated_current_appid :
1848 proc::proc.running();
1849
1850 if (isolated_resume && rtsp_stream::find_session(named_cert_p->uuid)) {
1851 tree.put("root.resume", 0);
1852 tree.put("root.<xmlattr>.status_code", 409);
1853 tree.put("root.<xmlattr>.status_message", "This client already has an active stream");
1854 return;
1855 }
1856 if (current_appid == 0) {
1857 tree.put("root.resume", 0);
1858 tree.put("root.<xmlattr>.status_code", 503);
1859 tree.put("root.<xmlattr>.status_message", "No running app to resume");
1860
1861 return;
1862 }
1863
1864 auto args = request->parse_query_string();
1865 if (
1866 args.find("rikey"s) == std::end(args) ||
1867 args.find("rikeyid"s) == std::end(args)
1868 ) {
1869 tree.put("root.resume", 0);
1870 tree.put("root.<xmlattr>.status_code", 400);
1871 tree.put("root.<xmlattr>.status_message", "Missing a required resume parameter");
1872
1873 return;
1874 }
1875
1876 // Newer Moonlight clients send localAudioPlayMode on /resume too,
1877 // so we should use it if it's present in the args and there are
1878 // no active sessions we could be interfering with.
1879 const bool no_active_sessions {rtsp_stream::session_count() == 0};
1880 const bool no_active_shared_sessions {rtsp_stream::shared_session_count() == 0};
1881 if (no_active_sessions && args.find("localAudioPlayMode"s) != std::end(args)) {
1882 host_audio = util::from_view(get_arg(args, "localAudioPlayMode"));
1883 }
1884 auto launch_session = make_launch_session(host_audio, false, args, named_cert_p);
1885
1886 if ((!isolated_resume && !proc::proc.allow_client_commands) ||
1887 !named_cert_p->allow_client_commands) {
1888 launch_session->client_do_cmds.clear();
1889 launch_session->client_undo_cmds.clear();
1890 }
1891
1892 if (isolated_resume && !proc::proc.prepare_isolated_resume(launch_session)) {
1893 tree.put("root.resume", 0);
1894 tree.put("root.<xmlattr>.status_code", 503);
1895 tree.put("root.<xmlattr>.status_message", launch_session->launch_error_message.empty() ? "No isolated session is available to resume" : launch_session->launch_error_message);
1896 return;
1897 }
1898
1899 if (config::input.enable_input_only_mode && current_appid == proc::input_only_app_id) {
1900 launch_session->input_only = true;
1901 }
1902
1903 if (!isolated_resume && no_active_shared_sessions && !proc::proc.virtual_display) {
1904 // We want to prepare display only if there are no active sessions
1905 // and the current session isn't virtual display at the moment.
1906 // This should be done before probing encoders as it could change the active displays.
1907 display_device::configure_display(config::video, *launch_session);
1908
1909 // Probe encoders again before streaming to ensure our chosen
1910 // encoder matches the active GPU (which could have changed
1911 // due to hotplugging, driver crash, primary monitor change,
1912 // or any number of other factors).
1913 if (video::probe_encoders()) {
1914 tree.put("root.resume", 0);
1915 tree.put("root.<xmlattr>.status_code", 503);
1916 tree.put("root.<xmlattr>.status_message", "Failed to initialize video capture/encoding. Is a display connected and turned on?");
1917
1918 return;
1919 }
1920 }
1921 else if (!isolated_resume && no_active_shared_sessions && proc::proc.virtual_display && !proc::proc.display_name.empty()) {
1922 // A resumed app keeps its virtual display, but every client brings its
1923 // own mode. Without this, the first client's geometry outlives it: A
1924 // streams at 1440p and disconnects, B resumes the same app at 1080p and
1925 // gets A's mode.
1926 int target_fps = launch_session->fps ? launch_session->fps : 60000;
1927 if (target_fps < 1000) {
1928 target_fps *= 1000;
1929 }
1930 if (launch_session->width > 0 && launch_session->height > 0) {
1931 // No activateVirtualDisplayOutput() here, unlike the launch path in
1932 // process.cpp: reaching this branch requires a running app that still
1933 // owns its virtual display, so the output was activated at launch and
1934 // is kept alive by the session. Only the mode may differ for the new
1935 // client. The deadline is shorter than the default because this runs
1936 // synchronously inside the /resume handler and clients time out on long
1937 // stalls; on failure the stream simply keeps the display's active mode.
1938 const int change_result = VDISPLAY::changeDisplaySettings(
1939 proc::proc.display_name.c_str(),
1940 launch_session->width,
1941 launch_session->height,
1942 target_fps,
1943 1500
1944 );
1945 if (change_result != 0) {
1946 // Capture re-reads the active scanout geometry on init, so the
1947 // encoders below follow the display's real mode, not the request.
1948 BOOST_LOG(warning) << "Virtual display did not reach "sv
1949 << launch_session->width << 'x' << launch_session->height
1950 << "; streaming the display's active mode instead."sv;
1951 }
1952 }
1953
1954 if (!VDISPLAY::configureVirtualDisplayHdr(proc::proc.display_name, launch_session->enable_hdr)) {
1955 tree.put("root.resume", 0);
1956 tree.put("root.<xmlattr>.status_code", 503);
1957 tree.put("root.<xmlattr>.status_message", "The virtual display could not apply the requested HDR/SDR mode.");
1958 return;
1959 }
1960
1961 if (video::probe_encoders()) {
1962 tree.put("root.resume", 0);
1963 tree.put("root.<xmlattr>.status_code", 503);
1964 tree.put("root.<xmlattr>.status_message", "Failed to initialize video capture/encoding. Is a display connected and turned on?");
1965
1966 return;
1967 }
1968 }
1969
1970 auto encryption_mode = net::encryption_mode_for_address(request->remote_endpoint().address());
1971 if (!launch_session->rtsp_cipher && encryption_mode == config::ENCRYPTION_MODE_MANDATORY) {
1972 BOOST_LOG(error) << "Rejecting client that cannot comply with mandatory encryption requirement"sv;
1973
1974 tree.put("root.<xmlattr>.status_code", 403);
1975 tree.put("root.<xmlattr>.status_message", "Encryption is mandatory for this host but unsupported by the client");
1976 tree.put("root.gamesession", 0);
1977
1978 return;
1979 }
1980
1981 if (config::video.virtual_display_backend == "hermes_kms" &&
1982 !isolated_resume &&
1983 config::video.hermes_kms_multi_output &&
1984 (proc::proc.virtual_display || launch_session->virtual_display || config::video.headless_mode)) {
1985 if (const int result = proc::proc.prepare_session_virtual_display(launch_session); result != 0) {
1986 tree.put("root.resume", 0);
1987 tree.put("root.<xmlattr>.status_code", result);
1988 tree.put("root.<xmlattr>.status_message", "No independent Hermes-KMS output is available for this client.");
1989 return;
1990 }
1991 }
1992
1993 if (!rtsp_stream::launch_session_raise(launch_session)) {
1994 tree.put("root.resume", 0);
1995 tree.put("root.<xmlattr>.status_code", 503);
1996 tree.put("root.<xmlattr>.status_message", "Another client is still completing its RTSP handshake. Please retry.");
1997 return;
1998 }
1999
2000 tree.put("root.<xmlattr>.status_code", 200);
2001 tree.put(
2002 "root.sessionUrl0",
2003 std::format(
2004 "{}{}:{}",
2005 launch_session->rtsp_url_scheme,
2006 net::addr_to_url_escaped_string(request->local_endpoint().address()),
2007 static_cast<int>(net::map_port(rtsp_stream::RTSP_SETUP_PORT))
2008 )
2009 );
2010 tree.put("root.resume", 1);
2011
2012#if defined HERMES_TRAY && HERMES_TRAY >= 1
2013 system_tray::update_tray_client_connected(named_cert_p->name);
2014#endif
2015 }
2016
2017 void cancel(resp_https_t response, req_https_t request) {
2018 print_req<SunshineHTTPS>(request);
2019
2020 pt::ptree tree;
2021 auto g = util::fail_guard([&]() {
2022 std::ostringstream data;
2023
2024 pt::write_xml(data, tree);
2025 response->write(data.str());
2026 response->close_connection_after_response = true;
2027 });
2028
2029 auto named_cert_p = get_verified_cert(request);
2030 if (!(named_cert_p->perm & PERM::launch)) {
2031 BOOST_LOG(debug) << "Permission CancelApp denied for [" << named_cert_p->name << "] (" << (uint32_t)named_cert_p->perm << ")";
2032
2033 tree.put("root.resume", 0);
2034 tree.put("root.<xmlattr>.status_code", 403);
2035 tree.put("root.<xmlattr>.status_message", "Permission denied");
2036
2037 return;
2038 }
2039
2040 tree.put("root.cancel", 1);
2041 tree.put("root.<xmlattr>.status_code", 200);
2042
2043 const auto stream_route =
2044 rtsp_stream::session_is_isolated(named_cert_p->uuid);
2045 const bool cancel_isolated =
2046 stream_route.value_or(
2047 experimental_isolated_sessions_enabled() &&
2048 proc::proc.isolated_client_present(named_cert_p->uuid)
2049 );
2050
2051 rtsp_stream::cancel_pending_launch(named_cert_p->uuid);
2052 BOOST_LOG(info) << "Client " << named_cert_p->name << " quit its app" << (cancel_isolated ? " and isolated session." : ".");
2053 if (cancel_isolated) {
2054 rtsp_stream::terminate_session(named_cert_p->uuid);
2055 proc::proc.terminate_isolated_client(named_cert_p->uuid);
2056 } else {
2058 if (proc::proc.running() > 0) {
2059 proc::proc.terminate();
2060 }
2061 // Shared-host display state does not belong to isolated runtimes.
2063 }
2064 }
2065
2066 void appasset(resp_https_t response, req_https_t request) {
2067 print_req<SunshineHTTPS>(request);
2068
2069 auto fg = util::fail_guard([&]() {
2070 response->write(SimpleWeb::StatusCode::server_error_internal_server_error);
2071 response->close_connection_after_response = true;
2072 });
2073
2074 auto named_cert_p = get_verified_cert(request);
2075
2076 if (!(named_cert_p->perm & PERM::_all_actions)) {
2077 BOOST_LOG(debug) << "Permission Get AppAsset denied for [" << named_cert_p->name << "] (" << (uint32_t)named_cert_p->perm << ")";
2078
2079 fg.disable();
2080 response->write(SimpleWeb::StatusCode::client_error_unauthorized);
2081 response->close_connection_after_response = true;
2082 return;
2083 }
2084
2085 auto args = request->parse_query_string();
2086 auto app_image = proc::proc.get_app_image(util::from_view(get_arg(args, "appid")));
2087
2088 fg.disable();
2089
2090 std::ifstream in(app_image, std::ios::binary);
2091 SimpleWeb::CaseInsensitiveMultimap headers;
2092 headers.emplace("Content-Type", "image/png");
2093 response->write(SimpleWeb::StatusCode::success_ok, in, headers);
2094 response->close_connection_after_response = true;
2095 }
2096
2097 void getClipboard(resp_https_t response, req_https_t request) {
2098 print_req<SunshineHTTPS>(request);
2099
2100 auto named_cert_p = get_verified_cert(request);
2101
2102 if (
2103 !(named_cert_p->perm & PERM::_allow_view)
2104 || !(named_cert_p->perm & PERM::clipboard_read)
2105 ) {
2106 BOOST_LOG(debug) << "Permission Read Clipboard denied for [" << named_cert_p->name << "] (" << (uint32_t)named_cert_p->perm << ")";
2107
2108 response->write(SimpleWeb::StatusCode::client_error_unauthorized);
2109 response->close_connection_after_response = true;
2110 return;
2111 }
2112
2113 auto args = request->parse_query_string();
2114 auto clipboard_type = get_arg(args, "type");
2115 if (clipboard_type != "text"sv) {
2116 BOOST_LOG(debug) << "Clipboard type [" << clipboard_type << "] is not supported!";
2117
2118 response->write(SimpleWeb::StatusCode::client_error_bad_request);
2119 response->close_connection_after_response = true;
2120 return;
2121 }
2122
2123 std::list<std::string> connected_uuids = rtsp_stream::get_all_session_uuids();
2124
2125 bool found = !connected_uuids.empty();
2126
2127 if (found) {
2128 found = (std::find(connected_uuids.begin(), connected_uuids.end(), named_cert_p->uuid) != connected_uuids.end());
2129 }
2130
2131 if (!found) {
2132 BOOST_LOG(debug) << "Client ["<< named_cert_p->name << "] trying to get clipboard is not connected to a stream";
2133
2134 response->write(SimpleWeb::StatusCode::client_error_forbidden);
2135 response->close_connection_after_response = true;
2136 return;
2137 }
2138
2139 std::string content = platf::get_clipboard();
2140 response->write(content);
2141 return;
2142 }
2143
2144 void
2145 setClipboard(resp_https_t response, req_https_t request) {
2146 print_req<SunshineHTTPS>(request);
2147
2148 auto named_cert_p = get_verified_cert(request);
2149
2150 if (
2151 !(named_cert_p->perm & PERM::_allow_view)
2152 || !(named_cert_p->perm & PERM::clipboard_set)
2153 ) {
2154 BOOST_LOG(debug) << "Permission Write Clipboard denied for [" << named_cert_p->name << "] (" << (uint32_t)named_cert_p->perm << ")";
2155
2156 response->write(SimpleWeb::StatusCode::client_error_unauthorized);
2157 response->close_connection_after_response = true;
2158 return;
2159 }
2160
2161 auto args = request->parse_query_string();
2162 auto clipboard_type = get_arg(args, "type");
2163 if (clipboard_type != "text"sv) {
2164 BOOST_LOG(debug) << "Clipboard type [" << clipboard_type << "] is not supported!";
2165
2166 response->write(SimpleWeb::StatusCode::client_error_bad_request);
2167 response->close_connection_after_response = true;
2168 return;
2169 }
2170
2171 std::list<std::string> connected_uuids = rtsp_stream::get_all_session_uuids();
2172
2173 bool found = !connected_uuids.empty();
2174
2175 if (found) {
2176 found = (std::find(connected_uuids.begin(), connected_uuids.end(), named_cert_p->uuid) != connected_uuids.end());
2177 }
2178
2179 if (!found) {
2180 BOOST_LOG(debug) << "Client ["<< named_cert_p->name << "] trying to set clipboard is not connected to a stream";
2181
2182 response->write(SimpleWeb::StatusCode::client_error_forbidden);
2183 response->close_connection_after_response = true;
2184 return;
2185 }
2186
2187 std::string content = request->content.string();
2188
2189 bool success = platf::set_clipboard(content);
2190
2191 if (!success) {
2192 BOOST_LOG(debug) << "Setting clipboard failed!";
2193
2194 response->write(SimpleWeb::StatusCode::server_error_internal_server_error);
2195 response->close_connection_after_response = true;
2196 }
2197
2198 response->write();
2199 return;
2200 }
2201
2202 void setup(const std::string &pkey, const std::string &cert) {
2203 conf_intern.pkey = pkey;
2204 conf_intern.servercert = cert;
2205 }
2206
2207 bool verify_paired_client_certificate(X509 *certificate, crypto::p_named_cert_t &named_cert_out) {
2208 return certificate != nullptr && cert_chain.verify(certificate, named_cert_out) == nullptr;
2209 }
2210
2211 void store_hestia_session_prepare(const std::string &client_uuid, hestia_session_prepare_t prepare) {
2212 std::lock_guard lock(pending_hestia_session_prepares_mutex);
2213 pending_hestia_session_prepares[client_uuid] = {
2214 .prepare = std::move(prepare),
2215 .expires_at = std::chrono::steady_clock::now() + 60s,
2216 };
2217 }
2218
2219 std::optional<hestia_session_prepare_t> take_hestia_session_prepare(const std::string &client_uuid) {
2220 std::lock_guard lock(pending_hestia_session_prepares_mutex);
2221 const auto it = pending_hestia_session_prepares.find(client_uuid);
2222 if (it == pending_hestia_session_prepares.end()) {
2223 return std::nullopt;
2224 }
2225
2226 if (it->second.expires_at < std::chrono::steady_clock::now()) {
2227 pending_hestia_session_prepares.erase(it);
2228 return std::nullopt;
2229 }
2230
2231 auto prepare = std::move(it->second.prepare);
2232 pending_hestia_session_prepares.erase(it);
2233 return prepare;
2234 }
2235
2236 void clear_hestia_session_prepare(const std::string &client_uuid) {
2237 std::lock_guard lock(pending_hestia_session_prepares_mutex);
2238 pending_hestia_session_prepares.erase(client_uuid);
2239 }
2240
2241 void start() {
2242 auto shutdown_event = mail::man->event<bool>(mail::shutdown);
2243
2244 auto port_http = net::map_port(PORT_HTTP);
2245 auto port_https = net::map_port(PORT_HTTPS);
2246 auto address_family = net::af_from_enum_string(config::sunshine.address_family);
2247
2248 bool clean_slate = config::sunshine.flags[config::flag::FRESH_STATE];
2249
2250 if (!clean_slate) {
2251 load_state();
2252 }
2253
2254 auto pkey = file_handler::read_file(config::nvhttp.pkey.c_str());
2255 auto cert = file_handler::read_file(config::nvhttp.cert.c_str());
2256 setup(pkey, cert);
2257
2258 // resume doesn't always get the parameter "localAudioPlayMode"
2259 // launch will store it in host_audio
2260 bool host_audio {};
2261
2262 https_server_t https_server {config::nvhttp.cert, config::nvhttp.pkey};
2263 http_server_t http_server;
2264
2265 // Verify certificates after establishing connection
2266 https_server.verify = [](req_https_t req, SSL *ssl) {
2267 crypto::x509_t x509 {
2268#if OPENSSL_VERSION_MAJOR >= 3
2269 SSL_get1_peer_certificate(ssl)
2270#else
2271 SSL_get_peer_certificate(ssl)
2272#endif
2273 };
2274 if (!x509) {
2275 BOOST_LOG(info) << "unknown -- denied"sv;
2276 return false;
2277 }
2278
2279 bool verified = false;
2280 p_named_cert_t named_cert_p;
2281
2282 auto fg = util::fail_guard([&]() {
2283 char subject_name[256];
2284
2285 X509_NAME_oneline(X509_get_subject_name(x509.get()), subject_name, sizeof(subject_name));
2286
2287 if (verified) {
2288 BOOST_LOG(debug) << subject_name << " -- "sv << "verified, device name: "sv << named_cert_p->name;
2289 } else {
2290 BOOST_LOG(debug) << subject_name << " -- "sv << "denied"sv;
2291 }
2292
2293 });
2294
2295 auto err_str = cert_chain.verify(x509.get(), named_cert_p);
2296 if (err_str) {
2297 BOOST_LOG(warning) << "SSL Verification error :: "sv << err_str;
2298 return verified;
2299 }
2300
2301 verified = true;
2302 req->userp = named_cert_p;
2303
2304 return true;
2305 };
2306
2307 https_server.on_verify_failed = [](resp_https_t resp, req_https_t req) {
2308 pt::ptree tree;
2309 auto g = util::fail_guard([&]() {
2310 std::ostringstream data;
2311
2312 pt::write_xml(data, tree);
2313 resp->write(data.str());
2314 resp->close_connection_after_response = true;
2315 });
2316
2317 tree.put("root.<xmlattr>.status_code"s, 401);
2318 tree.put("root.<xmlattr>.query"s, req->path);
2319 tree.put("root.<xmlattr>.status_message"s, "The client is not authorized. Certificate verification failed."s);
2320 };
2321
2322 https_server.default_resource["GET"] = not_found<SunshineHTTPS>;
2323 https_server.resource["^/serverinfo$"]["GET"] = serverinfo<SunshineHTTPS>;
2324 https_server.resource["^/pair$"]["GET"] = pair<SunshineHTTPS>;
2325 https_server.resource["^/applist$"]["GET"] = applist;
2326 https_server.resource["^/appasset$"]["GET"] = appasset;
2327 https_server.resource["^/launch$"]["GET"] = [&host_audio](auto resp, auto req) {
2328 launch(host_audio, resp, req);
2329 };
2330 https_server.resource["^/resume$"]["GET"] = [&host_audio](auto resp, auto req) {
2331 resume(host_audio, resp, req);
2332 };
2333 https_server.resource["^/cancel$"]["GET"] = cancel;
2334 https_server.resource["^/actions/clipboard$"]["GET"] = getClipboard;
2335 https_server.resource["^/actions/clipboard$"]["POST"] = setClipboard;
2336
2337 https_server.config.reuse_address = true;
2338 https_server.config.address = net::af_to_any_address_string(address_family);
2339 https_server.config.port = port_https;
2340
2341 http_server.default_resource["GET"] = not_found<SimpleWeb::HTTP>;
2342 http_server.resource["^/serverinfo$"]["GET"] = serverinfo<SimpleWeb::HTTP>;
2343 http_server.resource["^/pair$"]["GET"] = pair<SimpleWeb::HTTP>;
2344 http_server.resource["^/unpair$"]["GET"] = cancel_pairing_request;
2345
2346 http_server.config.reuse_address = true;
2347 http_server.config.address = net::af_to_any_address_string(address_family);
2348 http_server.config.port = port_http;
2349
2350 auto accept_and_run = [&](auto *http_server) {
2351 try {
2352 http_server->start();
2353 } catch (boost::system::system_error &err) {
2354 // It's possible the exception gets thrown after calling http_server->stop() from a different thread
2355 if (shutdown_event->peek()) {
2356 return;
2357 }
2358
2359 BOOST_LOG(fatal) << "Couldn't start http server on ports ["sv << port_http << ", "sv << port_https << "]: "sv << err.what();
2360 BOOST_LOG(fatal) << "Another host is most likely already bound to them. Hermes, Apollo and Sunshine all use these ports, so only one of them can run at a time."sv;
2361 shutdown_event->raise(true);
2362 return;
2363 }
2364 };
2365 std::thread ssl {accept_and_run, &https_server};
2366 std::thread tcp {accept_and_run, &http_server};
2367
2368 // Wait for any event
2369 shutdown_event->view();
2370
2371 {
2372 std::lock_guard lock {pair_session_mutex};
2373 clear_pending_pairs();
2374 map_id_sess.clear();
2375 }
2376
2377 https_server.stop();
2378 http_server.stop();
2379
2380 ssl.join();
2381 tcp.join();
2382 }
2383
2384 std::string request_otp(const std::string& passphrase, const std::string& deviceName) {
2385 if (passphrase.size() < 4) {
2386 return "";
2387 }
2388
2389 one_time_pin = crypto::rand_alphabet(4, "0123456789"sv);
2390 otp_passphrase = passphrase;
2391 otp_device_name = deviceName;
2392 otp_creation_time = std::chrono::steady_clock::now();
2393
2394 return one_time_pin;
2395 }
2396
2397 void
2399 client_t client;
2400 client_root = client;
2401 cert_chain.clear();
2402 save_state();
2403 load_state();
2404 }
2405
2406 void stop_session(stream::session_t& session, bool graceful) {
2407 if (graceful) {
2408 stream::session::graceful_stop(session);
2409 } else {
2410 stream::session::stop(session, stream::session::termination_reason_e::SERVER_STOPPED);
2411 }
2412 }
2413
2414 bool find_and_stop_session(const std::string& uuid, bool graceful) {
2415 auto session = rtsp_stream::find_session(uuid);
2416 if (session) {
2417 stop_session(*session, graceful);
2418 return true;
2419 }
2420 return false;
2421 }
2422
2423 void update_session_info(stream::session_t& session, const std::string& name, const crypto::PERM newPerm) {
2424 stream::session::update_device_info(session, name, newPerm);
2425 }
2426
2427 bool find_and_udpate_session_info(const std::string& uuid, const std::string& name, const crypto::PERM newPerm) {
2428 auto session = rtsp_stream::find_session(uuid);
2429 if (session) {
2430 update_session_info(*session, name, newPerm);
2431 return true;
2432 }
2433 return false;
2434 }
2435
2437 const std::string& uuid,
2438 const std::string& name,
2439 const std::string& display_mode,
2440 const cmd_list_t& do_cmds,
2441 const cmd_list_t& undo_cmds,
2442 const crypto::PERM newPerm,
2443 const bool enable_legacy_ordering,
2444 const bool allow_client_commands,
2445 const bool always_use_virtual_display
2446 ) {
2447 find_and_udpate_session_info(uuid, name, newPerm);
2448
2449 client_t &client = client_root;
2450 auto it = client.named_devices.begin();
2451 for (; it != client.named_devices.end(); ++it) {
2452 auto named_cert_p = *it;
2453 if (named_cert_p->uuid == uuid) {
2454 named_cert_p->name = name;
2455 named_cert_p->display_mode = display_mode;
2456 named_cert_p->perm = newPerm;
2457 named_cert_p->do_cmds = do_cmds;
2458 named_cert_p->undo_cmds = undo_cmds;
2459 named_cert_p->enable_legacy_ordering = enable_legacy_ordering;
2460 named_cert_p->allow_client_commands = allow_client_commands;
2461 named_cert_p->always_use_virtual_display = always_use_virtual_display;
2462 save_state();
2463 return true;
2464 }
2465 }
2466
2467 return false;
2468 }
2469
2470 bool unpair_client(const std::string_view uuid) {
2471 bool removed = false;
2472 client_t &client = client_root;
2473 for (auto it = client.named_devices.begin(); it != client.named_devices.end();) {
2474 if ((*it)->uuid == uuid) {
2475 it = client.named_devices.erase(it);
2476 removed = true;
2477 } else {
2478 ++it;
2479 }
2480 }
2481
2482 save_state();
2483 load_state();
2484
2485 if (removed) {
2486 auto session = rtsp_stream::find_session(uuid);
2487 if (session) {
2488 stop_session(*session, true);
2489 }
2490
2491 if (client.named_devices.empty()) {
2492 proc::proc.terminate();
2493 }
2494 }
2495
2496 return removed;
2497 }
2498} // namespace nvhttp
Declarations for common platform specific utilities.
std::string get_mac_address(const std::string_view &address)
The MAC address of the interface that holds address.
Definition misc.cpp:412
Declarations for the configuration of Sunshine.
@ FRESH_STATE
Do not load or save state.
Definition config.h:209
@ PIN_STDIN
Read PIN from stdin instead of http.
Definition config.h:208
void not_found(resp_https_t response, req_https_t request)
Send a 404 Not Found response.
sha256_t hash(const std::string_view &plaintext)
Hashes the given plaintext using SHA-256.
Definition crypto.cpp:364
PERM
The permissions of a client.
Definition crypto.h:45
void revert_configuration()
Revert the display configuration and restore the previous state.
void configure_display(const config::video_t &video_config, const rtsp_stream::launch_session_t &session)
Configure the display device based on the user configuration and the session information.
Declarations for display device handling.
Declarations for file handling functions.
Declarations for globally accessible variables and functions.
Declarations for common HTTP.
Declarations for logging related functions.
Functions for handling command line arguments.
std::string read_file(const char *path)
Read a file to string.
safe::mail_t man
A process-wide communication mechanism.
Definition globals.cpp:8
Contains all the functions and variables related to the nvhttp (GameStream) server.
Definition nvhttp.cpp:47
void update_session_info(stream::session_t &session, const std::string &name, const crypto::PERM newPerm)
Update device info associated to the session.
Definition nvhttp.cpp:2423
std::optional< hestia_session_prepare_t > take_hestia_session_prepare(const std::string &client_uuid)
Definition nvhttp.cpp:2219
bool find_and_udpate_session_info(const std::string &uuid, const std::string &name, const crypto::PERM newPerm)
Finds and udpate session information.
Definition nvhttp.cpp:2427
bool cancel_pending_pairing(const std::string &unique_id)
Definition nvhttp.cpp:615
constexpr auto PORT_HTTPS
The HTTPS port, as a difference from the config port.
Definition nvhttp.h:54
void store_hestia_session_prepare(const std::string &client_uuid, hestia_session_prepare_t prepare)
Definition nvhttp.cpp:2211
void start()
Start the nvhttp server.
Definition nvhttp.cpp:2241
void setup(const std::string &pkey, const std::string &cert)
Setup the nvhttp server.
Definition nvhttp.cpp:2202
constexpr auto PORT_HTTP
The HTTP port, as a difference from the config port.
Definition nvhttp.h:49
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::mutex pending_pair_mutex
The clients whose pairing requests are waiting for a PIN, if any.
Definition nvhttp.cpp:253
void stop_session(stream::session_t &session, bool graceful)
Stops a session.
Definition nvhttp.cpp:2406
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
uint32_t launch_count()
How many launch and resume requests have been accepted so far.
Definition nvhttp.cpp:231
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
pair_session_t & begin_pairing_session(pair_session_t session)
Definition nvhttp.cpp:637
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 remove_session(const pair_session_t &sess)
removes the temporary pairing session
Definition nvhttp.cpp:606
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
void update_tray_require_pin()
Spawns a notification for PIN Pairing. Clicking it opens the PIN Web UI Page.
std::uint16_t map_port(int port)
Map a specified port based on the base port.
Definition network.cpp:350
std::string addr_to_url_escaped_string(boost::asio::ip::address address)
Get the given address in a normalized form for the host portion of a URL.
Definition network.cpp:206
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
int encryption_mode_for_address(boost::asio::ip::address address)
Get the encryption mode for the given remote endpoint address.
Definition network.cpp:217
Declarations for networking related functions.
Declarations for the nvhttp (GameStream) server.
session_route_e resolve_session_route(const ctx_t &app, bool isolated_sessions_enabled, bool virtual_display_requested, std::string_view global_method)
Definition process.cpp:179
std::string_view describe(virtual_display_source_e source)
Definition process.cpp:126
virtual_display_decision_t decide_virtual_display(const ctx_t &app, const rtsp_stream::launch_session_t &launch_session, bool headless_mode)
Definition process.cpp:109
scale_factor_decision_t decide_scale_factor(const ctx_t &app, const rtsp_stream::launch_session_t &launch_session, int host_default)
Definition process.cpp:148
Declarations for the startup and shutdown of the apps started by a streaming Session.
@ app
The client sent none; the app's own scale.
Definition process.h:201
virtual_display_source_e
Definition process.h:168
@ app_forced
The app forces its setting on every client.
Definition process.h:170
@ client
The client chose (Hestia's session/prepare).
Definition process.h:171
@ headless
The host runs headless; there is nothing else to stream.
Definition process.h:169
@ default_rule
No explicit choice: client request, per-client or app setting.
Definition process.h:172
bool terminate_session(const std::string_view &uuid)
Definition rtsp.cpp:805
bool cancel_pending_launch(const std::string_view &uuid)
Definition rtsp.cpp:769
bool launch_session_raise(std::shared_ptr< launch_session_t > launch_session)
Definition rtsp.cpp:761
int session_count()
Get the number of active sessions.
Definition rtsp.cpp:773
void terminate_shared_sessions()
Definition rtsp.cpp:809
Declarations for RTSP streaming.
Declarations for the streaming protocols.
@ SERVER_STOPPED
Host stopped the session (API stop, shutdown).
Definition stream.h:72
std::optional< int > client_scale_factor
Definition rtsp.h:63
std::optional< bool > client_virtual_display
Definition rtsp.h:60
Declarations for the system tray icon and notification system.
Declarations for utility functions.
Declarations for UUID generation.
void forget_capture_readiness(const std::string &client)
Forget the last check if it was for client's launch: a later launch of theirs ran without one,...
Definition video.cpp:3217
int probe_encoders()
Probe encoders and select the preferred encoder. This is called once at startup and each time a strea...
Definition video.cpp:3232
int check_capture_path(const config_t &stream, std::string &failure, const std::string &client)
Run one real frame through the path a stream will use.
Definition video.cpp:3199
Declarations for video.
int changeDisplaySettings(const char *deviceName, int width, int height, int refresh_rate, int deadline_ms)
Change the display settings of a virtual display.
bool configureVirtualDisplayHdr(const std::string &displayName, bool hdr)
bool removeVirtualDisplay(const uuid_util::uuid_t &guid)
Remove a virtual display.
@ isolated_sessions
One seat and one compositor per client.
@ OK
Driver is operational.