Feature: Add window info RPC for foreground checks and window activation

Add a capability-gated main-connection RPC (COMMAND_MCP_WINDOW_INFO=179 /
TOKEN_MCP_WINDOW_INFO=180) that returns visible top-level windows with UTF-8
titles, screen rectangles, foreground flag and z-order, so MCP can verify
focus before injecting input. New tool get_foreground_window; host_list_windows
switches to the richer fields; host_control_window and operate_window gain
action=activate; remote_keyboard and remote_mouse gain expect_hwnd,
require_foreground and report_foreground. Old clients keep the previous
behavior: the RPC is refused up front via CLIENT_CAP_WINDOW_INFO.

The client caps a response at 96 windows (about 101 KB, under MAX_SEND_BUFFER).
Signal the cut-off in the mode byte (0x80) instead of silently dropping windows:
host_list_windows now reports truncated=true and says the list is incomplete,
and activate verification reports state=unknown with reason=list_truncated
rather than claiming the window is gone. expect_hwnd is checked only after the
session is validated, so an invalid session_id no longer burns a window RPC and
no longer reports a window error for a session that does not exist. Nullable
output fields (foreground, window) are declared as ["object","null"] so strict
clients do not reject responses.

Co-Authored-By: deepseek-flash
This commit is contained in:
yuanyuanxianganddeepseek-flash committed 2026-11-10 15:09:24 +01:00
1 parent c7e23f750d
commit b2c0d81396
18 files changed
+1298 -68

No files matched your search

