[fix] fix blocking issue on controlled-side during shutdown

This commit is contained in:
dijunkun
2026-04-21 16:52:59 +08:00
parent 97e48bfe71
commit d3b886c3f6
7 changed files with 287 additions and 313 deletions
@@ -2,23 +2,22 @@
#include <Windows.h> #include <Windows.h>
#include <nlohmann/json.hpp>
#include <cmath>
#include <chrono> #include <chrono>
#include <cmath>
#include <cstring> #include <cstring>
#include <filesystem> #include <filesystem>
#include <memory> #include <memory>
#include <nlohmann/json.hpp>
#include <sstream> #include <sstream>
#include <string> #include <string>
#include <thread> #include <thread>
#include <utility> #include <utility>
#include <vector> #include <vector>
#include "interactive_state.h"
#include "rd_log.h" #include "rd_log.h"
#include "screen_capturer_dxgi.h" #include "screen_capturer_dxgi.h"
#include "screen_capturer_gdi.h" #include "screen_capturer_gdi.h"
#include "interactive_state.h"
#include "service_host.h" #include "service_host.h"
#include "session_helper_shared.h" #include "session_helper_shared.h"
#include "wgc_plugin_api.h" #include "wgc_plugin_api.h"
@@ -146,8 +145,7 @@ std::string ExtractPipeTextResponse(const std::vector<uint8_t>& response) {
bool IsTransientSecureDesktopFrameError(const std::string& error_message) { bool IsTransientSecureDesktopFrameError(const std::string& error_message) {
return error_message.rfind("pipe_unavailable:", 0) == 0 || return error_message.rfind("pipe_unavailable:", 0) == 0 ||
error_message.find("\"error\":\"bitblt_failed\"") != error_message.find("\"error\":\"bitblt_failed\"") != std::string::npos;
std::string::npos;
} }
bool ReadPipeMessage(HANDLE pipe, std::vector<uint8_t>* response_out, bool ReadPipeMessage(HANDLE pipe, std::vector<uint8_t>* response_out,
@@ -266,8 +264,8 @@ bool QuerySecureDesktopServiceStatus(SecureDesktopServiceStatus* status) {
status->active_session_id = json.value("active_session_id", 0xFFFFFFFFu); status->active_session_id = json.value("active_session_id", 0xFFFFFFFFu);
status->helper_running = json.value("secure_input_helper_running", false); status->helper_running = json.value("secure_input_helper_running", false);
status->interactive_stage = json.value("interactive_stage", std::string()); status->interactive_stage = json.value("interactive_stage", std::string());
const bool secure_desktop_active = json.value( const bool secure_desktop_active =
"interactive_secure_desktop_active", json.value("interactive_secure_desktop_active",
json.value("secure_desktop_active", false)); json.value("secure_desktop_active", false));
status->capture_active = status->capture_active =
status->active_session_id != 0xFFFFFFFF && status->active_session_id != 0xFFFFFFFF &&
@@ -287,7 +285,8 @@ bool QuerySecureDesktopHelperFrame(DWORD session_id, int left, int top,
return false; return false;
} }
const std::wstring pipe_name = GetCrossDeskSecureInputHelperPipeName(session_id); const std::wstring pipe_name =
GetCrossDeskSecureInputHelperPipeName(session_id);
if (!WaitNamedPipeW(pipe_name.c_str(), kSecureDesktopHelperPipeTimeoutMs)) { if (!WaitNamedPipeW(pipe_name.c_str(), kSecureDesktopHelperPipeTimeoutMs)) {
if (error_out != nullptr) { if (error_out != nullptr) {
*error_out = "pipe_unavailable:" + std::to_string(GetLastError()); *error_out = "pipe_unavailable:" + std::to_string(GetLastError());
@@ -416,10 +415,8 @@ int ScreenCapturerWin::Init(const int fps, cb_desktop_data cb) {
} }
int ScreenCapturerWin::Destroy() { int ScreenCapturerWin::Destroy() {
StopSecureCaptureThread(); Stop();
running_.store(false, std::memory_order_relaxed);
paused_.store(false, std::memory_order_relaxed); paused_.store(false, std::memory_order_relaxed);
secure_desktop_capture_active_.store(false, std::memory_order_relaxed);
if (impl_) { if (impl_) {
impl_->Destroy(); impl_->Destroy();
impl_.reset(); impl_.reset();
@@ -585,8 +582,8 @@ void ScreenCapturerWin::StopSecureCaptureThread() {
} }
} }
bool ScreenCapturerWin::GetCurrentCaptureRegion(int* left, int* top, bool ScreenCapturerWin::GetCurrentCaptureRegion(int* left, int* top, int* width,
int* width, int* height, int* height,
std::string* display_name) { std::string* display_name) {
if (left == nullptr || top == nullptr || width == nullptr || if (left == nullptr || top == nullptr || width == nullptr ||
height == nullptr || display_name == nullptr) { height == nullptr || display_name == nullptr) {
@@ -653,11 +650,13 @@ void ScreenCapturerWin::SecureDesktopCaptureLoop() {
if (service_changed || service_error_changed) { if (service_changed || service_error_changed) {
if (status.service_available) { if (status.service_available) {
LOG_INFO( LOG_INFO(
"Windows capturer secure desktop service available, polling session_id={}", "Windows capturer secure desktop service available, polling "
"session_id={}",
status.active_session_id); status.active_session_id);
} else { } else {
LOG_WARN( LOG_WARN(
"Windows capturer secure desktop service unavailable: error={}, code={}", "Windows capturer secure desktop service unavailable: "
"error={}, code={}",
status.error, status.error_code); status.error, status.error_code);
} }
last_service_available = status.service_available; last_service_available = status.service_available;
@@ -665,8 +664,7 @@ void ScreenCapturerWin::SecureDesktopCaptureLoop() {
} }
} else if (last_service_available || } else if (last_service_available ||
last_service_error != "invalid_service_status_json") { last_service_error != "invalid_service_status_json") {
LOG_WARN( LOG_WARN("Windows capturer secure desktop service status query failed");
"Windows capturer secure desktop service status query failed");
last_service_available = false; last_service_available = false;
last_service_error = "invalid_service_status_json"; last_service_error = "invalid_service_status_json";
} }
@@ -677,7 +675,8 @@ void ScreenCapturerWin::SecureDesktopCaptureLoop() {
status.interactive_stage != last_stage) { status.interactive_stage != last_stage) {
capture_stage_started_tick = now; capture_stage_started_tick = now;
LOG_INFO( LOG_INFO(
"Windows capturer secure desktop state: active={}, stage='{}', session_id={}", "Windows capturer secure desktop state: active={}, stage='{}', "
"session_id={}",
status.capture_active, status.interactive_stage, status.capture_active, status.interactive_stage,
status.active_session_id); status.active_session_id);
last_capture_active = status.capture_active; last_capture_active = status.capture_active;
@@ -687,8 +686,8 @@ void ScreenCapturerWin::SecureDesktopCaptureLoop() {
} }
if (!status.capture_active || status.active_session_id == 0xFFFFFFFF) { if (!status.capture_active || status.active_session_id == 0xFFFFFFFF) {
std::this_thread::sleep_for(std::chrono::milliseconds( std::this_thread::sleep_for(
status.service_available ? 50 : 200)); std::chrono::milliseconds(status.service_available ? 50 : 200));
continue; continue;
} }
@@ -721,12 +720,11 @@ void ScreenCapturerWin::SecureDesktopCaptureLoop() {
} else { } else {
const bool transient_error = const bool transient_error =
IsTransientSecureDesktopFrameError(error_message); IsTransientSecureDesktopFrameError(error_message);
const bool in_grace_period = const bool in_grace_period = capture_stage_started_tick != 0 &&
capture_stage_started_tick != 0 && now - capture_stage_started_tick <
now - capture_stage_started_tick < kSecureDesktopTransientErrorGraceMs; kSecureDesktopTransientErrorGraceMs;
const DWORD log_interval = transient_error const DWORD log_interval =
? kSecureDesktopTransientErrorLogIntervalMs transient_error ? kSecureDesktopTransientErrorLogIntervalMs : 1000;
: 1000;
if (transient_error && in_grace_period) { if (transient_error && in_grace_period) {
std::this_thread::sleep_for( std::this_thread::sleep_for(
std::chrono::milliseconds(frame_interval_ms)); std::chrono::milliseconds(frame_interval_ms));
@@ -734,7 +732,8 @@ void ScreenCapturerWin::SecureDesktopCaptureLoop() {
} }
if (now - last_error_tick >= log_interval) { if (now - last_error_tick >= log_interval) {
LOG_WARN( LOG_WARN(
"Windows capturer secure desktop frame query failed, stage='{}', session_id={}, error={}", "Windows capturer secure desktop frame query failed, stage='{}', "
"session_id={}, error={}",
status.interactive_stage, status.active_session_id, error_message); status.interactive_stage, status.active_session_id, error_message);
last_error_tick = now; last_error_tick = now;
} }
+5 -5
View File
@@ -12,11 +12,11 @@ inline bool IsSecureDesktopInteractionRequired(
} }
inline bool ShouldNormalizeUnlockToUserDesktop( inline bool ShouldNormalizeUnlockToUserDesktop(
bool interactive_lock_screen_visible, bool interactive_lock_screen_visible, const std::string& interactive_stage,
const std::string& interactive_stage, bool session_locked, bool session_locked, bool interactive_logon_ui_visible,
bool interactive_logon_ui_visible, bool interactive_secure_desktop_active, bool interactive_secure_desktop_active, bool credential_ui_visible,
bool credential_ui_visible, bool password_box_visible, bool password_box_visible, bool unlock_ui_visible,
bool unlock_ui_visible, const std::string& last_session_event) { const std::string& last_session_event) {
if (!interactive_lock_screen_visible && interactive_stage != "lock-screen") { if (!interactive_lock_screen_visible && interactive_stage != "lock-screen") {
return false; return false;
} }
+3 -3
View File
@@ -17,7 +17,8 @@ std::wstring GetExecutablePath() {
} }
void PrintUsage() { void PrintUsage() {
std::cout << "CrossDesk Windows service skeleton\n" std::cout
<< "CrossDesk Windows service skeleton\n"
<< " --service Run under the Windows Service Control Manager\n" << " --service Run under the Windows Service Control Manager\n"
<< " --console Run the service loop in console mode\n" << " --console Run the service loop in console mode\n"
<< " --install Install the service for the current executable\n" << " --install Install the service for the current executable\n"
@@ -55,8 +56,7 @@ int main(int argc, char* argv[]) {
} }
if (command == "--uninstall") { if (command == "--uninstall") {
bool success = crossdesk::UninstallCrossDeskService(); bool success = crossdesk::UninstallCrossDeskService();
std::cout << (success ? "uninstall ok" : "uninstall failed") std::cout << (success ? "uninstall ok" : "uninstall failed") << std::endl;
<< std::endl;
return success ? 0 : 1; return success ? 0 : 1;
} }
if (command == "--start") { if (command == "--start") {
+74 -97
View File
@@ -1,17 +1,16 @@
#include "service_host.h" #include "service_host.h"
#include <nlohmann/json.hpp> #include <TlHelp32.h>
#include <Userenv.h> #include <Userenv.h>
#include <WtsApi32.h> #include <WtsApi32.h>
#include <sddl.h> #include <sddl.h>
#include <TlHelp32.h>
#include <algorithm> #include <algorithm>
#include <cctype> #include <cctype>
#include <filesystem> #include <filesystem>
#include <iostream> #include <iostream>
#include <mutex> #include <mutex>
#include <nlohmann/json.hpp>
#include <sstream> #include <sstream>
#include <string> #include <string>
#include <thread> #include <thread>
@@ -26,10 +25,8 @@ namespace {
using Json = nlohmann::json; using Json = nlohmann::json;
constexpr char kSecureDesktopKeyboardIpcCommandPrefix[] = constexpr char kSecureDesktopKeyboardIpcCommandPrefix[] = "secure-input-key:";
"secure-input-key:"; constexpr char kSecureDesktopMouseIpcCommandPrefix[] = "secure-input-mouse:";
constexpr char kSecureDesktopMouseIpcCommandPrefix[] =
"secure-input-mouse:";
using SendSasFunction = VOID(WINAPI*)(BOOL); using SendSasFunction = VOID(WINAPI*)(BOOL);
@@ -231,13 +228,12 @@ std::string BuildSecureDesktopKeyboardIpcCommand(int key_code, bool is_down) {
std::string BuildSecureDesktopMouseIpcCommand(int x, int y, int wheel, std::string BuildSecureDesktopMouseIpcCommand(int x, int y, int wheel,
int flag) { int flag) {
std::ostringstream stream; std::ostringstream stream;
stream << kSecureDesktopMouseIpcCommandPrefix << x << ":" << y << ":" stream << kSecureDesktopMouseIpcCommandPrefix << x << ":" << y << ":" << wheel
<< wheel << ":" << flag; << ":" << flag;
return stream.str(); return stream.str();
} }
std::string BuildSecureInputHelperKeyboardCommand(int key_code, std::string BuildSecureInputHelperKeyboardCommand(int key_code, bool is_down) {
bool is_down) {
std::ostringstream stream; std::ostringstream stream;
stream << kCrossDeskSecureInputKeyboardCommandPrefix << key_code << ":" stream << kCrossDeskSecureInputKeyboardCommandPrefix << key_code << ":"
<< (is_down ? 1 : 0); << (is_down ? 1 : 0);
@@ -487,15 +483,15 @@ std::string WideToUtf8(const std::wstring& value) {
return {}; return {};
} }
int size_needed = WideCharToMultiByte(CP_UTF8, 0, value.c_str(), -1, int size_needed = WideCharToMultiByte(CP_UTF8, 0, value.c_str(), -1, nullptr,
nullptr, 0, nullptr, nullptr); 0, nullptr, nullptr);
if (size_needed <= 1) { if (size_needed <= 1) {
return {}; return {};
} }
std::string result(static_cast<size_t>(size_needed), '\0'); std::string result(static_cast<size_t>(size_needed), '\0');
WideCharToMultiByte(CP_UTF8, 0, value.c_str(), -1, result.data(), WideCharToMultiByte(CP_UTF8, 0, value.c_str(), -1, result.data(), size_needed,
size_needed, nullptr, nullptr); nullptr, nullptr);
result.pop_back(); result.pop_back();
return result; return result;
} }
@@ -519,8 +515,7 @@ bool QuerySoftwareSasGeneration(DWORD* value_out, bool* existed_out) {
DWORD value_size = sizeof(value); DWORD value_size = sizeof(value);
DWORD type = REG_DWORD; DWORD type = REG_DWORD;
LONG result = RegQueryValueExW(key, L"SoftwareSASGeneration", nullptr, &type, LONG result = RegQueryValueExW(key, L"SoftwareSASGeneration", nullptr, &type,
reinterpret_cast<LPBYTE>(&value), reinterpret_cast<LPBYTE>(&value), &value_size);
&value_size);
if (result == ERROR_SUCCESS && type == REG_DWORD) { if (result == ERROR_SUCCESS && type == REG_DWORD) {
*value_out = value; *value_out = value;
*existed_out = true; *existed_out = true;
@@ -542,8 +537,7 @@ bool SetSoftwareSasGeneration(DWORD value) {
} }
result = RegSetValueExW(key, L"SoftwareSASGeneration", 0, REG_DWORD, result = RegSetValueExW(key, L"SoftwareSASGeneration", 0, REG_DWORD,
reinterpret_cast<const BYTE*>(&value), reinterpret_cast<const BYTE*>(&value), sizeof(value));
sizeof(value));
RegCloseKey(key); RegCloseKey(key);
return result == ERROR_SUCCESS; return result == ERROR_SUCCESS;
} }
@@ -552,8 +546,8 @@ bool RestoreSoftwareSasGeneration(DWORD original_value, bool existed_before) {
HKEY key = nullptr; HKEY key = nullptr;
constexpr wchar_t kPolicyKey[] = constexpr wchar_t kPolicyKey[] =
L"Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System"; L"Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System";
LONG result = RegOpenKeyExW(HKEY_LOCAL_MACHINE, kPolicyKey, 0, KEY_SET_VALUE, LONG result =
&key); RegOpenKeyExW(HKEY_LOCAL_MACHINE, kPolicyKey, 0, KEY_SET_VALUE, &key);
if (result != ERROR_SUCCESS) { if (result != ERROR_SUCCESS) {
return false; return false;
} }
@@ -580,8 +574,8 @@ SasResult SendSasNow() {
return result; return result;
} }
auto* send_sas = reinterpret_cast<SendSasFunction>( auto* send_sas =
GetProcAddress(sas_module, "SendSAS")); reinterpret_cast<SendSasFunction>(GetProcAddress(sas_module, "SendSAS"));
if (send_sas == nullptr) { if (send_sas == nullptr) {
result.error = "send_sas_proc_missing"; result.error = "send_sas_proc_missing";
result.error_code = GetLastError(); result.error_code = GetLastError();
@@ -625,8 +619,7 @@ struct PipeSecurityAttributes {
} }
bool Initialize() { bool Initialize() {
constexpr wchar_t kPipeSddl[] = constexpr wchar_t kPipeSddl[] = L"D:(A;;GA;;;SY)(A;;GA;;;BA)(A;;GRGW;;;AU)";
L"D:(A;;GA;;;SY)(A;;GA;;;BA)(A;;GRGW;;;AU)";
if (!ConvertStringSecurityDescriptorToSecurityDescriptorW( if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(
kPipeSddl, SDDL_REVISION_1, &security_descriptor_, nullptr)) { kPipeSddl, SDDL_REVISION_1, &security_descriptor_, nullptr)) {
return false; return false;
@@ -654,8 +647,7 @@ struct KernelObjectSecurityAttributes {
} }
bool Initialize() { bool Initialize() {
constexpr wchar_t kObjectSddl[] = constexpr wchar_t kObjectSddl[] = L"D:(A;;GA;;;SY)(A;;GA;;;BA)(A;;GA;;;AU)";
L"D:(A;;GA;;;SY)(A;;GA;;;BA)(A;;GA;;;AU)";
if (!ConvertStringSecurityDescriptorToSecurityDescriptorW( if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(
kObjectSddl, SDDL_REVISION_1, &security_descriptor_, nullptr)) { kObjectSddl, SDDL_REVISION_1, &security_descriptor_, nullptr)) {
return false; return false;
@@ -726,8 +718,7 @@ DWORD WINAPI CrossDeskServiceHost::ServiceControlHandler(
case SERVICE_CONTROL_SESSIONCHANGE: { case SERVICE_CONTROL_SESSIONCHANGE: {
DWORD session_id = 0xFFFFFFFF; DWORD session_id = 0xFFFFFFFF;
if (event_data != nullptr) { if (event_data != nullptr) {
auto* session = auto* session = reinterpret_cast<WTSSESSION_NOTIFICATION*>(event_data);
reinterpret_cast<WTSSESSION_NOTIFICATION*>(event_data);
session_id = session->dwSessionId; session_id = session->dwSessionId;
} }
instance_->RecordSessionEvent(event_type, session_id); instance_->RecordSessionEvent(event_type, session_id);
@@ -742,7 +733,8 @@ int CrossDeskServiceHost::RunAsService() {
instance_ = this; instance_ = this;
SERVICE_TABLE_ENTRYW service_table[] = { SERVICE_TABLE_ENTRYW service_table[] = {
{const_cast<LPWSTR>(kCrossDeskServiceName), &CrossDeskServiceHost::ServiceMain}, {const_cast<LPWSTR>(kCrossDeskServiceName),
&CrossDeskServiceHost::ServiceMain},
{nullptr, nullptr}}; {nullptr, nullptr}};
if (!StartServiceCtrlDispatcherW(service_table)) { if (!StartServiceCtrlDispatcherW(service_table)) {
@@ -897,7 +889,8 @@ int CrossDeskServiceHost::RunServiceLoop(bool as_service) {
if (console_mode_) { if (console_mode_) {
SetConsoleCtrlHandler(&CrossDeskServiceHost::ConsoleControlHandler, TRUE); SetConsoleCtrlHandler(&CrossDeskServiceHost::ConsoleControlHandler, TRUE);
std::cout << "CrossDesk service skeleton running in console mode. Press Ctrl+C to stop." std::cout << "CrossDesk service skeleton running in console mode. Press "
"Ctrl+C to stop."
<< std::endl; << std::endl;
} }
@@ -932,10 +925,9 @@ void CrossDeskServiceHost::IpcServerLoop() {
while (stop_event_ != nullptr && while (stop_event_ != nullptr &&
WaitForSingleObject(stop_event_, 0) != WAIT_OBJECT_0) { WaitForSingleObject(stop_event_, 0) != WAIT_OBJECT_0) {
HANDLE pipe = CreateNamedPipeW( HANDLE pipe = CreateNamedPipeW(
kCrossDeskServicePipeName, kCrossDeskServicePipeName, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, 1, 4096, 4096, 0,
PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, pipe_attributes);
1, 4096, 4096, 0, pipe_attributes);
if (pipe == INVALID_HANDLE_VALUE) { if (pipe == INVALID_HANDLE_VALUE) {
DWORD error = GetLastError(); DWORD error = GetLastError();
LOG_ERROR("CreateNamedPipeW failed, error={}", error); LOG_ERROR("CreateNamedPipeW failed, error={}", error);
@@ -1068,8 +1060,7 @@ bool CrossDeskServiceHost::ShouldKeepSecureInputHelperLocked(
return false; return false;
} }
return HasSecureInputUiLocked() || return HasSecureInputUiLocked() || (GetEffectiveSessionLockedLocked() &&
(GetEffectiveSessionLockedLocked() &&
IsHelperReportingLockScreenLocked()); IsHelperReportingLockScreenLocked());
} }
@@ -1257,8 +1248,8 @@ bool CrossDeskServiceHost::LaunchSessionHelper(DWORD session_id) {
event_attributes = event_security.get(); event_attributes = event_security.get();
} }
HANDLE stop_event_handle = CreateEventW(event_attributes, TRUE, FALSE, HANDLE stop_event_handle =
stop_event_name.c_str()); CreateEventW(event_attributes, TRUE, FALSE, stop_event_name.c_str());
if (stop_event_handle == nullptr) { if (stop_event_handle == nullptr) {
std::lock_guard<std::mutex> lock(state_mutex_); std::lock_guard<std::mutex> lock(state_mutex_);
session_helper_last_error_ = "create_helper_stop_event_failed"; session_helper_last_error_ = "create_helper_stop_event_failed";
@@ -1280,8 +1271,8 @@ bool CrossDeskServiceHost::LaunchSessionHelper(DWORD session_id) {
if (console_mode_ && process_session_id_ == session_id) { if (console_mode_ && process_session_id_ == session_id) {
created = CreateProcessW(helper_path.c_str(), mutable_command_line.data(), created = CreateProcessW(helper_path.c_str(), mutable_command_line.data(),
nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr,
nullptr, nullptr, &startup_info, &process_info); nullptr, &startup_info, &process_info);
} else { } else {
HANDLE user_token = nullptr; HANDLE user_token = nullptr;
HANDLE primary_token = nullptr; HANDLE primary_token = nullptr;
@@ -1315,8 +1306,7 @@ bool CrossDeskServiceHost::LaunchSessionHelper(DWORD session_id) {
FALSE); FALSE);
created = CreateProcessAsUserW( created = CreateProcessAsUserW(
primary_token, helper_path.c_str(), mutable_command_line.data(), primary_token, helper_path.c_str(), mutable_command_line.data(),
nullptr, nullptr, FALSE, nullptr, nullptr, FALSE, CREATE_UNICODE_ENVIRONMENT | CREATE_NO_WINDOW,
CREATE_UNICODE_ENVIRONMENT | CREATE_NO_WINDOW,
environment_block.environment, nullptr, &startup_info, &process_info); environment_block.environment, nullptr, &startup_info, &process_info);
DWORD error = created ? ERROR_SUCCESS : GetLastError(); DWORD error = created ? ERROR_SUCCESS : GetLastError();
CloseHandle(primary_token); CloseHandle(primary_token);
@@ -1364,8 +1354,8 @@ bool CrossDeskServiceHost::LaunchSecureInputHelper(DWORD session_id) {
event_attributes = event_security.get(); event_attributes = event_security.get();
} }
HANDLE stop_event_handle = CreateEventW(event_attributes, TRUE, FALSE, HANDLE stop_event_handle =
stop_event_name.c_str()); CreateEventW(event_attributes, TRUE, FALSE, stop_event_name.c_str());
if (stop_event_handle == nullptr) { if (stop_event_handle == nullptr) {
std::lock_guard<std::mutex> lock(state_mutex_); std::lock_guard<std::mutex> lock(state_mutex_);
secure_input_helper_last_error_ = secure_input_helper_last_error_ =
@@ -1388,8 +1378,8 @@ bool CrossDeskServiceHost::LaunchSecureInputHelper(DWORD session_id) {
if (console_mode_ && process_session_id_ == session_id) { if (console_mode_ && process_session_id_ == session_id) {
created = CreateProcessW(helper_path.c_str(), mutable_command_line.data(), created = CreateProcessW(helper_path.c_str(), mutable_command_line.data(),
nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr,
nullptr, nullptr, &startup_info, &process_info); nullptr, &startup_info, &process_info);
} else { } else {
HANDLE primary_token = nullptr; HANDLE primary_token = nullptr;
ScopedEnvironmentBlock environment_block; ScopedEnvironmentBlock environment_block;
@@ -1397,8 +1387,7 @@ bool CrossDeskServiceHost::LaunchSecureInputHelper(DWORD session_id) {
if (!CreateSessionSystemToken(session_id, &primary_token, &error)) { if (!CreateSessionSystemToken(session_id, &primary_token, &error)) {
CloseHandle(stop_event_handle); CloseHandle(stop_event_handle);
std::lock_guard<std::mutex> lock(state_mutex_); std::lock_guard<std::mutex> lock(state_mutex_);
secure_input_helper_last_error_ = secure_input_helper_last_error_ = "create_session_system_token_failed";
"create_session_system_token_failed";
secure_input_helper_last_error_code_ = error; secure_input_helper_last_error_code_ = error;
return false; return false;
} }
@@ -1407,16 +1396,14 @@ bool CrossDeskServiceHost::LaunchSecureInputHelper(DWORD session_id) {
FALSE); FALSE);
created = CreateProcessAsUserW( created = CreateProcessAsUserW(
primary_token, helper_path.c_str(), mutable_command_line.data(), primary_token, helper_path.c_str(), mutable_command_line.data(),
nullptr, nullptr, FALSE, nullptr, nullptr, FALSE, CREATE_UNICODE_ENVIRONMENT | CREATE_NO_WINDOW,
CREATE_UNICODE_ENVIRONMENT | CREATE_NO_WINDOW,
environment_block.environment, nullptr, &startup_info, &process_info); environment_block.environment, nullptr, &startup_info, &process_info);
error = created ? ERROR_SUCCESS : GetLastError(); error = created ? ERROR_SUCCESS : GetLastError();
CloseHandle(primary_token); CloseHandle(primary_token);
if (!created) { if (!created) {
CloseHandle(stop_event_handle); CloseHandle(stop_event_handle);
std::lock_guard<std::mutex> lock(state_mutex_); std::lock_guard<std::mutex> lock(state_mutex_);
secure_input_helper_last_error_ = secure_input_helper_last_error_ = "create_secure_input_helper_failed";
"create_secure_input_helper_failed";
secure_input_helper_last_error_code_ = error; secure_input_helper_last_error_code_ = error;
return false; return false;
} }
@@ -1515,8 +1502,7 @@ void CrossDeskServiceHost::RefreshSessionHelperReportedState() {
session_helper_report_session_id_ = session_helper_report_session_id_ =
json.value("session_id", static_cast<DWORD>(0xFFFFFFFF)); json.value("session_id", static_cast<DWORD>(0xFFFFFFFF));
session_helper_report_process_id_ = json.value("process_id", 0u); session_helper_report_process_id_ = json.value("process_id", 0u);
session_helper_report_session_locked_ = session_helper_report_session_locked_ = json.value("session_locked", false);
json.value("session_locked", false);
session_helper_report_input_desktop_available_ = session_helper_report_input_desktop_available_ =
json.value("input_desktop_available", false); json.value("input_desktop_available", false);
session_helper_report_input_desktop_error_code_ = session_helper_report_input_desktop_error_code_ =
@@ -1582,8 +1568,7 @@ void CrossDeskServiceHost::RecordSessionEvent(DWORD event_type,
} }
} }
std::string CrossDeskServiceHost::HandleIpcCommand( std::string CrossDeskServiceHost::HandleIpcCommand(const std::string& command) {
const std::string& command) {
std::string normalized = ToLower(Trim(command)); std::string normalized = ToLower(Trim(command));
if (normalized == "ping") { if (normalized == "ping") {
return "{\"ok\":true,\"reply\":\"pong\"}"; return "{\"ok\":true,\"reply\":\"pong\"}";
@@ -1596,8 +1581,7 @@ std::string CrossDeskServiceHost::HandleIpcCommand(
} }
int key_code = 0; int key_code = 0;
bool is_down = false; bool is_down = false;
if (ParseSecureDesktopKeyboardIpcCommand(normalized, &key_code, if (ParseSecureDesktopKeyboardIpcCommand(normalized, &key_code, &is_down)) {
&is_down)) {
return SendSecureDesktopKeyboardInput(key_code, is_down); return SendSecureDesktopKeyboardInput(key_code, is_down);
} }
return BuildErrorJson("unknown_command"); return BuildErrorJson("unknown_command");
@@ -1658,8 +1642,8 @@ std::string CrossDeskServiceHost::BuildStatusResponse() {
interactive_state_ready interactive_state_ready
? (effective_session_locked && IsHelperReportingLockScreenLocked()) ? (effective_session_locked && IsHelperReportingLockScreenLocked())
: false; : false;
bool credential_ui_visible = interactive_state_ready bool credential_ui_visible =
? session_helper_report_credential_ui_visible_ interactive_state_ready ? session_helper_report_credential_ui_visible_
: logon_ui_visible_; : logon_ui_visible_;
bool unlock_ui_visible = interactive_state_ready bool unlock_ui_visible = interactive_state_ready
? session_helper_report_unlock_ui_visible_ ? session_helper_report_unlock_ui_visible_
@@ -1670,15 +1654,14 @@ std::string CrossDeskServiceHost::BuildStatusResponse() {
bool interactive_logon_ui_visible = bool interactive_logon_ui_visible =
interactive_state_ready ? session_helper_report_logon_ui_visible_ interactive_state_ready ? session_helper_report_logon_ui_visible_
: logon_ui_visible_; : logon_ui_visible_;
bool interactive_session_locked = bool interactive_session_locked = effective_session_locked ||
effective_session_locked || interactive_lock_screen_visible || interactive_lock_screen_visible ||
unlock_ui_visible; unlock_ui_visible;
std::string interactive_input_desktop = EscapeJsonString( std::string interactive_input_desktop = EscapeJsonString(
interactive_state_ready ? session_helper_report_input_desktop_ interactive_state_ready ? session_helper_report_input_desktop_
: input_desktop_name_); : input_desktop_name_);
std::string interactive_stage = EscapeJsonString( std::string interactive_stage = EscapeJsonString(DetermineInteractiveStage(
DetermineInteractiveStage(interactive_lock_screen_visible, interactive_lock_screen_visible, credential_ui_visible,
credential_ui_visible,
interactive_secure_desktop_active)); interactive_secure_desktop_active));
std::ostringstream stream; std::ostringstream stream;
stream << "{\"ok\":true,\"service\":\"CrossDeskService\"" stream << "{\"ok\":true,\"service\":\"CrossDeskService\""
@@ -1687,27 +1670,25 @@ std::string CrossDeskServiceHost::BuildStatusResponse() {
<< ",\"session_locked\":" << (session_locked_ ? "true" : "false") << ",\"session_locked\":" << (session_locked_ ? "true" : "false")
<< ",\"interactive_state_ready\":" << ",\"interactive_state_ready\":"
<< (interactive_state_ready ? "true" : "false") << (interactive_state_ready ? "true" : "false")
<< ",\"interactive_state_source\":\"" << ",\"interactive_state_source\":\"" << interactive_state_source
<< interactive_state_source << "\"" << "\""
<< ",\"interactive_session_locked\":" << ",\"interactive_session_locked\":"
<< (interactive_session_locked ? "true" : "false") << (interactive_session_locked ? "true" : "false")
<< ",\"interactive_stage\":\"" << interactive_stage << "\"" << ",\"interactive_stage\":\"" << interactive_stage << "\""
<< ",\"interactive_input_desktop\":\"" << ",\"interactive_input_desktop\":\"" << interactive_input_desktop
<< interactive_input_desktop << "\"" << "\""
<< ",\"interactive_lock_screen_visible\":" << ",\"interactive_lock_screen_visible\":"
<< (interactive_lock_screen_visible ? "true" : "false") << (interactive_lock_screen_visible ? "true" : "false")
<< ",\"interactive_logon_ui_visible\":" << ",\"interactive_logon_ui_visible\":"
<< (interactive_logon_ui_visible ? "true" : "false") << (interactive_logon_ui_visible ? "true" : "false")
<< ",\"interactive_secure_desktop_active\":" << ",\"interactive_secure_desktop_active\":"
<< (interactive_secure_desktop_active ? "true" : "false") << (interactive_secure_desktop_active ? "true" : "false")
<< ",\"unlock_ui_visible\":" << ",\"unlock_ui_visible\":" << (unlock_ui_visible ? "true" : "false")
<< (unlock_ui_visible ? "true" : "false")
<< ",\"credential_ui_visible\":" << ",\"credential_ui_visible\":"
<< (credential_ui_visible ? "true" : "false") << (credential_ui_visible ? "true" : "false")
<< ",\"password_box_visible\":" << ",\"password_box_visible\":"
<< (credential_ui_visible ? "true" : "false") << (credential_ui_visible ? "true" : "false")
<< ",\"logon_ui_visible\":" << ",\"logon_ui_visible\":" << (logon_ui_visible_ ? "true" : "false")
<< (logon_ui_visible_ ? "true" : "false")
<< ",\"secure_desktop_active\":" << ",\"secure_desktop_active\":"
<< (secure_desktop_active_ ? "true" : "false") << (secure_desktop_active_ ? "true" : "false")
<< ",\"input_desktop_available\":" << ",\"input_desktop_available\":"
@@ -1720,17 +1701,15 @@ std::string CrossDeskServiceHost::BuildStatusResponse() {
<< ",\"session_helper_running\":" << ",\"session_helper_running\":"
<< (session_helper_running_ ? "true" : "false") << (session_helper_running_ ? "true" : "false")
<< ",\"session_helper_pid\":" << session_helper_process_id_ << ",\"session_helper_pid\":" << session_helper_process_id_
<< ",\"session_helper_session_id\":" << ",\"session_helper_session_id\":" << session_helper_session_id_
<< session_helper_session_id_
<< ",\"session_helper_exit_code\":" << session_helper_exit_code_ << ",\"session_helper_exit_code\":" << session_helper_exit_code_
<< ",\"session_helper_last_error\":\"" << ",\"session_helper_last_error\":\"" << session_helper_last_error
<< session_helper_last_error << "\"" << "\""
<< ",\"session_helper_last_error_code\":" << ",\"session_helper_last_error_code\":"
<< session_helper_last_error_code_ << session_helper_last_error_code_ << ",\"session_helper_status_ok\":"
<< ",\"session_helper_status_ok\":"
<< (session_helper_status_ok_ ? "true" : "false") << (session_helper_status_ok_ ? "true" : "false")
<< ",\"session_helper_status_error\":\"" << ",\"session_helper_status_error\":\"" << session_helper_status_error
<< session_helper_status_error << "\"" << "\""
<< ",\"session_helper_status_error_code\":" << ",\"session_helper_status_error_code\":"
<< session_helper_status_error_code_ << session_helper_status_error_code_
<< ",\"session_helper_report_session_id\":" << ",\"session_helper_report_session_id\":"
@@ -1760,17 +1739,15 @@ std::string CrossDeskServiceHost::BuildStatusResponse() {
<< ",\"session_helper_report_state_age_ms\":" << ",\"session_helper_report_state_age_ms\":"
<< session_helper_report_state_age_ms_ << session_helper_report_state_age_ms_
<< ",\"session_helper_report_uptime_ms\":" << ",\"session_helper_report_uptime_ms\":"
<< session_helper_report_uptime_ms_ << session_helper_report_uptime_ms_ << ",\"session_helper_uptime_ms\":"
<< ",\"session_helper_uptime_ms\":"
<< (session_helper_started_at_tick_ >= started_at_tick_ << (session_helper_started_at_tick_ >= started_at_tick_
? (GetTickCount64() - session_helper_started_at_tick_) ? (GetTickCount64() - session_helper_started_at_tick_)
: 0) : 0)
<< ",\"secure_input_helper_path\":\"" << ",\"secure_input_helper_path\":\"" << secure_input_helper_path
<< secure_input_helper_path << "\"" << "\""
<< ",\"secure_input_helper_running\":" << ",\"secure_input_helper_running\":"
<< (secure_input_helper_running_ ? "true" : "false") << (secure_input_helper_running_ ? "true" : "false")
<< ",\"secure_input_helper_pid\":" << ",\"secure_input_helper_pid\":" << secure_input_helper_process_id_
<< secure_input_helper_process_id_
<< ",\"secure_input_helper_session_id\":" << ",\"secure_input_helper_session_id\":"
<< secure_input_helper_session_id_ << secure_input_helper_session_id_
<< ",\"secure_input_helper_exit_code\":" << ",\"secure_input_helper_exit_code\":"
@@ -1783,8 +1760,7 @@ std::string CrossDeskServiceHost::BuildStatusResponse() {
<< (secure_input_helper_started_at_tick_ >= started_at_tick_ << (secure_input_helper_started_at_tick_ >= started_at_tick_
? (GetTickCount64() - secure_input_helper_started_at_tick_) ? (GetTickCount64() - secure_input_helper_started_at_tick_)
: 0) : 0)
<< ",\"last_sas_success\":" << ",\"last_sas_success\":" << (last_sas_success_ ? "true" : "false")
<< (last_sas_success_ ? "true" : "false")
<< ",\"last_sas_error\":\"" << last_sas_error << "\"" << ",\"last_sas_error\":\"" << last_sas_error << "\""
<< ",\"last_sas_error_code\":" << last_sas_error_code_ << ",\"last_sas_error_code\":" << last_sas_error_code_
<< ",\"last_sas_uptime_ms\":" << ",\"last_sas_uptime_ms\":"
@@ -1889,10 +1865,10 @@ bool InstallCrossDeskService(const std::wstring& binary_path) {
return false; return false;
} }
if (!ChangeServiceConfigW( if (!ChangeServiceConfigW(service, SERVICE_NO_CHANGE, SERVICE_AUTO_START,
service, SERVICE_NO_CHANGE, SERVICE_AUTO_START, SERVICE_NO_CHANGE, service_command.c_str(),
SERVICE_NO_CHANGE, service_command.c_str(), nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
nullptr, nullptr, nullptr, kCrossDeskServiceDisplayName)) { kCrossDeskServiceDisplayName)) {
LOG_ERROR("ChangeServiceConfigW failed, error={}", GetLastError()); LOG_ERROR("ChangeServiceConfigW failed, error={}", GetLastError());
CloseServiceHandle(service); CloseServiceHandle(service);
CloseServiceHandle(manager); CloseServiceHandle(manager);
@@ -1973,8 +1949,8 @@ bool StopCrossDeskService(DWORD timeout_ms) {
DWORD deadline = GetTickCount() + timeout_ms; DWORD deadline = GetTickCount() + timeout_ms;
while (GetTickCount() < deadline) { while (GetTickCount() < deadline) {
if (!QueryServiceStatusEx(service, SC_STATUS_PROCESS_INFO, if (!QueryServiceStatusEx(service, SC_STATUS_PROCESS_INFO,
reinterpret_cast<LPBYTE>(&status), reinterpret_cast<LPBYTE>(&status), sizeof(status),
sizeof(status), &bytes_needed)) { &bytes_needed)) {
LOG_ERROR("QueryServiceStatusEx failed, error={}", GetLastError()); LOG_ERROR("QueryServiceStatusEx failed, error={}", GetLastError());
CloseServiceHandle(service); CloseServiceHandle(service);
CloseServiceHandle(manager); CloseServiceHandle(manager);
@@ -2001,7 +1977,8 @@ bool UninstallCrossDeskService() {
return false; return false;
} }
SC_HANDLE service = OpenServiceW(manager, kCrossDeskServiceName, SC_HANDLE service =
OpenServiceW(manager, kCrossDeskServiceName,
DELETE | SERVICE_STOP | SERVICE_QUERY_STATUS); DELETE | SERVICE_STOP | SERVICE_QUERY_STATUS);
if (service == nullptr) { if (service == nullptr) {
DWORD error = GetLastError(); DWORD error = GetLastError();
+2 -4
View File
@@ -10,8 +10,7 @@
namespace crossdesk { namespace crossdesk {
inline constexpr wchar_t kCrossDeskServiceName[] = L"CrossDeskService"; inline constexpr wchar_t kCrossDeskServiceName[] = L"CrossDeskService";
inline constexpr wchar_t kCrossDeskServiceDisplayName[] = inline constexpr wchar_t kCrossDeskServiceDisplayName[] = L"CrossDesk Service";
L"CrossDesk Service";
inline constexpr wchar_t kCrossDeskServicePipeName[] = inline constexpr wchar_t kCrossDeskServicePipeName[] =
L"\\\\.\\pipe\\CrossDeskService"; L"\\\\.\\pipe\\CrossDeskService";
@@ -59,8 +58,7 @@ class CrossDeskServiceHost {
static void WINAPI ServiceMain(DWORD argc, LPWSTR* argv); static void WINAPI ServiceMain(DWORD argc, LPWSTR* argv);
static BOOL WINAPI ConsoleControlHandler(DWORD control_type); static BOOL WINAPI ConsoleControlHandler(DWORD control_type);
static DWORD WINAPI ServiceControlHandler(DWORD control, DWORD event_type, static DWORD WINAPI ServiceControlHandler(DWORD control, DWORD event_type,
LPVOID event_data, LPVOID event_data, LPVOID context);
LPVOID context);
private: private:
SERVICE_STATUS_HANDLE status_handle_ = nullptr; SERVICE_STATUS_HANDLE status_handle_ = nullptr;
+54 -51
View File
@@ -1,17 +1,14 @@
#include <Windows.h>
#include <nlohmann/json.hpp>
#include <libyuv.h>
#include <TlHelp32.h> #include <TlHelp32.h>
#include <Windows.h>
#include <WtsApi32.h> #include <WtsApi32.h>
#include <libyuv.h>
#include <sddl.h> #include <sddl.h>
#include <cstring> #include <cstring>
#include <filesystem> #include <filesystem>
#include <iostream> #include <iostream>
#include <mutex> #include <mutex>
#include <nlohmann/json.hpp>
#include <sstream> #include <sstream>
#include <string> #include <string>
#include <thread> #include <thread>
@@ -23,8 +20,8 @@
namespace { namespace {
using crossdesk::InitLogger;
using crossdesk::get_logger; using crossdesk::get_logger;
using crossdesk::InitLogger;
using Json = nlohmann::json; using Json = nlohmann::json;
struct InputDesktopInfo { struct InputDesktopInfo {
@@ -76,8 +73,7 @@ struct PipeSecurityAttributes {
} }
bool Initialize() { bool Initialize() {
constexpr wchar_t kPipeSddl[] = constexpr wchar_t kPipeSddl[] = L"D:(A;;GA;;;SY)(A;;GA;;;BA)(A;;GRGW;;;AU)";
L"D:(A;;GA;;;SY)(A;;GA;;;BA)(A;;GRGW;;;AU)";
if (!ConvertStringSecurityDescriptorToSecurityDescriptorW( if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(
kPipeSddl, SDDL_REVISION_1, &security_descriptor_, nullptr)) { kPipeSddl, SDDL_REVISION_1, &security_descriptor_, nullptr)) {
return false; return false;
@@ -100,7 +96,8 @@ void InitializeHelperLogger() {
static std::once_flag once_flag; static std::once_flag once_flag;
std::call_once(once_flag, []() { std::call_once(once_flag, []() {
crossdesk::PathManager path_manager("CrossDesk"); crossdesk::PathManager path_manager("CrossDesk");
std::filesystem::path log_path = path_manager.GetLogPath() / "session_helper"; std::filesystem::path log_path =
path_manager.GetLogPath() / "session_helper";
if (!log_path.empty() && path_manager.CreateDirectories(log_path)) { if (!log_path.empty() && path_manager.CreateDirectories(log_path)) {
InitLogger(log_path.string()); InitLogger(log_path.string());
return; return;
@@ -114,8 +111,8 @@ std::wstring Utf8ToWide(const std::string& value) {
return {}; return {};
} }
int size_needed = MultiByteToWideChar(CP_UTF8, 0, value.c_str(), -1, int size_needed =
nullptr, 0); MultiByteToWideChar(CP_UTF8, 0, value.c_str(), -1, nullptr, 0);
if (size_needed <= 1) { if (size_needed <= 1) {
return {}; return {};
} }
@@ -132,15 +129,15 @@ std::string WideToUtf8(const std::wstring& value) {
return {}; return {};
} }
int size_needed = WideCharToMultiByte(CP_UTF8, 0, value.c_str(), -1, int size_needed = WideCharToMultiByte(CP_UTF8, 0, value.c_str(), -1, nullptr,
nullptr, 0, nullptr, nullptr); 0, nullptr, nullptr);
if (size_needed <= 1) { if (size_needed <= 1) {
return {}; return {};
} }
std::string result(static_cast<size_t>(size_needed), '\0'); std::string result(static_cast<size_t>(size_needed), '\0');
WideCharToMultiByte(CP_UTF8, 0, value.c_str(), -1, result.data(), WideCharToMultiByte(CP_UTF8, 0, value.c_str(), -1, result.data(), size_needed,
size_needed, nullptr, nullptr); nullptr, nullptr);
result.pop_back(); result.pop_back();
return result; return result;
} }
@@ -330,8 +327,7 @@ std::string BuildHelperStatusResponse(HelperState* helper_state) {
json["interactive_stage"] = DetermineInteractiveStage( json["interactive_stage"] = DetermineInteractiveStage(
helper_state->lock_app_visible, credential_ui_visible, helper_state->lock_app_visible, credential_ui_visible,
helper_state->secure_desktop_active); helper_state->secure_desktop_active);
json["uptime_ms"] = json["uptime_ms"] = GetTickCount64() >= helper_state->started_at_tick
GetTickCount64() >= helper_state->started_at_tick
? (GetTickCount64() - helper_state->started_at_tick) ? (GetTickCount64() - helper_state->started_at_tick)
: 0; : 0;
json["state_age_ms"] = json["state_age_ms"] =
@@ -349,12 +345,14 @@ void HelperIpcServerLoop(HANDLE stop_event, DWORD session_id,
pipe_attributes = security_attributes.get(); pipe_attributes = security_attributes.get();
} }
std::wstring pipe_name = crossdesk::GetCrossDeskSessionHelperPipeName(session_id); std::wstring pipe_name =
while (stop_event == nullptr || WaitForSingleObject(stop_event, 0) != WAIT_OBJECT_0) { crossdesk::GetCrossDeskSessionHelperPipeName(session_id);
while (stop_event == nullptr ||
WaitForSingleObject(stop_event, 0) != WAIT_OBJECT_0) {
HANDLE pipe = CreateNamedPipeW( HANDLE pipe = CreateNamedPipeW(
pipe_name.c_str(), PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, pipe_name.c_str(), PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, 1, 4096, 4096, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, 1, 4096, 4096, 0,
0, pipe_attributes); pipe_attributes);
if (pipe == INVALID_HANDLE_VALUE) { if (pipe == INVALID_HANDLE_VALUE) {
LOG_ERROR("CreateNamedPipeW failed in helper, error={}", GetLastError()); LOG_ERROR("CreateNamedPipeW failed in helper, error={}", GetLastError());
if (stop_event != nullptr) { if (stop_event != nullptr) {
@@ -465,10 +463,9 @@ bool EnsureThreadDesktop(const wchar_t* desktop_name,
return true; return true;
} }
HDESK desktop = OpenDesktopW( HDESK desktop = OpenDesktopW(desktop_name, 0, FALSE,
desktop_name, 0, FALSE, DESKTOP_CREATEWINDOW | DESKTOP_WRITEOBJECTS |
DESKTOP_CREATEWINDOW | DESKTOP_WRITEOBJECTS | DESKTOP_READOBJECTS | DESKTOP_READOBJECTS | DESKTOP_SWITCHDESKTOP);
DESKTOP_SWITCHDESKTOP);
if (desktop == nullptr) { if (desktop == nullptr) {
return false; return false;
} }
@@ -515,14 +512,13 @@ int InjectKeyboardInput(int key_code, bool is_down) {
} }
bool ParseSecureInputKeyboardCommand(const std::string& command, bool ParseSecureInputKeyboardCommand(const std::string& command,
int* key_code_out, int* key_code_out, bool* is_down_out) {
bool* is_down_out) {
if (key_code_out == nullptr || is_down_out == nullptr) { if (key_code_out == nullptr || is_down_out == nullptr) {
return false; return false;
} }
if (command.rfind(crossdesk::kCrossDeskSecureInputKeyboardCommandPrefix, if (command.rfind(crossdesk::kCrossDeskSecureInputKeyboardCommandPrefix, 0) !=
0) != 0) { 0) {
return false; return false;
} }
@@ -622,8 +618,7 @@ bool ParseSecureInputCaptureCommand(const std::string& command,
for (int index = 0; index < 5; ++index) { for (int index = 0; index < 5; ++index) {
const size_t separator = command.find(':', token_begin); const size_t separator = command.find(':', token_begin);
const bool is_last = index == 4; const bool is_last = index == 4;
const size_t token_end = const size_t token_end = is_last ? command.size() : separator;
is_last ? command.size() : separator;
if (token_end == std::string::npos || token_end <= token_begin) { if (token_end == std::string::npos || token_end <= token_begin) {
return false; return false;
} }
@@ -734,8 +729,7 @@ std::vector<uint8_t> CaptureSecureDesktopFrame(
const DWORD error = GetLastError(); const DWORD error = GetLastError();
DeleteDC(mem_dc); DeleteDC(mem_dc);
ReleaseDC(nullptr, screen_dc); ReleaseDC(nullptr, screen_dc);
return BuildTextResponseBytes( return BuildTextResponseBytes(BuildErrorJson("create_dib_failed", error));
BuildErrorJson("create_dib_failed", error));
} }
HGDIOBJ old_bitmap = SelectObject(mem_dc, dib); HGDIOBJ old_bitmap = SelectObject(mem_dc, dib);
@@ -746,8 +740,7 @@ std::vector<uint8_t> CaptureSecureDesktopFrame(
DeleteObject(dib); DeleteObject(dib);
DeleteDC(mem_dc); DeleteDC(mem_dc);
ReleaseDC(nullptr, screen_dc); ReleaseDC(nullptr, screen_dc);
return BuildTextResponseBytes( return BuildTextResponseBytes(BuildErrorJson("bitblt_failed", error));
BuildErrorJson("bitblt_failed", error));
} }
if (request.show_cursor) { if (request.show_cursor) {
@@ -757,8 +750,8 @@ std::vector<uint8_t> CaptureSecureDesktopFrame(
cursor_info.hCursor != nullptr) { cursor_info.hCursor != nullptr) {
const int cursor_x = cursor_info.ptScreenPos.x - request.left; const int cursor_x = cursor_info.ptScreenPos.x - request.left;
const int cursor_y = cursor_info.ptScreenPos.y - request.top; const int cursor_y = cursor_info.ptScreenPos.y - request.top;
if (cursor_x >= -64 && cursor_y >= -64 && if (cursor_x >= -64 && cursor_y >= -64 && cursor_x < request.width + 64 &&
cursor_x < request.width + 64 && cursor_y < request.height + 64) { cursor_y < request.height + 64) {
DrawIconEx(mem_dc, cursor_x, cursor_y, cursor_info.hCursor, 0, 0, 0, DrawIconEx(mem_dc, cursor_x, cursor_y, cursor_info.hCursor, 0, 0, 0,
nullptr, DI_NORMAL); nullptr, DI_NORMAL);
} }
@@ -790,7 +783,8 @@ std::vector<uint8_t> CaptureSecureDesktopFrame(
header.top = request.top; header.top = request.top;
header.width = static_cast<uint32_t>(request.width); header.width = static_cast<uint32_t>(request.width);
header.height = static_cast<uint32_t>(request.height); header.height = static_cast<uint32_t>(request.height);
header.payload_size = static_cast<uint32_t>(capture_buffers->nv12_frame.size()); header.payload_size =
static_cast<uint32_t>(capture_buffers->nv12_frame.size());
std::vector<uint8_t> response(sizeof(header) + std::vector<uint8_t> response(sizeof(header) +
capture_buffers->nv12_frame.size()); capture_buffers->nv12_frame.size());
@@ -804,8 +798,7 @@ std::vector<uint8_t> CaptureSecureDesktopFrame(
} }
std::vector<uint8_t> HandleSecureInputHelperCommand( std::vector<uint8_t> HandleSecureInputHelperCommand(
const std::string& command, const std::string& command, SecureCaptureBuffers* capture_buffers) {
SecureCaptureBuffers* capture_buffers) {
if (command == "ping") { if (command == "ping") {
return BuildTextResponseBytes("{\"ok\":true,\"reply\":\"pong\"}"); return BuildTextResponseBytes("{\"ok\":true,\"reply\":\"pong\"}");
} }
@@ -816,7 +809,8 @@ std::vector<uint8_t> HandleSecureInputHelperCommand(
const int inject_result = InjectKeyboardInput(key_code, is_down); const int inject_result = InjectKeyboardInput(key_code, is_down);
if (inject_result != 0) { if (inject_result != 0) {
LOG_WARN( LOG_WARN(
"Secure input helper SendInput failed for key_code={}, is_down={}, err={}", "Secure input helper SendInput failed for key_code={}, is_down={}, "
"err={}",
key_code, is_down, inject_result); key_code, is_down, inject_result);
return BuildTextResponseBytes(BuildErrorJson( return BuildTextResponseBytes(BuildErrorJson(
"send_input_failed", static_cast<DWORD>(inject_result))); "send_input_failed", static_cast<DWORD>(inject_result)));
@@ -836,7 +830,8 @@ std::vector<uint8_t> HandleSecureInputHelperCommand(
const int inject_result = InjectMouseInput(mouse_request); const int inject_result = InjectMouseInput(mouse_request);
if (inject_result != 0) { if (inject_result != 0) {
LOG_WARN( LOG_WARN(
"Secure input helper SendInput failed for mouse x={}, y={}, wheel={}, flag={}, err={}", "Secure input helper SendInput failed for mouse x={}, y={}, "
"wheel={}, flag={}, err={}",
mouse_request.x, mouse_request.y, mouse_request.wheel, mouse_request.x, mouse_request.y, mouse_request.wheel,
mouse_request.flag, inject_result); mouse_request.flag, inject_result);
return BuildTextResponseBytes(BuildErrorJson( return BuildTextResponseBytes(BuildErrorJson(
@@ -1010,7 +1005,9 @@ int main(int argc, char* argv[]) {
} }
if (run_secure_input_helper) { if (run_secure_input_helper) {
LOG_INFO("Secure input helper starting: pid={}, current_session_id={}, expected_session_id={}", LOG_INFO(
"Secure input helper starting: pid={}, current_session_id={}, "
"expected_session_id={}",
GetCurrentProcessId(), current_session_id, expected_session_id); GetCurrentProcessId(), current_session_id, expected_session_id);
if (expected_session_id != 0xFFFFFFFF && if (expected_session_id != 0xFFFFFFFF &&
expected_session_id != current_session_id) { expected_session_id != current_session_id) {
@@ -1020,7 +1017,8 @@ int main(int argc, char* argv[]) {
HDESK secure_desktop = nullptr; HDESK secure_desktop = nullptr;
if (!EnsureThreadDesktop(L"Winlogon", &secure_desktop)) { if (!EnsureThreadDesktop(L"Winlogon", &secure_desktop)) {
LOG_ERROR("Failed to switch secure input helper to Winlogon desktop, error={}", LOG_ERROR(
"Failed to switch secure input helper to Winlogon desktop, error={}",
GetLastError()); GetLastError());
if (stop_event != nullptr) { if (stop_event != nullptr) {
CloseHandle(stop_event); CloseHandle(stop_event);
@@ -1042,7 +1040,9 @@ int main(int argc, char* argv[]) {
return 0; return 0;
} }
LOG_INFO("Session helper starting: pid={}, current_session_id={}, expected_session_id={}", LOG_INFO(
"Session helper starting: pid={}, current_session_id={}, "
"expected_session_id={}",
GetCurrentProcessId(), current_session_id, expected_session_id); GetCurrentProcessId(), current_session_id, expected_session_id);
HelperState helper_state; HelperState helper_state;
@@ -1087,9 +1087,11 @@ int main(int argc, char* argv[]) {
session_locked != last_session_locked || session_locked != last_session_locked ||
lock_app_visible != last_lock_app || lock_app_visible != last_lock_app ||
logon_ui_running != last_logon_ui || logon_ui_running != last_logon_ui ||
secure_desktop_active != last_secure_desktop || secure_desktop_active != last_secure_desktop || stage != last_stage) {
stage != last_stage) { LOG_INFO(
LOG_INFO("Session helper state: session_id={}, input_desktop='{}', session_locked={}, lock_app_visible={}, logon_ui_running={}, secure_desktop_active={}, stage={}", "Session helper state: session_id={}, input_desktop='{}', "
"session_locked={}, lock_app_visible={}, logon_ui_running={}, "
"secure_desktop_active={}, stage={}",
current_session_id, desktop_name, session_locked, lock_app_visible, current_session_id, desktop_name, session_locked, lock_app_visible,
logon_ui_running, secure_desktop_active, stage); logon_ui_running, secure_desktop_active, stage);
last_desktop_name = desktop_name; last_desktop_name = desktop_name;
@@ -1100,8 +1102,9 @@ int main(int argc, char* argv[]) {
last_stage = stage; last_stage = stage;
} }
DWORD wait_result = DWORD wait_result = stop_event != nullptr
stop_event != nullptr ? WaitForSingleObject(stop_event, 1000) : WAIT_TIMEOUT; ? WaitForSingleObject(stop_event, 1000)
: WAIT_TIMEOUT;
if (wait_result == WAIT_OBJECT_0) { if (wait_result == WAIT_OBJECT_0) {
break; break;
} }
+3 -6
View File
@@ -15,12 +15,9 @@ inline constexpr wchar_t kCrossDeskSecureInputHelperPipePrefix[] =
inline constexpr char kCrossDeskSessionHelperStatusCommand[] = "status"; inline constexpr char kCrossDeskSessionHelperStatusCommand[] = "status";
inline constexpr char kCrossDeskSecureInputKeyboardCommandPrefix[] = inline constexpr char kCrossDeskSecureInputKeyboardCommandPrefix[] =
"keyboard:"; "keyboard:";
inline constexpr char kCrossDeskSecureInputMouseCommandPrefix[] = inline constexpr char kCrossDeskSecureInputMouseCommandPrefix[] = "mouse:";
"mouse:"; inline constexpr char kCrossDeskSecureInputCaptureCommandPrefix[] = "capture:";
inline constexpr char kCrossDeskSecureInputCaptureCommandPrefix[] = inline constexpr DWORD kCrossDeskSecureInputPipeBufferBytes = 16 * 1024 * 1024;
"capture:";
inline constexpr DWORD kCrossDeskSecureInputPipeBufferBytes =
16 * 1024 * 1024;
inline constexpr uint32_t kCrossDeskSecureDesktopFrameMagic = 0x50444358; inline constexpr uint32_t kCrossDeskSecureDesktopFrameMagic = 0x50444358;
inline constexpr uint32_t kCrossDeskSecureDesktopFrameVersion = 1; inline constexpr uint32_t kCrossDeskSecureDesktopFrameVersion = 1;