diff --git a/src/crypto.cpp b/src/crypto.cpp index 6472c8fa7..452efbd14 100644 --- a/src/crypto.cpp +++ b/src/crypto.cpp @@ -64,9 +64,7 @@ namespace crypto { // that OpenSSL doesn't detect as self-signed due to some X509v3 extensions. X509_STORE_CTX_set_flags(_cert_ctx.get(), X509_V_FLAG_PARTIAL_CHAIN); - auto err = X509_verify_cert(_cert_ctx.get()); - - if (err == 1) { + if (auto err = X509_verify_cert(_cert_ctx.get()); err == 1) { if (X509_cmp(trusted_cert.get(), cert) == 0) { return nullptr; } diff --git a/src/input.cpp b/src/input.cpp index 8f1b867a6..37eaaa8fb 100644 --- a/src/input.cpp +++ b/src/input.cpp @@ -948,8 +948,7 @@ namespace input { */ if (button == BUTTON_LEFT && release && !input->mouse_left_button_timeout) { auto f = [=]() { - auto left_released = mouse_press[BUTTON_LEFT]; - if (left_released) { + if (auto left_released = mouse_press[BUTTON_LEFT]; left_released) { // Already released left button return; } @@ -985,8 +984,7 @@ namespace input { * @return Remapped keycode when configured, otherwise the original keycode. */ short map_keycode(short keycode) { - auto it = config::input.keybindings.find(keycode); - if (it != std::end(config::input.keybindings)) { + if (auto it = config::input.keybindings.find(keycode); it != std::end(config::input.keybindings)) { return it->second; } diff --git a/src/network.cpp b/src/network.cpp index b04d6f888..85003814f 100644 --- a/src/network.cpp +++ b/src/network.cpp @@ -66,9 +66,7 @@ namespace net { * @brief Convert a Boost address family to Sunshine network enum value. */ net_e from_address(const std::string_view &view) { - auto addr = normalize_address(ip::make_address(view)); - - if (addr.is_v6()) { + if (auto addr = normalize_address(ip::make_address(view)); addr.is_v6()) { for (auto &range : pc_ips_v6) { if (range.hosts().find(addr.to_v6()) != range.hosts().end()) { return PC; diff --git a/src/nvhttp.cpp b/src/nvhttp.cpp index 6f6936fb6..d8ead116a 100644 --- a/src/nvhttp.cpp +++ b/src/nvhttp.cpp @@ -101,49 +101,56 @@ namespace nvhttp { } } + /** + * @brief Process a completed TLS handshake under the callback's server lifetime guard. + * + * @param session Session whose TLS handshake has completed. + * @param ec Result of the asynchronous handshake. + * @pre The caller holds the session's handler scope guard. + */ + void handle_handshake(const std::shared_ptr &session, const SimpleWeb::error_code &ec) { + if (!ec) { + if (verify && !verify(session->connection->socket->native_handle())) { + this->write(session, on_verify_failed); + } else { + this->read(session); + } + } else if (this->on_error) { + this->on_error(session->request, ec); + } + } + // This is Server::accept() with SSL validation support added /** * @brief Accept a pending connection and arm the server for the next client. + * @details Keep each handler's scope guard alive until all access to the server has finished. */ void accept() override { auto connection = create_connection(*io_service, context); acceptor->async_accept(connection->socket->lowest_layer(), [this, connection](const SimpleWeb::error_code &ec) { - auto lock = connection->handler_runner->continue_lock(); - if (!lock) { - return; - } + if (auto lock = connection->handler_runner->continue_lock(); lock) { + if (ec != SimpleWeb::error::operation_aborted) { + this->accept(); + } - if (ec != SimpleWeb::error::operation_aborted) { - this->accept(); - } + auto session = std::make_shared(config.max_request_streambuf_size, connection); - auto session = std::make_shared(config.max_request_streambuf_size, connection); + if (!ec) { + boost::asio::ip::tcp::no_delay option(true); + SimpleWeb::error_code option_error; + session->connection->socket->lowest_layer().set_option(option, option_error); - if (!ec) { - boost::asio::ip::tcp::no_delay option(true); - SimpleWeb::error_code option_error; - session->connection->socket->lowest_layer().set_option(option, option_error); - - session->connection->set_timeout(config.timeout_request); - session->connection->socket->async_handshake(boost::asio::ssl::stream_base::server, [this, session](const SimpleWeb::error_code &ec) { - session->connection->cancel_timeout(); - auto lock = session->connection->handler_runner->continue_lock(); - if (!lock) { - return; - } - if (!ec) { - if (verify && !verify(session->connection->socket->native_handle())) { - this->write(session, on_verify_failed); - } else { - this->read(session); + session->connection->set_timeout(config.timeout_request); + session->connection->socket->async_handshake(boost::asio::ssl::stream_base::server, [this, session](const SimpleWeb::error_code &ec) { + session->connection->cancel_timeout(); + if (auto lock = session->connection->handler_runner->continue_lock(); lock) { + this->handle_handshake(session, ec); } - } else if (this->on_error) { - this->on_error(session->request, ec); - } - }); - } else if (this->on_error) { - this->on_error(session->request, ec); + }); + } else if (this->on_error) { + this->on_error(session->request, ec); + } } }); } @@ -1844,6 +1851,25 @@ namespace nvhttp { #ifdef SUNSHINE_TESTS namespace test_support { + std::unique_ptr> make_https_server( + const std::string &certificate_file, + const std::string &private_key_file, + std::shared_ptr &handler_scope + ) { + /** + * @brief Expose the production HTTPS handler scope to lifetime regression tests. + */ + class test_https_server_t: public SunshineHTTPSServer { + public: + using SunshineHTTPSServer::handler_runner; + using SunshineHTTPSServer::SunshineHTTPSServer; + }; + + auto server = std::make_unique(certificate_file, private_key_file); + handler_scope = server->handler_runner; + return server; + } + void pair_http( std::shared_ptr::Response> response, std::shared_ptr::Request> request diff --git a/src/nvhttp.h b/src/nvhttp.h index 0717c91f8..e8d50c595 100644 --- a/src/nvhttp.h +++ b/src/nvhttp.h @@ -384,6 +384,20 @@ namespace nvhttp { * @brief Test-only accessors for paired-client authorization state. */ namespace test_support { + /** + * @brief Create the production HTTPS server and expose its callback lifetime guard. + * + * @param certificate_file Path to the server certificate PEM file. + * @param private_key_file Path to the matching private key PEM file. + * @param handler_scope Receives the scope runner that prevents destruction during callbacks. + * @return HTTPS server ready for test endpoint configuration. + */ + std::unique_ptr> make_https_server( + const std::string &certificate_file, + const std::string &private_key_file, + std::shared_ptr &handler_scope + ); + /** * @brief Dispatch a plain-HTTP pairing request through the production handler. * diff --git a/src/platform/linux/misc.cpp b/src/platform/linux/misc.cpp index 1de4e5d12..55740a888 100644 --- a/src/platform/linux/misc.cpp +++ b/src/platform/linux/misc.cpp @@ -1041,9 +1041,8 @@ namespace platf { virtual ~qos_t() { if (--qos_ref_count == 0) { - for (const auto &tuple : options) { - auto reset_val = std::get<2>(tuple); - if (setsockopt(sockfd, std::get<0>(tuple), std::get<1>(tuple), &reset_val, sizeof(reset_val)) < 0) { + for (const auto &[level, option, reset_val] : options) { + if (setsockopt(sockfd, level, option, &reset_val, sizeof(reset_val)) < 0) { BOOST_LOG(warning) << "Failed to reset option: "sv << errno; } } diff --git a/src/platform/linux/publish.cpp b/src/platform/linux/publish.cpp index 803752c09..ec74da297 100644 --- a/src/platform/linux/publish.cpp +++ b/src/platform/linux/publish.cpp @@ -304,19 +304,18 @@ namespace avahi { } } - std::vector> funcs { - {(dyn::apiproc *) &alternative_service_name, "avahi_alternative_service_name"}, - {(dyn::apiproc *) &free, "avahi_free"}, - {(dyn::apiproc *) &strdup, "avahi_strdup"}, - {(dyn::apiproc *) &strerror, "avahi_strerror"}, - {(dyn::apiproc *) &simple_poll_get, "avahi_simple_poll_get"}, - {(dyn::apiproc *) &simple_poll_loop, "avahi_simple_poll_loop"}, - {(dyn::apiproc *) &simple_poll_quit, "avahi_simple_poll_quit"}, - {(dyn::apiproc *) &simple_poll_new, "avahi_simple_poll_new"}, - {(dyn::apiproc *) &simple_poll_free, "avahi_simple_poll_free"}, - }; - - if (dyn::load(handle, funcs)) { + if (std::vector> funcs { + {(dyn::apiproc *) &alternative_service_name, "avahi_alternative_service_name"}, + {(dyn::apiproc *) &free, "avahi_free"}, + {(dyn::apiproc *) &strdup, "avahi_strdup"}, + {(dyn::apiproc *) &strerror, "avahi_strerror"}, + {(dyn::apiproc *) &simple_poll_get, "avahi_simple_poll_get"}, + {(dyn::apiproc *) &simple_poll_loop, "avahi_simple_poll_loop"}, + {(dyn::apiproc *) &simple_poll_quit, "avahi_simple_poll_quit"}, + {(dyn::apiproc *) &simple_poll_new, "avahi_simple_poll_new"}, + {(dyn::apiproc *) &simple_poll_free, "avahi_simple_poll_free"}, + }; + dyn::load(handle, funcs)) { return -1; } @@ -348,19 +347,18 @@ namespace avahi { } } - std::vector> funcs { - {(dyn::apiproc *) &client_new, "avahi_client_new"}, - {(dyn::apiproc *) &client_free, "avahi_client_free"}, - {(dyn::apiproc *) &entry_group_get_client, "avahi_entry_group_get_client"}, - {(dyn::apiproc *) &entry_group_new, "avahi_entry_group_new"}, - {(dyn::apiproc *) &entry_group_add_service, "avahi_entry_group_add_service"}, - {(dyn::apiproc *) &entry_group_is_empty, "avahi_entry_group_is_empty"}, - {(dyn::apiproc *) &entry_group_reset, "avahi_entry_group_reset"}, - {(dyn::apiproc *) &entry_group_commit, "avahi_entry_group_commit"}, - {(dyn::apiproc *) &client_errno, "avahi_client_errno"}, - }; - - if (dyn::load(handle, funcs)) { + if (std::vector> funcs { + {(dyn::apiproc *) &client_new, "avahi_client_new"}, + {(dyn::apiproc *) &client_free, "avahi_client_free"}, + {(dyn::apiproc *) &entry_group_get_client, "avahi_entry_group_get_client"}, + {(dyn::apiproc *) &entry_group_new, "avahi_entry_group_new"}, + {(dyn::apiproc *) &entry_group_add_service, "avahi_entry_group_add_service"}, + {(dyn::apiproc *) &entry_group_is_empty, "avahi_entry_group_is_empty"}, + {(dyn::apiproc *) &entry_group_reset, "avahi_entry_group_reset"}, + {(dyn::apiproc *) &entry_group_commit, "avahi_entry_group_commit"}, + {(dyn::apiproc *) &client_errno, "avahi_client_errno"}, + }; + dyn::load(handle, funcs)) { return -1; } diff --git a/src/platform/linux/x11grab.cpp b/src/platform/linux/x11grab.cpp index 9f8a75654..7307ab7c0 100644 --- a/src/platform/linux/x11grab.cpp +++ b/src/platform/linux/x11grab.cpp @@ -101,16 +101,15 @@ namespace platf { } } - std::vector> funcs { - {(dyn::apiproc *) &GetScreenResources, "XRRGetScreenResources"}, - {(dyn::apiproc *) &GetOutputInfo, "XRRGetOutputInfo"}, - {(dyn::apiproc *) &GetCrtcInfo, "XRRGetCrtcInfo"}, - {(dyn::apiproc *) &FreeScreenResources, "XRRFreeScreenResources"}, - {(dyn::apiproc *) &FreeOutputInfo, "XRRFreeOutputInfo"}, - {(dyn::apiproc *) &FreeCrtcInfo, "XRRFreeCrtcInfo"}, - }; - - if (dyn::load(handle, funcs)) { + if (std::vector> funcs { + {(dyn::apiproc *) &GetScreenResources, "XRRGetScreenResources"}, + {(dyn::apiproc *) &GetOutputInfo, "XRRGetOutputInfo"}, + {(dyn::apiproc *) &GetCrtcInfo, "XRRGetCrtcInfo"}, + {(dyn::apiproc *) &FreeScreenResources, "XRRFreeScreenResources"}, + {(dyn::apiproc *) &FreeOutputInfo, "XRRFreeOutputInfo"}, + {(dyn::apiproc *) &FreeCrtcInfo, "XRRFreeCrtcInfo"}, + }; + dyn::load(handle, funcs)) { return -1; } @@ -138,11 +137,10 @@ namespace platf { } } - std::vector> funcs { - {(dyn::apiproc *) &GetCursorImage, "XFixesGetCursorImage"}, - }; - - if (dyn::load(handle, funcs)) { + if (std::vector> funcs { + {(dyn::apiproc *) &GetCursorImage, "XFixesGetCursorImage"}, + }; + dyn::load(handle, funcs)) { return -1; } @@ -166,16 +164,15 @@ namespace platf { } } - std::vector> funcs { - {(dyn::apiproc *) &GetImage, "XGetImage"}, - {(dyn::apiproc *) &OpenDisplay, "XOpenDisplay"}, - {(dyn::apiproc *) &GetWindowAttributes, "XGetWindowAttributes"}, - {(dyn::apiproc *) &Free, "XFree"}, - {(dyn::apiproc *) &CloseDisplay, "XCloseDisplay"}, - {(dyn::apiproc *) &InitThreads, "XInitThreads"}, - }; - - if (dyn::load(handle, funcs)) { + if (std::vector> funcs { + {(dyn::apiproc *) &GetImage, "XGetImage"}, + {(dyn::apiproc *) &OpenDisplay, "XOpenDisplay"}, + {(dyn::apiproc *) &GetWindowAttributes, "XGetWindowAttributes"}, + {(dyn::apiproc *) &Free, "XFree"}, + {(dyn::apiproc *) &CloseDisplay, "XCloseDisplay"}, + {(dyn::apiproc *) &InitThreads, "XInitThreads"}, + }; + dyn::load(handle, funcs)) { return -1; } @@ -222,14 +219,13 @@ namespace platf { } } - std::vector> funcs { - {(dyn::apiproc *) &shm_id, "xcb_shm_id"}, - {(dyn::apiproc *) &shm_get_image_reply, "xcb_shm_get_image_reply"}, - {(dyn::apiproc *) &shm_get_image_unchecked, "xcb_shm_get_image_unchecked"}, - {(dyn::apiproc *) &shm_attach, "xcb_shm_attach"}, - }; - - if (dyn::load(handle, funcs)) { + if (std::vector> funcs { + {(dyn::apiproc *) &shm_id, "xcb_shm_id"}, + {(dyn::apiproc *) &shm_get_image_reply, "xcb_shm_get_image_reply"}, + {(dyn::apiproc *) &shm_get_image_unchecked, "xcb_shm_get_image_unchecked"}, + {(dyn::apiproc *) &shm_attach, "xcb_shm_attach"}, + }; + dyn::load(handle, funcs)) { return -1; } @@ -257,17 +253,16 @@ namespace platf { } } - std::vector> funcs { - {(dyn::apiproc *) &get_extension_data, "xcb_get_extension_data"}, - {(dyn::apiproc *) &get_setup, "xcb_get_setup"}, - {(dyn::apiproc *) &disconnect, "xcb_disconnect"}, - {(dyn::apiproc *) &connection_has_error, "xcb_connection_has_error"}, - {(dyn::apiproc *) &connect, "xcb_connect"}, - {(dyn::apiproc *) &setup_roots_iterator, "xcb_setup_roots_iterator"}, - {(dyn::apiproc *) &generate_id, "xcb_generate_id"}, - }; - - if (dyn::load(handle, funcs)) { + if (std::vector> funcs { + {(dyn::apiproc *) &get_extension_data, "xcb_get_extension_data"}, + {(dyn::apiproc *) &get_setup, "xcb_get_setup"}, + {(dyn::apiproc *) &disconnect, "xcb_disconnect"}, + {(dyn::apiproc *) &connection_has_error, "xcb_connection_has_error"}, + {(dyn::apiproc *) &connect, "xcb_connect"}, + {(dyn::apiproc *) &setup_roots_iterator, "xcb_setup_roots_iterator"}, + {(dyn::apiproc *) &generate_id, "xcb_generate_id"}, + }; + dyn::load(handle, funcs)) { return -1; } diff --git a/src/platform/windows/audio.cpp b/src/platform/windows/audio.cpp index b0cd28b80..2a37cbe0d 100644 --- a/src/platform/windows/audio.cpp +++ b/src/platform/windows/audio.cpp @@ -942,8 +942,7 @@ namespace platf::audio { // Encoding format: // [virtual-(format name)]device_id std::string current = sink; - auto prefix = "virtual-"sv; - if (current.find(prefix) == 0) { + if (auto prefix = "virtual-"sv; current.find(prefix) == 0) { current = current.substr(prefix.size(), current.size() - prefix.size()); for (const auto &format : formats) { diff --git a/src/platform/windows/input.cpp b/src/platform/windows/input.cpp index 65a197a46..73f2acf03 100644 --- a/src/platform/windows/input.cpp +++ b/src/platform/windows/input.cpp @@ -419,10 +419,8 @@ namespace platf { if (gamepad.gp.get() == target) { // Convert from 8-bit to 16-bit values const auto normalizedLargeMotor = vigem::scale_rumble(largeMotor); - const auto normalizedSmallMotor = vigem::scale_rumble(smallMotor); - // Don't resend duplicate rumble data - if (normalizedSmallMotor != gamepad.last_rumble.data.rumble.highfreq || normalizedLargeMotor != gamepad.last_rumble.data.rumble.lowfreq) { + if (const auto normalizedSmallMotor = vigem::scale_rumble(smallMotor); normalizedSmallMotor != gamepad.last_rumble.data.rumble.highfreq || normalizedLargeMotor != gamepad.last_rumble.data.rumble.lowfreq) { // We have to use the client-relative index when communicating back to the client gamepad_feedback_msg_t msg = gamepad_feedback_msg_t::make_rumble( gamepad.client_relative_index, @@ -833,8 +831,7 @@ namespace platf { } static DS4_DPAD_DIRECTIONS ds4_dpad(const gamepad_state_t &gamepad_state) { - auto flags = gamepad_state.buttonFlags; - if (flags & DPAD_UP) { + if (auto flags = gamepad_state.buttonFlags; flags & DPAD_UP) { if (flags & DPAD_RIGHT) { return DS4_BUTTON_DPAD_NORTHEAST; } else if (flags & DPAD_LEFT) { diff --git a/src/platform/windows/misc.cpp b/src/platform/windows/misc.cpp index 9fdc466b1..c7aeaf08c 100644 --- a/src/platform/windows/misc.cpp +++ b/src/platform/windows/misc.cpp @@ -178,8 +178,7 @@ namespace platf { std::string from_sockaddr(const sockaddr *const socket_address) { std::array data = {}; - auto family = socket_address->sa_family; - if (family == AF_INET6) { + if (auto family = socket_address->sa_family; family == AF_INET6) { inet_ntop(AF_INET6, &((const sockaddr_in6 *) socket_address)->sin6_addr, data.data(), INET6_ADDRSTRLEN); } else if (family == AF_INET) { inet_ntop(AF_INET, &((const sockaddr_in *) socket_address)->sin_addr, data.data(), INET_ADDRSTRLEN); @@ -1768,8 +1767,7 @@ namespace platf { * @brief Read the current Windows high-resolution performance counter. */ int64_t qpc_counter() { - LARGE_INTEGER performance_counter; - if (QueryPerformanceCounter(&performance_counter)) { + if (LARGE_INTEGER performance_counter; QueryPerformanceCounter(&performance_counter)) { return performance_counter.QuadPart; } return 0; @@ -1785,8 +1783,7 @@ namespace platf { QueryPerformanceFrequency(&frequency); return frequency.QuadPart; }; - static const double frequency = get_frequency(); - if (frequency) { + if (static const double frequency = get_frequency(); frequency) { return std::chrono::nanoseconds((int64_t) ((performance_counter1 - performance_counter2) * frequency / std::nano::den)); } return {}; diff --git a/src/platform/windows/nvprefs/driver_settings.cpp b/src/platform/windows/nvprefs/driver_settings.cpp index 42410729a..3e4eecd1a 100644 --- a/src/platform/windows/nvprefs/driver_settings.cpp +++ b/src/platform/windows/nvprefs/driver_settings.cpp @@ -70,8 +70,7 @@ namespace nvprefs { return false; } - NvAPI_Status status = NvAPI_DRS_LoadSettings(session_handle); - if (status != NVAPI_OK) { + if (NvAPI_Status status = NvAPI_DRS_LoadSettings(session_handle); status != NVAPI_OK) { nvapi_error_message(status); error_message("NvAPI_DRS_LoadSettings() failed"); destroy(); @@ -86,8 +85,7 @@ namespace nvprefs { return false; } - NvAPI_Status status = NvAPI_DRS_SaveSettings(session_handle); - if (status != NVAPI_OK) { + if (NvAPI_Status status = NvAPI_DRS_SaveSettings(session_handle); status != NVAPI_OK) { nvapi_error_message(status); error_message("NvAPI_DRS_SaveSettings() failed"); return false; @@ -101,8 +99,7 @@ namespace nvprefs { return false; } - const auto &swapchain_data = undo_data.get_opengl_swapchain(); - if (swapchain_data) { + if (const auto &swapchain_data = undo_data.get_opengl_swapchain(); swapchain_data) { NvAPI_Status status; NvDRSProfileHandle profile_handle = nullptr; diff --git a/src/platform/windows/nvprefs/nvapi_opensource_wrapper.cpp b/src/platform/windows/nvprefs/nvapi_opensource_wrapper.cpp index 735a58056..bf9f8f212 100644 --- a/src/platform/windows/nvprefs/nvapi_opensource_wrapper.cpp +++ b/src/platform/windows/nvprefs/nvapi_opensource_wrapper.cpp @@ -57,15 +57,16 @@ NvAPI_Initialize() { return NVAPI_OK; } + if (const auto *dll_name = [] { #if defined(_M_ARM64) || defined(__aarch64__) - auto dll_name = "nvapia64.dll"; + return "nvapia64.dll"; #elif defined(_WIN64) - auto dll_name = "nvapi64.dll"; + return "nvapi64.dll"; #else - auto dll_name = "nvapi.dll"; + return "nvapi.dll"; #endif - - if ((dll = LoadLibraryEx(dll_name, nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32))) { + }(); + (dll = LoadLibraryEx(dll_name, nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32))) { if (auto query_interface = (decltype(nvapi_QueryInterface) *) GetProcAddress(dll, "nvapi_QueryInterface")) { for (const auto &item : nvapi_interface_table) { interfaces[item.func] = query_interface(item.id); diff --git a/src/platform/windows/nvprefs/nvprefs_interface.cpp b/src/platform/windows/nvprefs/nvprefs_interface.cpp index ce27cee09..4bfa00bdb 100644 --- a/src/platform/windows/nvprefs/nvprefs_interface.cpp +++ b/src/platform/windows/nvprefs/nvprefs_interface.cpp @@ -109,8 +109,7 @@ namespace nvprefs { } // Modify and save sunshine.exe application profile settings, if needed - bool modified = false; - if (!pimpl->driver_settings.check_and_modify_application_profile(modified)) { + if (bool modified = false; !pimpl->driver_settings.check_and_modify_application_profile(modified)) { error_message("Failed to modify application profile settings"); return false; } else if (modified) { diff --git a/src/platform/windows/nvprefs/undo_file.cpp b/src/platform/windows/nvprefs/undo_file.cpp index 477af0339..41fd41b38 100644 --- a/src/platform/windows/nvprefs/undo_file.cpp +++ b/src/platform/windows/nvprefs/undo_file.cpp @@ -19,8 +19,7 @@ namespace { } safe_sid users_sid; - SID_IDENTIFIER_AUTHORITY nt_authorithy = SECURITY_NT_AUTHORITY; - if (!AllocateAndInitializeSid(&nt_authorithy, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, &users_sid)) { + if (SID_IDENTIFIER_AUTHORITY nt_authorithy = SECURITY_NT_AUTHORITY; !AllocateAndInitializeSid(&nt_authorithy, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, &users_sid)) { return GetLastError(); } @@ -109,8 +108,7 @@ namespace nvprefs { return false; } - DWORD bytes_written = 0; - if (!WriteFile(file_handle.get(), buffer.data(), buffer.size(), &bytes_written, nullptr) || bytes_written != buffer.size()) { + if (DWORD bytes_written = 0; !WriteFile(file_handle.get(), buffer.data(), buffer.size(), &bytes_written, nullptr) || bytes_written != buffer.size()) { error_message("Couldn't write undo file"); return false; } @@ -139,8 +137,7 @@ namespace nvprefs { } std::vector buffer(file_size.QuadPart); - DWORD bytes_read = 0; - if (!ReadFile(file_handle.get(), buffer.data(), buffer.size(), &bytes_read, nullptr) || bytes_read != buffer.size()) { + if (DWORD bytes_read = 0; !ReadFile(file_handle.get(), buffer.data(), buffer.size(), &bytes_read, nullptr) || bytes_read != buffer.size()) { error_message("Couldn't read undo file"); return std::nullopt; } diff --git a/src/rtsp.cpp b/src/rtsp.cpp index 882266424..a3065f24d 100644 --- a/src/rtsp.cpp +++ b/src/rtsp.cpp @@ -529,8 +529,7 @@ namespace rtsp_stream { * @param req Parsed RTSP request being handled. */ void handle_msg(tcp::socket &sock, launch_session_t &session, msg_t &&req) { - auto func = _map_cmd_cb.find(req->message.request.command); - if (func != std::end(_map_cmd_cb)) { + if (auto func = _map_cmd_cb.find(req->message.request.command); func != std::end(_map_cmd_cb)) { func->second(this, sock, session, std::move(req)); } else { cmd_not_found(sock, session, std::move(req)); @@ -804,12 +803,12 @@ namespace rtsp_stream { * @param resp RTSP response string to send to the client. */ void respond(tcp::socket &sock, launch_session_t &session, msg_t &resp) { - auto payload = std::make_pair(resp->payload, resp->payloadLength); + auto [payload, original_payload_length] = std::make_pair(resp->payload, resp->payloadLength); // Restore response message for proper destruction auto lg = util::fail_guard([&]() { - resp->payload = payload.first; - resp->payloadLength = payload.second; + resp->payload = payload; + resp->payloadLength = original_payload_length; }); resp->payload = nullptr; @@ -820,7 +819,7 @@ namespace rtsp_stream { BOOST_LOG(debug) << "---Begin Response---"sv << std::endl << std::string_view {raw_resp.get(), (std::size_t) serialized_len} << std::endl - << std::string_view {payload.first, (std::size_t) payload.second} << std::endl + << std::string_view {payload, (std::size_t) original_payload_length} << std::endl << "---End Response---"sv << std::endl; // Encrypt the RTSP message if encryption is enabled @@ -840,21 +839,21 @@ namespace rtsp_stream { iv[11] = 'R'; // RTSP // Allocate the message with an empty header and reserved space for the payload - auto payload_length = serialized_len + payload.second; + auto message_length = serialized_len + original_payload_length; std::vector message(sizeof(encrypted_rtsp_header_t)); - message.reserve(message.size() + payload_length); + message.reserve(message.size() + message_length); // Copy the complete plaintext into the message std::copy_n(raw_resp.get(), serialized_len, std::back_inserter(message)); - std::copy_n(payload.first, payload.second, std::back_inserter(message)); + std::copy_n(payload, original_payload_length, std::back_inserter(message)); // Initialize the message header auto header = (encrypted_rtsp_header_t *) message.data(); - header->typeAndLength = util::endian::big(encrypted_rtsp_header_t::ENCRYPTED_MESSAGE_TYPE_BIT + payload_length); + header->typeAndLength = util::endian::big(encrypted_rtsp_header_t::ENCRYPTED_MESSAGE_TYPE_BIT + message_length); header->sequenceNumber = util::endian::big(session.rtsp_iv_counter); // Encrypt the RTSP message in place - session.rtsp_cipher->encrypt(std::string_view {(const char *) header->payload(), (std::size_t) payload_length}, header->tag.data(), &iv); + session.rtsp_cipher->encrypt(std::string_view {(const char *) header->payload(), (std::size_t) message_length}, header->tag.data(), &iv); // Send the full encrypted message send(sock, std::string_view {(char *) message.data(), message.size()}); @@ -867,7 +866,7 @@ namespace rtsp_stream { } // Send the plaintext RTSP message payload (if present) - send(sock, std::string_view {payload.first, (std::size_t) payload.second}); + send(sock, std::string_view {payload, (std::size_t) original_payload_length}); } } @@ -935,8 +934,7 @@ namespace rtsp_stream { uint32_t encryption_flags_requested = SS_ENC_CONTROL_V2; // Determine the encryption desired for this remote endpoint - auto encryption_mode = net::encryption_mode_for_address(sock.remote_endpoint().address()); - if (encryption_mode != config::ENCRYPTION_MODE_NEVER) { + if (auto encryption_mode = net::encryption_mode_for_address(sock.remote_endpoint().address()); encryption_mode != config::ENCRYPTION_MODE_NEVER) { // Advertise support for video encryption if it's not disabled encryption_flags_supported |= SS_ENC_VIDEO; diff --git a/src/stream.cpp b/src/stream.cpp index aedb3f2a1..1cbbea105 100644 --- a/src/stream.cpp +++ b/src/stream.cpp @@ -449,8 +449,7 @@ namespace stream { * @return Network operation status. */ int send(const std::string_view &payload, net::peer_t peer) { - auto packet = enet_packet_create(payload.data(), payload.size(), ENET_PACKET_FLAG_RELIABLE); - if (enet_peer_send(peer, 0, packet)) { + if (auto packet = enet_packet_create(payload.data(), payload.size(), ENET_PACKET_FLAG_RELIABLE); enet_peer_send(peer, 0, packet)) { enet_packet_destroy(packet); return -1; diff --git a/src/thread_safe.h b/src/thread_safe.h index fa432ee7e..91c424cac 100644 --- a/src/thread_safe.h +++ b/src/thread_safe.h @@ -822,8 +822,7 @@ namespace safe { event_t event(const std::string_view &id) { std::lock_guard lg {mutex}; - auto it = id_to_post.find(id); - if (it != std::end(id_to_post)) { + if (auto it = id_to_post.find(id); it != std::end(id_to_post)) { return lock>(it->second); } @@ -843,8 +842,7 @@ namespace safe { queue_t queue(const std::string_view &id) { std::lock_guard lg {mutex}; - auto it = id_to_post.find(id); - if (it != std::end(id_to_post)) { + if (auto it = id_to_post.find(id); it != std::end(id_to_post)) { return lock>(it->second); } diff --git a/src/video.cpp b/src/video.cpp index 71066b488..0dad7311c 100644 --- a/src/video.cpp +++ b/src/video.cpp @@ -1034,9 +1034,8 @@ namespace video { {"enforce_hrd"s, &config::video.amd.amd_enforce_hrd}, {"max_au_size"s, &config::video.amd.amd_max_au_size}, {"level"s, [](const config_t &cfg) { - auto size = cfg.width * cfg.height; // For 4K and below, try to use level 5.1 or 5.2 if possible - if (size <= 8912896) { + if (auto size = cfg.width * cfg.height; size <= 8912896) { if (size * cfg.framerate <= 534773760) { return "5.1"s; } else if (size * cfg.framerate <= 1069547520) { diff --git a/tests/unit/test_nvhttp_https.cpp b/tests/unit/test_nvhttp_https.cpp new file mode 100644 index 000000000..3bb94e54a --- /dev/null +++ b/tests/unit/test_nvhttp_https.cpp @@ -0,0 +1,160 @@ +/** + * @file tests/unit/test_nvhttp_https.cpp + * @brief Verify HTTPS callbacks retain the guard protecting server lifetime. + */ + +// test includes +#include "../tests_common.h" + +// standard includes +#include +#include +#include +#include +#include + +// local includes +#include +#include + +namespace { + using namespace std::chrono_literals; + using boost::asio::ip::tcp; + + /** + * @brief Run real HTTPS callbacks against an isolated loopback listener. + */ + struct HttpsHandlerLifetimeTest: BaseTest { + /** + * @brief Create credentials and start the production HTTPS accept handler. + */ + void SetUp() override { + BaseTest::SetUp(); + const auto credentials = crypto::gen_creds("Sunshine HTTPS lifetime test", 2048); + certificate_file = std::filesystem::path {SUNSHINE_TEST_BIN_DIR} / "https_lifetime_cert.pem"; + private_key_file = std::filesystem::path {SUNSHINE_TEST_BIN_DIR} / "https_lifetime_key.pem"; + std::ofstream {certificate_file} << credentials.x509; + std::ofstream {private_key_file} << credentials.pkey; + + server = nvhttp::test_support::make_https_server(certificate_file.string(), private_key_file.string(), handler_scope); + server->io_service = std::make_shared(); + server->config.address = "127.0.0.1"; + server->config.port = 0; + server->start([this](unsigned short assigned_port) { + port = assigned_port; + }); + server->io_service->poll(); + ASSERT_NE(port, 0); + } + + /** + * @brief Drain canceled callbacks and remove the generated credentials. + */ + void TearDown() override { + if (server) { + server->stop(); + server->io_service->restart(); + server->io_service->poll(); + server.reset(); + } + if (stop_thread.joinable()) { + stop_thread.join(); + } + std::error_code cleanup_error; + std::filesystem::remove(certificate_file, cleanup_error); + std::filesystem::remove(private_key_file, cleanup_error); + BaseTest::TearDown(); + } + + /** + * @brief Check that stopping the scope runner waits until the error callback exits. + * + * @param callback_error Error delivered by the real accept or TLS handshake operation. + */ + void check_handler_guard(const boost::system::error_code &callback_error) { + EXPECT_TRUE(callback_error); + ++error_callbacks; + std::promise stopping; + auto stopping_future = stopping.get_future(); + std::promise stopped; + stopped_future = stopped.get_future(); + stop_thread = std::jthread([this, stopping = std::move(stopping), stopped = std::move(stopped)]() mutable { + stopping.set_value(); + handler_scope->stop(); + stopped.set_value(); + }); + stopping_future.wait(); + EXPECT_EQ(stopped_future.wait_for(50ms), std::future_status::timeout); + } + + std::unique_ptr> server; ///< Server running production accept and handshake callbacks. + std::shared_ptr handler_scope; ///< Guard used by the server destructor. + std::jthread stop_thread; ///< Concurrent attempt to stop the handler scope. + std::future stopped_future; ///< Signals that all callback guards have been released. + unsigned short port = 0; ///< Assigned loopback port. + int error_callbacks = 0; ///< Number of errors delivered while testing a handler. + std::filesystem::path certificate_file; ///< Generated server certificate. + std::filesystem::path private_key_file; ///< Generated server private key. + }; + + /** + * @brief Canceling a pending accept holds the server guard through its error callback. + */ + TEST_F(HttpsHandlerLifetimeTest, AcceptErrorRetainsGuardUntilCallbackReturns) { + server->on_error = [this](auto, const auto &callback_error) { + check_handler_guard(callback_error); + }; + server->stop(); + server->io_service->run_for(2s); + ASSERT_EQ(error_callbacks, 1); + ASSERT_TRUE(stopped_future.valid()); + EXPECT_EQ(stopped_future.wait_for(2s), std::future_status::ready); + } + + /** + * @brief A failed TLS handshake holds the server guard through its error callback. + */ + TEST_F(HttpsHandlerLifetimeTest, HandshakeErrorRetainsGuardUntilCallbackReturns) { + server->on_error = [this](auto, const auto &callback_error) { + check_handler_guard(callback_error); + }; + boost::asio::io_context client_io; + tcp::socket client {client_io}; + client.connect({boost::asio::ip::address_v4::loopback(), port}); + client.close(); + server->io_service->run_for(2s); + ASSERT_EQ(error_callbacks, 1); + ASSERT_TRUE(stopped_future.valid()); + EXPECT_EQ(stopped_future.wait_for(2s), std::future_status::ready); + } + + /** + * @brief A stopped server scope prevents a canceled accept from dispatching an error. + */ + TEST_F(HttpsHandlerLifetimeTest, StoppedScopeSkipsAcceptCallback) { + server->on_error = [this](auto, const auto &) { + ++error_callbacks; + }; + handler_scope->stop(); + server->stop(); + server->io_service->run_for(2s); + EXPECT_EQ(error_callbacks, 0); + } + + /** + * @brief A stopped server scope prevents an outstanding handshake from dispatching an error. + */ + TEST_F(HttpsHandlerLifetimeTest, StoppedScopeSkipsHandshakeCallback) { + server->on_error = [this](auto, const auto &) { + ++error_callbacks; + }; + boost::asio::io_context client_io; + tcp::socket client {client_io}; + client.connect({boost::asio::ip::address_v4::loopback(), port}); + server->io_service->poll(); + handler_scope->stop(); + client.close(); + server->io_service->run_for(2s); + EXPECT_EQ(error_callbacks, 0); + } +} // namespace diff --git a/tools/sunshinesvc.cpp b/tools/sunshinesvc.cpp index 9ec1e1930..a5363f3f4 100644 --- a/tools/sunshinesvc.cpp +++ b/tools/sunshinesvc.cpp @@ -323,8 +323,7 @@ VOID WINAPI ServiceMain(DWORD, LPTSTR *) { { // Sunshine terminated itself. - DWORD exit_code; - if (GetExitCodeProcess(process_info.hProcess, &exit_code) && exit_code == ERROR_SHUTDOWN_IN_PROGRESS) { + if (DWORD exit_code; GetExitCodeProcess(process_info.hProcess, &exit_code) && exit_code == ERROR_SHUTDOWN_IN_PROGRESS) { // Sunshine is asking for us to shut down, so gracefully stop ourselves. SetEvent(stop_event); }