+25
View File
@@ -36,6 +36,31 @@ DWORD WINAPI ThreadProc(LPVOID lParam)
return dwReturn;
}
bool ClientActivateWindow(HWND hwnd)
{
if (!hwnd || !::IsWindow(hwnd))
return false;
if (::IsIconic(hwnd))
::ShowWindow(hwnd, SW_RESTORE); // 最小化窗口先还原,否则 SetForegroundWindow 不生效
else
::ShowWindow(hwnd, SW_SHOW);
HWND fg = ::GetForegroundWindow();
const DWORD fgThread = fg ? ::GetWindowThreadProcessId(fg, NULL) : 0;
const DWORD thisThread = ::GetCurrentThreadId();
const BOOL attached = (fgThread && fgThread != thisThread)
? ::AttachThreadInput(thisThread, fgThread, TRUE) : FALSE;
::BringWindowToTop(hwnd);
::SetForegroundWindow(hwnd);
if (attached)
::AttachThreadInput(thisThread, fgThread, FALSE);
return ::GetForegroundWindow() == hwnd;
}
template <class Manager, int n> DWORD WINAPI LoopManager(LPVOID lParam)
{
ThreadInfo *pInfo = (ThreadInfo *)lParam;
+4
View File
@@ -21,6 +21,10 @@ typedef struct UserParam {
} UserParam;
DWORD WINAPI ThreadProc(LPVOID lParam);
// 把窗口真正切到前台。与裸 ShowWindow(SW_SHOW) 不同:最小化先还原,再临时附加到
// 前台线程的输入队列,绕过 SetForegroundWindow 的焦点窃取限制。返回最终是否在前台。
bool ClientActivateWindow(HWND hwnd);
DWORD private_desktop(CONNECT_ADDRESS* conn, const State& exit, const std::string& msg, const std::string& signature,
const std::string& hash, const std::string& hmac, const std::vector<BYTE>& bmpData = std::vector<BYTE>());
+91
View File
@@ -849,6 +849,80 @@ static void ApplyTlsAnchorChange(IOCPClient* client)
client->Disconnect(); // 断开后由重连循环用新传输方式重新登录
}
// ── MCP 窗口信息 RPC(CLIENT_CAP_WINDOW_INFO)────────────────────────────────
// 与 TOKEN_MACHINE_WINDOWS 的固定 1044 字节记录不同:这里输出 UTF-8 标题、屏幕矩形、
// z 序与前后台/最小化状态,供服务端把截图坐标和窗口直接对上。
struct McpWindowEnumCtx {
std::vector<WINDOWINFO_MCP>* out;
HWND foreground;
int z;
};
static BOOL CALLBACK McpEnumWindowProc(HWND hwnd, LPARAM lParam)
{
auto* ctx = reinterpret_cast<McpWindowEnumCtx*>(lParam);
if (!hwnd || !::IsWindowVisible(hwnd))
return TRUE;
WINDOWINFO_MCP info = {};
RECT rc = {};
::GetWindowRect(hwnd, &rc);
info.hwnd = (uint32_t)(uintptr_t)hwnd;
DWORD pid = 0;
::GetWindowThreadProcessId(hwnd, &pid);
info.pid = pid;
info.left = rc.left;
info.top = rc.top;
info.right = rc.right;
info.bottom = rc.bottom;
info.flags = WINDOWINFO_VISIBLE;
if (::IsIconic(hwnd)) info.flags |= WINDOWINFO_MINIMIZED;
if (::IsZoomed(hwnd)) info.flags |= WINDOWINFO_MAXIMIZED;
if (hwnd == ctx->foreground) info.flags |= WINDOWINFO_FOREGROUND;
info.zorder = ctx->z++;
wchar_t title[1024] = {};
int n = ::GetWindowTextW(hwnd, title, (int)(sizeof(title) / sizeof(title[0])));
if (n > 0) {
// 先转到足够大的临时区再截断:直接把 1023 字节的 info.title 交给
// WideCharToMultiByte,长中文标题会整条转换失败(返回 0)而丢掉标题。
std::vector<char> utf8((size_t)n * 4 + 1, 0);
int bytes = ::WideCharToMultiByte(CP_UTF8, 0, title, n, utf8.data(),
(int)utf8.size() - 1, NULL, NULL);
if (bytes > 0) {
size_t len = (size_t)bytes < sizeof(info.title) - 1 ? (size_t)bytes : sizeof(info.title) - 1;
while (len > 0 && ((unsigned char)utf8[len] & 0xC0) == 0x80) --len; // 不回退到半个 UTF-8 字符
memcpy(info.title, utf8.data(), len);
}
}
ctx->out->push_back(info);
return TRUE;
}
static void ReplyMcpWindowInfo(IOCPClient* client, uint8_t mode)
{
std::vector<WINDOWINFO_MCP> windows;
// EnumWindows 按 z 序从上到下枚举
McpWindowEnumCtx ctx = { &windows, ::GetForegroundWindow(), 0 };
::EnumWindows(McpEnumWindowProc, (LPARAM)&ctx);
// 单包上限 MAX_SEND_BUFFER(128KB):96 × 1056 ≈ 101KB,留余量。被截断时在模式
// 字节最高位置 1,服务端据此报告"列表不完整",而不是把第 97 个以后的窗口当成不存在。
size_t count = windows.size() > 96 ? 96 : windows.size();
const bool truncated = windows.size() > count;
std::vector<BYTE> pkt(4 + count * sizeof(WINDOWINFO_MCP), 0);
pkt[0] = TOKEN_MCP_WINDOW_INFO;
pkt[1] = (BYTE)(mode | (truncated ? 0x80 : 0));
pkt[2] = (BYTE)(count & 0xFF);
pkt[3] = (BYTE)(count >> 8);
if (count)
memcpy(pkt.data() + 4, windows.data(), count * sizeof(WINDOWINFO_MCP));
if (client && client->IsConnected())
client->Send2Server((char*)pkt.data(), (int)pkt.size());
}
VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
{
bool isExit = szBuffer[0] == COMMAND_BYE || szBuffer[0] == SERVER_EXIT;
@@ -1593,6 +1667,23 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
break;
}
case COMMAND_MCP_WINDOW_INFO: {
// 请求 payload: [mode:1]。EnumWindows/GetWindowTextW 可能被挂起的窗口拖住,
// 投递到工作线程,避免阻塞主连接收包。
const uint8_t mode = (ulLength > 1) ? szBuffer[1] : 0;
static std::atomic<int> s_winInfoInFlight{0};
if (s_winInfoInFlight.fetch_add(1) >= 1) {
s_winInfoInFlight.fetch_sub(1);
break; // 已有任务在跑:直接丢弃,服务端按超时处理
}
IOCPClient* client = m_ClientObject;
std::thread([client, mode]() {
struct Guard { ~Guard() { s_winInfoInFlight.fetch_sub(1); } } guard;
ReplyMcpWindowInfo(client, mode);
}).detach();
break;
}
case COMMAND_SCREEN_SPY: {
if (!ENABLE_SCREEN) {
return ResponseDisable(m_ClientObject, "SCREEN", szBuffer + 1, ulLength - 1);
+9 -1
View File
@@ -3,6 +3,9 @@
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "MachineManager.h"
// 不能包含 Common.h:本文件里的注入用 ThreadProc 会与 Common.h 的同名函数形成重载,
// 导致下面 (DWORD_PTR)ThreadProc 的取址歧义。这里只声明需要的辅助函数。
bool ClientActivateWindow(HWND hwnd);
#include <psapi.h>
#include <LMACCESS.h>
#include <LMERR.h>
@@ -165,7 +168,12 @@ void CMachineManager::OnReceive(PBYTE lpBuffer, ULONG nSize)
DWORD dHow;
memcpy((void*)&hwnd, lpBuffer + 1, sizeof(DWORD)); //得到窗口句柄
memcpy(&dHow, lpBuffer + 1 + sizeof(DWORD), sizeof(DWORD)); //得到窗口处理参数
ShowWindow((HWND__*)hwnd, dHow);
// 能力位 CLIENT_CAP_WINDOW_INFO 下的“激活”哨兵:ShowWindow 只能改可见性,
// 后台窗口仍会被别的窗口盖住,必须走真正的置前逻辑。
if (dHow == CMD_WINDOW_ACTIVATE_FLAG)
ClientActivateWindow((HWND)hwnd);
else
ShowWindow((HWND__*)hwnd, dHow);
}
break;
case COMMAND_WINDOW_CLOSE: { //关闭
+5 -1
View File
@@ -218,7 +218,11 @@ void CSystemManager::TestWindow(LPBYTE szBuffer) //窗口的最大 最小 隐
DWORD dHow;
memcpy((void*)&Hwnd,szBuffer,sizeof(DWORD)); //得到窗口句柄
memcpy(&dHow,szBuffer+sizeof(DWORD),sizeof(DWORD)); //得到窗口处理参数
ShowWindow((HWND__ *)Hwnd,dHow);
// 激活哨兵(见 CMD_WINDOW_ACTIVATE_FLAG):老客户端会把它当非法 SW 值,故仅能力位下下发。
if (dHow == CMD_WINDOW_ACTIVATE_FLAG)
ClientActivateWindow((HWND)Hwnd);
else
ShowWindow((HWND__ *)Hwnd,dHow);
//窗口句柄 干啥(大 小 隐藏 还原)
}