Files
SimpleRemoter/server/2015Remote/McpServer.cpp
T
yuanyuanxianganddeepseek-flash d8048979e3 Feature: Report activity history on Linux clients
Implement COMMAND_QUERY_ACTIVITY -> TOKEN_REPORT_ACTIVITY with two backends
picked at startup. With a desktop, a sampler thread reads the foreground
window every second and books dwell time like the Windows client: under
five seconds is dropped, five idle minutes close the window, the last 500
records stay newest first, each line being "[YYYY-MM-DD HH:MM:SS] [title]
duration". It uses its own ActivityChecker because an Xlib connection
cannot be shared with the heartbeat thread, and it is stopped before main's
locals go away.

A reachable X server is not enough: the window backend is only chosen when
the root window carries _NET_SUPPORTING_WM_CHECK, so Xvfb or a bare X
without an EWMH window manager falls back to the headless backend instead
of sampling a window id that never appears.

Without a desktop the answer is computed on demand: logins from
"last -n 100 -F" plus bash/zsh history of root and /home/*, tagged [登录] or
[命令] after a [来源] header. Both halves are merged and sorted by
timestamp; three fifths of the budget goes to logins and reboot records are
capped at ten, since a WSL or container writes one reboot per start.
activity_commands=0 drops the command half.

A single detached thread builds and sends it, only while the main link is up.

The MCP gate now admits Linux for get_activity_history and documents both
shapes. test/unit/linux covers the parsers, ordering and UTF-8 truncation;
15 cases pass.

Co-Authored-By: deepseek-flash
2026-11-08 15:22:09 +01:00

11541 lines
536 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include "stdafx.h"
#include "McpServer.h"
#include "jsoncpp/json.h"
#include "HostJson.h" // BuildHostJson(单台主机序列化公共函数)
#include "context.h" // context 接口
#include "2015RemoteDlg.h" // CMy2015RemoteDlg 成员(m_HostList/m_cs/m_ClientMap)+ VERSION_STR
#include "WebService.h" // 远程控制复用屏幕子连接(StartRemoteDesktop / GetScreenContext / GetScreenSize)
#include "Server.h" // CONTEXT_OBJECT 定义(GetScreenContext 返回 CONTEXT_OBJECT* → context* 上转型)
#include "LangManager.h" // _TR(审计日志标题语言映射)
#include "common/file_upload.h" // V2 文件传输(RecvFileChunkV2 / HandleFileCompleteV2 / 包结构)
#include "McpInternal.h" // 共享助手(McpMachine.cpp 也使用)
#include "McpMachine.h" // 主机管理 / 连接管理工具族
#include "McpChat.h" // 远程交谈工具族
#include <sstream>
#ifndef _WIN64
#ifdef _DEBUG
#pragma comment(lib, "jsoncpp/jsoncppd.lib")
#else
#pragma comment(lib, "jsoncpp/jsoncpp.lib")
#endif
#else
#ifdef _DEBUG
#pragma comment(lib, "jsoncpp/jsoncpp_x64d.lib")
#else
#pragma comment(lib, "jsoncpp/jsoncpp_x64.lib")
#endif
#endif
// P6 download_file 复用 V2 落盘接口,需 FileManagerDlg 同款密码哈希 / HMAC 参数
// (声明见 CPasswordDlg.h,避免在此引入重量级 MFC 头)。
std::string GetPwdHash();
std::string GetHMAC(int offset);
// 共享助手(JsonToString/BuildResult/ParseHostIdArg/FindMainContext/ToUtf8/ToAnsi/...)
// 已抽到 McpInternal.cpp;此处引入后调用点保持原样。
using namespace McpInternal;
namespace {
// JSON-RPC id 的「展示文本」:字符串 id 取原文、整数 id 取十进制数字。
// 与紧凑序列化(字符串带引号)相对:mcp_list_sessions 输出的是文本,调用方原样
// 回传给 mcp_cancel_session / notifications/cancelled 也能命中。
std::string McpRequestIdText(const Json::Value& v) {
if (v.isString()) return v.asString();
if (v.isInt64()) return std::to_string(v.asInt64());
if (v.isUInt64()) return std::to_string(v.asUInt64());
return JsonToString(v); // 其余类型(null / 浮点)不会出现在 tools/call 的 id 上
}
} // namespace
// ============================================================================
// P11:progress / cancelled —— 在飞调用上下文与 SSE 进度通道
// ============================================================================
//
// 传输层事实:本服务端每个 POST 只回一个 JSON 响应,没有 SSE。MCP Streamable HTTP
// 允许(并要求客户端接受)POST 的响应是 text/event-stream——带 _meta.progressToken
// 的 tools/call 就走这条路径:工具在独立线程执行,进度通知与最终响应都从同一个
// chunked 流写出。不需要额外的 GET 流,也不影响不带 token 的请求(仍是一次性 JSON)。
namespace {
// 客户端读得慢时最多积压的进度通知条数:进度是「最新值有意义」的信号,丢最旧的。
const size_t kProgressQueueMax = 64;
std::string SseMessage(const std::string& json) {
return "event: message\ndata: " + json + "\n\n";
}
// 进度数值:本服务端的进度都是整数(字节/文件数/条数)。%g 只有 6 位有效数字,
// 67108864 会被写成 6.71089e+07 —— 客户端拿它算百分比就偏了,故整数值按十进制整数
// 输出;非整数(理论上的比例值)才退回 %g。
std::string FormatProgressNum(double v) {
char buf[64];
if (v >= -9.0e15 && v <= 9.0e15 && v == (double)(long long)v)
_snprintf_s(buf, sizeof(buf), _TRUNCATE, "%lld", (long long)v);
else
_snprintf_s(buf, sizeof(buf), _TRUNCATE, "%g", v);
return buf;
}
} // namespace
// 一次 SSE 请求的写出队列。工具线程 Push,httplib 的 content provider 线程 Pump。
struct McpProgressChannel {
std::mutex mu;
std::condition_variable cv;
std::deque<std::string> events;
bool finished = false;
std::string finalBody;
// 反向引用用 weak_ptr:McpCallContext 持有 channel,不能形成循环。
std::weak_ptr<McpCallContext> call;
void Push(std::string ev) {
std::lock_guard<std::mutex> lk(mu);
if (events.size() >= kProgressQueueMax) events.pop_front();
events.push_back(std::move(ev));
cv.notify_one();
}
void Finish(std::string body) {
{
std::lock_guard<std::mutex> lk(mu);
finalBody = std::move(body);
finished = true;
}
cv.notify_one();
}
// 由 httplib 反复调用:有事件就写一条,收尾时写最终响应并结束流。
// 客户端提前断开(write 失败)→ 置取消位,让仍在跑的工具尽快停下并清理。
bool Pump(httplib::DataSink& sink) {
std::unique_lock<std::mutex> lk(mu);
while (events.empty() && !finished)
cv.wait_for(lk, std::chrono::milliseconds(500));
if (!events.empty()) {
std::string ev = std::move(events.front());
events.pop_front();
lk.unlock();
if (!sink.write(ev.data(), ev.size())) {
if (auto c = call.lock()) c->cancelled.store(true);
return false;
}
return true;
}
std::string body = std::move(finalBody);
lk.unlock();
std::string ev = SseMessage(body);
sink.write(ev.data(), ev.size()); // 写失败也要收尾(客户端已走,done 自己会跳过)
// 必须显式收尾:httplib 的 chunked provider 在返回 false 时不会补终止块
// (write_content_chunked 直接返回 Canceled),客户端会看到「传输被截断」
// —— curl 报 18,.NET 报 "Unable to read data from the transport connection"。
// done() 会写出 0\r\n\r\n 并把 data_available 置 false,因此这里返回 true,
// 让 provider 循环按正常结束退出。
sink.done();
return true;
}
};
void McpCallContext::EmitProgress(double current, double total, bool hasTotal) {
if (!hasProgressToken || !channel) return;
{
std::lock_guard<std::mutex> lk(progressMu);
const auto now = std::chrono::steady_clock::now();
if (lastProgressAt.time_since_epoch().count() != 0 &&
now - lastProgressAt < std::chrono::milliseconds(1000))
return;
lastProgressAt = now;
}
std::string json = "{\"jsonrpc\":\"2.0\",\"method\":\"notifications/progress\",\"params\":{\"progressToken\":";
json += progressTokenJson;
json += ",\"progress\":";
json += FormatProgressNum(current);
if (hasTotal) {
json += ",\"total\":";
json += FormatProgressNum(total);
}
json += "}}";
channel->Push(SseMessage(json));
}
// 「当前线程正在跑的 MCP 调用」上下文。工具实现(含 McpMachine.cpp / McpChat.cpp)在
// 工具线程上直接取它,MFC 的 IO/UI 线程永远是空的。
//
// 这里刻意不用 C++ 的 thread_local:本工程有一部分代码跑在 shellcode / MemoryModule
// 手工映射出来的线程上(见 common/SafeString.h 的同类告警),实测给服务端加一个静态
// thread_local(哪怕只是一个 int)就会让进程启动约 1s 后跳飞。改用 FLS(Fiber Local
// Storage):纯 Win32 的每线程槽,不依赖 PE 的 TLS 目录,线程退出时由系统回调释放。
namespace {
DWORD g_mcpCallSlot = FLS_OUT_OF_INDEXES;
using McpCallSlotPtr = std::shared_ptr<McpCallContext>*;
void NTAPI McpCallSlotDetach(void* p) { delete static_cast<McpCallSlotPtr>(p); }
// 静态构造时取槽位:FlsAlloc 只为整个进程分配一个索引,与线程数无关。
struct McpCallSlotInit {
McpCallSlotInit() { g_mcpCallSlot = FlsAlloc(McpCallSlotDetach); }
} g_mcpCallSlotInit;
inline McpCallSlotPtr LoadCallSlot() {
if (g_mcpCallSlot == FLS_OUT_OF_INDEXES) return nullptr;
return static_cast<McpCallSlotPtr>(FlsGetValue(g_mcpCallSlot));
}
} // namespace
std::shared_ptr<McpCallContext> CurrentMcpCall() {
McpCallSlotPtr p = LoadCallSlot();
return p ? *p : std::shared_ptr<McpCallContext>();
}
bool McpCallCancelled() {
McpCallSlotPtr p = LoadCallSlot();
return p && *p && (*p)->IsCancelled();
}
void McpCallProgress(double current) {
McpCallSlotPtr p = LoadCallSlot();
if (p && *p) (*p)->EmitProgress(current, 0, false);
}
void McpCallProgress(double current, double total) {
McpCallSlotPtr p = LoadCallSlot();
if (p && *p) (*p)->EmitProgress(current, total, true);
}
namespace {
// 作用域内把当前线程的在飞上下文设为 call,离开时恢复上一层(普通路径与 SSE 工具线程共用)。
// 所有权:槽里保存的是堆上那份 shared_ptr 副本,离开时 delete 掉(释放本层引用);
// 上一层指针仍由外层 McpCallScope 拥有,这里只把槽位恢复回去。
struct McpCallScope {
explicit McpCallScope(std::shared_ptr<McpCallContext> c) {
prev_ = LoadCallSlot();
auto slot = new std::shared_ptr<McpCallContext>(std::move(c));
if (g_mcpCallSlot == FLS_OUT_OF_INDEXES || !FlsSetValue(g_mcpCallSlot, slot)) {
delete slot; // 取不到槽位时退化为「本线程没有在飞调用」,工具照常执行
return;
}
set_ = true;
}
~McpCallScope() {
if (!set_) return;
delete LoadCallSlot(); // 释放本层持有的引用(槽位里的那份)
FlsSetValue(g_mcpCallSlot, prev_);
}
McpCallScope(const McpCallScope&) = delete;
McpCallScope& operator=(const McpCallScope&) = delete;
private:
McpCallSlotPtr prev_ = nullptr;
bool set_ = false;
};
// 切片上限:取消后工具层最多再等这么久就回到自己的超时清理分支。
const int kWaitCancelSliceMs = 500;
std::chrono::steady_clock::time_point DeadlineAfter(int timeoutMs) {
return std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutMs);
}
// 带取消的有限期等待:把一次长等待切成 ≤500ms 的片,每片之间检查取消位。
// 返回 pred 是否满足;超时与取消都返回 false —— 调用方按各自既有的超时分支清理,
// 取消本身不需要另写一条清理路径(失败结果由分发层统一改写成 -32800)。
template <class Pred>
bool WaitWithCancel(std::unique_lock<std::mutex>& lk, std::condition_variable& cv,
std::chrono::steady_clock::time_point deadline, Pred pred) {
for (;;) {
if (pred()) return true;
if (McpCallCancelled()) return false;
const auto now = std::chrono::steady_clock::now();
if (now >= deadline) return false;
auto slice = deadline - now;
if (slice > std::chrono::milliseconds(kWaitCancelSliceMs))
slice = std::chrono::milliseconds(kWaitCancelSliceMs);
cv.wait_for(lk, slice);
}
}
} // namespace
namespace {
// P2b 工具等待响应的超时(ms)改为运行期可配:CMcpServer::ToolTimeoutMs(),默认 20000,
// 由 settings.ini 的 [settings] McpToolTimeoutMs 覆盖(见 2015RemoteDlg 的 MCP 初始化块)。
// initialize.instructions(MCP 2025-06-18 起为 result 的顶层字段)。模型看不到 docs/,
// 这套服务端的「隐性知识」只能靠这里讲清楚:主机 id 的来源与形态、工具的可见性与开关、
// 错误码对应的动作、典型任务编排、以及「一台主机同时只能有一个请求在飞」的约束。
// 用 u8 字面量拼接:项目 /execution-charset:.936 会把普通窄字面量编译成 GBK。
const char* kServerInstructions =
u8"这是 YAMA 主控服务端的 MCP 端点,用于读取并操作已上线的主机(被控端)。以下规则优先于各个工具的描述。\n"
u8"\n"
u8"1) 主机 id\n"
u8"id 是 64 位无符号十进制字符串,由服务端分配,无法从 IP 或计算机名推算,不要猜测、也不要把示例值当真。"
u8"需要 id 时先用 list_online_hosts(仅在线)或 list_all_hosts(含离线)取得;离线主机除 "
u8"host_set_remark、host_set_watch_level 外都不能操作。拿不到 id 就向用户确认。\n"
u8"\n"
u8"2) 工具的可见性与开关\n"
u8"tools/list 只返回当前服务端开关允许的工具:终端(terminal)、远程控制(remote_control)、"
u8"文件传输(file_transfer)、文件写入(file_write)、管理动作(manage)、主机管理(machine)、键盘记录(keylog)、"
u8"远程交谈(chat)各有独立开关。工具不在列表里就是不可用,直接调用返回 -32006;"
u8"当前开关状态可查 get_server_status 的 switches。只读模式(readonly=true)会挡掉大部分写工具,"
u8"但只改服务端本地数据的 host_set_remark / host_set_watch_level 仍会列出,调用时才被拒;"
u8"get_keylog 也始终可见,只读模式下只是它的 clear / set_offline 参数被拒,读取不受影响。\n"
u8"同一能力存在两套工具时优先用主机管理族:host_list_processes / host_list_windows / "
u8"host_list_win32_services 字段更全(host_list_windows 支持 pid/title 过滤,"
u8"host_list_win32_services 支持 name/status 过滤),list_processes / list_windows / list_services "
u8"是它们在 McpMachine=0 时的降级路径。关闭窗口只有 operate_window 能做,host_control_window 没有 close。\n"
u8"\n"
u8"3) 错误码与动作\n"
u8"-32002 主机离线或不存在:先刷新主机列表再选,不要拿旧快照反复重试。\n"
u8"-32003 主机忙:同一台主机同一时刻只允许一个请求在飞(列表、截屏、文件、管理动作共用这一道锁,"
u8"文件传输会话另有一道互斥),并发重试只会继续被拒;message 末尾会点名占用者与已持续时长,"
u8"用 mcp_list_sessions 可看全部会话,确需打断(例如上一条请求已无意义)用 mcp_cancel_session 释放。\n"
u8"-32004 命令未能送达主机:多半是链路瞬断,可重试一次。\n"
u8"-32005 该主机不支持这项能力:换主机或换工具,改参数没有用。\n"
u8"-32006 策略拒绝:开关未开或只读模式,重试无效,需要管理员改服务端配置。\n"
u8"-32007 不在命令白名单:换成白名单内的命令,重试无效。\n"
u8"-32012 参数被校验拒绝(命令里的 shell 元字符、控制字符等):按 message 修正参数后重试。"
u8"历史版本用 -32008 表示同一语义,遇到时按同样方式处理。\n"
u8"-32009 目标不存在(文件/目录等):先列一次确认目标,再重试。\n"
u8"-32001 超时:可加大 timeout_ms 重试一次;持续超时说明主机卡住。\n"
u8"-32800 请求被取消:这是客户端自己取消(notifications/cancelled / mcp_cancel_session / 连接断开)"
u8"导致的中止,不是主机故障;主机占用已释放,可以直接重试。\n"
u8"-32602 参数错误:按 message 修正后重试。\n"
u8"\n"
u8"4) 典型编排\n"
u8"看主机:get_host_detail 先看 clientType 与 monitors,再决定用哪些工具;列表结果是快照,"
u8"主机可能在你操作期间掉线。\n"
u8"文件:list_files 列盘(省略 path)或列目录 → search_file 按名字查找(递归深度 32、最多 1 万条,"
u8"从盘符根扫描很慢且易截断,尽量指定具体目录)→ download_file 取回、upload_file 送到目标。"
u8"整理目标机上的东西用 delete_path / move_path / create_folder(需 McpFileWrite 开关),"
u8"它们的 ok 同样只代表客户端回了完成包,真实结果看 verified(true=复核确认生效、"
u8"false=复核确认未生效、null=复核没做成);删除不可恢复,recursive 必须显式传 true。"
u8"列表结果按 limit/offset 分页,total 是命中数、totalAll 是过滤前的总数。\n"
u8"进程排查:host_list_processes 或 list_processes 定位,kill_process 结束。这类动作没有真实回执,"
u8"拿到 ok 后应再列一次复核,不要凭 ok 断言已生效。\n"
u8"GUI 自动化:remote_open 取得 session_id 与分辨率(screen_w/screen_h)→ get_screenshot 看画面 → "
u8"remote_mouse / remote_keyboard 用归一化坐标(0..1)操作 → 必须 remote_close 释放会话,闲置会话会被回收。"
u8"要防止真人操作打断自动化时用 remote_block_input 锁定对端键鼠(必须带 max_block_ms,到期自动解除;"
u8"客户端无管理员权限时 Windows 会让 BlockInput 静默失败,成功只代表命令已送达)。\n"
u8"命令执行:exec_command 一次性取输出;需要保持 cd 或环境变量时用 terminal_open + terminal_exec,用毕 terminal_close。\n"
u8"\n"
u8"5) 客户端平台差异\n"
u8"工具能否执行取决于目标主机的平台,这与服务端开关无关,两者是叠加关系。调用前用 "
u8"list_online_hosts / get_host_detail 的 capabilities.platform 确认,宁可先查一次,不要先试后错。\n"
u8"支持面从宽到窄依次是 win > lnx > mac ≈ apk:Windows 是唯一全量支持的平台,Linux 次之,"
u8"macOS 与 Android 只覆盖一部分。拿不准时按这个顺序假设。\n"
u8"win(EXE / DLL / MEXE / SC / MDLL):全部工具可用。\n"
u8"lnx(LNX):不支持服务、注册表、键日志、活动历史、文件搜索/删除/移动/建目录、"
u8"窗口列表(list_windows)、网络连接列表与断开"
u8"(list_network_connections / kill_network_connection)、"
u8"块输入、host_* 全族、chat_* 全族、operate_window、power_action。远程控制与截屏要求目标机"
u8"有 X11/Xorg(或 XWayland)桌面,纯 Wayland 或无桌面的服务器不行。\n"
u8"mac(MAC):在 lnx 的基础上,还不支持远程控制全族(remote_open / remote_close / "
u8"remote_mouse / remote_keyboard / remote_clipboard)、get_screenshot、"
u8"exec_command、terminal_open / terminal_exec / terminal_close"
u8"(客户端有 PTY 实现,但服务端本轮未开放)、kill_process;"
u8"文件传输、进程列表、日志可用。\n"
u8"apk(APK):只支持主机列表(list_online_hosts / list_all_hosts)/ 详情 / 搜索 / "
u8"审计日志 / 服务状态 / 会话管理,以及 "
u8"host_set_remark / host_set_watch_level 这两个只改服务端本地数据的工具。其余一律不支持"
u8"(客户端未实现 SYSTEM 与 SHELL)。\n"
u8"copy_files_c2c 是唯一有方向性的工具:源端 src_id 必须是 win,目标端 dst_id 可以是 "
u8"win / lnx / mac。Linux 和 macOS 只能当接收方,不能当发送方(反向不支持)。\n"
u8"这些不支持的组合会立刻返回 -32005,不会白等超时;反之,遇到超时不要当成平台不支持。\n"
u8"\n"
u8"6) 安全约定\n"
u8"写操作前先读一次现状,动作后再用读工具复核;删改类工具的 ok 只表示命令已送达客户端,不代表成功。"
u8"涉及删除、重启、结束进程、关机等不可逆操作时,先把目标和影响范围讲给用户,得到确认再执行。"
u8"主机上可能有人正在办公,注入输入、截屏、关机都是会被察觉的动作。";
// initialize 握手(MCP 规范:protocolVersion + capabilities + serverInfo + instructions)
std::string BuildInitializeResult(const Json::Value& id) {
Json::Value result(Json::objectValue);
result["protocolVersion"] = "2025-06-18";
Json::Value caps(Json::objectValue);
caps["tools"] = Json::Value(Json::objectValue);
result["capabilities"] = caps;
Json::Value serverInfo(Json::objectValue);
serverInfo["name"] = "yama";
serverInfo["version"] = VERSION_STR;
result["serverInfo"] = serverInfo;
result["instructions"] = kServerInstructions;
return BuildResult(id, result);
}
// ping 健康检查:返回空 result
std::string BuildPingResult(const Json::Value& id) {
return BuildResult(id, Json::Value(Json::objectValue));
}
// ========== P2a 通用辅助 ==========
// 读取 tools/call 的入参(MCP 规范:params.arguments 为工具入参对象)
Json::Value GetCallArguments(const Json::Value& params) {
if (params.isObject() && params.isMember("arguments") && params["arguments"].isObject())
return params["arguments"];
return Json::Value(Json::objectValue);
}
// ========== P2b 辅助 ==========
// 从 "title|status|pid|r1|r2" 解析(自末尾 4 个 '|' 反推),兼容只有标题的老客户端。
// 逻辑复刻 SystemDlg.cpp::ParseWindowAttrs。
void ParseWindowAttrsStr(const char* s, std::string& title, std::string& status, uint64_t& pid) {
title.clear();
status = "normal";
pid = 0;
if (!s || !*s) return;
std::string t(s);
int len = (int)t.size();
int pipePos[4] = { -1, -1, -1, -1 };
int cnt = 0;
for (int i = len - 1; i >= 0 && cnt < 4; --i) {
if (t[i] == '|') pipePos[cnt++] = i;
}
if (cnt < 4) { // 老格式:只有标题
title = t;
return;
}
pid = strtoull(t.c_str() + pipePos[2] + 1, nullptr, 10);
status = t.substr(pipePos[3] + 1, pipePos[2] - pipePos[3] - 1);
title = t.substr(0, pipePos[3]);
}
// 解析 TOKEN_PSLIST 缓冲(data[0]=token,其后为 [pid:4][name:arch\0][path\0] 记录)。
// 进程名/路径为客户端 ANSI(编码由 cp 指定),转 UTF-8 输出。
Json::Value ParseProcessList(const std::vector<BYTE>& data, UINT cp) {
Json::Value arr(Json::arrayValue);
if (data.size() < 2) return arr;
const char* p = (const char*)data.data();
size_t len = data.size();
size_t off = 1; // 跳过 TOKEN 字节
while (off + sizeof(DWORD) <= len) {
DWORD pid = *(const DWORD*)(p + off);
off += sizeof(DWORD);
const char* exeFile = p + off;
size_t exeLen = BoundedStrlen(exeFile, len - off);
if (exeLen >= len - off) break; // 未以 '\0' 结尾,异常数据
if (exeLen == 0) break; // 空进程名 = 尾部零填充(LocalSize 对齐),停止解析
off += exeLen + 1;
const char* fullPath = p + off;
size_t pathLen = BoundedStrlen(fullPath, len - off);
if (pathLen >= len - off) break;
off += pathLen + 1;
std::string name(exeFile, exeLen);
std::string arch;
size_t colon = name.find(':');
if (colon != std::string::npos) {
arch = name.substr(colon + 1);
name = name.substr(0, colon);
}
Json::Value item(Json::objectValue);
item["pid"] = (Json::UInt64)pid;
item["name"] = ToUtf8(name.c_str(), cp);
item["arch"] = arch.empty() ? "N/A" : ToUtf8(arch.c_str(), cp);
item["path"] = ToUtf8(fullPath, cp);
arr.append(item);
}
return arr;
}
// 解析 TOKEN_WSLIST 缓冲(data[0]=token,其后为 [hwnd:4][title|status|pid|r1|r2\0] 记录)。
// 窗口标题为客户端 UTF-8(老客户端为 CP_ACP),用 cp 解码后转 UTF-8 输出。
Json::Value ParseWindowList(const std::vector<BYTE>& data, UINT cp) {
Json::Value arr(Json::arrayValue);
if (data.size() < 2) return arr;
const char* p = (const char*)data.data();
size_t len = data.size();
size_t off = 1;
while (off + sizeof(DWORD) <= len) {
DWORD hwnd = *(const DWORD*)(p + off);
off += sizeof(DWORD);
const char* titleWithAttrs = p + off;
size_t tlen = BoundedStrlen(titleWithAttrs, len - off);
if (tlen >= len - off) break;
if (tlen == 0) break; // 空记录 = 尾部零填充(LocalSize 对齐),停止解析
off += tlen + 1;
std::string title, status;
uint64_t pid = 0;
ParseWindowAttrsStr(titleWithAttrs, title, status, pid);
Json::Value item(Json::objectValue);
item["hwnd"] = (Json::UInt64)hwnd;
item["title"] = ToUtf8(title.c_str(), cp);
item["status"] = status;
item["pid"] = (Json::UInt64)pid;
arr.append(item);
}
return arr;
}
// 解析 TOKEN_DRIVE_LIST 缓冲(data[0]=token,其后为
// [letter:1][GetDriveType:1][totalMB:4][freeMB:4][typeName\0][fileSystem\0] 记录,
// 以 letter=='\0' 终止)。typeName/fileSystem 为客户端 ANSI(编码由 cp 指定)。
Json::Value ParseDriveList(const std::vector<BYTE>& data, UINT cp) {
Json::Value arr(Json::arrayValue);
if (data.size() < 2) return arr;
const char* p = (const char*)data.data();
size_t len = data.size();
size_t off = 1; // 跳过 TOKEN 字节
while (off + 10 <= len && p[off] != '\0') {
char letter = p[off];
unsigned int type = (unsigned int)(unsigned char)p[off + 1];
DWORD totalMB = *(const DWORD*)(p + off + 2);
DWORD freeMB = *(const DWORD*)(p + off + 6);
off += 10;
const char* typeName = p + off;
size_t tlen = BoundedStrlen(typeName, len - off);
if (tlen >= len - off) break;
off += tlen + 1;
const char* fileSystem = p + off;
size_t flen = BoundedStrlen(fileSystem, len - off);
if (flen >= len - off) break;
off += flen + 1;
std::string drive;
drive += letter;
drive += ":\\";
Json::Value item(Json::objectValue);
item["drive"] = drive;
item["type"] = (Json::UInt64)type;
item["typeName"] = ToUtf8(typeName, cp);
item["fileSystem"] = ToUtf8(fileSystem, cp);
item["totalMB"] = (Json::UInt64)totalMB;
item["freeMB"] = (Json::UInt64)freeMB;
arr.append(item);
}
return arr;
}
// 解析 TOKEN_FILE_LIST 缓冲(data[0]=token,其后为
// [attr:1][filename\0][sizeHigh:4][sizeLow:4][ftLastWriteTime:8] 记录)。
// 文件名为客户端 ANSI(编码由 cp 指定);attr 非 0 表示目录(FILE_ATTRIBUTE_DIRECTORY)。
Json::Value ParseFileList(const std::vector<BYTE>& data, int maxEntries, UINT cp) {
Json::Value arr(Json::arrayValue);
if (data.size() < 2) return arr;
const char* p = (const char*)data.data();
size_t len = data.size();
size_t off = 1;
int count = 0;
while (off + 1 <= len && count < maxEntries) {
bool isDir = (p[off] & FILE_ATTRIBUTE_DIRECTORY) != 0;
off += 1;
const char* name = p + off;
size_t nlen = BoundedStrlen(name, len - off);
if (nlen >= len - off) break;
if (nlen == 0) break; // 空记录 = 尾部零填充(LocalAlloc 对齐),停止解析
off += nlen + 1;
if (off + 16 > len) break;
DWORD sizeHigh = *(const DWORD*)(p + off);
DWORD sizeLow = *(const DWORD*)(p + off + 4);
ULONGLONG size = ((ULONGLONG)sizeHigh << 32) | sizeLow;
// 修改时间(FILETIME,100ns since 1601-01-01)→ Unix 秒
// FILETIME 在线上是 dwLowDateTime(低 4 字节) 在前、dwHighDateTime(高 4 字节) 在后
// (客户端 memcpy(&ftLastWriteTime, sizeof(FILETIME)),见 FileManager.cpp::SendFilesList)。
DWORD ftLow = *(const DWORD*)(p + off + 8);
DWORD ftHigh = *(const DWORD*)(p + off + 12);
off += 16;
ULONGLONG ft = ((ULONGLONG)ftHigh << 32) | ftLow;
Json::Int64 mtime = (Json::Int64)(ft / 10000000ULL) - 11644473600LL;
Json::Value item(Json::objectValue);
item["name"] = ToUtf8(name, cp);
item["isDir"] = isDir;
item["size"] = (Json::UInt64)size;
item["mtime"] = mtime;
arr.append(item);
++count;
}
return arr;
}
// 解析 TOKEN_SERVERLIST 缓冲(data[0]=token,其后为
// [displayName\0][serviceName\0][binaryPath\0][runWay\0][autoRun\0] 记录)。
// 字段全部来自 Windows A 接口(EnumServicesStatus / QueryServiceConfig),为客户端
// ANSI(编码由 cp 指定)。以 displayName 与 serviceName 同时为空作为尾部零填充
// (LocalAlloc/LocalReAlloc LMEM_ZEROINIT 对齐)的终止条件。
Json::Value ParseServiceList(const std::vector<BYTE>& data, UINT cp) {
Json::Value arr(Json::arrayValue);
if (data.size() < 2) return arr;
const char* p = (const char*)data.data();
size_t len = data.size();
size_t off = 1; // 跳过 TOKEN 字节
while (off < len) {
const char* f[5];
bool ok = true;
for (int i = 0; i < 5; ++i) {
size_t n = BoundedStrlen(p + off, len - off);
if (n >= len - off) { ok = false; break; } // 未以 '\0' 结尾,异常数据
f[i] = p + off;
off += n + 1;
}
if (!ok) break;
// displayName 与 serviceName 都为空 → 尾部零填充,停止解析
if (f[0][0] == '\0' && f[1][0] == '\0') break;
Json::Value item(Json::objectValue);
item["display_name"] = ToUtf8(f[0], cp);
item["service_name"] = ToUtf8(f[1], cp);
item["binary_path"] = ToUtf8(f[2], cp);
item["status"] = ToUtf8(f[3], cp); // Stopped/Running/Paused/... 英文
item["start_type"] = ToUtf8(f[4], cp); // Boot-Start/Auto-Start/Demand-Start/... 英文
arr.append(item);
}
return arr;
}
// ========== list_registry:注册表解析 ==========
// 注册表 REGMSG 头(client RegisterOperation.cpp / server RegisterDlg.cpp 各自本地定义,此处同构)。
struct RegMsgHeader {
int count; // 名字个数
DWORD size; // 名字大小(定宽)
DWORD valsize; // 值大小(定宽)
};
// client KEYVALUE 枚举(RegisterOperation.cpp):MREG_SZ=0 … MREG_NONE=6。
enum RegValueType {
REG_T_SZ = 0,
REG_T_DWORD = 1,
REG_T_BINARY = 2,
REG_T_EXPAND_SZ = 3,
REG_T_MULTI_SZ = 4,
REG_T_QWORD = 5,
REG_T_NONE = 6,
};
// client MYKEY 枚举:根键 token。
enum RegRootToken {
REG_ROOT_CLASSES_ROOT = 0,
REG_ROOT_CURRENT_USER = 1,
REG_ROOT_LOCAL_MACHINE = 2,
REG_ROOT_USERS = 3,
REG_ROOT_CURRENT_CONFIG = 4,
};
// ASCII 不区分大小写前缀匹配(注册表根键名大小写不敏感)。
bool StrPrefixCI(const std::string& s, const char* prefix, size_t len) {
if (s.size() < len) return false;
for (size_t i = 0; i < len; ++i) {
char a = s[i], b = prefix[i];
if (a >= 'A' && a <= 'Z') a += 32;
if (b >= 'A' && b <= 'Z') b += 32;
if (a != b) return false;
}
return true;
}
// 值类型名(可读字符串)
const char* RegTypeName(BYTE type) {
switch (type) {
case REG_T_SZ: return "REG_SZ";
case REG_T_DWORD: return "REG_DWORD";
case REG_T_BINARY: return "REG_BINARY";
case REG_T_EXPAND_SZ: return "REG_EXPAND_SZ";
case REG_T_MULTI_SZ: return "REG_MULTI_SZ";
case REG_T_QWORD: return "REG_QWORD";
case REG_T_NONE: return "REG_NONE";
default: return "REG_UNKNOWN";
}
}
// 将注册表值数据格式化为字符串。valSize 为定宽(client 按 MaxDataLen+1 填充),
// 字符串类取到 '\0' 为止、数值类取定长前缀;REG_BINARY 长度无法从协议还原,按 valSize 输出 hex。
std::string FormatRegData(BYTE type, const BYTE* val, size_t valSize, UINT cp) {
switch (type) {
case REG_T_SZ:
case REG_T_EXPAND_SZ:
return ToUtf8((const char*)val, cp);
case REG_T_MULTI_SZ: { // 多个 '\0' 结尾串、双 '\0' 结束
std::string out;
size_t i = 0;
while (i < valSize && val[i] != '\0') {
const char* s = (const char*)(val + i);
size_t n = BoundedStrlen(s, valSize - i);
if (!out.empty()) out += "\n";
out += ToUtf8(s, cp);
i += n + 1;
}
return out;
}
case REG_T_DWORD: { // 4 字节小端
if (valSize < 4) return "";
DWORD v = 0;
memcpy(&v, val, 4);
char buf[64];
sprintf(buf, "0x%08lX (%lu)", (unsigned long)v, (unsigned long)v);
return buf;
}
case REG_T_QWORD: { // 8 字节小端
if (valSize < 8) return "";
uint64_t v = 0;
memcpy(&v, val, 8);
char buf[96];
sprintf(buf, "0x%016I64X (%I64u)", (unsigned __int64)v, (unsigned __int64)v);
return buf;
}
case REG_T_BINARY: { // hex,尾部可能含 0 填充
std::string out;
char buf[4];
for (size_t i = 0; i < valSize; ++i) {
sprintf(buf, "%02X", val[i]);
out += buf;
}
return out;
}
case REG_T_NONE:
default:
return "";
}
}
// 解析 TOKEN_REG_PATH 缓冲:[token:1][RegMsgHeader:12][count * size 定宽子键名]。cp 为客户端 ANSI。
Json::Value ParseRegPath(const std::vector<BYTE>& data, UINT cp) {
Json::Value arr(Json::arrayValue);
if (data.size() < 1 + sizeof(RegMsgHeader)) return arr;
const char* p = (const char*)data.data();
size_t off = 1; // 跳过 TOKEN 字节
RegMsgHeader hdr;
memcpy(&hdr, p + off, sizeof(hdr));
off += sizeof(hdr);
int count = hdr.count;
size_t nameSize = hdr.size;
for (int i = 0; i < count; ++i) {
if (off + nameSize > data.size()) break;
const char* name = p + off;
off += nameSize;
if (name[0] == '\0') break; // 空名 = 尾部零填充,停止
arr.append(ToUtf8(name, cp));
}
return arr;
}
// 解析 TOKEN_REG_KEY 缓冲:[token:1][RegMsgHeader:12][count * {type:1,name:size,data:valsize}]。
Json::Value ParseRegKey(const std::vector<BYTE>& data, UINT cp) {
Json::Value arr(Json::arrayValue);
if (data.size() < 1 + sizeof(RegMsgHeader)) return arr;
const char* p = (const char*)data.data();
size_t off = 1; // 跳过 TOKEN 字节
RegMsgHeader hdr;
memcpy(&hdr, p + off, sizeof(hdr));
off += sizeof(hdr);
int count = hdr.count;
size_t nameSize = hdr.size;
size_t valSize = hdr.valsize;
for (int i = 0; i < count; ++i) {
if (off + 1 + nameSize + valSize > data.size()) break;
BYTE type = (BYTE)p[off];
off += 1;
const char* name = p + off; // 定宽 nameSize 内以 '\0' 结尾
off += nameSize;
const BYTE* val = (const BYTE*)(p + off);
off += valSize;
Json::Value item(Json::objectValue);
item["name"] = ToUtf8(name, cp);
item["type"] = RegTypeName(type);
item["data"] = FormatRegData(type, val, valSize, cp);
arr.append(item);
}
return arr;
}
// 解析 "HKEY_LOCAL_MACHINE\Software\..." → rootToken + 相对子键路径(去掉根键名与首个 '\')。
// 返回 false 表示 path 为空(调用方列根键)或未匹配任何根键(调用方报错)。
bool ParseRegistryPath(const std::string& path, BYTE& rootToken, std::string& relPath) {
struct RootMap { const char* name; BYTE token; };
static const RootMap roots[] = {
{ "HKEY_CLASSES_ROOT", REG_ROOT_CLASSES_ROOT },
{ "HKEY_CURRENT_USER", REG_ROOT_CURRENT_USER },
{ "HKEY_LOCAL_MACHINE", REG_ROOT_LOCAL_MACHINE },
{ "HKEY_USERS", REG_ROOT_USERS },
{ "HKEY_CURRENT_CONFIG", REG_ROOT_CURRENT_CONFIG },
};
if (path.empty()) return false;
for (const RootMap& r : roots) {
size_t n = strlen(r.name);
if (StrPrefixCI(path, r.name, n)) {
rootToken = r.token;
relPath = path.substr(n);
if (!relPath.empty() && relPath[0] == '\\') relPath.erase(0, 1);
return true;
}
}
return false;
}
// 列根键(path 为空):返回 5 个固定根键,无需查询客户端。
std::string BuildRegistryRoots(const Json::Value& id) {
Json::Value keys(Json::arrayValue);
const char* roots[] = {
"HKEY_CLASSES_ROOT", "HKEY_CURRENT_USER", "HKEY_LOCAL_MACHINE",
"HKEY_USERS", "HKEY_CURRENT_CONFIG"
};
for (const char* r : roots) keys.append(r);
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
// path 恒为 "":根键这一层没有路径,但补上它能让「列根键」与「列子键」返回同一组
// 字段(path/keys,子键那次多一个 values),调用方不必按分支判断。
structuredContent["path"] = "";
structuredContent["keys"] = keys;
result["structuredContent"] = structuredContent;
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = std::string(u8"共 ") + std::to_string((int)keys.size()) + std::string(u8" 个根键。");
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
// 收集所有在线主机 JSON 数组(m_cs 锁内遍历,复用 BuildHostJson 序列化,方案 C)
void CollectOnlineHosts(CMy2015RemoteDlg* parent, Json::Value& hosts) {
if (!parent) return;
EnterCriticalSection(&parent->m_cs);
for (context* ctx : parent->m_HostList) {
if (!ctx || !ctx->IsLogin()) continue;
hosts.append(BuildHostJson(ctx, parent->m_ClientMap));
}
LeaveCriticalSection(&parent->m_cs);
}
// MAP_AUTH 的三态(见 common/commands.h):0 未授权 / 1 超级管理员授权 / 2 管理员授权 / 9 禁止登录。
// 导出成字符串而不是布尔:AUTH_FORBIDDEN 与 UNAUTHORIZED 对运维是两回事。
const char* AuthStatusName(int auth) {
switch (auth) {
case AUTHED_BY_SUPER: return "authorized_by_super";
case AUTHED_BY_ADMIN: return "authorized_by_admin";
case AUTH_FORBIDDEN: return "forbidden";
default: return "unauthorized";
}
}
// 离线主机 JSON:字段与 BuildHostJson 同形,缺实时字段(rtt/version/activeWindow/screen/clientType)。
// ClientValue.Location 已统一按 UTF-8 存储(见 AddList 的 NormalizeLocationToUtf8),直接透传;
// 其余窄字符串来自客户端的 CString,按 CP_ACP 转 UTF-8。
Json::Value BuildOfflineHostJson(_ClientList* clientMap, uint64_t key, const ClientValue& cv) {
Json::Value h(Json::objectValue);
h["id"] = std::to_string(key);
h["name"] = ToUtf8(cv.ComputerName, CP_ACP);
if (clientMap) {
CString remark = clientMap->GetClientMapData(key, MAP_NOTE);
if (!remark.IsEmpty()) h["remark"] = ToUtf8(remark.GetString(), CP_ACP);
}
h["ip"] = std::string(cv.IP);
h["os"] = ToUtf8(cv.OsName, CP_ACP);
h["location"] = std::string(cv.Location);
h["online"] = false;
h["group"] = "default"; // 分组只存在于在线 context 上,离线条目拿不到
h["last_seen"] = std::string(cv.LastLoginTime);
h["install_time"] = std::string(cv.InstallTime);
h["authStatus"] = AuthStatusName(cv.Authorized);
return h;
}
// 收集全部已知主机(m_cs 锁内)。在线主机取实时字段,离线主机取 m_ClientMap 元数据快照。
// includeOnline / includeOffline 决定保留哪一类:两者都 false 时返回空数组。
void CollectAllHosts(CMy2015RemoteDlg* parent, Json::Value& hosts,
bool includeOnline, bool includeOffline) {
if (!parent || !parent->m_ClientMap) return;
EnterCriticalSection(&parent->m_cs);
// 在线集合始终要建:用来判断 map 里的条目当前是否在线(决定它算哪一类)
std::unordered_map<uint64_t, context*> online;
for (context* ctx : parent->m_HostList) {
if (ctx && ctx->IsLogin()) online[ctx->GetClientID()] = ctx;
}
std::set<uint64_t> emitted;
for (const auto& kv : parent->m_ClientMap->GetAll()) {
auto it = online.find(kv.first);
if (it != online.end()) {
if (includeOnline) {
Json::Value h = BuildHostJson(it->second, parent->m_ClientMap);
if (h.isObject()) h["authStatus"] = AuthStatusName(kv.second.Authorized);
hosts.append(h);
emitted.insert(kv.first);
}
} else if (includeOffline) {
hosts.append(BuildOfflineHostJson(parent->m_ClientMap, kv.first, kv.second));
}
}
// 在线但还没写进 m_ClientMap 的新客户端(首次上线瞬间)也要能列出来
if (includeOnline) {
for (const auto& kv : online) {
if (!emitted.count(kv.first)) {
Json::Value h = BuildHostJson(kv.second, parent->m_ClientMap);
if (h.isObject()) h["authStatus"] = AuthStatusName(UNAUTHORIZED); // 不在 map 里即从未登记
hosts.append(h);
}
}
}
LeaveCriticalSection(&parent->m_cs);
}
// ===== C3:list_online_hosts / list_all_hosts 的公共过滤 =====
// 口径与 search_hosts 一致:条件都可选、AND 组合、子串匹配、ASCII 不区分大小写。
// 只过滤已有字段,不额外拉取主机数据;离线主机没有 clientType(历史记录里不存),
// 所以带 client_type 条件时离线主机不会命中——需要按平台筛历史主机请用 os。
struct HostListFilter {
std::string group;
std::string os;
std::string clientType;
bool Any() const { return !group.empty() || !os.empty() || !clientType.empty(); }
};
HostListFilter ReadHostListFilter(const Json::Value& args) {
HostListFilter f;
f.group = GetStringArg(args, "group");
f.os = GetStringArg(args, "os");
f.clientType = GetStringArg(args, "client_type");
return f;
}
void ApplyHostListFilter(const Json::Value& in, const HostListFilter& f, Json::Value& out) {
out = Json::Value(Json::arrayValue);
for (Json::Value::ArrayIndex i = 0; i < in.size(); ++i) {
const Json::Value& h = in[i];
if (!f.group.empty() && !ContainsCI(JsonStrField(h, "group"), f.group)) continue;
if (!f.os.empty() && !ContainsCI(JsonStrField(h, "os"), f.os)) continue;
if (!f.clientType.empty() && !ContainsCI(JsonStrField(h, "clientType"), f.clientType)) continue;
out.append(h);
}
}
void AppendHostListFilterProps(Json::Value& props) {
Json::Value groupProp(Json::objectValue);
groupProp["type"] = "string";
groupProp["description"] = u8"按分组过滤(子串,不区分大小写)。省略则不过滤。";
props["group"] = groupProp;
Json::Value osProp(Json::objectValue);
osProp["type"] = "string";
osProp["description"] = u8"按操作系统过滤(子串,不区分大小写,如 Windows、Linux、Android)。省略则不过滤。";
props["os"] = osProp;
Json::Value typeProp(Json::objectValue);
typeProp["type"] = "string";
typeProp["description"] = u8"按客户端类型过滤(子串,不区分大小写,如 EXE、LNX、MAC)。离线主机没有该字段,不会命中。省略则不过滤。";
props["client_type"] = typeProp;
}
// ========== 工具 schema ==========
// 单台主机字段 schema(hosts 数组元素 / 单机详情共用的形状)
Json::Value BuildHostItemSchema() {
Json::Value itemProps(Json::objectValue);
const char* strFields[] = {
"id", "name", "remark", "ip", "os", "location", "rtt",
"version", "activeWindow", "group", "screen", "clientType",
// 以下两项只有离线主机(来自 m_ClientMap 的历史记录)才有值
"last_seen", "install_time"
};
for (const char* f : strFields) {
Json::Value p(Json::objectValue);
p["type"] = "string";
itemProps[f] = p;
}
Json::Value onlineProp(Json::objectValue);
onlineProp["type"] = "boolean";
itemProps["online"] = onlineProp;
// 客户端登录时上报的 TLS 传输标志(老客户端恒为 false)
Json::Value tlsProp(Json::objectValue);
tlsProp["type"] = "boolean";
itemProps["tls"] = tlsProp;
// 主机授权状态:unauthorized / authorized_by_super / authorized_by_admin / forbidden
Json::Value authProp(Json::objectValue);
authProp["type"] = "string";
itemProps["authStatus"] = authProp;
return itemProps;
}
// 列表型 outputSchema 的公共翻页字段,字段名与 McpMachine.cpp 的 host_list_* 保持一致
void AppendPageOutputProps(Json::Value& props) {
const char* intFields[] = { "total", "totalAll", "offset", "limit" };
for (const char* f : intFields) {
Json::Value p(Json::objectValue);
p["type"] = "integer";
props[f] = p;
}
Json::Value moreProp(Json::objectValue);
moreProp["type"] = "boolean";
props["hasMore"] = moreProp;
}
// list_online_hosts / search_hosts 的 outputSchema(hosts 数组)
Json::Value BuildHostOutputSchema() {
Json::Value props(Json::objectValue);
Json::Value hostsProp(Json::objectValue);
hostsProp["type"] = "array";
Json::Value items(Json::objectValue);
items["type"] = "object";
items["properties"] = BuildHostItemSchema();
hostsProp["items"] = items;
props["hosts"] = hostsProp;
AppendPageOutputProps(props);
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("hosts");
schema["required"] = required;
return schema;
}
// get_host_detail 的 outputSchema(单台主机)
Json::Value BuildHostDetailOutputSchema() {
Json::Value props(Json::objectValue);
// get_host_detail 在通用主机字段之外还补技术字段与 capabilities;schema 只声明
// capabilities——它是「该不该调某个工具」的判据,其余字段缺声明不影响取值。
Json::Value hostProps = BuildHostItemSchema();
{
auto boolProp = [](const char* desc) {
Json::Value p(Json::objectValue);
p["type"] = "boolean";
p["description"] = desc;
return p;
};
Json::Value capProps(Json::objectValue);
Json::Value platform(Json::objectValue);
platform["type"] = "string";
platform["description"] = u8"客户端形态:EXE/DLL/MEXE/SC/MDLL(Windows)、LNX(Linux)、MAC、APK";
capProps["platform"] = platform;
capProps["screenPreview"] = boolProp(u8"能否截屏(get_screenshot 的前提)");
capProps["remoteControl"] = boolProp(
u8"能否建立远程控制会话(remote_open/remote_mouse/remote_keyboard 的前提);"
u8"还要求服务端 Web 远程服务已启动(WebSvrPort>0)");
capProps["fileTransferV2"] = boolProp(u8"是否支持 V2 文件传输(download_file / upload_file 的前提)");
capProps["c2cPaths"] = boolProp(u8"能否按路径清单接收另一台主机的文件(copy_files_c2c 源端的前提)");
capProps["registry"] = boolProp(u8"是否有 Windows 注册表可查(list_registry);仅 Windows 客户端为 true");
Json::Value caps(Json::objectValue);
caps["type"] = "object";
caps["properties"] = capProps;
hostProps["capabilities"] = caps;
}
Json::Value hostProp(Json::objectValue);
hostProp["type"] = "object";
hostProp["properties"] = hostProps;
props["host"] = hostProp;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("host");
schema["required"] = required;
return schema;
}
// search_hosts 的 inputSchema(全部可选)
Json::Value BuildSearchHostsInputSchema() {
Json::Value props(Json::objectValue);
const char* strParams[] = { "name", "ip", "group", "os" };
for (const char* p : strParams) {
Json::Value s(Json::objectValue);
s["type"] = "string";
props[p] = s;
}
Json::Value onlineProp(Json::objectValue);
onlineProp["type"] = "boolean";
props["online"] = onlineProp;
AppendPagingProps(props);
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
return schema;
}
// list_all_hosts 的 inputSchema:两类开关,默认都返回
Json::Value BuildListAllHostsInputSchema() {
Json::Value props(Json::objectValue);
Json::Value onlineProp(Json::objectValue);
onlineProp["type"] = "boolean";
onlineProp["description"] = u8"是否包含在线主机,默认 true";
props["online"] = onlineProp;
Json::Value offlineProp(Json::objectValue);
offlineProp["type"] = "boolean";
offlineProp["description"] = u8"是否包含离线主机(历史连接过、当前未连接的),默认 true";
props["offline"] = offlineProp;
AppendHostListFilterProps(props);
AppendPagingProps(props);
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
return schema;
}
// get_host_detail 的 inputSchema(id 必填;只读工具另支持 ids[] 批量)
Json::Value BuildGetHostDetailInputSchema() {
Json::Value props(Json::objectValue);
Json::Value idProp(Json::objectValue);
idProp["type"] = "string";
idProp["description"] = u8"主机 id,取 list_online_hosts / search_hosts 返回的 id 字段;与 ids 二选一";
props["id"] = idProp;
AppendBatchIdsProp(props);
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
MakeIdOrIdsRequired(schema);
return schema;
}
// 列表型单主机工具(list_processes / list_windows / list_services):{ id } + limit/offset
Json::Value BuildPagedHostListInputSchema() {
Json::Value schema = BuildGetHostDetailInputSchema();
AppendPagingProps(schema["properties"]);
return schema;
}
// list_processes / list_windows:在分页参数之上再加服务端过滤(name 子串 + pid 精确)。
// 过滤在分页之前生效,所以 total 是命中数、totalAll 是过滤前的总数。
Json::Value BuildFilteredPagedHostListInputSchema(const char* nameDesc, const char* pidDesc) {
Json::Value schema = BuildPagedHostListInputSchema();
Json::Value props = schema["properties"]; // 拷贝后补字段,避免直接改返回的引用树
Json::Value nameProp(Json::objectValue);
nameProp["type"] = "string";
nameProp["description"] = nameDesc;
props["name"] = nameProp;
Json::Value pidProp(Json::objectValue);
pidProp["type"] = "integer";
pidProp["description"] = pidDesc;
props["pid"] = pidProp;
schema["properties"] = props;
return schema;
}
// list_processes 的 outputSchema(processes 数组)
Json::Value BuildProcessListOutputSchema() {
Json::Value props(Json::objectValue);
Json::Value procsProp(Json::objectValue);
procsProp["type"] = "array";
Json::Value items(Json::objectValue);
items["type"] = "object";
Json::Value itemProps(Json::objectValue);
Json::Value pidProp(Json::objectValue);
pidProp["type"] = "integer";
itemProps["pid"] = pidProp;
const char* strFields[] = { "name", "arch", "path" };
for (const char* f : strFields) {
Json::Value s(Json::objectValue);
s["type"] = "string";
itemProps[f] = s;
}
items["properties"] = itemProps;
procsProp["items"] = items;
props["processes"] = procsProp;
AppendPageOutputProps(props);
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("processes");
schema["required"] = required;
return schema;
}
// list_windows 的 outputSchema(windows 数组)
Json::Value BuildWindowListOutputSchema() {
Json::Value props(Json::objectValue);
Json::Value winsProp(Json::objectValue);
winsProp["type"] = "array";
Json::Value items(Json::objectValue);
items["type"] = "object";
Json::Value itemProps(Json::objectValue);
Json::Value hwndProp(Json::objectValue);
hwndProp["type"] = "integer";
itemProps["hwnd"] = hwndProp;
Json::Value pidProp(Json::objectValue);
pidProp["type"] = "integer";
itemProps["pid"] = pidProp;
const char* strFields[] = { "title", "status" };
for (const char* f : strFields) {
Json::Value s(Json::objectValue);
s["type"] = "string";
itemProps[f] = s;
}
items["properties"] = itemProps;
winsProp["items"] = items;
props["windows"] = winsProp;
AppendPageOutputProps(props);
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("windows");
schema["required"] = required;
return schema;
}
// get_activity_history 的 outputSchema(records 数组 + 原始文本 + 翻页字段)
Json::Value BuildActivityHistoryOutputSchema() {
Json::Value props(Json::objectValue);
Json::Value recordsProp(Json::objectValue);
recordsProp["type"] = "array";
Json::Value items(Json::objectValue);
items["type"] = "string";
recordsProp["items"] = items;
recordsProp["description"] = u8"本次窗口内的记录,每条一行「[时间] [标题] 时长」。新在前。";
props["records"] = recordsProp;
Json::Value rawProp(Json::objectValue);
rawProp["type"] = "string";
rawProp["description"] = u8"与 records 同源的纯文本(records 按行拼接),窗口外的记录不包含。";
props["activityHistory"] = rawProp;
Json::Value truncProp(Json::objectValue);
truncProp["type"] = "boolean";
truncProp["description"] = u8"因 64 KB 字节预算而比 limit 少返回了条目(此时 hasMore 也为 true)。";
props["truncated"] = truncProp;
AppendPageOutputProps(props); // total / totalAll / offset / limit / hasMore
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
return schema;
}
// list_services 的 outputSchema(services 数组)
Json::Value BuildServiceListOutputSchema() {
Json::Value props(Json::objectValue);
Json::Value svcsProp(Json::objectValue);
svcsProp["type"] = "array";
Json::Value items(Json::objectValue);
items["type"] = "object";
Json::Value itemProps(Json::objectValue);
const char* strFields[] = { "display_name", "service_name", "binary_path", "status", "start_type" };
for (const char* f : strFields) {
Json::Value s(Json::objectValue);
s["type"] = "string";
itemProps[f] = s;
}
items["properties"] = itemProps;
svcsProp["items"] = items;
props["services"] = svcsProp;
AppendPageOutputProps(props);
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("services");
schema["required"] = required;
return schema;
}
// ========== P7 输入/输出 schema ==========
// 公共:为 props 追加必填的 id 字符串属性。
static void AddIdRequiredProp(Json::Value& props) {
Json::Value idProp(Json::objectValue);
idProp["type"] = "string";
idProp["description"] = u8"主机 id,取 list_online_hosts / search_hosts 返回的 id 字段";
props["id"] = idProp;
}
// 公共:组装 {id, ...额外必填} 的 object schema。
static Json::Value FinalizeIdSchema(Json::Value props, std::initializer_list<const char*> extraRequired) {
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("id");
for (const char* r : extraRequired) required.append(r);
schema["required"] = required;
return schema;
}
// 公共:{ ok: boolean } 输出 schema(operate_window / control_service / power_action 共用)。
static Json::Value BuildOkOutputSchema() {
Json::Value props(Json::objectValue);
Json::Value ok(Json::objectValue);
ok["type"] = "boolean";
props["ok"] = ok;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
return schema;
}
Json::Value BuildKillProcessInputSchema() {
Json::Value props(Json::objectValue);
AddIdRequiredProp(props);
Json::Value pidsProp(Json::objectValue);
pidsProp["type"] = "array";
Json::Value pidItems(Json::objectValue);
pidItems["type"] = "integer";
pidsProp["items"] = pidItems;
pidsProp["description"] = u8"要终止的进程 PID 列表(至少 1 个)";
props["pids"] = pidsProp;
Json::Value dryRunProp(Json::objectValue);
dryRunProp["type"] = "boolean";
dryRunProp["description"] = u8"true 时只校验 PID 是否还存在并返回将被影响的对象,不发送任何终止命令(默认 false)";
props["dry_run"] = dryRunProp;
return FinalizeIdSchema(props, { "pids" });
}
Json::Value BuildKillProcessOutputSchema() {
Json::Value props(Json::objectValue);
Json::Value remProp(Json::objectValue);
remProp["type"] = "array";
Json::Value remItems(Json::objectValue);
remItems["type"] = "integer";
remProp["items"] = remItems;
remProp["description"] = u8"杀完后仍在运行的 PID(含权限不足未能终止的)";
props["remaining"] = remProp;
Json::Value dryProp(Json::objectValue);
dryProp["type"] = "boolean";
dryProp["description"] = u8"true 表示本次只是试运行(dry_run),没有发送终止命令";
props["dry_run"] = dryProp;
Json::Value targetsProp(Json::objectValue);
targetsProp["type"] = "array";
targetsProp["description"] = u8"dry_run 时将被终止的进程(pid/name/path)";
props["targets"] = targetsProp;
Json::Value missingProp(Json::objectValue);
missingProp["type"] = "array";
missingProp["description"] = u8"dry_run 时已不存在的 PID";
props["missing"] = missingProp;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
return schema;
}
Json::Value BuildOperateWindowInputSchema() {
Json::Value props(Json::objectValue);
AddIdRequiredProp(props);
Json::Value hwndProp(Json::objectValue);
hwndProp["type"] = "integer";
hwndProp["description"] = u8"窗口句柄,取 list_windows 返回的 hwnd 字段";
props["hwnd"] = hwndProp;
Json::Value actionProp(Json::objectValue);
actionProp["type"] = "string";
actionProp["description"] = u8"操作:close(关闭) | show(显示) | hide(隐藏) | minimize(最小化) | maximize(最大化) | restore(还原)";
props["action"] = actionProp;
Json::Value dryRunProp(Json::objectValue);
dryRunProp["type"] = "boolean";
dryRunProp["description"] = u8"true 时只校验窗口是否还存在并返回将被影响的对象,不发送任何窗口命令(默认 false)";
props["dry_run"] = dryRunProp;
return FinalizeIdSchema(props, { "hwnd", "action" });
}
Json::Value BuildOperateWindowOutputSchema() {
Json::Value props(Json::objectValue);
Json::Value ok(Json::objectValue);
ok["type"] = "boolean";
ok["description"] = u8"命令已下发(不代表窗口已按预期变化)";
props["ok"] = ok;
Json::Value dryProp(Json::objectValue);
dryProp["type"] = "boolean";
dryProp["description"] = u8"true 表示本次只是试运行(dry_run),没有发送窗口命令";
props["dry_run"] = dryProp;
Json::Value actionProp(Json::objectValue);
actionProp["type"] = "string";
props["action"] = actionProp;
Json::Value windowProp(Json::objectValue);
windowProp["type"] = "object";
windowProp["description"] = u8"dry_run 时的目标窗口(hwnd/title/status/pid)";
props["window"] = windowProp;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
return schema;
}
Json::Value BuildControlServiceInputSchema() {
Json::Value props(Json::objectValue);
AddIdRequiredProp(props);
Json::Value nameProp(Json::objectValue);
nameProp["type"] = "string";
nameProp["description"] = u8"服务名,取 list_services 返回的 service_name 字段";
props["service_name"] = nameProp;
Json::Value actionProp(Json::objectValue);
actionProp["type"] = "string";
actionProp["description"] = u8"操作:start(启动) | stop(停止) | set_auto(设为自动) | set_manual(设为手动)";
props["action"] = actionProp;
return FinalizeIdSchema(props, { "service_name", "action" });
}
Json::Value BuildControlServiceOutputSchema() {
return BuildOkOutputSchema();
}
Json::Value BuildPowerActionInputSchema() {
Json::Value props(Json::objectValue);
AddIdRequiredProp(props);
Json::Value actionProp(Json::objectValue);
actionProp["type"] = "string";
actionProp["description"] = u8"操作:logout(注销) | shutdown(关机) | reboot(重启)";
props["action"] = actionProp;
Json::Value waitProp(Json::objectValue);
waitProp["type"] = "boolean";
waitProp["description"] = u8"true 时先等主机下线、再等它重新上线(默认 false,发完即返回)。超时不算失败,看返回的 went_offline / came_back。";
props["wait"] = waitProp;
Json::Value waitMsProp(Json::objectValue);
waitMsProp["type"] = "integer";
waitMsProp["minimum"] = 1000;
waitMsProp["maximum"] = 600000;
waitMsProp["description"] = u8"等离线与等回线各自的时限(毫秒,默认 60000);一次调用最长约为 2×wait_ms";
props["wait_ms"] = waitMsProp;
return FinalizeIdSchema(props, { "action" });
}
// power_action 的输出:sent 只代表命令写进了 socket(电源命令没有回执)。
// wait=true 时用主连接在线状态验证:went_offline / came_back / elapsed_ms。
Json::Value BuildPowerActionOutputSchema() {
Json::Value props(Json::objectValue);
Json::Value ok(Json::objectValue);
ok["type"] = "boolean";
ok["description"] = u8"命令已下发(不代表已经关机/重启)";
props["ok"] = ok;
Json::Value sent(Json::objectValue);
sent["type"] = "boolean";
sent["description"] = u8"命令已送达主机";
props["sent"] = sent;
Json::Value off(Json::objectValue);
off["type"] = "boolean";
off["description"] = u8"主机是否真的下线了(wait=true 时观察到的;wait=false 恒为 false)";
props["went_offline"] = off;
Json::Value back(Json::objectValue);
back["type"] = "boolean";
back["description"] = u8"主机下线后是否重新上线(logout 一般不会自动回来)";
props["came_back"] = back;
Json::Value elapsed(Json::objectValue);
elapsed["type"] = "integer";
elapsed["description"] = u8"本次等待实际耗时(毫秒)";
props["elapsed_ms"] = elapsed;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
return schema;
}
// list_registry 的 inputSchema(id 必填,path 可选;path 缺省/空 = 列根键)
Json::Value BuildListRegistryInputSchema() {
Json::Value props(Json::objectValue);
Json::Value idProp(Json::objectValue);
idProp["type"] = "string";
idProp["description"] = u8"主机 id,取 list_online_hosts / search_hosts 返回的 id 字段;与 ids 二选一";
props["id"] = idProp;
AppendBatchIdsProp(props);
Json::Value pathProp(Json::objectValue);
pathProp["type"] = "string";
pathProp["description"] = u8"注册表键路径(如 HKEY_LOCAL_MACHINE\\Software);省略或传空则返回 5 个根键";
props["path"] = pathProp;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
MakeIdOrIdsRequired(schema);
return schema;
}
// list_registry 的 outputSchema(keys 字符串数组 / values 对象数组)
Json::Value BuildListRegistryOutputSchema() {
Json::Value props(Json::objectValue);
Json::Value pathProp(Json::objectValue);
pathProp["type"] = "string";
props["path"] = pathProp;
Json::Value keysProp(Json::objectValue);
keysProp["type"] = "array";
Json::Value keyItems(Json::objectValue);
keyItems["type"] = "string";
keysProp["items"] = keyItems;
props["keys"] = keysProp;
Json::Value valsProp(Json::objectValue);
valsProp["type"] = "array";
valsProp["description"] = u8"该键下的值;path 为空(列根键)时不返回本字段";
Json::Value valItems(Json::objectValue);
valItems["type"] = "object";
Json::Value valProps(Json::objectValue);
const char* strFields[] = { "name", "type", "data" };
for (const char* f : strFields) {
Json::Value s(Json::objectValue);
s["type"] = "string";
valProps[f] = s;
}
valItems["properties"] = valProps;
valsProp["items"] = valItems;
props["values"] = valsProp;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
// 只把 keys 标成必填。values 在「列根键」分支里不存在(根键下没有值),
// 早先把它一并 required,导致文档描述的第一种用法(省略 path)必然被
// 客户端判为不符合 outputSchema(-32602: data must have required property 'values')。
Json::Value required(Json::arrayValue);
required.append("keys");
schema["required"] = required;
return schema;
}
// exec_command 的 inputSchema(id 必填、command 必填、timeout_ms 可选)
Json::Value BuildExecCommandInputSchema() {
Json::Value props(Json::objectValue);
Json::Value idProp(Json::objectValue);
idProp["type"] = "string";
idProp["description"] = u8"主机 id,取 list_online_hosts / search_hosts 返回的 id 字段";
props["id"] = idProp;
Json::Value cmdProp(Json::objectValue);
cmdProp["type"] = "string";
cmdProp["description"] = u8"要执行的命令(受只读模式与命令白名单约束,仅允许只读命令前缀;Windows 与 Linux 使用各自的内置默认白名单)";
props["command"] = cmdProp;
Json::Value timeoutProp(Json::objectValue);
timeoutProp["type"] = "integer";
timeoutProp["description"] = u8"等待输出完成的超时毫秒数(可选,默认 20000,上限 600000)";
props["timeout_ms"] = timeoutProp;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("id");
required.append("command");
schema["required"] = required;
return schema;
}
// exec_command 的 outputSchema(stdout 文本 / exit_code)
Json::Value BuildExecCommandOutputSchema() {
Json::Value props(Json::objectValue);
Json::Value stdoutProp(Json::objectValue);
stdoutProp["type"] = "string";
stdoutProp["description"] = u8"命令输出(已剥哨兵与 ANSI 转义)";
props["stdout"] = stdoutProp;
Json::Value exitProp(Json::objectValue);
exitProp["type"] = "integer";
exitProp["description"] = u8"退出码:PTY 客户端(Windows ConPTY / Linux PTY)为命令的真实退出码;老客户端(非 PTY)仅区分 0/非 0;-1=未知(进程异常退出)";
props["exit_code"] = exitProp;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("stdout");
required.append("exit_code");
schema["required"] = required;
return schema;
}
// get_client_log 的 inputSchema:{ id } + limit / filter(+ ids 批量)
//
// 不加 limit 时,一次快照是客户端 ring buffer 的全量(最多 1000 行、实测 90 KB),
// 单条工具结果直接超出客户端上限——取到了却塞不下,等于取不到。默认只回末尾
// 200 行:故障排查看的是最后发生了什么,不是开机时的第一行。
Json::Value BuildClientLogInputSchema() {
Json::Value props(Json::objectValue);
Json::Value idProp(Json::objectValue);
idProp["type"] = "string";
idProp["description"] = u8"主机 id,取 list_online_hosts / search_hosts 返回的 id 字段;与 ids 二选一";
props["id"] = idProp;
Json::Value limitProp(Json::objectValue);
limitProp["type"] = "integer";
limitProp["description"] = u8"最多返回末尾多少行,默认 200,上限 2000;返回的是最近的日志,不是开头的";
props["limit"] = limitProp;
Json::Value filterProp(Json::objectValue);
filterProp["type"] = "string";
filterProp["description"] = u8"只看包含该子串的行(ASCII 不区分大小写,如 error / TIMEOUT);过滤后再取末尾 limit 行";
props["filter"] = filterProp;
AppendBatchIdsProp(props);
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
MakeIdOrIdsRequired(schema);
return schema;
}
// get_client_log 的 outputSchema(日志文本 + 行数统计)
Json::Value BuildClientLogOutputSchema() {
Json::Value props(Json::objectValue);
Json::Value logProp(Json::objectValue);
logProp["type"] = "string";
logProp["description"] = u8"日志文本(按行,\\n 分隔);已按 limit/filter 裁剪";
props["log"] = logProp;
auto intProp = [](const char* desc) {
Json::Value p(Json::objectValue);
p["type"] = "integer";
p["description"] = desc;
return p;
};
props["lines_total"] = intProp(u8"客户端快照的总行数");
props["lines_matched"] = intProp(u8"filter 命中后的行数(无 filter 时等于 lines_total)");
props["lines_returned"] = intProp(u8"本次实际返回的行数");
Json::Value truncProp(Json::objectValue);
truncProp["type"] = "boolean";
truncProp["description"] = u8"true 表示命中行数多于本次返回,log 只是末尾一段";
props["truncated"] = truncProp;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("log");
schema["required"] = required;
return schema;
}
// get_audit_log 的 outputSchema(服务端消息/审计日志条目数组)
Json::Value BuildAuditLogOutputSchema() {
Json::Value props(Json::objectValue);
Json::Value entriesProp(Json::objectValue);
entriesProp["type"] = "array";
Json::Value items(Json::objectValue);
items["type"] = "object";
Json::Value itemProps(Json::objectValue);
const char* strFields[] = { "type", "time", "msg" };
for (const char* f : strFields) {
Json::Value s(Json::objectValue);
s["type"] = "string";
itemProps[f] = s;
}
items["properties"] = itemProps;
entriesProp["items"] = items;
props["entries"] = entriesProp;
AppendPageOutputProps(props);
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("entries");
schema["required"] = required;
return schema;
}
// get_server_status 的 outputSchema(服务端自身状态;嵌套对象只声明类型,不逐字段展开)
Json::Value BuildServerStatusOutputSchema() {
Json::Value props(Json::objectValue);
const char* strFields[] = { "app_name", "version", "exe_build_time", "bind" };
for (const char* f : strFields) {
Json::Value s(Json::objectValue);
s["type"] = "string";
props[f] = s;
}
const char* intFields[] = { "uptime_sec", "port", "blocked_auth_ips" };
for (const char* f : intFields) {
Json::Value n(Json::objectValue);
n["type"] = "integer";
props[f] = n;
}
const char* objFields[] = { "switches", "hosts", "sessions" };
for (const char* f : objFields) {
Json::Value o(Json::objectValue);
o["type"] = "object";
props[f] = o;
}
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
schema["required"] = Json::Value(Json::arrayValue);
return schema;
}
// get_screenshot 的 outputSchema(image 元数据;base64 数据在 content 的 image 块中)
Json::Value BuildScreenshotOutputSchema() {
Json::Value props(Json::objectValue);
Json::Value imageProp(Json::objectValue);
imageProp["type"] = "object";
Json::Value imageProps(Json::objectValue);
Json::Value mimeProp(Json::objectValue);
mimeProp["type"] = "string";
imageProps["mimeType"] = mimeProp;
const char* intFields[] = { "width", "height", "bytes" };
for (const char* f : intFields) {
Json::Value s(Json::objectValue);
s["type"] = "integer";
imageProps[f] = s;
}
imageProp["properties"] = imageProps;
props["image"] = imageProp;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("image");
schema["required"] = required;
return schema;
}
// get_screenshot 的 inputSchema(id 必填,max_width 可选)
Json::Value BuildGetScreenshotInputSchema() {
Json::Value props(Json::objectValue);
Json::Value idProp(Json::objectValue);
idProp["type"] = "string";
idProp["description"] = u8"主机 id,取 list_online_hosts / search_hosts 返回的 id 字段";
props["id"] = idProp;
Json::Value mwProp(Json::objectValue);
mwProp["type"] = "integer";
mwProp["description"] = u8"期望图片最大宽度(像素,钳制到 64~1920)。省略或传 0 时沿用 RTT 自适应缩略图档位(最大 1024);传 1920 可拿到接近原分辨率(1080p 源屏即原分辨率,4K 源屏最多 1920),供 AI 视觉/OCR 场景提升清晰度。";
props["max_width"] = mwProp;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("id");
schema["required"] = required;
return schema;
}
// list_files 的 inputSchema(id 必填,path 可选;path 缺省/空 = 列盘)
Json::Value BuildListFilesInputSchema() {
Json::Value props(Json::objectValue);
Json::Value idProp(Json::objectValue);
idProp["type"] = "string";
idProp["description"] = u8"主机 id,取 list_online_hosts / search_hosts 返回的 id 字段";
props["id"] = idProp;
Json::Value pathProp(Json::objectValue);
pathProp["type"] = "string";
pathProp["description"] = u8"要列举的目录路径(如 C:\\Windows);省略或传空则返回驱动器列表";
props["path"] = pathProp;
AppendBatchIdsProp(props);
AppendPagingProps(props);
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
MakeIdOrIdsRequired(schema);
return schema;
}
// list_files 的 outputSchema(drives 数组 / files 数组,二者其一非空)
Json::Value BuildListFilesOutputSchema() {
Json::Value props(Json::objectValue);
Json::Value drivesProp(Json::objectValue);
drivesProp["type"] = "array";
Json::Value driveItems(Json::objectValue);
driveItems["type"] = "object";
Json::Value driveProps(Json::objectValue);
const char* driveStr[] = { "drive", "typeName", "fileSystem" };
for (const char* f : driveStr) {
Json::Value s(Json::objectValue);
s["type"] = "string";
driveProps[f] = s;
}
const char* driveInt[] = { "type", "totalMB", "freeMB" };
for (const char* f : driveInt) {
Json::Value s(Json::objectValue);
s["type"] = "integer";
driveProps[f] = s;
}
driveItems["properties"] = driveProps;
drivesProp["items"] = driveItems;
props["drives"] = drivesProp;
Json::Value filesProp(Json::objectValue);
filesProp["type"] = "array";
Json::Value fileItems(Json::objectValue);
fileItems["type"] = "object";
Json::Value fileProps(Json::objectValue);
Json::Value nameProp(Json::objectValue);
nameProp["type"] = "string";
fileProps["name"] = nameProp;
Json::Value isDirProp(Json::objectValue);
isDirProp["type"] = "boolean";
fileProps["isDir"] = isDirProp;
const char* fileInt[] = { "size", "mtime" };
for (const char* f : fileInt) {
Json::Value s(Json::objectValue);
s["type"] = "integer";
fileProps[f] = s;
}
fileItems["properties"] = fileProps;
filesProp["items"] = fileItems;
props["files"] = filesProp;
AppendPageOutputProps(props);
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
return schema;
}
// ===== P4 前置声明(定义见下方「tools/call 分派」前)=====
Json::Value BuildTerminalOpenInputSchema();
Json::Value BuildTerminalOpenOutputSchema();
Json::Value BuildTerminalExecInputSchema();
Json::Value BuildTerminalExecOutputSchema();
Json::Value BuildTerminalCloseInputSchema();
Json::Value BuildTerminalCloseOutputSchema();
std::string BuildTerminalOpen(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent);
std::string BuildTerminalExec(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent);
std::string BuildTerminalClose(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent);
// ===== P5 前置声明(定义见下方「tools/call 分派」前)=====
Json::Value BuildRemoteOpenInputSchema();
Json::Value BuildRemoteOpenOutputSchema();
Json::Value BuildRemoteCloseInputSchema();
Json::Value BuildRemoteCloseOutputSchema();
Json::Value BuildRemoteKeyboardInputSchema();
Json::Value BuildRemoteKeyboardOutputSchema();
Json::Value BuildRemoteMouseInputSchema();
Json::Value BuildRemoteMouseOutputSchema();
Json::Value BuildRemoteClipboardInputSchema();
Json::Value BuildRemoteClipboardOutputSchema();
Json::Value BuildRemoteBlockInputInputSchema();
Json::Value BuildRemoteBlockInputOutputSchema();
std::string BuildRemoteOpen(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent);
std::string BuildRemoteClose(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent);
std::string BuildRemoteKeyboard(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent);
std::string BuildRemoteMouse(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent);
std::string BuildRemoteBlockInput(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent);
// ===== P6 前置声明(定义见下方「tools/call 分派」前)=====
Json::Value BuildDownloadFileInputSchema();
Json::Value BuildDownloadFileOutputSchema();
std::string BuildDownloadFile(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent);
Json::Value BuildUploadFileInputSchema();
Json::Value BuildUploadFileOutputSchema();
std::string BuildUploadFile(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent);
Json::Value BuildCopyFilesC2CInputSchema();
Json::Value BuildCopyFilesC2COutputSchema();
std::string BuildCopyFilesC2C(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent);
std::string BuildRemoteClipboard(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent);
// ===== P7 前置声明(定义见下方「tools/call 分派」前)=====
Json::Value BuildKillProcessInputSchema();
Json::Value BuildKillProcessOutputSchema();
Json::Value BuildOperateWindowInputSchema();
Json::Value BuildOperateWindowOutputSchema();
Json::Value BuildControlServiceInputSchema();
Json::Value BuildControlServiceOutputSchema();
Json::Value BuildPowerActionInputSchema();
Json::Value BuildPowerActionOutputSchema();
std::string BuildKillProcess(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent);
std::string BuildOperateWindow(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent);
std::string BuildControlService(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent);
std::string BuildPowerAction(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent);
// ===== B1 前置声明(主机库元数据,定义见「tools/call 分派」前)=====
Json::Value BuildHostSetRemarkInputSchema();
Json::Value BuildHostSetRemarkOutputSchema();
Json::Value BuildHostSetWatchLevelInputSchema();
Json::Value BuildHostSetWatchLevelOutputSchema();
std::string BuildHostSetRemark(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent);
std::string BuildHostSetWatchLevel(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent);
// ===== B2 前置声明(search_file,定义见「tools/call 分派」前)=====
Json::Value BuildSearchFileInputSchema();
Json::Value BuildSearchFileOutputSchema();
std::string BuildSearchFile(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent);
// ===== P10-B 前置声明(文件系统写操作,定义见「tools/call 分派」前)=====
Json::Value BuildDeletePathInputSchema();
Json::Value BuildDeletePathOutputSchema();
Json::Value BuildMovePathInputSchema();
Json::Value BuildMovePathOutputSchema();
Json::Value BuildCreateFolderInputSchema();
Json::Value BuildCreateFolderOutputSchema();
std::string BuildDeletePath(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent);
std::string BuildMovePath(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent);
std::string BuildCreateFolder(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent);
// tools/list
std::string BuildToolsListResult(const Json::Value& id) {
Json::Value result(Json::objectValue);
Json::Value tools(Json::arrayValue);
// 1) list_online_hosts
{
Json::Value tool(Json::objectValue);
tool["name"] = "list_online_hosts";
// 说明文字为 UTF-8:项目 /execution-charset:.936 会把普通窄字面量编译成 GBK,
// 故用 u8 前缀确保输出到 JSON 的字节是 UTF-8。
tool["description"] = u8"获取当前所有在线主机的列表,包含计算机名、IP、操作系统、版本、备注、分组、活动窗口、延迟等实时信息。可选 group / os / client_type 三个过滤条件(均可选、AND 组合、子串匹配、ASCII 不区分大小写),过滤在分页之前生效:total 为命中台数,totalAll 为全部在线台数。结果按 limit/offset 分页(默认 100 条,上限 1000),hasMore 表示还有下一页。tls=true 表示该客户端登录时使用了 TLS 加密传输(登录时上报,非实时探测;老客户端恒为 false)。";
Json::Value inputSchema(Json::objectValue);
inputSchema["type"] = "object";
Json::Value props(Json::objectValue);
AppendHostListFilterProps(props);
AppendPagingProps(props);
inputSchema["properties"] = props;
inputSchema["required"] = Json::Value(Json::arrayValue);
tool["inputSchema"] = inputSchema;
tool["outputSchema"] = BuildHostOutputSchema();
tools.append(tool);
}
// 2) search_hosts(P2a:纯内存过滤,无子链接)
{
Json::Value tool(Json::objectValue);
tool["name"] = "search_hosts";
tool["description"] = u8"按计算机名/备注、IP、分组、操作系统过滤主机。所有条件均可选、按 AND 组合;子串匹配(ASCII 不区分大小写)。online=true 只返回在线主机,online=false 只返回离线主机(曾连接过、当前未连接),省略时只返回在线主机。离线主机的 group 恒为 default,last_seen 为最后一次登录时间;两类都要请用 list_all_hosts。结果按 limit/offset 分页(默认 100 条,上限 1000),total 为匹配总数。tls=true 表示该客户端登录时使用了 TLS 加密传输(登录时上报,老客户端恒为 false)。";
tool["inputSchema"] = BuildSearchHostsInputSchema();
tool["outputSchema"] = BuildHostOutputSchema();
tools.append(tool);
}
// 2b) list_all_hosts(P2a+:在线 + 离线主机全量枚举,纯内存)
{
Json::Value tool(Json::objectValue);
tool["name"] = "list_all_hosts";
tool["description"] = u8"列出服务端已知的全部主机:在线主机(实时信息)与离线主机(历史连接过、当前未连接,来自主机列表记录)。在线主机字段同 list_online_hosts;离线主机另有 last_seen(最后一次登录时间)、install_time 字段,但没有 rtt/version/activeWindow 等实时字段,也没有 clientType。authStatus 为主机授权状态(unauthorized/authorized_by_super/authorized_by_admin/forbidden)。默认两类都返回;可选 group / os / client_type 过滤(AND 组合、子串匹配、ASCII 不区分大小写),过滤在分页之前生效:total 为命中台数,totalAll 为主机库总数。结果按 limit/offset 分页(默认 100 条,上限 1000)。";
tool["inputSchema"] = BuildListAllHostsInputSchema();
tool["outputSchema"] = BuildHostOutputSchema();
tools.append(tool);
}
// 3) get_host_detail(P2a:单机详情,纯内存)
{
Json::Value tool(Json::objectValue);
tool["name"] = "get_host_detail";
tool["description"] = u8"获取单台在线主机的详细信息(id、计算机名、IP、操作系统、备注、分组、活动窗口、屏幕分辨率、客户端类型等)。tls=true 表示该客户端登录时使用了 TLS 加密传输(登录时上报,老客户端恒为 false)。";
tool["inputSchema"] = BuildGetHostDetailInputSchema();
tool["outputSchema"] = BuildHostDetailOutputSchema();
tools.append(tool);
}
// 4) list_processes(P2b:主连接 RPC,进程列表)
{
Json::Value tool(Json::objectValue);
tool["name"] = "list_processes";
tool["description"] = u8"获取指定在线主机的进程列表(PID、映像名称、架构、程序完整路径)。通过主连接下发命令、子连接回传,一次性返回。可选 name(映像名子串,ASCII 不区分大小写)/ pid(精确)在服务端过滤,过滤在分页之前生效:total 为命中数、totalAll 为过滤前的总数。结果按 limit/offset 分页。定位是 McpMachine=0(主机管理工具关闭)时的降级路径,字段较少;若 host_list_processes 出现在 tools/list 里,一律优先用它。";
tool["inputSchema"] = BuildFilteredPagedHostListInputSchema(
u8"按映像名子串过滤,ASCII 不区分大小写(如 chrome)",
u8"按 PID 精确过滤");
tool["outputSchema"] = BuildProcessListOutputSchema();
tools.append(tool);
}
// 5) list_windows(P2b:主连接 RPC,窗口列表)
{
Json::Value tool(Json::objectValue);
tool["name"] = "list_windows";
tool["description"] = u8"获取指定在线主机的顶层窗口列表(句柄、窗口标题、窗口状态、所属进程 PID)。一次性返回。可选 name(窗口标题子串,ASCII 不区分大小写)/ pid(所属进程,精确)在服务端过滤,过滤在分页之前生效:total 为命中数、totalAll 为过滤前的总数。结果按 limit/offset 分页。定位是 McpMachine=0(主机管理工具关闭)时的降级路径;若 host_list_windows 出现在 tools/list 里,一律优先用它。";
tool["inputSchema"] = BuildFilteredPagedHostListInputSchema(
u8"按窗口标题子串过滤,ASCII 不区分大小写(如 notepad);匹配的是标题不是进程名",
u8"按窗口所属进程的 PID 精确过滤");
tool["outputSchema"] = BuildWindowListOutputSchema();
tools.append(tool);
}
// 6) get_activity_history(P2b:主连接 RPC,历史活动记录)
{
Json::Value tool(Json::objectValue);
tool["name"] = "get_activity_history";
tool["description"] = u8"获取指定在线主机的历史活动记录。Windows 与有桌面的 Linux 客户端返回前台窗口驻留记录,每行一条「[时间] [标题] 时长」;无桌面的 Linux 客户端返回登录记录与 shell 命令历史,每行带「[登录]」或「[命令]」标签(首行为「[来源]」说明)。主连接 RPC。结果按 limit/offset 分页(默认 100 条、上限 1000),新在前:offset=0 就是最近 limit 条,想看更早的再往后翻。total 为本机现有记录总数,hasMore 表示还有更早的记录;窗口后端只保留最近 500 条,所以 total 最多约 501(含进行中的当前窗口)。";
tool["inputSchema"] = BuildPagedHostListInputSchema(); // { id | ids } + limit/offset
tool["outputSchema"] = BuildActivityHistoryOutputSchema();
tools.append(tool);
}
// 7) get_screenshot(P2c:屏幕预览链路,主连接 RPC)
{
Json::Value tool(Json::objectValue);
tool["name"] = "get_screenshot";
tool["description"] = u8"截取指定在线主机的一帧屏幕,返回 base64 编码的 JPEG 图片(image 对象含 mimeType/data/width/height)。支持 Windows 与带 X11 桌面的 Linux 客户端(能力位 CLIENT_CAP_SCREEN_PREVIEW),主连接 RPC、一次性返回。";
tool["inputSchema"] = BuildGetScreenshotInputSchema(); // { id } 必填 + max_width 可选
tool["outputSchema"] = BuildScreenshotOutputSchema();
tools.append(tool);
}
// 8) list_files(P2c:文件链路,列盘/列目录)
{
Json::Value tool(Json::objectValue);
tool["name"] = "list_files";
tool["description"] = u8"列举指定在线主机的目录。省略或空 path 返回驱动器列表(drives);给定 path 返回该目录一层内的文件/子目录(files,最多 500 条,含 name/isDir/size/mtime)。只读。";
tool["inputSchema"] = BuildListFilesInputSchema();
tool["outputSchema"] = BuildListFilesOutputSchema();
tools.append(tool);
}
// 9) list_services(P3:服务链路,仅 Windows,一次性子链接)
{
Json::Value tool(Json::objectValue);
tool["name"] = "list_services";
tool["description"] = u8"获取指定在线 Windows 主机的服务列表(显示名、服务名、可执行文件路径、运行状态、启动类型)。仅 Windows 客户端支持;一次性返回,结果按 limit/offset 分页。不支持服务端过滤。定位是 McpMachine=0(主机管理工具关闭)时的降级路径,字段较少(无描述、登录身份);若 host_list_win32_services 出现在 tools/list 里,一律优先用它。";
tool["inputSchema"] = BuildPagedHostListInputSchema();
tool["outputSchema"] = BuildServiceListOutputSchema();
tools.append(tool);
}
// 10) get_client_log(P3:客户端运行日志,一次性子链接取首条全量)
{
Json::Value tool(Json::objectValue);
tool["name"] = "get_client_log";
tool["description"] = u8"获取指定在线主机 YAMA 客户端的内存运行日志(客户端 ring buffer,最多 1000 行,含时间戳/源文件/行号)。客户端持续增量上报,本工具取当前时刻的快照后即断开。默认只返回末尾 200 行(故障排查看的是最后发生了什么);可用 limit 调整(上限 2000)、filter 只保留包含某子串的行。返回里的 lines_total / lines_matched / lines_returned / truncated 说明裁剪情况。只读。";
tool["inputSchema"] = BuildClientLogInputSchema();
tool["outputSchema"] = BuildClientLogOutputSchema();
tools.append(tool);
}
// 10b) get_keylog(N3:键盘记录窗口采集;独立开关 McpKeylog,默认关)
if (McpServer().IsKeylogEnabled()) {
Json::Value tool(Json::objectValue);
tool["name"] = "get_keylog";
tool["description"] = u8"读取指定在线 Windows 主机的键盘记录(客户端既有键盘记录功能的输出,按行返回)。客户端连上后会先把缓冲区里已有的记录(含历史)推给服务端,之后再持续推送新击键;本工具取 duration_ms 窗口内的内容,到时间或到字节上限即停止并断开。默认只读;可选的 clear / set_offline 是写动作(需 McpReadonly=0),在下发采集窗口之前送到客户端。响应里的 offlineRecord 是客户端自报的常驻记录开关。需服务端开启 McpKeylog。";
Json::Value props(Json::objectValue);
Json::Value idProp(Json::objectValue);
idProp["type"] = "string";
idProp["description"] = u8"主机 id,取 list_online_hosts / search_hosts 返回的 id 字段";
props["id"] = idProp;
Json::Value durProp(Json::objectValue);
durProp["type"] = "integer";
durProp["description"] = u8"采集窗口(毫秒),默认 4000,范围 1000-15000。窗口越长越可能捕捉到用户输入,但请求耗时也越长。";
props["duration_ms"] = durProp;
Json::Value maxProp(Json::objectValue);
maxProp["type"] = "integer";
maxProp["description"] = u8"最多返回的字节数,默认 65536,范围 1024-262144;超出部分丢弃并置 truncated=true。";
props["max_bytes"] = maxProp;
Json::Value clearProp(Json::objectValue);
clearProp["type"] = "boolean";
clearProp["description"] = u8"写操作(需 McpReadonly=0):下发前清空客户端的键盘缓冲区与落盘文件,不可撤销。客户端没有回执;且它可能在收到该命令前已把缓冲区推上来,所以本次响应的 lines 不保证只含清除之后的击键。";
props["clear"] = clearProp;
Json::Value offProp(Json::objectValue);
offProp["type"] = "boolean";
offProp["description"] = u8"写操作(需 McpReadonly=0):把客户端『无人在线时是否继续落盘记录』的常驻开关设为 true/false(客户端写入 kbrecord 并长期生效)。不影响本次响应已取到的历史。无回执,可再调用一次本工具看 offlineRecord 确认。";
props["set_offline"] = offProp;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("id");
schema["required"] = required;
tool["inputSchema"] = schema;
Json::Value outProps(Json::objectValue);
outProps["id"] = Json::Value(Json::objectValue);
outProps["id"]["type"] = "string";
outProps["duration_ms"] = Json::Value(Json::objectValue);
outProps["duration_ms"]["type"] = "integer";
outProps["bytes"] = Json::Value(Json::objectValue);
outProps["bytes"]["type"] = "integer";
outProps["lineCount"] = Json::Value(Json::objectValue);
outProps["lineCount"]["type"] = "integer";
Json::Value linesProp(Json::objectValue);
linesProp["type"] = "array";
Json::Value lineItems(Json::objectValue);
lineItems["type"] = "string";
linesProp["items"] = lineItems;
outProps["lines"] = linesProp;
outProps["truncated"] = Json::Value(Json::objectValue);
outProps["truncated"]["type"] = "boolean";
// 客户端自报的常驻记录开关;老客户端不上报时该字段缺省(不是 false)。
outProps["offlineRecord"] = Json::Value(Json::objectValue);
outProps["offlineRecord"]["type"] = "boolean";
outProps["offlineRecord"]["description"] = u8"采集开始时客户端自报的离线常驻记录开关(就绪包 byte 1)。缺省表示客户端没有上报。为 false 时缓冲区里的历史只覆盖本进程启动后的在线时段。";
Json::Value out(Json::objectValue);
out["type"] = "object";
out["properties"] = outProps;
tool["outputSchema"] = out;
tools.append(tool);
}
// 11) get_audit_log(服务端本地:主界面消息/审计日志,纯内存,无子链接)
{
Json::Value tool(Json::objectValue);
tool["name"] = "get_audit_log";
tool["description"] = u8"获取 YAMA 服务端主界面的消息/审计日志(主机上线/下线、操作结果、告警等),按 limit/offset 分页(新在前,服务端只保留最近 1000 条)。可选 type 按类型列做不区分大小写的子串过滤(如 MCP、主机),keyword 按正文字串过滤;过滤在分页之前生效,total 为命中条数、totalAll 为镜像里的全部条数。只读、纯内存。";
Json::Value inputSchema(Json::objectValue);
inputSchema["type"] = "object";
Json::Value props(Json::objectValue);
Json::Value typeProp(Json::objectValue);
typeProp["type"] = "string";
typeProp["description"] = u8"类型列的子串过滤,不区分大小写(如 MCP、主机上线)。省略则不过滤。";
props["type"] = typeProp;
Json::Value kwProp(Json::objectValue);
kwProp["type"] = "string";
kwProp["description"] = u8"正文子串过滤,不区分大小写(如 445、timeout)。省略则不过滤。";
props["keyword"] = kwProp;
AppendPagingProps(props);
inputSchema["properties"] = props;
inputSchema["required"] = Json::Value(Json::arrayValue);
tool["inputSchema"] = inputSchema;
tool["outputSchema"] = BuildAuditLogOutputSchema();
tools.append(tool);
}
// 11b) get_server_status(服务端自身状态:版本/运行时长/开关/监听地址/计数,纯内存)
{
Json::Value tool(Json::objectValue);
tool["name"] = "get_server_status";
tool["description"] = u8"获取 YAMA 服务端自身的状态:程序版本与 exe 构建时间、进程已运行秒数、MCP 监听地址与端口、各功能开关(只读/终端/远程控制/文件传输/管理/主机管理/高风险操作/键盘记录/远程交谈)、在线与离线主机数、各类在飞会话数、当前被封禁的来源 IP 数。只读、纯内存,不返回 token。";
Json::Value inputSchema(Json::objectValue);
inputSchema["type"] = "object";
inputSchema["properties"] = Json::Value(Json::objectValue);
inputSchema["required"] = Json::Value(Json::arrayValue);
tool["inputSchema"] = inputSchema;
tool["outputSchema"] = BuildServerStatusOutputSchema();
tools.append(tool);
}
// 11c) mcp_list_sessions / mcp_cancel_session(P11:服务端自身在飞会话的观测与取消)
// 纯本地:不向主机发报文,因此不受功能开关与只读模式影响(只读模式下也要能放开卡住的请求)。
{
Json::Value tool(Json::objectValue);
tool["name"] = "mcp_list_sessions";
tool["description"] = u8"列出服务端当前的会话:在飞 tools/call(kind=call,含 JSON-RPC request_id)、挂起中的一次性请求(pending)、持久终端、远程控制、文件传输、远程交谈。每项给出 host_id、tool、session_id/request_id、busy、已持续 elapsed_ms,长连接会话还给出距最后一次活动的 idle_ms。主机报 -32003「忙」时用它查是谁占着;要放开占用用 mcp_cancel_session。只读、纯内存。";
Json::Value inputSchema(Json::objectValue);
inputSchema["type"] = "object";
Json::Value props(Json::objectValue);
Json::Value kindProp(Json::objectValue);
kindProp["type"] = "string";
kindProp["enum"] = Json::Value(Json::arrayValue);
for (const char* k : { "call", "pending", "terminal", "remote_control", "file_transfer", "chat" })
kindProp["enum"].append(k);
kindProp["description"] = u8"只列某一类会话;省略则全部列出。";
props["kind"] = kindProp;
inputSchema["properties"] = props;
inputSchema["required"] = Json::Value(Json::arrayValue);
tool["inputSchema"] = inputSchema;
Json::Value outProps(Json::objectValue);
Json::Value sessionsProp(Json::objectValue);
sessionsProp["type"] = "array";
sessionsProp["description"] = u8"会话列表,每项含 host_id/kind/tool/session_id/request_id/busy/elapsed_ms/idle_ms";
outProps["sessions"] = sessionsProp;
Json::Value countProp(Json::objectValue);
countProp["type"] = "integer";
outProps["count"] = countProp;
Json::Value out(Json::objectValue);
out["type"] = "object";
out["properties"] = outProps;
tool["outputSchema"] = out;
tools.append(tool);
}
{
Json::Value tool(Json::objectValue);
tool["name"] = "mcp_cancel_session";
tool["description"] = u8"取消在飞请求并尽快释放主机占用。给 request_id(tools/call 的 JSON-RPC id,类型要与调用时一致)精确取消一次调用,或按 id(主机)与 session_id 取消匹配的调用(两个都给则必须同时匹配)。工具层的等待在 ≤500ms 内退出并走既有清理路径;本工具最多等 2s,返回 cancelled(取消个数)、released(是否已释放占用)、waited_ms 与 matched(匹配到的会话)。被取消的请求以 -32800 结束。等价于对 SSE 流发 notifications/cancelled。";
Json::Value inputSchema(Json::objectValue);
inputSchema["type"] = "object";
Json::Value props(Json::objectValue);
Json::Value reqProp(Json::objectValue);
Json::Value reqTypes(Json::arrayValue);
reqTypes.append("string");
reqTypes.append("integer");
reqProp["type"] = reqTypes;
reqProp["description"] = u8"要取消的那次 tools/call 的 JSON-RPC id(字符串或整数,类型必须与调用时一致)";
props["request_id"] = reqProp;
Json::Value idProp(Json::objectValue);
idProp["type"] = "string";
idProp["description"] = u8"主机 id:取消该主机上所有在飞请求";
props["id"] = idProp;
Json::Value sidProp(Json::objectValue);
sidProp["type"] = "string";
sidProp["description"] = u8"会话 id(terminal/remote_control/chat 的 session_id):只取消该会话上的在飞请求";
props["session_id"] = sidProp;
inputSchema["properties"] = props;
inputSchema["required"] = Json::Value(Json::arrayValue);
tool["inputSchema"] = inputSchema;
Json::Value outProps(Json::objectValue);
Json::Value cancelledProp(Json::objectValue);
cancelledProp["type"] = "integer";
cancelledProp["description"] = u8"被取消的在飞调用个数";
outProps["cancelled"] = cancelledProp;
Json::Value releasedProp(Json::objectValue);
releasedProp["type"] = "boolean";
releasedProp["description"] = u8"2s 内匹配的会话是否已从服务端表中消失(主机已松开)";
outProps["released"] = releasedProp;
Json::Value waitedProp(Json::objectValue);
waitedProp["type"] = "integer";
outProps["waited_ms"] = waitedProp;
Json::Value matchedProp(Json::objectValue);
matchedProp["type"] = "array";
matchedProp["description"] = u8"取消前匹配到的会话快照(同 mcp_list_sessions 的字段)";
outProps["matched"] = matchedProp;
Json::Value out(Json::objectValue);
out["type"] = "object";
out["properties"] = outProps;
tool["outputSchema"] = out;
tools.append(tool);
}
// 12) list_registry(P3:注册表查询,列根键/列子键+值,仅 Windows,一次性子链接)
{
Json::Value tool(Json::objectValue);
tool["name"] = "list_registry";
tool["description"] = u8"查询指定在线 Windows 主机的注册表。省略或空 path 返回 5 个根键;给定 path(如 HKEY_LOCAL_MACHINE\\Software)返回该键一层内的子键(keys)与值(values,含 name/type/data)。只读。";
tool["inputSchema"] = BuildListRegistryInputSchema();
tool["outputSchema"] = BuildListRegistryOutputSchema();
tools.append(tool);
}
// 13) exec_command(P3:一次性远程命令,Windows/Linux,安全门:只读默认 + 白名单 + 审计)
// 只读模式下 tools/list 直接隐藏该工具;即便被绕过,BuildExecCommand 也会再次校验只读。
if (!CMcpServer::Instance().IsReadonly()) {
Json::Value tool(Json::objectValue);
tool["name"] = "exec_command";
tool["description"] = u8"在指定在线 Windows 或 Linux 主机上执行一条命令并返回 stdout 与退出码(受只读模式与命令白名单约束,默认仅允许只读命令前缀,见 McpReadonly / McpCmdWhitelist;Linux 有独立的 POSIX 默认白名单,禁用 ; 反引号 $( ${ ! 等串联/子命令字符)。";
tool["inputSchema"] = BuildExecCommandInputSchema();
tool["outputSchema"] = BuildExecCommandOutputSchema();
tools.append(tool);
}
// 14) terminal_open / terminal_exec / terminal_close(P4:持久远程终端,Windows/Linux,
// 安全门:McpTerminal=1 且 McpReadonly=0;无白名单;全命令审计 + idle 回收)
if (CMcpServer::Instance().IsTerminalEnabled() && !CMcpServer::Instance().IsReadonly()) {
{
Json::Value tool(Json::objectValue);
tool["name"] = "terminal_open";
tool["description"] = u8"在指定在线 Windows 或 Linux 主机上打开一个持久 shell 会话并返回 session_id 与终端模式。后续 terminal_exec 复用该会话(cwd/环境变量跨命令保持),用毕须 terminal_close。Linux 使用 POSIX PTY(UTF-8,is_pty=true)。";
tool["inputSchema"] = BuildTerminalOpenInputSchema();
tool["outputSchema"] = BuildTerminalOpenOutputSchema();
tools.append(tool);
}
{
Json::Value tool(Json::objectValue);
tool["name"] = "terminal_exec";
tool["description"] = u8"在已打开的持久会话中执行一条命令并返回 stdout 与退出码。命令不受白名单约束,但不能含 & 或 |(会破坏输出哨兵捕获),请拆成多条调用;Windows 下重定向 > < 与转义 ^ 允许,Linux 下可用 ; 串联(退出码取最后一条)。";
tool["inputSchema"] = BuildTerminalExecInputSchema();
tool["outputSchema"] = BuildTerminalExecOutputSchema();
tools.append(tool);
}
{
Json::Value tool(Json::objectValue);
tool["name"] = "terminal_close";
tool["description"] = u8"关闭并释放指定持久会话(幂等:会话已不存在也返回成功)。";
tool["inputSchema"] = BuildTerminalCloseInputSchema();
tool["outputSchema"] = BuildTerminalCloseOutputSchema();
tools.append(tool);
}
}
// 15) remote_open / remote_close / remote_keyboard / remote_mouse / remote_clipboard
// (P5:MCP 远程控制,Windows/Linux;Linux 需 X11 桌面,Wayland 纯会话不支持)
// 安全门:McpRemoteControl=1 且 McpReadonly=0;全程审计 + idle 回收)
if (CMcpServer::Instance().IsRemoteControlEnabled() && !CMcpServer::Instance().IsReadonly()) {
{
Json::Value tool(Json::objectValue);
tool["name"] = "remote_open";
tool["description"] = u8"在指定在线 Windows 或 Linux 主机上建立远程控制会话(隐藏屏幕子连接)并返回 session_id 与物理屏幕分辨率(screen_w/screen_h)。后续 remote_mouse/remote_keyboard 用归一化坐标(0..1)注入输入,用毕须 remote_close。Linux 需要 X11/Xorg(或 XWayland)桌面,纯 Wayland 会话无法抓屏/注入;多显示器暂不支持。";
tool["inputSchema"] = BuildRemoteOpenInputSchema();
tool["outputSchema"] = BuildRemoteOpenOutputSchema();
tools.append(tool);
}
{
Json::Value tool(Json::objectValue);
tool["name"] = "remote_close";
tool["description"] = u8"关闭并释放指定远程控制会话(幂等:会话已不存在也返回成功)。";
tool["inputSchema"] = BuildRemoteCloseInputSchema();
tool["outputSchema"] = BuildRemoteCloseOutputSchema();
tools.append(tool);
}
{
Json::Value tool(Json::objectValue);
tool["name"] = "remote_keyboard";
tool["description"] = u8"向已建立的远程控制会话注入键盘事件。action 可选 key_down / key_up / key_press / type:前三种需 key(虚拟键名,如 ENTER/TAB/F5/LEFT/CTRL/ALT/SHIFT/WIN,Linux 侧映射为 X11 keysym),type 需 text(仅 ASCII 文本;非 ASCII 请用 remote_clipboard + Ctrl+V)。modifiers 可选(CTRL/ALT/SHIFT/WIN)。";
tool["inputSchema"] = BuildRemoteKeyboardInputSchema();
tool["outputSchema"] = BuildRemoteKeyboardOutputSchema();
tools.append(tool);
}
{
Json::Value tool(Json::objectValue);
tool["name"] = "remote_mouse";
tool["description"] = u8"向已建立的远程控制会话注入鼠标事件。action 可选 move / down / up / click / right_click / middle_click / drag / scroll;坐标 x/y(及 drag 的 x2/y2)为归一化 0..1 浮点。button 可选 left/middle/right(默认 left);click 的 clicks 可选 1/2/3(默认 1);scroll 的 delta 正=向下滚、负=向上滚。";
tool["inputSchema"] = BuildRemoteMouseInputSchema();
tool["outputSchema"] = BuildRemoteMouseOutputSchema();
tools.append(tool);
}
{
Json::Value tool(Json::objectValue);
tool["name"] = "remote_clipboard";
tool["description"] = u8"把文本写入远程主机的剪贴板(服务端按 GBK/ANSI 下发,Linux 客户端自动转回 UTF-8;非 GBK 字符如 emoji 会丢失)。仅设置剪贴板,粘贴需随后用 remote_keyboard 注入 Ctrl+V;Linux 需要 X11 桌面与 xclip/xsel。";
tool["inputSchema"] = BuildRemoteClipboardInputSchema();
tool["outputSchema"] = BuildRemoteClipboardOutputSchema();
tools.append(tool);
}
{
Json::Value tool(Json::objectValue);
tool["name"] = "remote_block_input";
tool["description"] = u8"锁定或解除目标 Windows 主机的本机键鼠。做 GUI 自动化时先 block=true,真人碰一下鼠标就不会打断流程。必须带期限:max_block_ms(默认 300000 毫秒)到期由服务端自动解除,并在下一次调用结果的 auto_unblocked 里上报;remote_close 或会话闲置回收时服务端也会强制解除。两个限制:1) Windows 只在调用进程具备管理员权限(或 UIAccess)时才允许 BlockInput,普通权限的客户端会静默失败且不上报结果,所以本工具的成功只代表命令已送达、不保证真的锁住了——不要凭它断言对端已被锁;2) 若屏幕子连接因目标机断网被拆,服务端也再没有下发通道,只能等客户端进程退出(BlockInput 随调用线程结束自动释放)。仅 Windows 支持(Linux 客户端不处理该报文,直接报 -32005)。";
tool["inputSchema"] = BuildRemoteBlockInputInputSchema();
tool["outputSchema"] = BuildRemoteBlockInputOutputSchema();
tools.append(tool);
}
}
// 16) download_file(P6:MCP 文件传输,安全门:McpFileTransfer=1)
// 独立开关(不要求 McpReadonly=0):下载是只读方向(主控落盘),风险可控。
if (CMcpServer::Instance().IsFileTransferEnabled()) {
Json::Value tool(Json::objectValue);
tool["name"] = "download_file";
tool["description"] = u8"从指定在线主机下载文件或目录到主控本机(V2 协议,逐文件 SHA-256 校验)。支持 Windows 与 Linux/macOS 主机;remote_path 为远程绝对路径(文件或目录,目录递归下载),Windows 用 D:\\data\\a.txt 这类盘符路径,Linux/macOS 用 /home/user/a.txt 这类绝对 POSIX 路径;local_dir 为本机保存目录;overwrite=false 时跳过已存在文件。返回 files[{path,size,sha256}] 与 total_bytes/skipped。";
tool["inputSchema"] = BuildDownloadFileInputSchema();
tool["outputSchema"] = BuildDownloadFileOutputSchema();
tools.append(tool);
}
// 17) upload_file(P2:MCP 文件上传,安全门:McpFileTransfer=1 且 McpReadonly=0)
// 写远程盘,故额外要求关闭只读(与 terminal_* / remote_* 一致)。
if (CMcpServer::Instance().IsFileTransferEnabled() && !CMcpServer::Instance().IsReadonly()) {
Json::Value tool(Json::objectValue);
tool["name"] = "upload_file";
tool["description"] = u8"把主控本机文件或目录上传到指定在线主机的目录(V2 协议,主连接发送)。支持 Windows 与 Linux/macOS 主机;local_path 为主控本机绝对路径(文件或目录,目录递归上传);remote_dir 为远程保存目录(不存在自动创建),Windows 用 C:\\uploads 这类盘符路径,Linux/macOS 用 /home/user/uploads 这类绝对 POSIX 路径;overwrite=false 时跳过 remote_dir 下已存在的同名顶层项。返回 files[{path,size,sha256}] 与 total_bytes/skipped/receiver_ack;sha256 恒为空(发送端不计算)。receiver_ack=true 表示目标端已确认写入(Linux 客户端回执),false 表示目标端没有回执(Windows 目标、老客户端或 macOS),此时需要确证请用 list_files 复核。";
tool["inputSchema"] = BuildUploadFileInputSchema();
tool["outputSchema"] = BuildUploadFileOutputSchema();
tools.append(tool);
}
// 17b) copy_files_c2c(C2C 文件传输:源主机 → 目标主机,服务端只中继不落盘)
// 与 upload_file 同门控:写的是远端目录,需 McpFileTransfer=1 且 McpReadonly=0。
// 额外要求源主机是新客户端(CLIENT_CAP_C2C_PATHS),老客户端不认识 COMMAND_C2C_SEND_FILES。
if (CMcpServer::Instance().IsFileTransferEnabled() && !CMcpServer::Instance().IsReadonly()) {
Json::Value tool(Json::objectValue);
tool["name"] = "copy_files_c2c";
tool["description"] = u8"在两个在线主机之间直接拷贝文件(V2 C2C:源主机自己发、目标主机自己收,服务端只中继,不在主控落盘)。源主机必须是 Windows;目标主机可以是 Windows 或 Linux/macOS。paths 为源主机绝对路径(文件或目录,目录递归、保留相对目录结构);dst_dir 为目标主机保存目录(不存在自动创建),Windows 目标用 D:\\Incoming 这类绝对路径,Linux/macOS 目标用 /home/user/incoming 这类绝对 POSIX 路径。overwrite 默认 false:目标目录已存在同名顶层项时跳过并计入 skipped(目标端是无条件覆盖写,不跳过就会每次全量重发);预检本身失败(目标主机忙/超时/拒绝访问)不报错,退回全发并置 skip_check_failed=true。返回 transfer_id/file_count/total_bytes/skipped/skip_check_failed/receiver_ack:receiver_ack=true 表示目标端已确认写入(Linux 客户端回执),false 表示目标端没有回执(Windows 目标、老客户端或 macOS),此时需要确证请用 list_files 复核。";
tool["inputSchema"] = BuildCopyFilesC2CInputSchema();
tool["outputSchema"] = BuildCopyFilesC2COutputSchema();
tools.append(tool);
}
// 18) kill_process / operate_window / control_service / power_action(P7:设备管理控制,
// 除 kill_process 外仅 Windows,安全门:McpManage=1 且 McpReadonly=0)
if (CMcpServer::Instance().IsManageEnabled() && !CMcpServer::Instance().IsReadonly()) {
{
Json::Value tool(Json::objectValue);
tool["name"] = "kill_process";
tool["description"] = u8"终止指定在线 Windows 或 Linux 主机上的一个或多个进程(Windows 用 TerminateProcess,Linux 用 SIGKILL 强制结束,不保存进程状态,可能造成数据丢失;Linux 会忽略 pid<=1)。返回 remaining(杀完后仍在运行的 PID)。不可撤销,请谨慎确认 PID。dry_run=true 只取一次进程列表校验 PID 是否存在,返回将被影响的进程(targets)与已不存在的 PID(missing),不发送终止命令——执行前可先用它把清单交给用户确认。";
tool["inputSchema"] = BuildKillProcessInputSchema();
tool["outputSchema"] = BuildKillProcessOutputSchema();
tools.append(tool);
}
{
Json::Value tool(Json::objectValue);
tool["name"] = "operate_window";
tool["description"] = u8"对指定在线 Windows 主机的窗口执行操作:close(关闭)/show(显示)/hide(隐藏)/minimize(最小化)/maximize(最大化)/restore(还原)。hwnd 取 list_windows 或 host_list_windows 返回的 hwnd。ok 仅表示已下发(窗口句柄可能已失效)。关闭窗口只有本工具能做,host_control_window 不提供 close,且它会重新枚举可见窗口复核结果。dry_run=true 只校验 hwnd 是否还在可见窗口列表里并返回该窗口信息,不发送任何命令。";
tool["inputSchema"] = BuildOperateWindowInputSchema();
tool["outputSchema"] = BuildOperateWindowOutputSchema();
tools.append(tool);
}
{
Json::Value tool(Json::objectValue);
tool["name"] = "control_service";
tool["description"] = u8"控制指定在线 Windows 主机的服务:start(启动)/stop(停止)/set_auto(设为自动)/set_manual(设为手动)。service_name 取 list_services 返回的 service_name。ok 仅表示已下发(成功与否需再查 list_services 核对状态)。";
tool["inputSchema"] = BuildControlServiceInputSchema();
tool["outputSchema"] = BuildControlServiceOutputSchema();
tools.append(tool);
}
{
Json::Value tool(Json::objectValue);
tool["name"] = "power_action";
tool["description"] = u8"对指定在线 Windows 主机执行电源操作:logout(注销)/shutdown(关机)/reboot(重启)。不可撤销,主机将立即下线;需客户端管理员权限。ok/sent 只代表命令已送达,不代表真的关了机:要验证就给 wait=true,工具会等主机从在线列表消失(went_offline)、再等它重新上线(came_back),并返回 elapsed_ms;每个阶段最多等 wait_ms(默认 60000),等不到不算失败。注销后客户端一般不会自动回线。";
tool["inputSchema"] = BuildPowerActionInputSchema();
tool["outputSchema"] = BuildPowerActionOutputSchema();
tools.append(tool);
}
}
// 18b) 主机库元数据(B1:host_set_remark / host_set_watch_level)。
// 只写服务端本地的备注/关注等级,不触达客户端,因此只受 McpReadonly 约束。
{
Json::Value tool(Json::objectValue);
tool["name"] = "host_set_remark";
tool["description"] = u8"给主机设置备注(在线或离线历史记录都可)。只写入服务端本地主机库,不向客户端下发任何命令;remark 传空字符串表示清除备注,GBK 编码后最长 63 字节。";
tool["inputSchema"] = BuildHostSetRemarkInputSchema();
tool["outputSchema"] = BuildHostSetRemarkOutputSchema();
tools.append(tool);
}
{
Json::Value tool(Json::objectValue);
tool["name"] = "host_set_watch_level";
tool["description"] = u8"设置主机在服务端在线列表里的关注等级:0=无、1=蓝字、2=红字、3=红底。只影响主控端本机显示,重复设置同一等级幂等。";
tool["inputSchema"] = BuildHostSetWatchLevelInputSchema();
tool["outputSchema"] = BuildHostSetWatchLevelOutputSchema();
tools.append(tool);
}
// 18c) 远程文件搜索(B2:search_file)。只读、仅 Windows 客户端,
// 故与其它只读工具一样始终登记,调用时按 McpReadonly / 客户端平台复核。
{
Json::Value tool(Json::objectValue);
tool["name"] = "search_file";
tool["description"] = u8"在指定主机(仅 Windows)的某个目录下按文件名搜索文件(不区分大小写;pattern 不含通配符时按子串匹配,含 * / ? 时按通配符匹配)。客户端始终递归子目录(深度 32、最多 10000 条,跳过隐藏+系统目录与符号链接),结果边搜边收集、按 limit/offset 分页;finished=false 表示到达 timeout_ms 时限、返回的是部分结果(服务端已通知客户端停止搜索)。单次最多收集 5000 条 / 4 MB,超出时 truncated=true。可选 min_size / max_size(字节)与 modified_after(YYYY-MM-DD 或 YYYY-MM-DD HH:MM:SS)在服务端做结果侧过滤,name_only=true 只返回 path 与 name;这些过滤不减少客户端搜索耗时,total 为命中数、totalAll 为过滤前条数。注意:客户端用 char[MAX_PATH] 缓冲拼路径,超过 260 字节的路径会被静默跳过(既不记录也不继续向下递归),所以从盘符根扫描会漏掉深层结果、也更容易先撞上 10000 条上限;请尽量指定具体的中浅层目录(服务端已把 path/pattern 限在 200 字节 GBK 内,给客户端留出余量)。";
tool["inputSchema"] = BuildSearchFileInputSchema();
tool["outputSchema"] = BuildSearchFileOutputSchema();
tools.append(tool);
}
// 18d) 文件系统写操作(P10-B:delete_path / move_path / create_folder)。
// 独立开关 McpFileWrite(默认关)且要求 McpReadonly=0:上传是「覆盖」,删除是
// 「毁灭」,风险等级不同,必须能分别关掉。关闭时不追加任何工具。
if (CMcpServer::Instance().IsFileWriteEnabled() && !CMcpServer::Instance().IsReadonly()) {
{
Json::Value tool(Json::objectValue);
tool["name"] = "delete_path";
tool["description"] = u8"删除指定主机(仅 Windows)上的文件或目录。recursive=false(默认)删除单个文件;recursive=true 递归删除整个目录及其全部内容——没有回收站,不可恢复。path 必须是绝对路径(C:\\... 或 \\\\server\\share\\...),不接受相对路径,也不接受含 %VAR% 环境变量的路径(客户端会展开,服务端无法校验真实目标)。服务端一律拒绝盘符/共享根,以及系统目录(Windows、Program Files、Program Files (x86)、ProgramData、$Recycle.Bin、System Volume Information)及其子树——需要清理这些位置请改用 exec_command 或逐项确认。客户端对删除命令无条件回完成包(根本不看 DeleteFile 的返回值),所以 ok 只代表命令已送达;真正的结果看 verified:true=复核确认目标已不在,false=复核确认目标还在(只读文件会静默失败,被占用/权限不足同理),null=复核没做成(列目录超时或断线),此时请自己用 list_files 再确认。注意目标本来就不存在时客户端同样回完成包、复核也只能看到「现在没有这个名字」,所以会表现为 verified=true——动手前最好先 list_files 确认目标确实存在。";
tool["inputSchema"] = BuildDeletePathInputSchema();
tool["outputSchema"] = BuildDeletePathOutputSchema();
tools.append(tool);
}
{
Json::Value tool(Json::objectValue);
tool["name"] = "move_path";
tool["description"] = u8"重命名或移动指定主机(仅 Windows)上的文件或目录:把 from 改成 to,to 必须是完整的新路径(含新名字)。客户端用 ::MoveFile,只能在同一卷内移动;跨盘请改用 download_file + upload_file。目录也支持(同一卷内整体移动)。from 不能是盘符/共享根或系统目录(Windows、Program Files、ProgramData 等),to 只拒绝根路径;from 与 to 都必须是不含 %VAR% 的绝对路径。ok 只代表命令已送达(客户端无条件回完成包),verified=true 表示复核确认 to 已出现在父目录里,false 表示没出现(目标已存在、跨卷、只读或被占用),null 表示复核没做成。";
tool["inputSchema"] = BuildMovePathInputSchema();
tool["outputSchema"] = BuildMovePathOutputSchema();
tools.append(tool);
}
{
Json::Value tool(Json::objectValue);
tool["name"] = "create_folder";
tool["description"] = u8"在指定主机(仅 Windows)上创建目录。客户端用 MakeSureDirectoryPathExists,会连同缺失的中间层一起建(C:\\a\\b\\c 会把 a、b 也建出来),目录已存在时同样算成功。path 若误带上了文件名,就会建出一个同名目录——本工具不会创建文件,也不会覆盖同名文件(那种情况 verified=false)。path 必须是绝对路径,不能含 %VAR%,不能是盘符/共享根。ok 只代表命令已送达,verified=true 表示复核确认该目录已存在且确实是目录,false 表示复核时没看到它(权限不足、被同名文件占用等),null 表示复核没做成。";
tool["inputSchema"] = BuildCreateFolderInputSchema();
tool["outputSchema"] = BuildCreateFolderOutputSchema();
tools.append(tool);
}
}
// 19) 连接管理 / 主机管理(P8:list_network_connections / kill_network_connection /
// host_* 共 16 个工具)。开关在 McpMachine.cpp 内部按 McpMachine /
// McpMachineDangerous / McpReadonly 逐项判断,关闭时不追加任何工具。
McpMachine::AppendTools(tools);
// 20) 远程交谈(P9:chat_open / chat_send / chat_wait / chat_close)。
// 独立开关 McpChat(默认关),与 McpReadonly 无关;关闭时不追加任何工具。
McpChat::AppendTools(tools);
// 21) 统一补 annotations(A3):只读/破坏性/幂等/开放世界四类提示。
// 放在最后一步,三个注册点(本文件内联、McpMachine、McpChat)一视同仁,
// 以后新增工具只需在 McpInternal.cpp 的 kToolHints 表里登记一行。
ApplyToolAnnotations(tools);
// 22) 批量只读工具补第二个 outputSchema 分支(N2):批量结果的形状是
// { tool, total, ..., results[] },与单机形状不同;只声明单机形状会让
// 任何 ids 调用在客户端校验 structuredContent 时以 -32602 失败。
// 同样放在最后一步,三个注册点一视同仁。
ApplyBatchOutputSchema(tools);
result["tools"] = tools;
return BuildResult(id, result);
}
// tools/call:list_online_hosts
std::string BuildListOnlineHosts(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
Json::Value all(Json::arrayValue);
CollectOnlineHosts(parent, all);
// 过滤在分页之前:total 是命中数,totalAll 是全部在线数(与 get_audit_log 同口径)。
HostListFilter filter = ReadHostListFilter(args);
Json::Value matched;
ApplyHostListFilter(all, filter, matched);
PageWindow page = ResolvePageWindow(args);
Json::Value hosts;
ApplyPageWindow(matched, page, hosts);
if (filter.Any()) page.totalAll = (int)all.size();
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
structuredContent["hosts"] = hosts;
WritePageFields(structuredContent, page);
result["structuredContent"] = structuredContent;
std::string text = PageSummary(page, filter.Any() ? u8"台主机匹配" : u8"台主机在线");
if (filter.Any())
text += std::string(u8"在线共 ") + std::to_string((int)all.size()) + std::string(u8" 台。");
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = text;
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
// tools/call:list_all_hosts(在线 + 离线,纯内存,不建子连接)
std::string BuildListAllHosts(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
bool includeOnline = !(args.isObject() && args.isMember("online") && args["online"].isBool()) || args["online"].asBool();
bool includeOffline = !(args.isObject() && args.isMember("offline") && args["offline"].isBool()) || args["offline"].asBool();
Json::Value hosts(Json::arrayValue);
CollectAllHosts(parent, hosts, includeOnline, includeOffline);
// 过滤先于统计与分页:total/totalAll 与摘要里的在线/离线数都按命中条目算。
HostListFilter filter = ReadHostListFilter(args);
Json::Value matched;
ApplyHostListFilter(hosts, filter, matched);
int onlineCount = 0;
for (unsigned int i = 0; i < matched.size(); ++i) {
if (matched[i]["online"].asBool()) onlineCount++;
}
PageWindow page = ResolvePageWindow(args);
Json::Value pageItems;
ApplyPageWindow(matched, page, pageItems);
if (filter.Any()) page.totalAll = (int)hosts.size();
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
structuredContent["hosts"] = pageItems;
WritePageFields(structuredContent, page);
result["structuredContent"] = structuredContent;
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
std::string text = PageSummary(page, filter.Any() ? u8"台主机匹配" : u8"台主机");
text += std::string(u8"其中在线 ") + std::to_string(onlineCount) +
std::string(u8",离线 ") + std::to_string(page.total - onlineCount) + std::string(u8"。");
if (filter.Any())
text += std::string(u8"主机库共 ") + std::to_string((int)hosts.size()) + std::string(u8" 台。");
item["text"] = text;
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
// tools/call:search_hosts
std::string BuildSearchHosts(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
Json::Value all(Json::arrayValue);
std::string fName = GetStringArg(args, "name");
std::string fIp = GetStringArg(args, "ip");
std::string fGroup = GetStringArg(args, "group");
std::string fOs = GetStringArg(args, "os");
// online=true → 仅在线;online=false → 仅离线(历史主机);省略 → 仅在线(保持本工具原有行为,
// 想要两类都要请用 list_all_hosts)。
bool hasOnline = args.isObject() && args.isMember("online") && args["online"].isBool();
bool wantOnline = hasOnline ? args["online"].asBool() : true;
CollectAllHosts(parent, all, wantOnline, hasOnline && !wantOnline);
Json::Value hosts(Json::arrayValue);
for (unsigned int i = 0; i < all.size(); ++i) {
const Json::Value& h = all[i];
if (!fName.empty()) {
std::string name = JsonStrField(h, "name");
std::string remark = JsonStrField(h, "remark");
if (!ContainsCI(name, fName) && !ContainsCI(remark, fName)) continue;
}
if (!fIp.empty() && !ContainsCI(JsonStrField(h, "ip"), fIp)) continue;
if (!fGroup.empty() && !ContainsCI(JsonStrField(h, "group"), fGroup)) continue;
if (!fOs.empty() && !ContainsCI(JsonStrField(h, "os"), fOs)) continue;
hosts.append(h);
}
PageWindow page = ResolvePageWindow(args);
Json::Value pageItems;
ApplyPageWindow(hosts, page, pageItems);
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
structuredContent["hosts"] = pageItems;
WritePageFields(structuredContent, page);
result["structuredContent"] = structuredContent;
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = PageSummary(page, u8"台主机匹配");
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
// tools/call:get_host_detail
//
// 登录时上报的 RES_* 技术字段(CPU 核数/内存/系统位数/账号/安装时间/分辨率…)只在
// get_host_detail 里补充,不改 BuildHostJson —— 那是 Web UI 与 list_online_hosts 共用的
// 序列化函数,动它会改变已有调用方的输出形状。
std::string ResFieldUtf8(context* ctx, UINT cp, int idx) {
CString v = ctx->GetAdditionalData(idx);
if (v.IsEmpty()) return "";
return ToUtf8(v.GetString(), cp);
}
int DigitsOrZero(const std::string& s) {
return IsDigits(s) ? atoi(s.c_str()) : 0;
}
void AppendHostTechnicalDetail(CMy2015RemoteDlg* parent, uint64_t devId, Json::Value& host) {
context* ctx = FindMainContext(parent, devId);
if (!ctx) return;
const UINT cp = GetClientEncoding(ctx);
int cpu = DigitsOrZero(ResFieldUtf8(ctx, cp, RES_SYSTEM_CPU));
if (cpu > 0) host["cpuCores"] = cpu;
// 内存是 double 上报(client/LoginServer.cpp 的 GetMemorySizeGB → to_string),
// 例如 "15.903053";不能按整数解析,否则整段被丢掉。保留 1 位小数。
std::string memStr = ResFieldUtf8(ctx, cp, RES_SYSTEM_MEM);
if (!memStr.empty() && memStr[0] >= '0' && memStr[0] <= '9') {
double mem = atof(memStr.c_str());
if (mem > 0) host["memoryGB"] = (double)((long long)(mem * 10.0 + 0.5)) / 10.0;
}
std::string bits = ResFieldUtf8(ctx, cp, RES_SYSTEM_BITS);
if (!bits.empty()) host["systemBits"] = bits; // "64" / "32"
std::string progBits = ResFieldUtf8(ctx, cp, RES_PROGRAM_BITS);
if (!progBits.empty()) host["programBits"] = progBits;
std::string user = ResFieldUtf8(ctx, cp, RES_USERNAME);
if (!user.empty()) host["user"] = user;
std::string admin = ResFieldUtf8(ctx, cp, RES_ISADMIN);
if (!admin.empty()) host["isAdmin"] = (admin == "1");
std::string install = ResFieldUtf8(ctx, cp, RES_INSTALL_TIME);
if (!install.empty()) host["installTime"] = install;
std::string expired = ResFieldUtf8(ctx, cp, RES_EXPIRED_DATE);
if (!expired.empty()) host["expiredDate"] = expired;
// 心跳格式 "N:W*H":N=显示器数。多显示器时 remote_open/remote_* 会拒(-32005),
// 把 N 直接给出,AI 不必自己拆 screen 字符串。老客户端没有冒号 → 0 表示未知。
int monitorCount = 0;
std::string res = ResFieldUtf8(ctx, cp, RES_RESOLUTION);
size_t colon = res.find(':');
if (colon != std::string::npos) {
monitorCount = DigitsOrZero(res.substr(0, colon));
if (monitorCount > 0) host["monitors"] = monitorCount;
}
std::string exeVer = ResFieldUtf8(ctx, cp, RES_EXE_VERSION);
if (!exeVer.empty()) host["exeVersion"] = exeVer;
std::string exePath = ResFieldUtf8(ctx, cp, RES_FILE_PATH);
if (!exePath.empty()) host["clientPath"] = exePath;
std::string pid = ResFieldUtf8(ctx, cp, RES_PID);
if (!pid.empty()) host["pid"] = pid;
std::string pubIp = ResFieldUtf8(ctx, cp, RES_CLIENT_PUBIP);
if (!pubIp.empty()) host["publicIp"] = pubIp;
// 主机自身的能力位:回答「这台主机能不能做」,服务端开关(McpReadonly / McpMachine /
// McpFileTransfer …)不在这里重复——get_server_status 的 switches 已经完整暴露。
// 每一项都对应一处真实门控,改这里时要一起看向下派发:screenPreview→get_screenshot
// (SupportsScreenPreview)、remoteControl→remote_*(ResolveScreenCtrlSessionHost 的
// 平台门 + remote_open 的单显示器门)、fileTransferV2→download_file/upload_file、
// c2cPaths→copy_files_c2c 源端、registry→list_registry。
CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
Json::Value caps(Json::objectValue);
caps["platform"] = ToUtf8(clientType.GetString(), cp); // EXE/DLL/MEXE/SC/MDLL/LNX/MAC/APK
caps["screenPreview"] = ctx->SupportsScreenPreview();
// 远程控制只实现于 Windows / Linux,且阶段一要求单显示器;monitorCount=0(老客户端
// 没报格式)无法判定,与 remote_open 一样按放行处理。
caps["remoteControl"] = (IsWindowsClient(ctx) || clientType == "LNX") && monitorCount <= 1;
caps["fileTransferV2"] = ctx->SupportsFileV2();
caps["c2cPaths"] = ctx->SupportsC2CPaths();
caps["registry"] = IsWindowsClient(ctx);
host["capabilities"] = caps;
}
std::string BuildGetHostDetail(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
std::string sid = GetStringArg(args, "id");
if (sid.empty()) {
return BuildError(id, -32602, "Missing required parameter: id");
}
if (!IsDigits(sid)) {
return BuildError(id, -32602, "Invalid id: expected a decimal host id string");
}
Json::Value all(Json::arrayValue);
CollectOnlineHosts(parent, all);
for (unsigned int i = 0; i < all.size(); ++i) {
const Json::Value& h = all[i];
if (JsonStrField(h, "id") == sid) {
// 复制后再补充技术字段:all[] 里的是本次调用内的临时对象,补字段不影响
// BuildHostJson 本身(list_online_hosts 用同一份序列化,输出形状不变)。
Json::Value host = h;
AppendHostTechnicalDetail(parent, strtoull(sid.c_str(), nullptr, 10), host);
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
structuredContent["host"] = host;
result["structuredContent"] = structuredContent;
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
std::string name = JsonStrField(host, "name");
std::string ip = JsonStrField(host, "ip");
item["text"] = std::string(u8"主机 ") + name + " (" + ip + ")" + u8" 的详情。";
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
}
// 在线列表里没有 → 回落到主机列表历史记录(离线主机),而不是直接报错
uint64_t key = 0;
std::string perr;
if (ParseHostIdArg(args, key, perr)) {
Json::Value offline;
bool found = false;
if (parent && parent->m_ClientMap) {
EnterCriticalSection(&parent->m_cs);
if (parent->m_ClientMap->Exists(key)) {
for (const auto& kv : parent->m_ClientMap->GetAll()) {
if (kv.first != key) continue;
offline = BuildOfflineHostJson(parent->m_ClientMap, kv.first, kv.second);
found = true;
break;
}
}
LeaveCriticalSection(&parent->m_cs);
}
if (found) {
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
structuredContent["host"] = offline;
result["structuredContent"] = structuredContent;
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = std::string(u8"主机 ") + JsonStrField(offline, "name") + " (" +
JsonStrField(offline, "ip") + ")" +
std::string(u8" 当前离线,以下为其最后一次登录时的记录。");
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
}
return BuildError(id, -32002, "Host not found or offline: " + sid);
}
// list_processes / list_windows 的服务端过滤:name 是子串匹配(ASCII 不区分大小写,
// 口径同 list_online_hosts 的过滤),pid 是精确匹配;nameField 指定被匹配的字段
// (进程看映像名 "name",窗口看标题 "title")。两个条件都没给就原样返回。
Json::Value FilterByPidAndName(const Json::Value& items, const Json::Value& args,
const char* nameField) {
const std::string name = GetStringArg(args, "name");
int pid = 0;
const bool hasPid = GetIntArg(args, "pid", pid);
if (name.empty() && !hasPid) return items;
Json::Value out(Json::arrayValue);
for (unsigned int i = 0; i < items.size(); ++i) {
const Json::Value& it = items[i];
if (hasPid && (int)it["pid"].asUInt() != pid) continue;
if (!name.empty() && !ContainsCI(JsonStrField(it, nameField), name)) continue;
out.append(it);
}
return out;
}
// tools/call:list_processes(主连接 RPC,子连接一次性回传)
std::string BuildListProcesses(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
uint64_t devId = 0;
std::string err;
if (!ParseHostIdArg(args, devId, err))
return BuildError(id, -32602, err);
context* ctx = FindMainContext(parent, devId);
if (!ctx)
return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId));
CMcpServer& mcp = CMcpServer::Instance();
if (!mcp.BeginPending(devId, "list_processes"))
return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId));
BYTE cmd = COMMAND_SYSTEM;
if (!ctx->Send2Client(&cmd, 1)) {
mcp.ClearPending(devId);
return BuildError(id, -32004, "Failed to send command to host");
}
std::vector<BYTE> data;
if (!mcp.WaitPending(devId, data, mcp.ToolTimeoutMs()))
return BuildError(id, -32001, "Timeout waiting for process list");
// 进程名/路径编码按 clientType 判定:Windows 走 A 接口(QueryFullProcessImageNameA 等)
// =客户端 ANSI(GBK/936),不随 CLIENT_CAP_UTF8 转 UTF-8;LNX/MAC 的 /proc 天然 UTF-8。
// 不能用 GetClientEncoding——它按能力位返回 CP_UTF8,会误解 Windows 客户端的 GBK 进程名。
CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
UINT cp = (clientType == "LNX" || clientType == "MAC") ? CP_UTF8 : 936;
Json::Value procs = ParseProcessList(data, cp);
// 过滤先于分页:total 是命中数,totalAll 是过滤前的总数(口径同 search_hosts)。
Json::Value matched = FilterByPidAndName(procs, args, "name");
PageWindow page = ResolvePageWindow(args);
Json::Value pageItems;
ApplyPageWindow(matched, page, pageItems);
if (matched.size() != procs.size()) page.totalAll = (int)procs.size();
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
structuredContent["processes"] = pageItems;
WritePageFields(structuredContent, page);
result["structuredContent"] = structuredContent;
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = PageSummary(page, u8"个进程");
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
// tools/call:list_windows(主连接 RPC,子连接一次性回传)
std::string BuildListWindows(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
uint64_t devId = 0;
std::string err;
if (!ParseHostIdArg(args, devId, err))
return BuildError(id, -32602, err);
context* ctx = FindMainContext(parent, devId);
if (!ctx)
return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId));
CMcpServer& mcp = CMcpServer::Instance();
if (!mcp.BeginPending(devId, "list_windows"))
return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId));
BYTE cmd = COMMAND_WSLIST;
if (!ctx->Send2Client(&cmd, 1)) {
mcp.ClearPending(devId);
return BuildError(id, -32004, "Failed to send command to host");
}
std::vector<BYTE> data;
if (!mcp.WaitPending(devId, data, mcp.ToolTimeoutMs()))
return BuildError(id, -32001, "Timeout waiting for window list");
// 窗口标题编码由客户端能力位决定(新客户端 UTF-8,老客户端 CP_ACP)。
UINT cp = GetClientEncoding(ctx);
Json::Value wins = ParseWindowList(data, cp);
// 过滤先于分页:total 是命中数,totalAll 是过滤前的总数(口径同 search_hosts)。
Json::Value matched = FilterByPidAndName(wins, args, "title");
PageWindow page = ResolvePageWindow(args);
Json::Value pageItems;
ApplyPageWindow(matched, page, pageItems);
if (matched.size() != wins.size()) page.totalAll = (int)wins.size();
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
structuredContent["windows"] = pageItems;
WritePageFields(structuredContent, page);
result["structuredContent"] = structuredContent;
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = PageSummary(page, u8"个窗口");
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
// tools/call:get_activity_history(主连接 RPC,无子链接、不弹框、不 CancelIO)
std::string BuildGetActivityHistory(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
uint64_t devId = 0;
std::string err;
if (!ParseHostIdArg(args, devId, err))
return BuildError(id, -32602, err);
context* ctx = FindMainContext(parent, devId);
if (!ctx)
return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId));
CMcpServer& mcp = CMcpServer::Instance();
if (!mcp.BeginPending(devId, "get_activity_history"))
return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId));
BYTE cmd = COMMAND_QUERY_ACTIVITY;
if (!ctx->Send2Client(&cmd, 1)) {
mcp.ClearPending(devId);
return BuildError(id, -32004, "Failed to send command to host");
}
std::vector<BYTE> data;
if (!mcp.WaitPending(devId, data, mcp.ToolTimeoutMs()))
return BuildError(id, -32001, "Timeout waiting for activity history");
// data[0]=token,其后为客户端 ActivityHistory::Dump() 的 UTF-8 纯文本
// (标题在客户端已由 GetActiveWindowTitle 转 UTF-8,服务端无需再转码)。
std::string text;
if (data.size() > 1)
text.assign((const char*)data.data() + 1, data.size() - 1);
// 拆行:每行一条记录,过滤空行(含 Dump 末尾的换行)。
// 顺序是「新在前」:客户端 m_records 用 push_front 维护,Dump() 又把进行中的
// 当前窗口放在最前面。所以 offset=0 天然就是“最近 limit 条”,不需要先取
// total 再倒着算 offset——这正是日志类数据最常用的取法。
Json::Value all(Json::arrayValue);
size_t start = 0;
while (start <= text.size()) {
size_t nl = text.find('\n', start);
std::string line = text.substr(start, (nl == std::string::npos ? text.size() : nl) - start);
if (!line.empty()) all.append(line);
if (nl == std::string::npos) break;
start = nl + 1;
}
// 分页:实测一次 501 条会把上下文撑爆(P2-1)。本工具无服务端过滤,
// total == totalAll,ApplyPageWindow 的默认口径即可。
PageWindow page = ResolvePageWindow(args);
Json::Value records(Json::arrayValue);
ApplyPageWindow(all, page, records);
// 字节预算:limit 上限 1000,窗口内若标题很长仍可能过大。从窗口末尾裁
// (保留最新的那些),裁掉的部分由 truncated 与 hasMore 一起表达。
const size_t kMaxBytes = 64 * 1024;
bool byteTrimmed = false;
{
size_t bytes = 0;
int kept = 0;
for (const Json::Value& r : records) {
const std::string s = r.asString();
if (bytes + s.size() + 1 > kMaxBytes) { byteTrimmed = true; break; }
bytes += s.size() + 1;
++kept;
}
if (byteTrimmed) {
// 至少留一条,保证调用方按 offset+returned 前进时不会原地打转
// (单条超过 64 KB 在窗口标题上几乎不可能,这里只是兜底)。
if (kept == 0) {
kept = 1;
Json::Value one(Json::arrayValue);
one.append(records[0]);
records = one;
} else {
Json::Value trimmed(Json::arrayValue);
for (int i = 0; i < kept; ++i) trimmed.append(records[i]);
records = trimmed;
}
page.returned = kept;
// 还有没有更早的记录,按「已返回到的绝对位置」算,而不是一律置 true:
// 末尾那条自己超预算时,offset+kept 已经等于 total,不该再报 hasMore。
page.hasMore = (page.offset + kept < page.total);
}
}
// activityHistory 是同一份数据的纯文本形态:必须按窗口重建,
// 否则整包原文会绕过分页,等于没分页。
std::string shown;
for (const Json::Value& r : records) {
shown += r.asString();
shown += '\n';
}
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
structuredContent["records"] = records;
structuredContent["activityHistory"] = shown;
structuredContent["truncated"] = byteTrimmed;
WritePageFields(structuredContent, page);
result["structuredContent"] = structuredContent;
// 正文外的 JSON 块只放 records:activityHistory 是同一份数据的原文,
// 整包外露等于同样内容出现三遍。
Json::Value textPayload(Json::objectValue);
textPayload["records"] = records;
SetStructuredTextPayload(result, textPayload);
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = std::string(u8"共 ") + std::to_string(page.total) + std::string(u8" 条历史活动记录(新在前),本次返回第 ") +
std::to_string(page.offset) + std::string(u8" 条起的 ") + std::to_string(page.returned) + std::string(u8" 条") +
(page.hasMore ? std::string(u8";hasMore=true 表示还有更早的记录,可用 offset=") +
std::to_string(page.offset + page.returned) + std::string(u8" 继续取。")
: std::string(u8"。"));
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
// tools/call:get_screenshot(屏幕预览链路,主连接 RPC,不建子链接、不弹框)
std::string BuildGetScreenshot(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
uint64_t devId = 0;
std::string err;
if (!ParseHostIdArg(args, devId, err))
return BuildError(id, -32602, err);
context* ctx = FindMainContext(parent, devId);
if (!ctx)
return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId));
// 能力位门槛:只有能抓屏的客户端才声明 CLIENT_CAP_SCREEN_PREVIEW
// (Windows 恒声明;Linux 仅在登录时探测到可用 X11 桌面才声明),否则返回明确错误
if (!ctx->SupportsScreenPreview())
return BuildError(id, -32005, "Host does not support screen preview");
CMcpServer& mcp = CMcpServer::Instance();
if (!mcp.BeginPending(devId, "get_screenshot"))
return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId));
uint16_t reqId = mcp.NextPreviewReqId();
mcp.SetPendingReqId(devId, reqId);
// 复用 MFC 预览的 RTT/FRP 自适应参数挑选,避免重复实现 GetTargetQualityLevel 逻辑
WORD maxWidth = 0;
BYTE quality = 0;
parent->ChooseScreenPreviewParams(ctx, maxWidth, quality);
// 可选 max_width:缺省/0 沿用缩略图档位;>0 覆盖宽度(钳制到客户端上限 [64,1920]),
// 供 AI 视觉/OCR 场景请求接近原分辨率的大图。jpegQuality 仍沿用档位自适应值。
if (args.isMember("max_width") && args["max_width"].isInt()) {
int mw = args["max_width"].asInt();
if (mw > 0) {
if (mw < 64) mw = 64;
if (mw > 1920) mw = 1920;
maxWidth = (WORD)mw;
}
}
parent->SendScreenPreviewRequest(ctx, reqId, maxWidth, quality);
std::vector<BYTE> data;
if (!mcp.WaitPending(devId, data, mcp.ToolTimeoutMs()))
return BuildError(id, -32001, "Timeout waiting for screenshot");
// data = [ScreenPreviewRspHeader][JPEG]
if (data.size() < sizeof(ScreenPreviewRspHeader))
return BuildError(id, -32000, "Invalid screenshot response");
const ScreenPreviewRspHeader* hdr = reinterpret_cast<const ScreenPreviewRspHeader*>(data.data());
if (hdr->status != SCREEN_PREVIEW_OK || hdr->format != SCREEN_PREVIEW_FMT_JPEG ||
hdr->bytes == 0 || data.size() < sizeof(ScreenPreviewRspHeader) + hdr->bytes) {
return BuildError(id, -32000,
"Screenshot capture failed (status " + std::to_string((int)hdr->status) + ")");
}
std::string b64 = httplib::detail::base64_encode(
std::string((const char*)data.data() + sizeof(ScreenPreviewRspHeader), hdr->bytes));
Json::Value image(Json::objectValue);
image["mimeType"] = "image/jpeg";
image["width"] = (Json::UInt64)hdr->width;
image["height"] = (Json::UInt64)hdr->height;
image["bytes"] = (Json::UInt64)hdr->bytes;
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
structuredContent["image"] = image; // 元数据(不含 base64,避免在 content 之外重复大 payload)
result["structuredContent"] = structuredContent;
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "image";
item["data"] = b64;
item["mimeType"] = "image/jpeg";
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
// 新客户端的结构化失败回报布局:[token:1][win32/status:4 LE]。读取其中 4 字节错误码。
static DWORD ReadWin32Payload(const std::vector<BYTE>& data) {
DWORD v = 0;
if (data.size() >= 1 + sizeof(DWORD)) memcpy(&v, data.data() + 1, sizeof(DWORD));
return v;
}
// 客户端结构化失败 → MCP 错误码:
// 5 ERROR_ACCESS_DENIED → -32010(目标存在但权限不足;重试无意义)
// 2/3 ERROR_FILE/PATH_NOT_FOUND → -32009(目标不存在)
// 其余 → -32000(文案带出 win32 码)
static std::string BuildRemoteWin32Error(const Json::Value& id, DWORD win32err,
const std::string& subject, const std::string& hint = "") {
std::string detail = " (win32=" + std::to_string((int)win32err) + ")";
if (!hint.empty()) detail += ". " + hint;
if (win32err == ERROR_ACCESS_DENIED)
return BuildError(id, -32010, subject + ": access denied" + detail);
if (win32err == ERROR_FILE_NOT_FOUND || win32err == ERROR_PATH_NOT_FOUND)
return BuildError(id, -32009, subject + ": target not found" + detail);
return BuildError(id, -32000, subject + ": client reported failure" + detail);
}
// tools/call:list_files(列盘走 COMMAND_LIST_DRIVE→TOKEN_DRIVE_LIST;
// 列目录走 COMMAND_LIST_DRIVE 开子链接后,再下发 COMMAND_LIST_FILES→TOKEN_FILE_LIST)
std::string BuildListFiles(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
uint64_t devId = 0;
std::string err;
if (!ParseHostIdArg(args, devId, err))
return BuildError(id, -32602, err);
context* ctx = FindMainContext(parent, devId);
if (!ctx)
return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId));
std::string path = GetStringArg(args, "path");
bool listDrives = path.empty() || path == "." || path == "/" || path == "\\";
// 目录路径/文件名编码按 clientType 判定:Windows 走 A 接口(FindFirstFileA 等)= 客户端
// ANSI(GBK/936),不随 CLIENT_CAP_UTF8 转 UTF-8;LNX/MAC 文件系统天然 UTF-8。不能用
// GetClientEncoding——它按能力位返回 CP_UTF8,会误解 Windows 客户端的 GBK 文件名。
CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
UINT cp = (clientType == "LNX" || clientType == "MAC") ? CP_UTF8 : 936;
// 下发前把 UTF-8 path 转成客户端 ANSI(空/./\/\\ 为 ASCII,转换后不变),OnDriveList 直接用。
std::string ansiPath = ToAnsi(path, cp);
CMcpServer& mcp = CMcpServer::Instance();
if (!mcp.BeginPending(devId, "list_files", ansiPath))
return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId));
BYTE cmd = COMMAND_LIST_DRIVE;
if (!ctx->Send2Client(&cmd, 1)) {
mcp.ClearPending(devId);
return BuildError(id, -32004, "Failed to send command to host");
}
std::vector<BYTE> data;
if (!mcp.WaitPending(devId, data, mcp.ToolTimeoutMs()))
return BuildError(id, -32001, "Timeout waiting for file list");
// 新客户端在失败分支回 TOKEN_FILE_LIST_ERROR(路径不存在/非法/不可访问)→ 立即转译;
// 老客户端没有这个包,仍按「空目录」处理(行为不变)。
if (!data.empty() && data[0] == TOKEN_FILE_LIST_ERROR)
return BuildRemoteWin32Error(id, ReadWin32Payload(data), "Failed to list \"" + path + "\"");
Json::Value drives(Json::arrayValue);
Json::Value files(Json::arrayValue);
if (listDrives) {
drives = ParseDriveList(data, cp);
} else {
// 服务端按 500 条截断(避免子连接/JSON 过大),再按 limit/offset 取窗口。
files = ParseFileList(data, 500, cp);
}
PageWindow page = ResolvePageWindow(args);
Json::Value pageItems;
ApplyPageWindow(listDrives ? drives : files, page, pageItems);
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
if (listDrives) structuredContent["drives"] = pageItems;
else structuredContent["files"] = pageItems;
WritePageFields(structuredContent, page);
result["structuredContent"] = structuredContent;
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = listDrives ? PageSummary(page, u8"个驱动器") : PageSummary(page, u8"个条目");
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
// tools/call:list_services(主连接下发 COMMAND_SERVICES,子连接一次性回传 TOKEN_SERVERLIST)
std::string BuildListServices(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
uint64_t devId = 0;
std::string err;
if (!ParseHostIdArg(args, devId, err))
return BuildError(id, -32602, err);
context* ctx = FindMainContext(parent, devId);
if (!ctx)
return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId));
// 服务管理仅 Windows 客户端实现(EnumServicesStatus 等 A 接口);LNX/MAC 无 Windows
// 服务概念,提前返回避免 20s 超时等待。
CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
if (clientType == "LNX" || clientType == "MAC")
return BuildError(id, -32005, "list_services is only supported on Windows hosts");
CMcpServer& mcp = CMcpServer::Instance();
if (!mcp.BeginPending(devId, "list_services"))
return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId));
BYTE cmd = COMMAND_SERVICES;
if (!ctx->Send2Client(&cmd, 1)) {
mcp.ClearPending(devId);
return BuildError(id, -32004, "Failed to send command to host");
}
std::vector<BYTE> data;
if (!mcp.WaitPending(devId, data, mcp.ToolTimeoutMs()))
return BuildError(id, -32001, "Timeout waiting for service list");
// TOKEN_SERVICE_ERROR:客户端 OpenSCManager 失败(典型=未提权,win32=5)。
if (!data.empty() && data[0] == TOKEN_SERVICE_ERROR)
return BuildRemoteWin32Error(id, ReadWin32Payload(data), "Failed to enumerate services",
"service enumeration requires the client to run elevated (administrator)");
// 服务名/路径/显示名来自 Windows A 接口 = 客户端 ANSI(GBK/936),按 clientType 判定。
UINT cp = (clientType == "LNX" || clientType == "MAC") ? CP_UTF8 : 936;
Json::Value services = ParseServiceList(data, cp);
PageWindow page = ResolvePageWindow(args);
Json::Value pageItems;
ApplyPageWindow(services, page, pageItems);
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
structuredContent["services"] = pageItems;
WritePageFields(structuredContent, page);
result["structuredContent"] = structuredContent;
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = PageSummary(page, u8"个服务");
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
// tools/call:list_registry(主连接下发 COMMAND_REGEDIT → 子连接 TOKEN_REGEDIT → 下发
// COMMAND_REG_FIND → TOKEN_REG_PATH + TOKEN_REG_KEY 两包;path 空 = 列根键,无需查询客户端)
std::string BuildListRegistry(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
uint64_t devId = 0;
std::string err;
if (!ParseHostIdArg(args, devId, err))
return BuildError(id, -32602, err);
context* ctx = FindMainContext(parent, devId);
if (!ctx)
return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId));
// 注册表仅 Windows 客户端实现(RegOpenKeyEx 等 A 接口);LNX/MAC/APK 没有注册表。
// APK 原来漏在门外:命令能下发,但客户端不会回 TOKEN_REGEDIT,只能白等到超时。
if (!IsWindowsClient(ctx))
return BuildError(id, -32005, "list_registry is only supported on Windows hosts");
// 注册表键路径与返回的键/值都是客户端 ANSI(RegisterManager 用 A 接口)= GBK/936。
const UINT cp = 936;
std::string path = GetStringArg(args, "path");
BYTE rootToken = 0;
std::string relPath;
if (!ParseRegistryPath(path, rootToken, relPath)) {
if (path.empty())
return BuildRegistryRoots(id); // 空 path → 列根键
return BuildError(id, -32602,
"Invalid path: expected a root key like HKEY_LOCAL_MACHINE\\Software");
}
// 客户端 RegisterOperation 以 char KeyPath[MAX_PATH] 承载相对子键路径(SetPath→strcpy 无界),
// 超长会栈溢出。按 UTF-8 字节数做保守上限(GBK/936 字节数 ≤ UTF-8,故只查 UTF-8 即可)。
if (relPath.size() >= MAX_PATH)
return BuildError(id, -32602, "Registry path too long (exceeds MAX_PATH)");
// rootToken 编码进 path[0] 供 OnRegeditReady 拆分。
std::string rootAndPath = std::string(1, (char)rootToken) + ToAnsi(relPath, cp);
CMcpServer& mcp = CMcpServer::Instance();
if (!mcp.BeginPending(devId, "list_registry", rootAndPath))
return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId));
BYTE cmd = COMMAND_REGEDIT;
if (!ctx->Send2Client(&cmd, 1)) {
mcp.ClearPending(devId);
return BuildError(id, -32004, "Failed to send command to host");
}
std::vector<BYTE> subkeys, values;
if (!mcp.WaitPendingRegistry(devId, subkeys, values, mcp.ToolTimeoutMs()))
return BuildError(id, -32001, "Timeout waiting for registry data");
// TOKEN_REG_ERROR:RegOpenKeyEx 失败(键/路径不存在或拒绝访问),此时只有这一包,
// 不做 ParseRegPath/ParseRegKey(它们会把错误包误当记录数据)。
if (!subkeys.empty() && subkeys[0] == TOKEN_REG_ERROR)
return BuildRemoteWin32Error(id, ReadWin32Payload(subkeys), "Failed to open \"" + path + "\"");
Json::Value keysArr = ParseRegPath(subkeys, cp);
Json::Value valsArr = ParseRegKey(values, cp);
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
structuredContent["path"] = path;
structuredContent["keys"] = keysArr;
structuredContent["values"] = valsArr;
result["structuredContent"] = structuredContent;
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = std::string(u8"共 ") + std::to_string((int)keysArr.size()) + std::string(u8" 个子键、")
+ std::to_string((int)valsArr.size()) + std::string(u8" 个值。");
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
// ========== P3:exec_command ==========
// exec_command 默认白名单:只读命令前缀(逗号分隔,前缀匹配,大小写不敏感)。
// 只放查询/只读类命令;写命令(del/copy/move/reg add/sc stop/...)一律不在列。
static const char* kDefaultCmdWhitelist =
"dir,type,cd,chdir,ver,hostname,whoami,where,tasklist,systeminfo,ipconfig,netstat,"
"path,set,find,findstr,reg query,sc query,"
"ping,tracert,nslookup,getmac,driverquery,query,gpresult,"
"arp -a,route print,schtasks /query";
// Linux 默认白名单:同一条命令名的 POSIX 语义与 Windows 不同(find/sort/date/hostname
// 都能写文件或改系统状态),故单独维护,只放参数也基本只读的命令。注意 env 不在列:
// `env rm -rf /` 会执行任意程序,等于白名单失效。管理员配置了 McpCmdWhitelist 时以
// 配置为准(两种平台共用同一份显式配置)。
static const char* kDefaultCmdWhitelistPosix =
"ls,cat,head,tail,grep,egrep,fgrep,wc,file,stat,pwd,id,whoami,uname,uptime,"
"df,du,free,ps,ss,netstat,lsblk,lsusb,lspci,"
"ip addr show,ip route show,ip link show,ip -s,"
"systemctl status,systemctl list-units,journalctl,dmesg,"
"last,lastb,w,who,printenv,getent,which,whereis";
// POSIX shell 元字符:& | < > 与 ; 都能在同一条命令行里追加命令,反引号与 $( / ${ 能
// 执行子命令,! 在交互式 bash 里会触发历史展开。全部拒绝,防止绕过白名单前缀。
static bool ContainsForbiddenPosixShellChars(const std::string& s) {
for (size_t i = 0; i < s.size(); ++i) {
char c = s[i];
if (c == '&' || c == '|' || c == '<' || c == '>' || c == ';' || c == '`' || c == '!')
return true;
if (c == '$' && i + 1 < s.size() && (s[i + 1] == '(' || s[i + 1] == '{'))
return true;
}
return false;
}
// 去首尾空白(空格/制表符/回车/换行)。
static std::string Trim(const std::string& s) {
size_t b = s.find_first_not_of(" \t\r\n");
if (b == std::string::npos) return "";
return s.substr(b, s.find_last_not_of(" \t\r\n") - b + 1);
}
// 去尾部空白(含尾部 CR/LF)。
static std::string TrimRight(const std::string& s) {
size_t e = s.find_last_not_of(" \t\r\n");
return (e == std::string::npos) ? "" : s.substr(0, e + 1);
}
// 命令白名单校验:命令(trim + ASCII 小写)以某白名单项为前缀,且其后字符为空/空格/制表符,
// 防止 "dirx" 前缀误配 "dir"。多词前缀(sc query / reg query)也按完整前缀匹配。
static bool IsCommandAllowed(const std::string& command, const std::string& whitelist) {
std::string c = ToLowerAscii(Trim(command));
if (c.empty()) return false;
size_t start = 0;
while (start < whitelist.size()) {
size_t comma = whitelist.find(',', start);
std::string item = Trim(whitelist.substr(
start, comma == std::string::npos ? std::string::npos : comma - start));
if (!item.empty()) {
std::string p = ToLowerAscii(item);
if (c.size() >= p.size() && c.compare(0, p.size(), p) == 0 &&
(c.size() == p.size() || c[p.size()] == ' ' || c[p.size()] == '\t')) {
return true;
}
}
if (comma == std::string::npos) break;
start = comma + 1;
}
return false;
}
// 剥 ANSI 转义序列(CSI/OSC/单字节 ESC),避免终端彩色码污染返回文本。
static std::string StripAnsi(const std::string& s) {
std::string out;
out.reserve(s.size());
for (size_t i = 0; i < s.size(); ++i) {
if (s[i] != '\x1b') { out += s[i]; continue; }
++i; // 吞 ESC
if (i < s.size() && s[i] == '[') { // CSI ... 结尾 @–~
while (++i < s.size() && !(s[i] >= '@' && s[i] <= '~')) {}
} else if (i < s.size() && s[i] == ']') { // OSC ... 结尾 BEL/ST(ESC \)
while (++i < s.size() && s[i] != '\x07' && s[i] != '\x1b') {}
// ST 是两字节 "ESC \":这里停在 ESC 上,须把 '\' 一起吞掉,否则会残留在输出里。
if (i + 1 < s.size() && s[i] == '\x1b' && s[i + 1] == '\\') ++i;
}
// 其它单字节 ESC 序列吞掉当前字节即可(循环 ++i 会跳过它)
}
return out;
}
// 去掉 ConPTY 把整行输入回显造成的噪声:line 是发送过的命令行(含唯一 nonce 或 "@echo off & "
// 前缀),输出里若出现这段文本(连同其后的换行)则剔除。回显会被 80 列折行插入换行,
// 所以比较时跳过 '\r'/'\n';随机 nonce/固定前缀保证命令真实输出不可能整行命中。
// 只删第一处命中(输入回显只发生一次)。
static void StripEchoedLine(std::string& s, const std::string& line) {
if (line.empty() || s.empty()) return;
const size_t n = s.size(), m = line.size();
for (size_t i = 0; i < n; ++i) {
size_t j = 0, k = i;
while (j < m && k < n) {
const char c = s[k];
if (c == '\r' || c == '\n') { ++k; continue; }
if (c != line[j]) break;
++j; ++k;
}
if (j != m) continue;
while (k < n && (s[k] == '\r' || s[k] == '\n')) ++k; // 连同回显行尾换行一起删
s.erase(i, k - i);
return;
}
}
// 把缓冲区开头一直删到回显行结束(含行尾换行)。ConPTY 起 shell 时会先回放启动画面与
// 提示符(一长串空行 + "Microsoft Windows [Version ...]" + "C:\path>"),紧接着才是我们这行
// 输入的回显;回显行即「真实输出的起点」,因此删到它结束可把启动噪声一并去掉。
// 返回 false 表示没找到回显(例如客户端不回显),此时不动缓冲区。
static bool CutThroughEchoedLine(std::string& s, const std::string& line) {
if (line.empty() || s.empty()) return false;
const size_t n = s.size(), m = line.size();
for (size_t i = 0; i < n; ++i) {
size_t j = 0, k = i;
while (j < m && k < n) {
const char c = s[k];
if (c == '\r' || c == '\n') { ++k; continue; }
if (c != line[j]) break;
++j; ++k;
}
if (j != m) continue;
while (k < n && (s[k] == '\r' || s[k] == '\n')) ++k;
s.erase(0, k);
return true;
}
return false;
}
// 去掉开头的空行(启动画面残留 / 上一行命令尾部的空行)。
static void TrimLeadingNewlines(std::string& s) {
size_t i = 0;
while (i < s.size() && (s[i] == '\r' || s[i] == '\n')) ++i;
if (i) s.erase(0, i);
}
// 擦掉输出里**残留**的哨兵文本。ConPTY 送回来的是「屏幕渲染流」而不是字节流:光标重绘
// 会把同一行再输出一次,剥掉 VT 序列后同一段文字就重复出现。于是哨兵可能留有副本
// (实测 `rem hello` 只剩哨兵、`cmd /c echo abc` 成了 "abc__MCP_DONE_x__0")。
// nonce 每条命令随机生成,命令的真实输出不可能包含它,故按 nonce 文本擦除既彻底又安全。
// 比较时跳过 '\r'/'\n'(折行回显);`%errorlevel%` 是回显模板本身,一并擦到行尾。
static void StripSentinelText(std::string& s, const std::string& nonce) {
if (nonce.empty() || s.empty()) return;
const std::string marker = "__MCP_DONE_" + nonce + "__";
size_t i = 0;
while (i < s.size()) {
size_t j = 0, k = i;
while (j < marker.size() && k < s.size()) {
const char c = s[k];
if (c == '\r' || c == '\n') { ++k; continue; }
if (c != marker[j]) break;
++j; ++k;
}
if (j != marker.size()) { ++i; continue; }
size_t end = k;
if (end < s.size() && s[end] == '-') ++end;
while (end < s.size() && s[end] >= '0' && s[end] <= '9') ++end;
if (end < s.size() && s[end] == '%') // 回显模板 ...__%errorlevel%
while (end < s.size() && s[end] != '\r' && s[end] != '\n') ++end;
size_t begin = i; // 连带前面残留的 "echo "
if (begin >= 5 && _strnicmp(s.c_str() + begin - 5, "echo ", 5) == 0) begin -= 5;
s.erase(begin, end - begin);
i = begin;
}
}
// 输入回显清洗(P4):PTY 下删「命令行」与「哨兵行」两处回显。非 PTY 只删哨兵行——
// 老 ShellManager 在客户端按写入长度自行跳过回显,删命令行反而可能吃掉命令自身的输出
// (如 `echo echo hello`)。
static std::string StripEchoedInput(const std::string& s, bool isPty,
const std::string& cmdLine, const std::string& sentLine,
const std::string& nonce) {
std::string out = s;
bool cut = isPty && CutThroughEchoedLine(out, cmdLine);
if (isPty && !cut) StripEchoedLine(out, cmdLine); // 没回显时退回按整行删
StripEchoedLine(out, sentLine);
StripSentinelText(out, nonce);
TrimLeadingNewlines(out);
return out;
}
// 哨兵行有三种形态(见 docs/Mcp_Design.md §12.1):
// - POSIX PTY(posix=true,Linux):命令与哨兵**分两行**下发,哨兵用 echo 内置命令 +
// $? 取上一行的真实退出码。不能用 Windows 的 "@echo off & ..." / %errorlevel%:
// POSIX shell 会把它们当成字面量,FindSentinel 永远匹配不到。
// - ConPTY(is_pty=true):命令与哨兵**分两行**下发。哨兵独立成行执行,于是 rem / cmd / c
// exit / if / for 这类「吞行」命令不会连哨兵一起吞掉(P1);哨兵用 %errorlevel% 取真实
// 退出码,回显文本里是字面 "%errorlevel%"、不是数字,FindSentinel 只认数字,折行回显再也
// 不会被误判成哨兵(P3),也能返回真实退出码而非 0/1。
// - 老 ShellManager(is_pty=false):客户端按写入字节数跳过回显,多写一行会吃掉上一行的
// 输出,故仍用单行 && / || 形式(老客户端维持既有行为,已知不支持 rem / cmd /c)。
static void BuildSentinelLines(bool isPty, bool posix, const std::string& command,
const std::string& nonce,
std::string& cmdLine, std::string& sentLine) {
if (posix) {
cmdLine = command;
sentLine = "echo __MCP_DONE_" + nonce + "__$?";
return;
}
if (!isPty) {
cmdLine = command + " 2>&1 && echo __MCP_DONE_" + nonce + "__0 || echo __MCP_DONE_" + nonce + "__1";
sentLine.clear();
return;
}
cmdLine = "@echo off & " + command;
sentLine = "echo __MCP_DONE_" + nonce + "__%errorlevel%";
}
// 组包下发;cmdLine/sentLine 回传给调用方用于剔除输入回显。sentLine 为空表示单行形态。
static void SendSentinelLines(context* subCtx, bool isPty, bool posix, const std::string& command,
const std::string& nonce, std::string& cmdLine, std::string& sentLine) {
BuildSentinelLines(isPty, posix, command, nonce, cmdLine, sentLine);
UINT cp = (posix || isPty) ? CP_UTF8 : 936;
// Linux 的交互式 bash 每读一行都打印 PS1,提示符会混进 stdout(Windows ConPTY 不会),
// 故先清空 PS1 再执行。这一行的回显在命令行回显之前,会被 CutThroughEchoedLine 连同
// 启动画面一起切掉,不进入返回文本。
std::string wire;
if (posix) wire = "PS1=\r\n";
wire += ToAnsi(cmdLine, cp) + "\r\n";
if (!sentLine.empty()) wire += ToAnsi(sentLine, cp) + "\r\n";
subCtx->Send2Client((BYTE*)wire.data(), (ULONG)wire.size());
}
// 命令是否含控制字符(<0x20,含 \r\n)。\r\n 会把命令拆成多行:一次性 exec 里会绕过
// 白名单执行任意后续行(安全);持久终端里只有末行被哨兵包装、退出码失真(正确性)。二者都拒绝。
static bool ContainsControlChar(const std::string& s) {
for (char ch : s)
if ((unsigned char)ch < 0x20) return true;
return false;
}
// tools/call:exec_command(Windows/Linux 一次性远程命令:主连接 COMMAND_SHELL → 子连接终端 →
// 哨兵命令行 → 收集 stdout + exit_code → 关子链接)。安全门:只读默认 + 白名单 + 审计。
std::string BuildExecCommand(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
uint64_t devId = 0;
std::string err;
if (!ParseHostIdArg(args, devId, err))
return BuildError(id, -32602, err);
context* ctx = FindMainContext(parent, devId);
if (!ctx)
return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId));
// Linux 客户端同样走 PTY + POSIX 哨兵;macOS 本轮不开放。
CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
const bool posix = (clientType == "LNX");
if (clientType == "MAC")
return BuildError(id, -32005, "exec_command is only supported on Windows and Linux hosts");
std::string command = Trim(GetStringArg(args, "command"));
if (command.empty())
return BuildError(id, -32602, "Missing required parameter: command");
CMcpServer& mcp = CMcpServer::Instance();
// 安全门 1:只读模式直接拒绝(默认只读,exec_command 需显式关只读才可用)。
if (mcp.IsReadonly())
return BuildError(id, -32006, "exec_command is disabled: MCP is in read-only mode (set McpReadonly=0 to enable)");
// 安全门 2:拒绝 shell 元字符与控制字符(\r\n 会把命令拆成多行绕过白名单),防注入。
// POSIX 下还要挡 ; 反引号 $( ${ !;^ 在 POSIX 里不是元字符,不能沿用 Windows 的字符集
// (否则 grep -v '^#' 这类只读命令会被误拒)。
const bool badMeta = posix ? ContainsForbiddenPosixShellChars(command)
: (command.find_first_of("&|<>^") != std::string::npos);
if (badMeta || ContainsControlChar(command))
return BuildError(id, kErrValidation, "Command contains forbidden shell characters: " + command);
// 安全门 3:命令白名单前缀校验(显式配置优先;否则按平台用内置默认表)。
std::string whitelist = mcp.GetCmdWhitelist();
if (whitelist.empty()) whitelist = posix ? kDefaultCmdWhitelistPosix : kDefaultCmdWhitelist;
if (!IsCommandAllowed(command, whitelist))
return BuildError(id, -32007, "Command not allowed by whitelist: " + command);
int timeoutMs = CMcpServer::Instance().ToolTimeoutMs();
int v = 0;
if (GetIntArg(args, "timeout_ms", v) && v > 0 && v <= 600000) timeoutMs = v;
std::string nonce = GenerateRandomToken().substr(0, 8);
if (!mcp.BeginTermPending(devId, command, nonce))
return BuildError(id, -32003, "Device busy: a terminal session is already active for this host");
// 主连接下发 COMMAND_SHELL,客户端建立 shell 子连接并回 TOKEN_*_START。
BYTE cmd = COMMAND_SHELL;
if (!ctx->Send2Client(&cmd, 1)) {
mcp.ClearTermPending(devId);
return BuildError(id, -32004, "Failed to send command to host");
}
context* subCtx = nullptr;
bool isPty = false;
if (!mcp.WaitTerminalReady(devId, subCtx, isPty, timeoutMs))
return BuildError(id, -32001, "Timeout waiting for shell to start");
// 编码:PTY(UTF-8) / 老 cmd 管道(GBK)。哨兵为纯 ASCII,两种编码下字节一致。
UINT cp = (posix || isPty) ? CP_UTF8 : 936;
// 哨兵形态见 BuildSentinelLines:POSIX PTY / ConPTY 下命令与哨兵分两行下发(吞行命令
// 不再超时),老 ShellManager 保持单行 && / || 形式(其客户端按写入长度跳回显)。
std::string cmdLine, sentLine;
SendSentinelLines(subCtx, isPty, posix, command, nonce, cmdLine, sentLine);
std::vector<BYTE> raw;
int exitCode = -1;
bool closed = false;
if (!mcp.WaitTerminalDone(devId, raw, exitCode, closed, timeoutMs)) {
subCtx->CancelIO();
return BuildError(id, -32001, "Timeout waiting for command output");
}
subCtx->CancelIO(); // 关子链接,结束 shell 进程
// 清洗:raw → UTF-8 → 剥 ANSI → CRLF 归一 → 去 ConPTY 回显命令行 → TrimRight。
// raw 已截断到哨兵前。
std::string stdoutStr;
if (!raw.empty()) {
std::string rawStr((const char*)raw.data(), raw.size());
stdoutStr = StripAnsi(ToUtf8(rawStr.c_str(), cp));
size_t p = 0;
while ((p = stdoutStr.find("\r\n", p)) != std::string::npos)
stdoutStr.erase(p, 1);
stdoutStr = StripEchoedInput(stdoutStr, isPty, cmdLine, sentLine, nonce);
stdoutStr = TrimRight(stdoutStr);
}
// 审计:命令执行落服务端消息/审计日志(不可关闭)。
if (parent) {
std::string text = "host " + std::to_string(devId) + " exec: " + command;
parent->PostMessageA(WM_SHOWERRORMSG,
(WPARAM)new CString(ToAnsi(text, 936).c_str()),
(LPARAM)new CString(_TR("MCP命令执行"))); // 标题走语言映射(GBK,随语言切换)
}
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
structuredContent["stdout"] = stdoutStr;
structuredContent["exit_code"] = exitCode;
result["structuredContent"] = structuredContent;
// stdout 已在正文里,正文外的 JSON 块只补退出码(只读 content 的客户端也能看到)。
Json::Value textPayload(Json::objectValue);
textPayload["exit_code"] = exitCode;
SetStructuredTextPayload(result, textPayload);
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = stdoutStr.empty() ? std::string(u8"(无输出)") : stdoutStr;
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
// tools/call:get_client_log(主连接下发 COMMAND_QUERY_LOG,子连接回传 TOKEN_REPORT_LOG)
std::string BuildGetClientLog(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
uint64_t devId = 0;
std::string err;
if (!ParseHostIdArg(args, devId, err))
return BuildError(id, -32602, err);
context* ctx = FindMainContext(parent, devId);
if (!ctx)
return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId));
CMcpServer& mcp = CMcpServer::Instance();
if (!mcp.BeginPending(devId, "get_client_log"))
return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId));
BYTE cmd = COMMAND_QUERY_LOG;
if (!ctx->Send2Client(&cmd, 1)) {
mcp.ClearPending(devId);
return BuildError(id, -32004, "Failed to send command to host");
}
std::vector<BYTE> data;
if (!mcp.WaitPending(devId, data, mcp.ToolTimeoutMs()))
return BuildError(id, -32001,
u8"Timeout waiting for client log. 客户端在超时内没有回传日志:常见原因是该客户端"
u8"版本尚未实现日志上报(Linux/MAC 需 2026-10-30 之后的客户端),也可能是子连接"
u8"建立失败。可先用 get_host_detail 看 capabilities,或改用 download_file 直接取"
u8"客户端日志文件。");
// data[0]=token,其后为 Logger 内存 ring buffer 的日志文本(无 '\0' 终止)。
// 客户端在子连接建立时 m_sentIdx=0 返回全量,随后每 3s 推增量;MessageHandle 在
// 取走首条全量后立即 CancelIO 关子链接,增量不再到达,故此处即为完整快照。
// 日志文本为客户端 ANSI(Windows 走 vsnprintf A 版),按 clientType 判定编码。
CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
UINT cp = (clientType == "LNX" || clientType == "MAC") ? CP_UTF8 : 936;
std::string log;
if (data.size() > 1) {
std::string raw((const char*)data.data() + 1, data.size() - 1);
log = ToUtf8(raw.c_str(), cp);
}
// 行级裁剪:客户端快照是全量(最多 1000 行、实测 90 KB),直接整段塞进结果会超出
// 客户端的工具结果上限。默认只回末尾 200 行——排障关心的是最后发生了什么。
int limit = 200;
if (args.isMember("limit") && args["limit"].isInt())
limit = args["limit"].asInt();
if (limit <= 0) limit = 200;
if (limit > 2000) limit = 2000;
const std::string filter = GetStringArg(args, "filter");
std::vector<std::string> lines;
{
size_t b = 0;
while (b < log.size()) {
size_t e = log.find('\n', b);
std::string one = (e == std::string::npos) ? log.substr(b) : log.substr(b, e - b);
if (!one.empty() && one.back() == '\r') one.pop_back();
lines.push_back(one);
if (e == std::string::npos) break;
b = e + 1;
}
}
const int linesTotal = (int)lines.size();
std::vector<std::string> matched;
matched.reserve(lines.size());
for (const auto& one : lines) {
if (filter.empty() || ContainsCI(one, filter))
matched.push_back(one);
}
const int linesMatched = (int)matched.size();
// 从末尾往前取:同时受 limit 行数与 64 KB 字节预算约束(单行可能是超长的堆栈或
// 报文转储,只按行数截断仍可能撑爆结果)。两个约束哪个先到就用哪个。
const size_t kMaxBytes = 64 * 1024;
std::string shown;
int linesReturned = 0;
bool contentTruncated = false;
{
size_t budget = kMaxBytes;
size_t firstKept = (size_t)linesMatched; // 保留 [firstKept, linesMatched)
while (firstKept > 0 && (int)((size_t)linesMatched - firstKept) < limit) {
const size_t need = matched[firstKept - 1].size() + 1;
if (need > budget) break;
budget -= need;
--firstKept;
}
if (firstKept == (size_t)linesMatched && linesMatched > 0) {
// 末尾一行自己就超过预算:至少回它的尾部(排障看的是最后发生了什么),
// 而不是回空串让人以为客户端没有日志。
const std::string& last = matched.back();
if (last.size() > kMaxBytes) {
shown = last.substr(last.size() - kMaxBytes);
contentTruncated = true;
} else {
shown = last;
}
shown += '\n';
linesReturned = 1;
} else {
for (size_t i = firstKept; i < (size_t)linesMatched; ++i) {
shown += matched[i];
shown += '\n';
}
linesReturned = linesMatched - (int)firstKept;
}
}
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
structuredContent["log"] = shown;
structuredContent["lines_total"] = linesTotal;
structuredContent["lines_matched"] = linesMatched;
structuredContent["lines_returned"] = linesReturned;
structuredContent["truncated"] = (linesMatched > linesReturned) || contentTruncated;
result["structuredContent"] = structuredContent;
std::string text;
if (linesTotal == 0) {
text = u8"客户端暂无内存日志。";
} else {
text = std::string(u8"客户端运行日志:共 ") + std::to_string(linesTotal) + std::string(u8" 行");
if (!filter.empty())
text += std::string(u8",匹配 \"") + filter + std::string(u8"\" 的 ") + std::to_string(linesMatched) + std::string(u8" 行");
text += std::string(u8",返回末尾 ") + std::to_string(linesReturned) + std::string(u8" 行");
if (linesMatched > linesReturned || contentTruncated)
text += std::string(u8"(还有更多,可调大 limit 或加 filter)");
text += std::string(u8"。");
}
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = text;
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
// tools/call:get_audit_log(服务端本地消息日志,读取 UI 日志列表的线程安全镜像)
std::string BuildGetAuditLog(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
std::string fType = GetStringArg(args, "type");
std::string fKeyword = GetStringArg(args, "keyword");
Json::Value all(Json::arrayValue);
int rawCount = 0;
if (parent) {
EnterCriticalSection(&parent->m_cs);
// m_MessageLog 新在前、旧在后(与界面一致),直接顺序输出。
// 镜像本身有 1000 条环形上限(MAX_MESSAGE_COUNT),过滤与分页都在内存里做,代价可忽略。
for (const auto& e : parent->m_MessageLog) {
std::string ty = ToUtf8(e.type.c_str(), 936);
std::string tm = ToUtf8(e.time.c_str(), 936);
std::string ms = ToUtf8(e.msg.c_str(), 936);
rawCount++;
if (!fType.empty() && !ContainsCI(ty, fType)) continue;
if (!fKeyword.empty() && !ContainsCI(ms, fKeyword)) continue;
Json::Value item(Json::objectValue);
item["type"] = ty;
item["time"] = tm;
item["msg"] = ms;
all.append(item);
}
LeaveCriticalSection(&parent->m_cs);
}
PageWindow page = ResolvePageWindow(args);
Json::Value entries;
ApplyPageWindow(all, page, entries);
page.totalAll = rawCount; // 过滤前的总条数:total 是命中数,totalAll 是镜像里全部条数
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
structuredContent["entries"] = entries;
WritePageFields(structuredContent, page);
result["structuredContent"] = structuredContent;
std::string text = PageSummary(page, u8"条日志");
if (!fType.empty() || !fKeyword.empty())
text += std::string(u8"过滤前共 ") + std::to_string(rawCount) + std::string(u8" 条。");
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = text;
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
// tools/call:get_server_status(服务端自身状态:版本/构建时间/运行时长/开关/监听地址/计数)
std::string BuildGetServerStatus(const Json::Value& id, CMy2015RemoteDlg* parent) {
CMcpServer& srv = CMcpServer::Instance();
Json::Value status(Json::objectValue);
status["app_name"] = BRAND_APP_NAME;
status["version"] = VERSION_STR;
// exe 的最后写入时间就是链接时间,比 __DATE__/__TIME__ 可靠(后者是编译本 .cpp 的时间)。
{
char exe[MAX_PATH] = { 0 };
if (GetModuleFileNameA(NULL, exe, MAX_PATH) > 0) {
WIN32_FILE_ATTRIBUTE_DATA fad;
if (GetFileAttributesExA(exe, GetFileExInfoStandard, &fad)) {
FILETIME local = fad.ftLastWriteTime;
FileTimeToLocalFileTime(&fad.ftLastWriteTime, &local);
SYSTEMTIME st = { 0 };
if (FileTimeToSystemTime(&local, &st)) {
char buf[32] = { 0 };
wsprintfA(buf, "%04d-%02d-%02d %02d:%02d:%02d",
(int)st.wYear, (int)st.wMonth, (int)st.wDay,
(int)st.wHour, (int)st.wMinute, (int)st.wSecond);
status["exe_build_time"] = buf;
}
}
}
}
// 进程运行时长:从进程创建时间算起(不是系统开机时间,也不受 MCP 启停影响)。
{
FILETIME createTime, exitTime, kernelTime, userTime, nowFt;
if (GetProcessTimes(GetCurrentProcess(), &createTime, &exitTime, &kernelTime, &userTime)) {
GetSystemTimeAsFileTime(&nowFt);
ULARGE_INTEGER c, n;
c.LowPart = createTime.dwLowDateTime; c.HighPart = createTime.dwHighDateTime;
n.LowPart = nowFt.dwLowDateTime; n.HighPart = nowFt.dwHighDateTime;
LONGLONG ticks100ns = (LONGLONG)(n.QuadPart - c.QuadPart);
if (ticks100ns > 0) status["uptime_sec"] = (Json::Int64)(ticks100ns / 10000000LL);
}
}
status["bind"] = srv.GetBind();
status["port"] = srv.GetPort();
// 开关只报「开/关」,不输出 token、白名单内容等敏感配置。
Json::Value switches(Json::objectValue);
switches["readonly"] = srv.IsReadonly();
switches["terminal"] = srv.IsTerminalEnabled();
switches["remote_control"] = srv.IsRemoteControlEnabled();
switches["file_transfer"] = srv.IsFileTransferEnabled();
switches["file_write"] = srv.IsFileWriteEnabled();
switches["manage"] = srv.IsManageEnabled();
switches["machine"] = srv.IsMachineEnabled();
switches["machine_dangerous"] = srv.IsMachineDangerousEnabled();
switches["keylog"] = srv.IsKeylogEnabled();
switches["chat"] = srv.IsChatEnabled();
status["switches"] = switches;
int onlineCount = 0, offlineCount = 0;
if (parent) {
Json::Value all(Json::arrayValue);
CollectAllHosts(parent, all, true, true);
for (Json::Value::ArrayIndex i = 0; i < all.size(); ++i) {
if (all[i]["online"].asBool()) onlineCount++;
else offlineCount++;
}
}
Json::Value hosts(Json::objectValue);
hosts["online"] = onlineCount;
hosts["offline"] = offlineCount;
status["hosts"] = hosts;
int pending = 0, terminal = 0, screenCtrl = 0, fileXfer = 0, chat = 0, blockedIps = 0;
srv.GetRuntimeCounters(pending, terminal, screenCtrl, fileXfer, chat, blockedIps);
Json::Value sessions(Json::objectValue);
sessions["pending"] = pending; // 一次性/管理/键盘记录挂起会话
sessions["terminal"] = terminal;
sessions["remote_control"] = screenCtrl;
sessions["file_transfer"] = fileXfer;
sessions["chat"] = chat;
status["sessions"] = sessions;
status["blocked_auth_ips"] = blockedIps;
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
structuredContent["status"] = status;
result["structuredContent"] = structuredContent;
std::string text = std::string(BRAND_APP_NAME) + " v" + VERSION_STR +
std::string(u8",已运行 ") + std::to_string((long long)status["uptime_sec"].asInt64()) +
std::string(u8" 秒,监听 ") + srv.GetBind() + ":" + std::to_string(srv.GetPort()) +
std::string(u8";在线主机 ") + std::to_string(onlineCount) +
std::string(u8" 台、离线 ") + std::to_string(offlineCount) + std::string(u8" 台。");
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = text;
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
// ===== P11:mcp_list_sessions / mcp_cancel_session =====
//
// 这两个工具只看/只改服务端自己的会话表,不向任何主机发报文,因此不受功能开关与
// 只读模式限制——它们回答的是「谁占着这台主机、怎么把占用放开」,包括只读模式下
// 卡住的长请求。取消是异步的:工具线程在 ≤500ms 的等待切片内退出并走既有清理路径,
// 这里再轮询同等条件最多 2s,好让返回的 released 反映「主机是否真的松开了」。
namespace {
const int kCancelWaitMs = 2000; // mcp_cancel_session 等「主机松开」的上限
}
static std::string BuildMcpListSessions(const Json::Value& id, const Json::Value& args) {
const std::string kindFilter = ToLowerAscii(GetStringArg(args, "kind"));
static const char* kKinds[] = { "call", "pending", "terminal", "remote_control",
"file_transfer", "chat" };
if (!kindFilter.empty()) {
bool known = false;
for (const char* k : kKinds) if (kindFilter == k) { known = true; break; }
if (!known)
return BuildError(id, -32602,
"kind must be one of call/pending/terminal/remote_control/"
"file_transfer/chat");
}
const auto all = CMcpServer::Instance().ListSessions();
Json::Value arr(Json::arrayValue);
std::string text;
int shown = 0;
for (const auto& s : all) {
if (!kindFilter.empty() && s.kind != kindFilter) continue;
Json::Value o(Json::objectValue);
if (s.device != 0) o["host_id"] = std::to_string(s.device);
o["kind"] = s.kind;
o["tool"] = s.tool;
if (!s.sessionId.empty()) o["session_id"] = s.sessionId;
if (!s.requestId.empty()) o["request_id"] = s.requestId;
o["busy"] = s.busy;
if (s.elapsedMs >= 0) o["elapsed_ms"] = (Json::Int64)s.elapsedMs;
if (s.idleMs >= 0) o["idle_ms"] = (Json::Int64)s.idleMs;
arr.append(o);
if (shown < 20) { // 正文只列前 20 条,完整内容在 structuredContent
if (!text.empty()) text += u8";";
if (s.device != 0) text += std::string(u8"主机 ") + std::to_string(s.device) + u8" ";
text += s.kind + "/" + s.tool;
if (s.elapsedMs >= 0)
text += std::string(u8"(已 ") + std::to_string(s.elapsedMs / 1000) + u8"s)";
++shown;
}
}
Json::Value sc(Json::objectValue);
sc["sessions"] = arr;
sc["count"] = (int)arr.size();
if (arr.empty()) {
text = u8"当前没有在飞请求或长连接会话,主机都空闲。";
} else {
text = std::string(u8"共 ") + std::to_string((int)arr.size()) + u8" 个会话:" + text;
if ((int)arr.size() > shown)
text += std::string(u8"…(正文只列前 ") + std::to_string(shown) + u8" 个)";
}
Json::Value result(Json::objectValue);
result["structuredContent"] = sc;
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = text;
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
static std::string BuildMcpCancelSession(const Json::Value& id, const Json::Value& args) {
// request_id:按 JSON-RPC id 精确取消一次 tools/call(与 notifications/cancelled 等价)。
// 同时接受紧凑写法与 mcp_list_sessions 里给出的文本写法(见 CancelCallById)。
std::string reqIdKey;
std::string reqIdText;
if (args.isObject() && args.isMember("request_id")) {
const Json::Value& v = args["request_id"];
if (!(v.isString() || v.isInt() || v.isUInt() || v.isInt64() || v.isUInt64()))
return BuildError(id, -32602,
"request_id must be a string or integer: the JSON-RPC id of a tools/call");
reqIdKey = JsonToString(v);
reqIdText = McpRequestIdText(v);
}
uint64_t devId = 0;
const bool hasDev = args.isObject() && args.isMember("id");
if (hasDev && !ReadUInt64Arg(args, "id", devId))
return BuildError(id, -32602, "id must be a decimal host id string");
const std::string sessionId = GetStringArg(args, "session_id");
if (reqIdKey.empty() && !hasDev && sessionId.empty())
return BuildError(id, -32602,
"Provide at least one of request_id (a tools/call id), id (host id), "
"or session_id");
// 条件匹配函数:request_id 优先,其余条件按「都给就必须都满足」。
auto matches = [&](const CMcpServer::SessionSnapshot& s) {
if (!reqIdKey.empty()) return s.idKey == reqIdKey || s.requestId == reqIdText;
if (hasDev && devId != 0 && s.device != devId) return false;
if (!sessionId.empty() && s.sessionId != sessionId) return false;
return true;
};
CMcpServer& srv = CMcpServer::Instance();
Json::Value matched(Json::arrayValue);
for (const auto& s : srv.ListSessions()) {
if (!matches(s)) continue;
Json::Value o(Json::objectValue);
if (s.device != 0) o["host_id"] = std::to_string(s.device);
o["kind"] = s.kind;
o["tool"] = s.tool;
if (!s.sessionId.empty()) o["session_id"] = s.sessionId;
if (!s.requestId.empty()) o["request_id"] = s.requestId;
matched.append(o);
}
int cancelled = 0;
if (!reqIdKey.empty()) cancelled = srv.CancelCallById(reqIdKey, reqIdText) ? 1 : 0;
else cancelled = srv.CancelCalls(devId, sessionId);
// 等主机松开(最多 2s):调用还在表里就说明工具线程还没走完清理。
int waitedMs = 0;
bool released = false;
if (cancelled > 0) {
while (waitedMs < kCancelWaitMs) {
bool stillThere = false;
for (const auto& s : srv.ListSessions()) {
if (matches(s)) { stillThere = true; break; }
}
if (!stillThere) { released = true; break; }
std::this_thread::sleep_for(std::chrono::milliseconds(100));
waitedMs += 100;
}
}
Json::Value sc(Json::objectValue);
sc["cancelled"] = cancelled;
sc["released"] = released;
sc["waited_ms"] = waitedMs;
sc["matched"] = matched;
std::string text;
if (cancelled == 0) {
text = u8"没有匹配的在飞请求:可能已经结束,或 request_id 与列表里的值不一致。";
} else if (released) {
text = std::string(u8"已取消 ") + std::to_string(cancelled) + u8" 个在飞请求," +
std::to_string(waitedMs) + u8" ms 内已释放占用;被取消的请求会收到 -32800。";
} else {
text = std::string(u8"已取消 ") + std::to_string(cancelled) + u8" 个在飞请求,但 " +
std::to_string(kCancelWaitMs) + u8" ms 内仍在收尾(主机可能要等到客户端回包或超时);"
u8"稍后用 mcp_list_sessions 复查。";
}
Json::Value result(Json::objectValue);
result["structuredContent"] = sc;
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = text;
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
// ===== P4:持久远程终端(terminal_open / terminal_exec / terminal_close)=====
static const int kTermIdleTimeoutSec = 300; // 持久终端 idle 回收超时(秒)
static const int kTermTombstoneSec = 600; // 「终端被销毁」墓碑保留时长(秒),供后续报错文案用
// 共享前置:校验 McpTerminal && !readonly → 解析 id → FindMainContext → 拒绝 macOS。
// 成功返回 true 并输出 devId/ctx;失败时 errJson 已写入对应 JSON 错误串。
static bool ResolveTerminalSessionHost(const Json::Value& id, const Json::Value& args,
CMy2015RemoteDlg* parent,
uint64_t& devId, context*& ctx, std::string& errJson) {
CMcpServer& mcp = CMcpServer::Instance();
if (!mcp.IsTerminalEnabled() || mcp.IsReadonly()) {
errJson = BuildError(id, -32006,
"Persistent terminal is disabled: requires McpTerminal=1 and McpReadonly=0");
return false;
}
std::string err;
if (!ParseHostIdArg(args, devId, err)) {
errJson = BuildError(id, -32602, err);
return false;
}
ctx = FindMainContext(parent, devId);
if (!ctx) {
errJson = BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId));
return false;
}
CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
if (clientType == "MAC") {
errJson = BuildError(id, -32005, "Persistent terminal is only supported on Windows and Linux hosts");
return false;
}
return true;
}
// 发送哨兵命令行(复用 exec_command 的哨兵逻辑);回传所发送的两行,
// 供调用方剔除 PTY 把输入整行回显造成的噪声。cp 由平台/isPty 决定。
static void SendTerminalCommandLine(context* subCtx, bool isPty, bool posix,
const std::string& command, const std::string& nonce,
std::string& cmdLine, std::string& sentLine) {
SendSentinelLines(subCtx, isPty, posix, command, nonce, cmdLine, sentLine);
}
// 输出清洗(复用 exec_command 尾部逻辑):raw → UTF-8 → 剥 ANSI → CRLF 归一 →
// 去输入回显 → TrimRight。
static std::string CleanTerminalOutput(const std::vector<BYTE>& raw, UINT cp, bool isPty,
const std::string& cmdLine, const std::string& sentLine,
const std::string& nonce) {
std::string stdoutStr;
if (!raw.empty()) {
std::string rawStr((const char*)raw.data(), raw.size());
stdoutStr = StripAnsi(ToUtf8(rawStr.c_str(), cp));
size_t p = 0;
while ((p = stdoutStr.find("\r\n", p)) != std::string::npos)
stdoutStr.erase(p, 1);
stdoutStr = StripEchoedInput(stdoutStr, isPty, cmdLine, sentLine, nonce);
stdoutStr = TrimRight(stdoutStr);
}
return stdoutStr;
}
// terminal_open 的 inputSchema(id 必填、timeout_ms 可选)
Json::Value BuildTerminalOpenInputSchema() {
Json::Value props(Json::objectValue);
Json::Value idProp(Json::objectValue);
idProp["type"] = "string";
idProp["description"] = u8"主机 id,取 list_online_hosts / search_hosts 返回的 id 字段";
props["id"] = idProp;
Json::Value timeoutProp(Json::objectValue);
timeoutProp["type"] = "integer";
timeoutProp["description"] = u8"等待 shell 启动的超时毫秒数(可选,默认 20000,上限 600000)";
props["timeout_ms"] = timeoutProp;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("id");
schema["required"] = required;
return schema;
}
Json::Value BuildTerminalOpenOutputSchema() {
Json::Value props(Json::objectValue);
Json::Value sid(Json::objectValue);
sid["type"] = "string";
sid["description"] = u8"持久会话 token,后续 terminal_exec / terminal_close 用";
props["session_id"] = sid;
Json::Value pty(Json::objectValue);
pty["type"] = "boolean";
pty["description"] = u8"true=PTY(UTF-8)(Windows ConPTY / Linux PTY);false=老 cmd 管道(GBK)";
props["is_pty"] = pty;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("session_id");
required.append("is_pty");
schema["required"] = required;
return schema;
}
Json::Value BuildTerminalExecInputSchema() {
Json::Value props(Json::objectValue);
Json::Value idProp(Json::objectValue);
idProp["type"] = "string";
idProp["description"] = u8"主机 id,取 list_online_hosts / search_hosts 返回的 id 字段";
props["id"] = idProp;
Json::Value sid(Json::objectValue);
sid["type"] = "string";
sid["description"] = u8"terminal_open 返回的 session_id";
props["session_id"] = sid;
Json::Value cmdProp(Json::objectValue);
cmdProp["type"] = "string";
cmdProp["description"] = u8"要执行的命令(完整 shell,不受白名单约束;但不能含 & 或 |,请拆成多条调用)。Linux 下通过 POSIX shell 执行,可用 ; 串联且退出码取最后一条命令";
props["command"] = cmdProp;
Json::Value timeoutProp(Json::objectValue);
timeoutProp["type"] = "integer";
timeoutProp["description"] = u8"等待输出完成的超时毫秒数(可选,默认 20000,上限 600000)";
props["timeout_ms"] = timeoutProp;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("id");
required.append("session_id");
required.append("command");
schema["required"] = required;
return schema;
}
Json::Value BuildTerminalExecOutputSchema() {
Json::Value props(Json::objectValue);
Json::Value stdoutProp(Json::objectValue);
stdoutProp["type"] = "string";
stdoutProp["description"] = u8"命令输出(已剥哨兵与 ANSI 转义)";
props["stdout"] = stdoutProp;
Json::Value exitProp(Json::objectValue);
exitProp["type"] = "integer";
exitProp["description"] = u8"退出码:PTY 客户端(Windows ConPTY / Linux PTY)为命令的真实退出码;老客户端(非 PTY)仅区分 0/非 0;-1=未知(进程异常退出)";
props["exit_code"] = exitProp;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("stdout");
required.append("exit_code");
schema["required"] = required;
return schema;
}
Json::Value BuildTerminalCloseInputSchema() {
Json::Value props(Json::objectValue);
Json::Value idProp(Json::objectValue);
idProp["type"] = "string";
idProp["description"] = u8"主机 id,取 list_online_hosts / search_hosts 返回的 id 字段";
props["id"] = idProp;
Json::Value sid(Json::objectValue);
sid["type"] = "string";
sid["description"] = u8"terminal_open 返回的 session_id";
props["session_id"] = sid;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("id");
required.append("session_id");
schema["required"] = required;
return schema;
}
Json::Value BuildTerminalCloseOutputSchema() {
Json::Value props(Json::objectValue);
Json::Value closed(Json::objectValue);
closed["type"] = "boolean";
closed["description"] = u8"恒为 true(关闭幂等)";
props["closed"] = closed;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("closed");
schema["required"] = required;
return schema;
}
// tools/call:terminal_open(打开持久 shell 会话,返回 session_id;用毕须 terminal_close)
std::string BuildTerminalOpen(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
CMcpServer& mcp = CMcpServer::Instance();
mcp.SweepIdleTerminals(kTermIdleTimeoutSec);
uint64_t devId = 0;
context* ctx = nullptr;
std::string errJson;
if (!ResolveTerminalSessionHost(id, args, parent, devId, ctx, errJson))
return errJson;
int timeoutMs = CMcpServer::Instance().ToolTimeoutMs();
int v = 0;
if (GetIntArg(args, "timeout_ms", v) && v > 0 && v <= 600000) timeoutMs = v;
std::string sessionId = GenerateRandomToken();
if (!mcp.BeginTermOpen(devId, sessionId))
return BuildError(id, -32003, "Device busy: a terminal session is already active for this host");
BYTE cmd = COMMAND_SHELL;
if (!ctx->Send2Client(&cmd, 1)) {
mcp.ClearTermPending(devId);
return BuildError(id, -32004, "Failed to send command to host");
}
context* subCtx = nullptr;
bool isPty = false;
if (!mcp.WaitTerminalReady(devId, subCtx, isPty, timeoutMs))
return BuildError(id, -32001, "Timeout waiting for shell to start");
// 审计:打开会话(不可关闭)。
if (parent) {
std::string text = "host " + std::to_string(devId) + " term-open: session " + sessionId;
parent->PostMessageA(WM_SHOWERRORMSG,
(WPARAM)new CString(ToAnsi(text, 936).c_str()),
(LPARAM)new CString(_TR("MCP持久终端")));
}
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
structuredContent["session_id"] = sessionId;
structuredContent["is_pty"] = isPty;
result["structuredContent"] = structuredContent;
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = sessionId;
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
// tools/call:terminal_exec(在已打开的持久会话中执行一条命令;无白名单,但禁 & |)
std::string BuildTerminalExec(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
CMcpServer& mcp = CMcpServer::Instance();
mcp.SweepIdleTerminals(kTermIdleTimeoutSec);
uint64_t devId = 0;
context* ctx = nullptr;
std::string errJson;
if (!ResolveTerminalSessionHost(id, args, parent, devId, ctx, errJson))
return errJson;
const bool posix = (ctx->GetAdditionalData(RES_CLIENT_TYPE) == "LNX");
std::string sessionId = GetStringArg(args, "session_id");
if (sessionId.empty())
return BuildError(id, -32602, "Missing required parameter: session_id");
std::string command = Trim(GetStringArg(args, "command"));
if (command.empty())
return BuildError(id, -32602, "Missing required parameter: command");
// 正确性门(非安全门):& 与 | 会破坏哨兵控制操作符链、导致退出码失真;拆成多条调用即可。
// \r\n 会把命令拆成多行、只有末行被哨兵包装,同样破坏退出码捕获,一并拒绝。
if (command.find_first_of("&|") != std::string::npos || ContainsControlChar(command))
return BuildError(id, kErrValidation,
"Command contains & or | or a newline (breaks output capture); run chained/piped commands as separate terminal_exec calls");
int timeoutMs = CMcpServer::Instance().ToolTimeoutMs();
int v = 0;
if (GetIntArg(args, "timeout_ms", v) && v > 0 && v <= 600000) timeoutMs = v;
std::string nonce = GenerateRandomToken().substr(0, 8);
context* subCtx = nullptr;
bool isPty = false;
int begin = mcp.BeginTermCommand(devId, sessionId, command, nonce, subCtx, isPty);
if (begin != 0) {
// 区分「会话被超时/退出/关闭销毁」与「session_id 写错」「另一条命令在飞」(评审 P1)。
std::string destroyed = mcp.DescribeTermDestroyed(devId, sessionId);
if (!destroyed.empty())
return BuildError(id, -32002, destroyed);
if (begin == 4)
return BuildError(id, -32003, "Device busy: another terminal_exec is already running for this session");
if (begin == 2)
return BuildError(id, -32002, "Terminal session_id mismatch: " + sessionId);
if (begin == 3)
return BuildError(id, -32002, "Terminal session is not ready yet: " + sessionId);
if (begin == 5)
return BuildError(id, -32002, "Terminal session is already closing: " + sessionId);
return BuildError(id, -32002, "Terminal session not found: " + sessionId + " (call terminal_open first)");
}
std::string cmdLine, sentLine;
SendTerminalCommandLine(subCtx, isPty, posix, command, nonce, cmdLine, sentLine);
std::vector<BYTE> raw;
int exitCode = -1;
bool closed = false;
if (!mcp.WaitTermCommand(devId, raw, exitCode, closed, timeoutMs)) {
subCtx->CancelIO();
return BuildError(id, -32001, "Timeout waiting for command output");
}
if (closed) {
// shell 进程退出:会话已被 WaitTermCommand 清理,子链接已死,CancelIO 仅对称(无害)。
subCtx->CancelIO();
}
std::string stdoutStr = CleanTerminalOutput(raw, (posix || isPty) ? CP_UTF8 : 936, isPty,
cmdLine, sentLine, nonce);
// 审计:命令执行(不可关闭)。
if (parent) {
std::string text = "host " + std::to_string(devId) + " term-exec [" + sessionId + "]: " + command;
parent->PostMessageA(WM_SHOWERRORMSG,
(WPARAM)new CString(ToAnsi(text, 936).c_str()),
(LPARAM)new CString(_TR("MCP持久终端")));
}
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
structuredContent["stdout"] = stdoutStr;
structuredContent["exit_code"] = exitCode;
result["structuredContent"] = structuredContent;
// 同 exec_command:stdout 在正文里,正文外只补退出码。
Json::Value textPayload(Json::objectValue);
textPayload["exit_code"] = exitCode;
SetStructuredTextPayload(result, textPayload);
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = stdoutStr.empty() ? std::string(u8"(无输出)") : stdoutStr;
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
// tools/call:terminal_close(关闭持久会话;幂等,session_id 不匹配报错)
std::string BuildTerminalClose(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
CMcpServer& mcp = CMcpServer::Instance();
mcp.SweepIdleTerminals(kTermIdleTimeoutSec);
if (!mcp.IsTerminalEnabled() || mcp.IsReadonly())
return BuildError(id, -32006, "Persistent terminal is disabled: requires McpTerminal=1 and McpReadonly=0");
uint64_t devId = 0;
std::string err;
if (!ParseHostIdArg(args, devId, err))
return BuildError(id, -32602, err);
std::string sessionId = GetStringArg(args, "session_id");
if (sessionId.empty())
return BuildError(id, -32602, "Missing required parameter: session_id");
int r = mcp.CloseTermSession(devId, sessionId);
if (r == 2)
return BuildError(id, -32002, "Terminal session_id mismatch: " + sessionId);
// 审计:关闭会话(不可关闭)。
if (parent) {
std::string text = "host " + std::to_string(devId) + " term-close: session " + sessionId;
parent->PostMessageA(WM_SHOWERRORMSG,
(WPARAM)new CString(ToAnsi(text, 936).c_str()),
(LPARAM)new CString(_TR("MCP持久终端")));
}
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
structuredContent["closed"] = true;
result["structuredContent"] = structuredContent;
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = std::string(u8"closed");
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
// ===== P5:MCP 远程控制(remote_open / remote_close)=====
static const int kScreenCtrlIdleTimeoutSec = 300; // 远程控制 idle 回收超时(秒)
// 共享前置:校验 McpRemoteControl && !readonly → 解析 id → FindMainContext → 拒绝 macOS。
// 成功返回 true 并输出 devId/ctx;失败时 errJson 已写入对应 JSON 错误串。
static bool ResolveScreenCtrlSessionHost(const Json::Value& id, const Json::Value& args,
CMy2015RemoteDlg* parent,
uint64_t& devId, context*& ctx, std::string& errJson) {
CMcpServer& mcp = CMcpServer::Instance();
if (!mcp.IsRemoteControlEnabled() || mcp.IsReadonly()) {
errJson = BuildError(id, -32006,
"Remote control is disabled: requires McpRemoteControl=1 and McpReadonly=0");
return false;
}
std::string err;
if (!ParseHostIdArg(args, devId, err)) {
errJson = BuildError(id, -32602, err);
return false;
}
ctx = FindMainContext(parent, devId);
if (!ctx) {
errJson = BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId));
return false;
}
CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
if (clientType == "MAC") {
errJson = BuildError(id, -32005, "Remote control is only supported on Windows and Linux hosts");
return false;
}
return true;
}
// remote_open 的 inputSchema(id 必填、timeout_ms 可选)
Json::Value BuildRemoteOpenInputSchema() {
Json::Value props(Json::objectValue);
Json::Value idProp(Json::objectValue);
idProp["type"] = "string";
idProp["description"] = u8"主机 id,取 list_online_hosts / search_hosts 返回的 id 字段";
props["id"] = idProp;
Json::Value timeoutProp(Json::objectValue);
timeoutProp["type"] = "integer";
timeoutProp["description"] = u8"等待屏幕子连接建立 + 分辨率到达的超时毫秒数(可选,默认 20000,上限 600000)";
props["timeout_ms"] = timeoutProp;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("id");
schema["required"] = required;
return schema;
}
Json::Value BuildRemoteOpenOutputSchema() {
Json::Value props(Json::objectValue);
Json::Value sid(Json::objectValue);
sid["type"] = "string";
sid["description"] = u8"控制会话 token,后续 remote_mouse / remote_keyboard / remote_close 用";
props["session_id"] = sid;
Json::Value sw(Json::objectValue);
sw["type"] = "integer";
sw["description"] = u8"物理屏幕宽度(虚拟桌面像素),用于把归一化坐标 0..1 映射为像素";
props["screen_w"] = sw;
Json::Value sh(Json::objectValue);
sh["type"] = "integer";
sh["description"] = u8"物理屏幕高度(虚拟桌面像素)";
props["screen_h"] = sh;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("session_id");
required.append("screen_w");
required.append("screen_h");
schema["required"] = required;
return schema;
}
Json::Value BuildRemoteCloseInputSchema() {
Json::Value props(Json::objectValue);
Json::Value idProp(Json::objectValue);
idProp["type"] = "string";
idProp["description"] = u8"主机 id,取 list_online_hosts / search_hosts 返回的 id 字段";
props["id"] = idProp;
Json::Value sid(Json::objectValue);
sid["type"] = "string";
sid["description"] = u8"remote_open 返回的 session_id";
props["session_id"] = sid;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("id");
required.append("session_id");
schema["required"] = required;
return schema;
}
Json::Value BuildRemoteCloseOutputSchema() {
Json::Value props(Json::objectValue);
Json::Value closed(Json::objectValue);
closed["type"] = "boolean";
closed["description"] = u8"恒为 true(幂等)";
props["closed"] = closed;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("closed");
schema["required"] = required;
return schema;
}
// tools/call:remote_open(建立隐藏屏幕子连接 + 取物理分辨率)
std::string BuildRemoteOpen(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
CMcpServer& mcp = CMcpServer::Instance();
mcp.SweepIdleScreenCtrl(kScreenCtrlIdleTimeoutSec);
uint64_t devId = 0;
context* ctx = nullptr;
std::string errJson;
if (!ResolveScreenCtrlSessionHost(id, args, parent, devId, ctx, errJson))
return errJson;
// 多显示器门(§7.2 / §12.1):Observe 抓主屏,Act 注入在虚拟桌面空间,两者仅单显示器时
// 重合。客户端心跳 RES_RESOLUTION = "N:W*H"(N=显示器数);N>1 时归一化坐标会系统性
// 偏移,阶段一直接拒绝。这是能力限制(改参数也修不好),故报 -32005 而非参数校验错误 -32012。
// 无冒号(老客户端格式)则无法判定,放行不拦。
{
CString res = ctx->GetAdditionalData(RES_RESOLUTION);
int colon = res.Find(':');
if (colon > 0) {
CString countStr = res.Left(colon);
int monitorCount = atoi(countStr);
if (monitorCount > 1)
return BuildError(id, -32005,
"Multi-monitor hosts are not supported yet (phase 1): monitor count " +
std::to_string(monitorCount));
}
}
// 远程控制复用 Web 的隐藏屏幕子连接(COMMAND_SCREEN_SPY → CScreenSpyDlg → RegisterScreenContext)。
// 该路径依赖 Web 远程服务已启动(WebSvrPort>0,默认开启);未启动时子连接无法建立/注册。
if (!WebService().IsRunning())
return BuildError(id, -32005,
"Remote control requires the Web remote service (WebSvrPort) to be enabled");
// 与人类远程桌面观看互斥:已有屏幕子连接(web 观看)→ 拒绝,避免向人类正在看的画面注入。
if (WebService().HasActiveSession(devId))
return BuildError(id, -32003, "Device busy: a remote desktop session is already active for this host");
int timeoutMs = CMcpServer::Instance().ToolTimeoutMs();
int v = 0;
if (GetIntArg(args, "timeout_ms", v) && v > 0 && v <= 600000) timeoutMs = v;
std::string sessionId = GenerateRandomToken();
if (!mcp.BeginScreenCtrlOpen(devId, sessionId))
return BuildError(id, -32003, "Device busy: a remote control session is already active for this host");
// 建立隐藏屏幕子连接(发 COMMAND_SCREEN_SPY、标记 web-triggered)。
if (!WebService().StartRemoteDesktop(devId)) {
mcp.CloseScreenCtrlSession(devId, sessionId);
// StartRemoteDesktop 先置 web-triggered 再 Send2Client,发送失败需一并清理,
// 否则该设备残留 web-triggered 标记、后续人类 web 观看会误走隐藏会话路径。
WebService().ClearWebTriggered(devId);
return BuildError(id, -32004, "Failed to start remote desktop session");
}
// 轮询等待子连接就绪(HasActiveSession)+ 分辨率到达(TOKEN_BITMAPINFO → NotifyResolutionChange)。
// 屏幕子连接的注册/分辨率由 CScreenSpyDlg 完成,无 McpServer 回调,故用轮询(open 低频)。
int screenW = 0, screenH = 0;
context* subCtx = nullptr;
auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutMs);
bool ready = false;
while (std::chrono::steady_clock::now() < deadline) {
if (WebService().HasActiveSession(devId) && WebService().GetScreenSize(devId, screenW, screenH)) {
subCtx = WebService().GetScreenContext(devId);
ready = (subCtx != nullptr);
break;
}
if (McpCallCancelled()) break; // 按「没就绪」走下面的清理与超时分支
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
if (!ready) {
mcp.CloseScreenCtrlSession(devId, sessionId);
if (parent) parent->CloseWebRemoteDesktopByClientID(devId);
WebService().ClearWebTriggered(devId);
return BuildError(id, -32001, "Timeout waiting for screen sub-connection / resolution");
}
if (!mcp.MarkScreenCtrlReady(devId, sessionId, subCtx, screenW, screenH)) {
// 并发 remote_close 已关掉会话:放弃本次 open(子连接已由 close 关闭)。
return BuildError(id, -32002, "Remote control session was closed concurrently: " + sessionId);
}
// 审计:打开会话(不可关闭)。
if (parent) {
std::string text = "host " + std::to_string(devId) + " remote-open: session " + sessionId
+ " (" + std::to_string(screenW) + "x" + std::to_string(screenH) + ")";
parent->PostMessageA(WM_SHOWERRORMSG,
(WPARAM)new CString(ToAnsi(text, 936).c_str()),
(LPARAM)new CString(_TR("MCP远程控制")));
}
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
structuredContent["session_id"] = sessionId;
structuredContent["screen_w"] = screenW;
structuredContent["screen_h"] = screenH;
result["structuredContent"] = structuredContent;
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = sessionId;
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
// tools/call:remote_close(关闭控制会话;幂等,session_id 不匹配报错)
std::string BuildRemoteClose(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
CMcpServer& mcp = CMcpServer::Instance();
mcp.SweepIdleScreenCtrl(kScreenCtrlIdleTimeoutSec);
if (!mcp.IsRemoteControlEnabled() || mcp.IsReadonly())
return BuildError(id, -32006, "Remote control is disabled: requires McpRemoteControl=1 and McpReadonly=0");
uint64_t devId = 0;
std::string err;
if (!ParseHostIdArg(args, devId, err))
return BuildError(id, -32602, err);
std::string sessionId = GetStringArg(args, "session_id");
if (sessionId.empty())
return BuildError(id, -32602, "Missing required parameter: session_id");
// 关闭前记下是否锁定着对端键鼠:CloseScreenCtrlSession 会强制补发 block=false,
// 审计里必须能看出「这次关闭顺带解了锁」(P10-C)。
const bool wasBlocked = mcp.IsScreenCtrlBlocked(devId, sessionId);
int r = mcp.CloseScreenCtrlSession(devId, sessionId);
if (r == 2)
return BuildError(id, -32002, "Remote control session_id mismatch: " + sessionId);
// 仅当确实关闭了 MCP 会话(r==0)时才关闭隐藏屏幕子连接;r==1(幂等,会话已不存在,
// 如已被 idle 回收)时不得误关人类正在观看的 web 会话(CloseWebRemoteDesktopByClientID
// 会关掉该设备任一 IsWebSession 的对话框)。
if (r == 0) {
// 关闭隐藏屏幕子连接(幂等):WM_CLOSE → CScreenSpyDlg 析构 → UnregisterScreenContext。
if (parent) parent->CloseWebRemoteDesktopByClientID(devId);
WebService().ClearWebTriggered(devId);
}
// 审计:关闭会话(不可关闭)。
if (parent) {
std::string text = "host " + std::to_string(devId) + " remote-close: session " + sessionId;
if (wasBlocked && r == 0) text += " (input lock forced off)";
parent->PostMessageA(WM_SHOWERRORMSG,
(WPARAM)new CString(ToAnsi(text, 936).c_str()),
(LPARAM)new CString(_TR("MCP远程控制")));
}
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
structuredContent["closed"] = true;
result["structuredContent"] = structuredContent;
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = std::string(u8"closed");
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
// ===== P5:remote_keyboard(键盘注入,key_down / key_up / key_press / type)=====
// 键名 → 虚拟键码(对齐 Windows VK_* 去掉前缀,见设计 §4.3)。
// 支持:单字符 A-Z/0-9、F1-F24、命名键、修饰键。未知返回 0(VK 0 非真实键)。
static int MapKeyNameToVk(const std::string& nameIn) {
std::string n;
for (char c : nameIn)
n += (c >= 'a' && c <= 'z') ? (char)(c - 'a' + 'A') : c;
if (n.size() == 1) {
unsigned char c = (unsigned char)n[0];
if (c >= 'A' && c <= 'Z') return c; // 'A'..'Z' == VK_A..VK_Z
if (c >= '0' && c <= '9') return c; // '0'..'9' == VK_0..VK_9
return 0; // 标点等请走 type
}
// F1..F24
if (n.size() >= 2 && n.size() <= 3 && n[0] == 'F') {
int fnum = atoi(n.c_str() + 1);
if (fnum >= 1 && fnum <= 24) return VK_F1 + (fnum - 1);
return 0;
}
struct Named { const char* name; int vk; };
static const Named kNames[] = {
{"ENTER", VK_RETURN}, {"RETURN", VK_RETURN}, {"TAB", VK_TAB}, {"SPACE", VK_SPACE},
{"ESC", VK_ESCAPE}, {"ESCAPE", VK_ESCAPE}, {"BACKSPACE", VK_BACK},
{"DELETE", VK_DELETE}, {"DEL", VK_DELETE}, {"INSERT", VK_INSERT}, {"INS", VK_INSERT},
{"HOME", VK_HOME}, {"END", VK_END}, {"PAGEUP", VK_PRIOR}, {"PRIOR", VK_PRIOR},
{"PAGEDOWN", VK_NEXT}, {"NEXT", VK_NEXT},
{"LEFT", VK_LEFT}, {"RIGHT", VK_RIGHT}, {"UP", VK_UP}, {"DOWN", VK_DOWN},
{"CAPSLOCK", VK_CAPITAL}, {"CAPITAL", VK_CAPITAL}, {"NUMLOCK", VK_NUMLOCK},
{"SCROLLLOCK", VK_SCROLL}, {"PRINTSCREEN", VK_SNAPSHOT}, {"SNAPSHOT", VK_SNAPSHOT},
{"PAUSE", VK_PAUSE}, {"APPS", VK_APPS}, {"CONTEXTMENU", VK_APPS},
{"CTRL", VK_CONTROL}, {"CONTROL", VK_CONTROL}, {"ALT", VK_MENU}, {"MENU", VK_MENU},
{"SHIFT", VK_SHIFT}, {"WIN", VK_LWIN}, {"WINDOWS", VK_LWIN}, {"CMD", VK_LWIN}, {"SUPER", VK_LWIN},
};
for (const Named& e : kNames)
if (n == e.name) return e.vk;
return 0;
}
// 是否修饰键(modifiers 白名单:CTRL/ALT/SHIFT/WIN)
static bool IsModifierVk(int vk) {
return vk == VK_CONTROL || vk == VK_MENU || vk == VK_SHIFT || vk == VK_LWIN || vk == VK_RWIN;
}
// 解析可选 modifiers 数组(JSON 字符串数组)→ 修饰键 VK 序列。非法返回 false 并填 err。
static bool ParseModifiers(const Json::Value& args, std::vector<int>& out, std::string& err) {
out.clear();
if (!args.isMember("modifiers")) return true;
const Json::Value& mods = args["modifiers"];
if (mods.isNull()) return true;
if (!mods.isArray()) { err = "modifiers must be an array of strings"; return false; }
for (const auto& m : mods) {
if (out.size() >= 8) { err = "too many modifiers (max 8)"; return false; }
int vk = MapKeyNameToVk(m.asString());
if (vk == 0 || !IsModifierVk(vk)) {
err = "invalid modifier: " + (m.isString() ? m.asString() : std::string("(non-string)"));
return false;
}
out.push_back(vk);
}
return true;
}
// 是否纯 ASCII(type 走物理键事件,只能可靠注入 ASCII/ANSI;见设计 §6.4)
static bool IsAscii(const std::string& s) {
for (unsigned char c : s) if (c >= 0x80) return false;
return true;
}
// type:逐字符 VkKeyScanA 映射为「(Shift↓)字符↓ 字符↑(Shift↑)」,回车/制表符映射为按键。
// 注:VkKeyScanA 在服务端按服务端线程键盘布局解析字符→虚拟键;仅限 ASCII(0..127)时
// 各布局的字母/数字/常用标点虚拟键一致,跨布局差异可忽略(非 ASCII 一律走剪贴板)。
static void BuildTypeBatch(const std::string& text, std::vector<MSG64>& batch) {
for (unsigned char ch : text) {
if (ch == '\r' || ch == '\n') {
batch.push_back(BuildKeyMsg64(VK_RETURN, true, false));
batch.push_back(BuildKeyMsg64(VK_RETURN, false, false));
continue;
}
if (ch == '\t') {
batch.push_back(BuildKeyMsg64(VK_TAB, true, false));
batch.push_back(BuildKeyMsg64(VK_TAB, false, false));
continue;
}
SHORT scan = VkKeyScanA((char)ch);
if (scan == -1) continue; // 无法映射(控制字符等)→ 跳过
int vk = scan & 0xFF;
bool needShift = (scan >> 8) & 1;
if (needShift) batch.push_back(BuildKeyMsg64(VK_SHIFT, true, false));
batch.push_back(BuildKeyMsg64(vk, true, false));
batch.push_back(BuildKeyMsg64(vk, false, false));
if (needShift) batch.push_back(BuildKeyMsg64(VK_SHIFT, false, false));
}
}
Json::Value BuildRemoteKeyboardInputSchema() {
Json::Value props(Json::objectValue);
Json::Value idProp(Json::objectValue);
idProp["type"] = "string";
idProp["description"] = u8"主机 id,取 list_online_hosts / search_hosts 返回的 id 字段";
props["id"] = idProp;
Json::Value sid(Json::objectValue);
sid["type"] = "string";
sid["description"] = u8"remote_open 返回的 session_id";
props["session_id"] = sid;
Json::Value act(Json::objectValue);
act["type"] = "string";
act["description"] = u8"动作:key_down / key_up / key_press / type";
props["action"] = act;
Json::Value key(Json::objectValue);
key["type"] = "string";
key["description"] = u8"按键(key_down/key_up/key_press 用):Windows 虚拟键名(如 ENTER/TAB/F5/LEFT/CTRL/ALT/SHIFT/WIN)或单个字母/数字";
props["key"] = key;
Json::Value text(Json::objectValue);
text["type"] = "string";
text["description"] = u8"文本(type 用,仅 ASCII;非 ASCII 请走 remote_clipboard + Ctrl+V)";
props["text"] = text;
Json::Value mods(Json::objectValue);
mods["type"] = "array";
Json::Value modItem(Json::objectValue);
modItem["type"] = "string";
mods["items"] = modItem;
mods["description"] = u8"修饰键(可选):CTRL/ALT/SHIFT/WIN";
props["modifiers"] = mods;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("id");
required.append("session_id");
required.append("action");
schema["required"] = required;
return schema;
}
Json::Value BuildRemoteKeyboardOutputSchema() {
Json::Value props(Json::objectValue);
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
return schema;
}
// 下发一批输入事件:每条 MSG64 单独一包([COMMAND_SCREEN_CONTROL][MSG64])。
// 协议上本可一包多条,但 Linux 客户端(ScreenHandler::OnReceive)只处理包内第一条,
// 多消息批量会让 key_press 只剩按下(触发键盘自动重复)、click 只剩按下、type 只打出
// 首字符。按消息拆包对 Windows 客户端完全等价(它本来就一次处理一条),且新老客户端
// 行为一致,故不改客户端。任一条发送失败即返回 false。
static bool SendScreenCtrlEvents(context* subCtx, const std::vector<MSG64>& batch) {
std::vector<BYTE> packet(1 + sizeof(MSG64));
packet[0] = COMMAND_SCREEN_CONTROL;
for (size_t i = 0; i < batch.size(); ++i) {
memcpy(packet.data() + 1, &batch[i], sizeof(MSG64));
if (!subCtx->Send2Client(packet.data(), (ULONG)packet.size()))
return false;
}
return true;
}
// tools/call:remote_keyboard(键盘注入;成功返回空对象)
std::string BuildRemoteKeyboard(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
CMcpServer& mcp = CMcpServer::Instance();
mcp.SweepIdleScreenCtrl(kScreenCtrlIdleTimeoutSec);
uint64_t devId = 0;
context* ctx = nullptr;
std::string errJson;
if (!ResolveScreenCtrlSessionHost(id, args, parent, devId, ctx, errJson))
return errJson;
std::string sessionId = GetStringArg(args, "session_id");
if (sessionId.empty())
return BuildError(id, -32602, "Missing required parameter: session_id");
std::string action = GetStringArg(args, "action");
if (action.empty())
return BuildError(id, -32602, "Missing required parameter: action");
std::string keyName = GetStringArg(args, "key");
std::string text = GetStringArg(args, "text");
std::vector<int> mods;
{
std::string mErr;
if (!ParseModifiers(args, mods, mErr))
return BuildError(id, -32602, mErr);
}
// 组装注入批次(按发送顺序)
std::vector<MSG64> batch;
if (action == "type") {
if (text.empty())
return BuildError(id, -32602, "Missing required parameter: text");
if (!IsAscii(text))
return BuildError(id, -32602, "text must be ASCII; non-ASCII text requires remote_clipboard + Ctrl+V");
if (text.size() > 1024)
return BuildError(id, -32602, "text too long (max 1024 bytes); use remote_clipboard + Ctrl+V for long text");
BuildTypeBatch(text, batch);
} else if (action == "key_down" || action == "key_up" || action == "key_press") {
if (keyName.empty())
return BuildError(id, -32602, "Missing required parameter: key");
int keyVk = MapKeyNameToVk(keyName);
if (keyVk == 0)
return BuildError(id, -32602, "Unknown key: " + keyName);
bool doDown = (action != "key_up");
bool doUp = (action != "key_down");
if (doDown) {
for (int m : mods) batch.push_back(BuildKeyMsg64(m, true, false));
batch.push_back(BuildKeyMsg64(keyVk, true, false));
}
if (doUp) {
batch.push_back(BuildKeyMsg64(keyVk, false, false));
for (auto it = mods.rbegin(); it != mods.rend(); ++it)
batch.push_back(BuildKeyMsg64(*it, false, false));
}
} else {
return BuildError(id, -32602, "Unknown action: " + action);
}
if (batch.empty())
return BuildError(id, -32602, "No key events generated");
// 校验 session_id/busy 并置 busy(注入期间 close/sweep/断线不擦会话,镜像终端 busy 模式)。
context* subCtx = nullptr;
int screenW = 0, screenH = 0;
int r = mcp.BeginScreenCtrlAction(devId, sessionId, subCtx, screenW, screenH);
if (r == 2) return BuildError(id, -32003, "Device busy: another injection is in flight for this session");
if (r == 1) return BuildError(id, -32002, "Remote control session not found, not ready, or closed: " + sessionId);
bool ok = SendScreenCtrlEvents(subCtx, batch);
mcp.EndScreenCtrlAction(devId, sessionId);
if (!ok)
return BuildError(id, -32004, "Failed to send keyboard injection");
// 审计(不可关闭)
if (parent) {
std::string audit = "host " + std::to_string(devId) + " remote-keyboard: session " + sessionId
+ " action=" + action;
if (action == "type") audit += " text=" + text;
else audit += " key=" + keyName;
parent->PostMessageA(WM_SHOWERRORMSG,
(WPARAM)new CString(ToAnsi(audit, 936).c_str()),
(LPARAM)new CString(_TR("MCP远程控制")));
}
Json::Value result(Json::objectValue);
result["structuredContent"] = Json::Value(Json::objectValue);
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = std::string(u8"ok");
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
// ===== P5:remote_mouse(鼠标注入,move/down/up/click/right_click/middle_click/drag/scroll)=====
// 读取归一化坐标(0..1 浮点,接受 JSON number 或数字字符串),越界钳到 [0,1]。
static bool GetNormCoord(const Json::Value& args, const char* key, double& out, std::string& err) {
if (!args.isMember(key)) { err = std::string("Missing required parameter: ") + key; return false; }
const Json::Value& v = args[key];
if (v.isNumeric()) {
out = v.asDouble();
} else if (v.isString()) {
const std::string s = v.asString();
if (s.empty()) { err = std::string("Invalid ") + key + ": expected a number in 0..1"; return false; }
char* end = nullptr;
double d = strtod(s.c_str(), &end);
if (end == s.c_str() || *end != '\0') { err = std::string("Invalid ") + key + ": expected a number in 0..1"; return false; }
out = d;
} else {
err = std::string("Invalid ") + key + ": expected a number in 0..1";
return false;
}
if (out != out) { // NaN(如字符串 "nan")会绕过钳制并令 (int)(n*screen) 未定义行为
err = std::string("Invalid ") + key + ": not a finite number";
return false;
}
if (out < 0.0) out = 0.0;
if (out > 1.0) out = 1.0;
return true;
}
// button 字符串 → 0=左/1=中/2=右;空或 left 默认左。
static bool ParseButton(const std::string& s, int& out) {
if (s.empty() || s == "left") { out = 0; return true; }
if (s == "middle") { out = 1; return true; }
if (s == "right") { out = 2; return true; }
return false;
}
// button → 按下/抬起消息 + 按下 wParam(对齐 WebService::HandleMouse)。
static void ButtonMessages(int button, UINT& downMsg, UINT& upMsg, uint64_t& downWParam) {
if (button == 1) { downMsg = WM_MBUTTONDOWN; upMsg = WM_MBUTTONUP; downWParam = MK_MBUTTON; }
else if (button == 2) { downMsg = WM_RBUTTONDOWN; upMsg = WM_RBUTTONUP; downWParam = MK_RBUTTON; }
else { downMsg = WM_LBUTTONDOWN; upMsg = WM_LBUTTONUP; downWParam = MK_LBUTTON; }
}
Json::Value BuildRemoteMouseInputSchema() {
Json::Value props(Json::objectValue);
Json::Value idProp(Json::objectValue);
idProp["type"] = "string";
idProp["description"] = u8"主机 id,取 list_online_hosts / search_hosts 返回的 id 字段";
props["id"] = idProp;
Json::Value sid(Json::objectValue);
sid["type"] = "string";
sid["description"] = u8"remote_open 返回的 session_id";
props["session_id"] = sid;
Json::Value act(Json::objectValue);
act["type"] = "string";
act["description"] = u8"动作:move / down / up / click / right_click / middle_click / drag / scroll";
Json::Value actEnum(Json::arrayValue);
actEnum.append("move"); actEnum.append("down"); actEnum.append("up"); actEnum.append("click");
actEnum.append("right_click"); actEnum.append("middle_click"); actEnum.append("drag"); actEnum.append("scroll");
act["enum"] = actEnum;
props["action"] = act;
Json::Value xProp(Json::objectValue);
xProp["type"] = "number";
xProp["description"] = u8"归一化 X 坐标(0=屏幕最左,1=最右)";
props["x"] = xProp;
Json::Value yProp(Json::objectValue);
yProp["type"] = "number";
yProp["description"] = u8"归一化 Y 坐标(0=屏幕最上,1=最下)";
props["y"] = yProp;
Json::Value x2Prop(Json::objectValue);
x2Prop["type"] = "number";
x2Prop["description"] = u8"拖拽终点 X(仅 drag)";
props["x2"] = x2Prop;
Json::Value y2Prop(Json::objectValue);
y2Prop["type"] = "number";
y2Prop["description"] = u8"拖拽终点 Y(仅 drag)";
props["y2"] = y2Prop;
Json::Value btn(Json::objectValue);
btn["type"] = "string";
btn["description"] = u8"按键:left / middle / right(默认 left)";
Json::Value btnEnum(Json::arrayValue);
btnEnum.append("left"); btnEnum.append("middle"); btnEnum.append("right");
btn["enum"] = btnEnum;
props["button"] = btn;
Json::Value clk(Json::objectValue);
clk["type"] = "integer";
clk["description"] = u8"点击次数 1/2/3(仅 click,默认 1)";
props["clicks"] = clk;
Json::Value del(Json::objectValue);
del["type"] = "integer";
del["description"] = u8"滚动量(仅 scroll;正=向下滚,负=向上滚,与 Web 控制台一致;仅垂直滚轮,忽略 button)";
props["delta"] = del;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("id");
required.append("session_id");
required.append("action");
required.append("x");
required.append("y");
schema["required"] = required;
return schema;
}
Json::Value BuildRemoteMouseOutputSchema() {
Json::Value props(Json::objectValue);
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
return schema;
}
// tools/call:remote_mouse(鼠标注入;归一化坐标 → 物理像素)
std::string BuildRemoteMouse(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
CMcpServer& mcp = CMcpServer::Instance();
mcp.SweepIdleScreenCtrl(kScreenCtrlIdleTimeoutSec);
uint64_t devId = 0;
context* ctx = nullptr;
std::string errJson;
if (!ResolveScreenCtrlSessionHost(id, args, parent, devId, ctx, errJson))
return errJson;
std::string sessionId = GetStringArg(args, "session_id");
if (sessionId.empty())
return BuildError(id, -32602, "Missing required parameter: session_id");
std::string action = GetStringArg(args, "action");
if (action.empty())
return BuildError(id, -32602, "Missing required parameter: action");
// ---- 纯参数解析(不依赖会话分辨率;BeginScreenCtrlAction 之后再无提前返回)----
bool knownAction =
action == "move" || action == "down" || action == "up" || action == "click" ||
action == "right_click" || action == "middle_click" || action == "drag" || action == "scroll";
if (!knownAction)
return BuildError(id, -32602, "Unknown action: " + action);
int button = 0;
std::string buttonStr = GetStringArg(args, "button");
if (!ParseButton(buttonStr, button))
return BuildError(id, -32602, "Invalid button: " + buttonStr + " (expected left/middle/right)");
int clicks = 1;
if (args.isMember("clicks")) {
if (!GetIntArg(args, "clicks", clicks))
return BuildError(id, -32602, "clicks must be an integer 1..3");
if (clicks < 1 || clicks > 3)
return BuildError(id, -32602, "clicks must be 1, 2 or 3");
}
int delta = 0;
if (args.isMember("delta") && !GetIntArg(args, "delta", delta))
return BuildError(id, -32602, "delta must be an integer");
int notches = 0; // scroll 实际注入的滚动档数(= clamp(delta, -10, 10)),审计用
double nx = 0, ny = 0, nx2 = 0, ny2 = 0;
std::string coordErr;
if (!GetNormCoord(args, "x", nx, coordErr)) return BuildError(id, -32602, coordErr);
if (!GetNormCoord(args, "y", ny, coordErr)) return BuildError(id, -32602, coordErr);
if (action == "drag") {
if (!GetNormCoord(args, "x2", nx2, coordErr)) return BuildError(id, -32602, coordErr);
if (!GetNormCoord(args, "y2", ny2, coordErr)) return BuildError(id, -32602, coordErr);
}
// 校验 session_id/busy 并置 busy,同时取物理分辨率(screenW/H>0 由会话就绪保证)。
context* subCtx = nullptr;
int screenW = 0, screenH = 0;
int r = mcp.BeginScreenCtrlAction(devId, sessionId, subCtx, screenW, screenH);
if (r == 2) return BuildError(id, -32003, "Device busy: another injection is in flight for this session");
if (r == 1) return BuildError(id, -32002, "Remote control session not found, not ready, or closed: " + sessionId);
// 归一化坐标 → 物理像素(round + clamp 到 [0, screen-1])
auto toPxX = [&](double n) -> int { int p = (int)(n * screenW + 0.5); return p < 0 ? 0 : (p > screenW - 1 ? screenW - 1 : p); };
auto toPxY = [&](double n) -> int { int p = (int)(n * screenH + 0.5); return p < 0 ? 0 : (p > screenH - 1 ? screenH - 1 : p); };
int px = toPxX(nx), py = toPxY(ny);
int px2 = 0, py2 = 0;
UINT downMsg, upMsg; uint64_t downWParam;
ButtonMessages(button, downMsg, upMsg, downWParam);
// 组装注入批次(按发送顺序;每个 MSG64 由客户端 ProcessCommand 分发到 SendInput)
std::vector<MSG64> batch;
if (action == "move") {
batch.push_back(BuildMouseMsg64(px, py, WM_MOUSEMOVE, 0));
} else if (action == "down") {
batch.push_back(BuildMouseMsg64(px, py, downMsg, downWParam));
} else if (action == "up") {
batch.push_back(BuildMouseMsg64(px, py, upMsg, 0));
} else if (action == "click" || action == "right_click" || action == "middle_click") {
int b = (action == "right_click") ? 2 : (action == "middle_click" ? 1 : button);
UINT dMsg, uMsg; uint64_t dW;
ButtonMessages(b, dMsg, uMsg, dW);
for (int i = 0; i < clicks; ++i) {
batch.push_back(BuildMouseMsg64(px, py, dMsg, dW));
batch.push_back(BuildMouseMsg64(px, py, uMsg, 0));
}
} else if (action == "drag") {
px2 = toPxX(nx2); py2 = toPxY(ny2);
batch.push_back(BuildMouseMsg64(px, py, downMsg, downWParam));
batch.push_back(BuildMouseMsg64(px2, py2, WM_MOUSEMOVE, 0));
batch.push_back(BuildMouseMsg64(px2, py2, upMsg, 0));
} else if (action == "scroll") {
// delta 正=向下滚(与 Web 控制台一致);WM_MOUSEWHEEL 负值=向下滚,故取反。
// 客户端对 WM_MOUSEWHEEL 会先 SetCursorPos(x,y) 再 MOUSEEVENTF_WHEEL,单条消息即可定位+滚动。
notches = delta;
if (notches > 10) notches = 10;
if (notches < -10) notches = -10;
short wheelDelta = (short)(-notches * 120);
batch.push_back(BuildMouseMsg64(px, py, WM_MOUSEWHEEL, MAKEWPARAM(0, wheelDelta)));
}
bool ok = SendScreenCtrlEvents(subCtx, batch);
mcp.EndScreenCtrlAction(devId, sessionId);
if (!ok)
return BuildError(id, -32004, "Failed to send mouse injection");
// 审计(不可关闭;含归一化坐标与换算后的物理像素)
if (parent) {
std::string audit = "host " + std::to_string(devId) + " remote-mouse: session " + sessionId
+ " action=" + action;
char cbuf[96];
sprintf(cbuf, " norm=(%.3f,%.3f) px=(%d,%d)", nx, ny, px, py);
audit += cbuf;
if (action == "drag") {
sprintf(cbuf, " -> norm2=(%.3f,%.3f) px2=(%d,%d)", nx2, ny2, px2, py2);
audit += cbuf;
}
if (action == "scroll")
audit += " notches=" + std::to_string(notches);
if (action == "click" || action == "right_click" || action == "middle_click")
audit += " clicks=" + std::to_string(clicks);
parent->PostMessageA(WM_SHOWERRORMSG,
(WPARAM)new CString(ToAnsi(audit, 936).c_str()),
(LPARAM)new CString(_TR("MCP远程控制")));
}
Json::Value result(Json::objectValue);
result["structuredContent"] = Json::Value(Json::objectValue);
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = std::string(u8"ok");
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
// ===== P5:remote_clipboard(写远程剪贴板,UTF-8 → GBK 直发,见设计 §6.4)=====
Json::Value BuildRemoteClipboardInputSchema() {
Json::Value props(Json::objectValue);
Json::Value idProp(Json::objectValue);
idProp["type"] = "string";
idProp["description"] = u8"主机 id,取 list_online_hosts / search_hosts 返回的 id 字段";
props["id"] = idProp;
Json::Value sid(Json::objectValue);
sid["type"] = "string";
sid["description"] = u8"remote_open 返回的 session_id";
props["session_id"] = sid;
Json::Value text(Json::objectValue);
text["type"] = "string";
text["description"] = u8"要写入剪贴板的文本(UTF-8;非 GBK 字符如 emoji 会丢失)";
props["text"] = text;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("id");
required.append("session_id");
required.append("text");
schema["required"] = required;
return schema;
}
Json::Value BuildRemoteClipboardOutputSchema() {
Json::Value props(Json::objectValue);
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
return schema;
}
// tools/call:remote_clipboard(写远程剪贴板;成功返回空对象)
std::string BuildRemoteClipboard(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
CMcpServer& mcp = CMcpServer::Instance();
mcp.SweepIdleScreenCtrl(kScreenCtrlIdleTimeoutSec);
uint64_t devId = 0;
context* ctx = nullptr;
std::string errJson;
if (!ResolveScreenCtrlSessionHost(id, args, parent, devId, ctx, errJson))
return errJson;
std::string sessionId = GetStringArg(args, "session_id");
if (sessionId.empty())
return BuildError(id, -32602, "Missing required parameter: session_id");
std::string text = GetStringArg(args, "text");
if (text.empty())
return BuildError(id, -32602, "Missing required parameter: text");
if (text.size() > 262144) // 256 KB 上限(CF_TEXT 单包,防内存/传输失控)
return BuildError(id, -32602, "text too long (max 262144 bytes)");
// UTF-8 → GBK:客户端 UpdateClientClipboard 以 CF_TEXT(ANSI/GBK)落剪贴板(设计 §6.4)。
// 非 GBK 字符(emoji 等)在此被替换为 '?',MVP 已知限制。
std::string ansi = ToAnsi(text, 936);
// 校验 session_id/busy 并置 busy,取屏幕子连接(注入与剪贴板共用同一子连接串行化)。
context* subCtx = nullptr;
int screenW = 0, screenH = 0;
int r = mcp.BeginScreenCtrlAction(devId, sessionId, subCtx, screenW, screenH);
if (r == 2) return BuildError(id, -32003, "Device busy: another injection is in flight for this session");
if (r == 1) return BuildError(id, -32002, "Remote control session not found, not ready, or closed: " + sessionId);
// 组包 [COMMAND_SCREEN_SET_CLIPBOARD][GBK text],经屏幕子连接发送(客户端自行补 '\0')。
const int len = (int)(1 + ansi.size());
std::vector<BYTE> packet((size_t)len);
packet[0] = COMMAND_SCREEN_SET_CLIPBOARD;
memcpy(packet.data() + 1, ansi.data(), ansi.size());
bool ok = subCtx->Send2Client(packet.data(), (ULONG)len) != FALSE;
mcp.EndScreenCtrlAction(devId, sessionId);
if (!ok)
return BuildError(id, -32004, "Failed to send clipboard text");
// 审计(不可关闭;记字节数,不落全文以免审计日志膨胀)
if (parent) {
std::string audit = "host " + std::to_string(devId) + " remote-clipboard: session " + sessionId
+ " input_bytes=" + std::to_string(text.size());
parent->PostMessageA(WM_SHOWERRORMSG,
(WPARAM)new CString(ToAnsi(audit, 936).c_str()),
(LPARAM)new CString(_TR("MCP远程控制")));
}
Json::Value result(Json::objectValue);
result["structuredContent"] = Json::Value(Json::objectValue);
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = std::string(u8"ok");
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
// ===== P10-C:remote_block_input(锁定/解除对端键鼠;零客户端改动)=====
//
// 报文与 MFC 端 IDM_BLOCK_INPUT 完全一致:[COMMAND_SCREEN_BLOCK_INPUT][0|1](2 字节,
// 见 client/ScreenManager.cpp:1198)。客户端把 byte[1] 存进 m_bIsBlockInput 并调用
// BlockInput(),此后真人的键鼠到不了桌面——这是「把人锁在电脑外」的能力,故门控紧跟
// remote_open(McpRemoteControl=1 且 McpReadonly=0),且三条解除路径缺一不可:
// 1) 工具显式 block=false;
// 2) 超过 max_block_ms 由看门狗自动解除(下一次结果里以 auto_unblocked 上报);
// 3) remote_close / idle 回收前强制补发 block=false(见 CloseScreenCtrlSession 等)。
// 子连接彻底断开(客户端掉线)时服务端已无从下发,只能指望客户端进程退出——
// BlockInput 在调用线程退出时自动解除,这是既有局限,工具描述里写明。
// 锁定报文(2 字节):byte[1] = 1 锁定 / 0 解除。与 MFC 端 bToken 逐字节一致。
static bool SendScreenBlockInput(context* subCtx, bool block) {
if (!subCtx) return false;
BYTE packet[2];
packet[0] = (BYTE)COMMAND_SCREEN_BLOCK_INPUT;
packet[1] = block ? 1 : 0;
return subCtx->Send2Client(packet, sizeof(packet)) != FALSE;
}
const int kBlockInputDefaultMaxMs = 300000; // 默认 5 分钟自动解除
const int kBlockInputMinMs = 1000;
const int kBlockInputMaxMs = 3600000; // 1 小时上限:再长就该用别的方式
Json::Value BuildRemoteBlockInputInputSchema() {
Json::Value props(Json::objectValue);
Json::Value idProp(Json::objectValue);
idProp["type"] = "string";
idProp["description"] = u8"主机 id,取 list_online_hosts / search_hosts 返回的 id 字段";
props["id"] = idProp;
Json::Value sid(Json::objectValue);
sid["type"] = "string";
sid["description"] = u8"remote_open 返回的 session_id";
props["session_id"] = sid;
Json::Value block(Json::objectValue);
block["type"] = "boolean";
block["description"] = u8"true=锁定对端键鼠,false=解除。必填(没有默认值,避免误锁)";
props["block"] = block;
Json::Value maxMs(Json::objectValue);
maxMs["type"] = "integer";
maxMs["description"] = u8"锁定自动解除期限(毫秒),仅 block=true 时有效;默认 300000,范围 1000..3600000。"
u8"到期由服务端强制解除并记入下一次结果的 auto_unblocked";
props["max_block_ms"] = maxMs;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("id");
required.append("session_id");
required.append("block");
schema["required"] = required;
return schema;
}
Json::Value BuildRemoteBlockInputOutputSchema() {
Json::Value props(Json::objectValue);
Json::Value blocked(Json::objectValue);
blocked["type"] = "boolean";
blocked["description"] = u8"本次调用后的锁定状态";
props["blocked"] = blocked;
Json::Value maxMs(Json::objectValue);
maxMs["type"] = "integer";
maxMs["description"] = u8"本次锁定的自动解除期限(毫秒);blocked=false 时为 0(无待解除的锁定)";
props["max_block_ms"] = maxMs;
Json::Value autoUnblocked(Json::objectValue);
autoUnblocked["type"] = "boolean";
autoUnblocked["description"] = u8"上一次锁定是否因超过 max_block_ms 被服务端自动解除(本次调用取走该通知)";
props["auto_unblocked"] = autoUnblocked;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("blocked");
required.append("max_block_ms");
required.append("auto_unblocked");
schema["required"] = required;
return schema;
}
// tools/call:remote_block_input(锁定/解除对端键鼠)
std::string BuildRemoteBlockInput(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
CMcpServer& mcp = CMcpServer::Instance();
mcp.SweepIdleScreenCtrl(kScreenCtrlIdleTimeoutSec);
uint64_t devId = 0;
context* ctx = nullptr;
std::string errJson;
if (!ResolveScreenCtrlSessionHost(id, args, parent, devId, ctx, errJson))
return errJson;
// Linux/Android 客户端根本没有 COMMAND_SCREEN_BLOCK_INPUT 分支(静默忽略),只做报文的
// 服务端不做「发了就算成功」的假动作——直接报不支持(能力限制,非参数错误)。
if (!IsWindowsClient(ctx))
return BuildError(id, -32005, "remote_block_input is only supported on Windows hosts");
std::string sessionId = GetStringArg(args, "session_id");
if (sessionId.empty())
return BuildError(id, -32602, "Missing required parameter: session_id");
// block 必须显式给:缺省按 true 会「默默锁住」对端,缺省按 false 又会让模型以为锁上了。
if (!args.isMember("block"))
return BuildError(id, -32602, "Missing required parameter: block");
const Json::Value& blockArg = args["block"];
bool block = false;
if (blockArg.isBool()) {
block = blockArg.asBool();
} else if (blockArg.isNumeric()) {
block = blockArg.asInt() != 0;
} else if (blockArg.isString()) {
const std::string s = blockArg.asString();
if (s == "true" || s == "1") block = true;
else if (s == "false" || s == "0") block = false;
else return BuildError(id, -32602, "Invalid parameter 'block': expected true or false");
} else {
return BuildError(id, -32602, "Invalid parameter 'block': expected true or false");
}
int maxBlockMs = kBlockInputDefaultMaxMs;
if (args.isMember("max_block_ms")) {
if (!GetIntArg(args, "max_block_ms", maxBlockMs))
return BuildError(id, -32602, "max_block_ms must be an integer");
if (maxBlockMs < kBlockInputMinMs || maxBlockMs > kBlockInputMaxMs)
return BuildError(id, -32602, "max_block_ms out of range (1000..3600000)");
}
context* subCtx = nullptr;
int screenW = 0, screenH = 0;
int r = mcp.BeginScreenCtrlAction(devId, sessionId, subCtx, screenW, screenH);
if (r == 2) return BuildError(id, -32003, "Device busy: another injection is in flight for this session");
if (r == 1) return BuildError(id, -32002, "Remote control session not found, not ready, or closed: " + sessionId);
// 先发报文再改状态:发不出去就不能声称锁上了(状态保持原样,看门狗仍按旧期限兜底)。
const bool ok = SendScreenBlockInput(subCtx, block);
bool autoUnblocked = false;
bool stateOk = false;
if (ok) stateOk = mcp.ScreenCtrlSetBlock(devId, sessionId, block, maxBlockMs, autoUnblocked);
mcp.EndScreenCtrlAction(devId, sessionId);
if (!ok)
return BuildError(id, -32004, "Failed to send block-input command");
if (!stateOk)
return BuildError(id, -32002, "Remote control session was closed concurrently: " + sessionId);
// 审计(不可关闭):锁定/解锁都是安全事件,记期限与自动解除标记。
if (parent) {
std::string audit = "host " + std::to_string(devId) + " remote-block-input: session " + sessionId;
audit += block ? (" block=true max_ms=" + std::to_string(maxBlockMs)) : std::string(" block=false");
if (autoUnblocked) audit += " (previous block auto-released)";
parent->PostMessageA(WM_SHOWERRORMSG,
(WPARAM)new CString(ToAnsi(audit, 936).c_str()),
(LPARAM)new CString(_TR("MCP远程控制")));
}
Json::Value structured(Json::objectValue);
structured["blocked"] = block;
structured["max_block_ms"] = block ? maxBlockMs : 0;
structured["auto_unblocked"] = autoUnblocked;
Json::Value result(Json::objectValue);
result["structuredContent"] = structured;
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
std::string text = block ? "blocked" : "unblocked";
if (autoUnblocked) text += " (previous block had auto-released)";
item["text"] = text;
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
// ===== P6:download_file 辅助 =====
// SHA-256 摘要转小写 hex(32 字节 → 64 字符)
std::string Sha256Hex(const uint8_t* b, size_t n) {
static const char hex[] = "0123456789abcdef";
std::string out;
out.reserve(n * 2);
for (size_t i = 0; i < n; ++i) {
out += hex[b[i] >> 4];
out += hex[b[i] & 0xF];
}
return out;
}
// 逐层创建目录(Windows 盘符路径;失败返回 false)。
bool EnsureDirA(const std::string& path) {
std::string current;
for (size_t i = 0; i < path.size(); ++i) {
current += path[i];
if (path[i] == '\\' || path[i] == '/' || i + 1 == path.size()) {
if (current.size() == 2 && current[1] == ':') continue; // 跳过盘符 "C:"
if (GetFileAttributesA(current.c_str()) == INVALID_FILE_ATTRIBUTES) {
if (!CreateDirectoryA(current.c_str(), nullptr) &&
GetLastError() != ERROR_ALREADY_EXISTS) {
return false;
}
}
}
}
return GetFileAttributesA(path.c_str()) != INVALID_FILE_ATTRIBUTES;
}
// 把 UTF-8 local_dir 转为 ANSI 绝对路径(结尾 '\'),并创建目录。失败返回 false 并写 err。
bool NormalizeLocalDir(const std::string& utf8, std::string& ansiOut, std::string& err) {
if (utf8.empty()) { err = "Missing required parameter: local_dir"; return false; }
std::string ansi = ToAnsi(utf8, CP_ACP);
if (ansi.empty()) { err = "Invalid local_dir encoding"; return false; }
char full[MAX_PATH];
DWORD n = GetFullPathNameA(ansi.c_str(), MAX_PATH, full, nullptr);
if (n == 0 || n >= MAX_PATH) { err = "Invalid local_dir: " + utf8; return false; }
std::string dir = full;
while (!dir.empty() && (dir.back() == '\\' || dir.back() == '/')) dir.pop_back();
if (dir.size() == 2 && dir[1] == ':') { err = "Invalid local_dir: " + utf8; return false; }
if (!EnsureDirA(dir)) { err = "Failed to create local_dir: " + utf8; return false; }
ansiOut = dir + "\\";
return true;
}
// 防路径穿越:fullPath 规范化后必须位于 baseDir 内(含 baseDir 本身)。
bool PathWithinDirA(const std::string& baseDir, const std::string& fullPath) {
char baseFull[MAX_PATH], pathFull[MAX_PATH];
if (!GetFullPathNameA(baseDir.c_str(), MAX_PATH, baseFull, nullptr)) return false;
if (!GetFullPathNameA(fullPath.c_str(), MAX_PATH, pathFull, nullptr)) return false;
for (char* p = baseFull; *p; ++p) { if (*p == '/') *p = '\\'; else if (*p >= 'A' && *p <= 'Z') *p = (char)(*p - 'A' + 'a'); }
for (char* p = pathFull; *p; ++p) { if (*p == '/') *p = '\\'; else if (*p >= 'A' && *p <= 'Z') *p = (char)(*p - 'A' + 'a'); }
size_t bl = strlen(baseFull);
while (bl > 0 && baseFull[bl - 1] == '\\') --bl;
if (bl == 0) return true; // 根目录
if (strncmp(pathFull, baseFull, bl) != 0) return false;
return pathFull[bl] == '\\' || pathFull[bl] == '\0';
}
Json::Value BuildDownloadFileInputSchema() {
Json::Value props(Json::objectValue);
Json::Value idProp(Json::objectValue);
idProp["type"] = "string";
idProp["description"] = u8"主机 id,取 list_online_hosts / search_hosts 返回的 id 字段";
props["id"] = idProp;
Json::Value rp(Json::objectValue);
rp["type"] = "string";
rp["description"] = u8"远程绝对路径(文件或目录;目录递归下载)。Windows 主机用 C:\\Users\\foo\\Pictures,Linux/macOS 主机用 /home/user/data 这类绝对 POSIX 路径";
props["remote_path"] = rp;
Json::Value ld(Json::objectValue);
ld["type"] = "string";
ld["description"] = u8"主控本机保存目录(不存在则自动创建),如 C:\\Downloads";
props["local_dir"] = ld;
Json::Value ow(Json::objectValue);
ow["type"] = "boolean";
ow["description"] = u8"是否覆盖已存在的同名文件;默认 false(跳过并计入 skipped)";
props["overwrite"] = ow;
Json::Value to(Json::objectValue);
to["type"] = "integer";
to["description"] = u8"超时毫秒(默认 600000=10 分钟,上限 3600000=1 小时)";
props["timeout_ms"] = to;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("id");
required.append("remote_path");
required.append("local_dir");
schema["required"] = required;
return schema;
}
Json::Value BuildDownloadFileOutputSchema() {
Json::Value props(Json::objectValue);
Json::Value filesProp(Json::objectValue);
filesProp["type"] = "array";
Json::Value items(Json::objectValue);
items["type"] = "object";
Json::Value itemProps(Json::objectValue);
Json::Value pathProp(Json::objectValue); pathProp["type"] = "string"; itemProps["path"] = pathProp;
Json::Value sizeProp(Json::objectValue); sizeProp["type"] = "integer"; itemProps["size"] = sizeProp;
Json::Value shaProp(Json::objectValue); shaProp["type"] = "string"; itemProps["sha256"] = shaProp;
items["properties"] = itemProps;
filesProp["items"] = items;
props["files"] = filesProp;
Json::Value tb(Json::objectValue); tb["type"] = "integer"; props["total_bytes"] = tb;
Json::Value sk(Json::objectValue); sk["type"] = "integer"; props["skipped"] = sk;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
return schema;
}
// 词法检查路径是否含 ".." 段(定义在下方 upload_file 辅助区;download_file 先用)。
static bool HasDotDotSegment(const std::string& path);
// tools/call:download_file(下载远程文件/目录到本机,V2 协议)
std::string BuildDownloadFile(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
// 分派门控(独立开关 McpFileTransfer,不要求 McpReadonly=0):即便绕过 tools/list 直调也拒绝。
if (!CMcpServer::Instance().IsFileTransferEnabled())
return BuildError(id, -32006, "File transfer is disabled: requires McpFileTransfer=1");
uint64_t devId = 0;
std::string err;
if (!ParseHostIdArg(args, devId, err))
return BuildError(id, -32602, err);
context* ctx = FindMainContext(parent, devId);
if (!ctx)
return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId));
// 目标端类型决定 remote_path 的写法:Windows 用盘符路径,LNX/MAC 用绝对 POSIX 路径。
// LNX/MAC 走 common/FileManager.h 里同一套 CMD_DOWN_FILES_V2(V2 发送器)。
CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
const bool posixTarget = (clientType == "LNX" || clientType == "MAC");
// 客户端须支持 V2 文件传输(否则 CMD_DOWN_FILES_V2 会被静默忽略 → 超时)。
if (!ctx->SupportsFileV2())
return BuildError(id, -32006, "Host does not support V2 file transfer");
std::string remotePathUtf8 = GetStringArg(args, "remote_path");
if (remotePathUtf8.empty())
return BuildError(id, -32602, "Missing required parameter: remote_path");
std::string localDirUtf8 = GetStringArg(args, "local_dir");
if (localDirUtf8.empty())
return BuildError(id, -32602, "Missing required parameter: local_dir");
bool overwrite = false;
if (args.isMember("overwrite") && args["overwrite"].isBool())
overwrite = args["overwrite"].asBool();
int timeoutMs = 600000;
if (args.isMember("timeout_ms")) {
int v = 0;
if (!GetIntArg(args, "timeout_ms", v) || v <= 0 || v > 3600000)
return BuildError(id, -32602, "timeout_ms must be in range 1..3600000");
timeoutMs = v;
}
// 本机保存目录:UTF-8 → ANSI 绝对路径(结尾 '\'),并创建。
std::string localDirAnsi;
if (!NormalizeLocalDir(localDirUtf8, localDirAnsi, err))
return BuildError(id, -32602, err);
// 远程路径:UTF-8 → 客户端 ANSI(Windows=936,与 list_files 一致)。
std::string remotePathAnsi = ToAnsi(remotePathUtf8, 936);
if (remotePathAnsi.empty())
return BuildError(id, -32602, "Invalid remote_path encoding");
// POSIX 端 WinPathToLinux 会把 "C:\x" 去盘符改写成 "/x",静默落到别处,
// 所以非 Windows 目标必须先按 POSIX 形态校验(\ 会被客户端归一化成 /,语义会漂)。
if (posixTarget) {
if (remotePathAnsi[0] != '/')
return BuildError(id, -32602, "remote_path must be an absolute POSIX path for Linux/macOS hosts, e.g. /home/user/file.txt");
if (remotePathAnsi.find('\\') != std::string::npos)
return BuildError(id, -32602, "remote_path must not contain backslashes on Linux/macOS hosts; use '/'");
if (HasDotDotSegment(remotePathAnsi))
return BuildError(id, -32602, "remote_path must not contain '..' path segments");
}
CMcpServer& mcp = CMcpServer::Instance();
if (!mcp.BeginFileTransferPending(devId, "download_file", localDirAnsi, remotePathAnsi, overwrite))
return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId));
BYTE cmd = COMMAND_LIST_DRIVE;
if (!ctx->Send2Client(&cmd, 1)) {
mcp.ClearFileTransfer(devId);
return BuildError(id, -32004, "Failed to send command to host");
}
std::vector<FileTransferEntry> files;
int skipped = 0, error = 0;
DWORD errorDetail = 0;
bool ok = mcp.WaitFileTransferDone(devId, timeoutMs, files, skipped, error, &errorDetail);
mcp.ClearFileTransfer(devId); // 擦会话 + CancelIO 子链接
if (ok) {
uint64_t totalBytes = 0;
for (auto& f : files) totalBytes += f.size;
// 审计(不可关闭;只记路径与字节数,不落文件内容)
if (parent) {
std::string audit = "host " + std::to_string(devId) + " download_file: "
+ remotePathUtf8 + " -> " + localDirUtf8
+ " (" + std::to_string(files.size()) + " files, "
+ std::to_string(totalBytes) + " bytes, skipped " + std::to_string(skipped) + ")";
parent->PostMessageA(WM_SHOWERRORMSG,
(WPARAM)new CString(ToAnsi(audit, 936).c_str()),
(LPARAM)new CString(_TR("MCP文件传输")));
}
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
Json::Value filesArr(Json::arrayValue);
for (auto& f : files) {
Json::Value fo(Json::objectValue);
fo["path"] = ToUtf8(f.path.c_str(), CP_ACP);
fo["size"] = (Json::UInt64)f.size;
fo["sha256"] = f.sha256;
filesArr.append(fo);
}
structuredContent["files"] = filesArr;
structuredContent["total_bytes"] = (Json::UInt64)totalBytes;
structuredContent["skipped"] = skipped;
result["structuredContent"] = structuredContent;
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = std::string(u8"下载完成:") + std::to_string(files.size()) + u8" 个文件("
+ std::to_string(totalBytes) + u8" 字节),跳过 " + std::to_string(skipped) + u8" 个。";
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
// 失败:删除已落盘的半成品文件(跳过的文件是既有的,不删)。
for (auto& f : files) {
if (!f.path.empty()) DeleteFileA(f.path.c_str());
}
if (parent) {
std::string audit = "host " + std::to_string(devId) + " download_file FAILED (error " + std::to_string(error)
+ "): " + remotePathUtf8 + " -> " + localDirUtf8;
parent->PostMessageA(WM_SHOWERRORMSG,
(WPARAM)new CString(ToAnsi(audit, 936).c_str()),
(LPARAM)new CString(_TR("MCP文件传输")));
}
// 新客户端在建立传输子链接之前就回报「远端路径不可用」(TOKEN_DOWNLOAD_ERROR):
// 1005=不存在、1006=拒绝访问、1007=其他。直接给可分支的错误码,不再等停滞看门狗。
if (error == 1005 || error == 1006 || error == 1007) {
std::string detail = " (win32=" + std::to_string((int)errorDetail) + ")";
if (error == 1005)
return BuildError(id, -32009, "Remote path does not exist: " + remotePathUtf8 + detail);
if (error == 1006)
return BuildError(id, -32010, "Access denied to remote path: " + remotePathUtf8 + detail);
return BuildError(id, -32000, "Client could not queue the download of " + remotePathUtf8 + detail);
}
const char* msg = (error == 1002) ? "Timeout waiting for file transfer"
: (error == 1004) ? "File transfer stalled: no data received for 60s "
"(the remote path is probably missing or inaccessible; "
"verify it with list_files first)"
: (error == 1001) ? "Path traversal detected in received path"
: (error == 1003) ? "Connection lost: the transfer sub-connection closed"
: (error == FEV2_HASH_MISMATCH) ? "File SHA-256 verification failed"
: "File transfer failed";
return BuildError(id, -32001, msg);
}
// ===== P2:upload_file 辅助 =====
// ASCII 小写(GBK 双字节首字节 0x81..0xFE 不含 A-Z,安全);Windows 路径名不区分大小写。
static std::string AsciiLower(std::string s) {
for (char& c : s) if (c >= 'A' && c <= 'Z') c = (char)(c - 'A' + 'a');
return s;
}
// 词法检查路径是否含 ".." 段(防上传目标逃逸到预期目录之外)。
static bool HasDotDotSegment(const std::string& path) {
size_t i = 0;
while (i < path.size()) {
size_t j = path.find_first_of("\\/", i);
if (j == std::string::npos) j = path.size();
size_t n = j - i;
if (n == 2 && path[i] == '.' && path[i + 1] == '.') return true;
i = j + 1;
}
return false;
}
// 递归收集本机目录下的文件与目录项(目录在前、子项随后,供 FileBatchTransferWorkerV2 发送)。
// 与 common/file_upload.cpp 的 ExpandDirectory 同构(该函数未在 file_upload.h 导出,故本地实现)。
static void CollectLocalFiles(const std::string& dir, std::vector<std::string>& out) {
std::string searchPath = dir + "\\*";
WIN32_FIND_DATAA fd;
HANDLE hFind = FindFirstFileA(searchPath.c_str(), &fd);
if (hFind == INVALID_HANDLE_VALUE) return;
do {
if (strcmp(fd.cFileName, ".") == 0 || strcmp(fd.cFileName, "..") == 0) continue;
std::string fullPath = dir + "\\" + fd.cFileName;
out.push_back(fullPath); // 文件与目录都加入
if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
CollectLocalFiles(fullPath, out); // 递归(目录项先于其子文件)
} while (FindNextFileA(hFind, &fd));
FindClose(hFind);
}
// upload_file 无头发送回调数据
struct UploadCallbackData {
CMy2015RemoteDlg* parent;
uint64_t clientID;
DWORD deadline = 0; // 整体传输截止(GetTickCount 毫秒;0=不限)
bool timedOut = false;
bool failed = false; // 任一 Send2Client 失败或客户端离线
// P11:进度与取消(worker 的每次分块回调都会经过这里)
uint64_t totalBytes = 0; // 待发送的数据字节总数(进度分母)
uint64_t bytesSent = 0; // 已发出的数据字节数(进度分子)
bool cancelled = false; // 调用被取消 → 中止发送(worker 以非 0 返回)
};
// upload_file 无头发送回调(镜像 GUI SendFileChunkToClientV2,去掉 dlg 进度)。
static bool UploadSendChunkHeadless(void* user, FileChunkPacketV2* chunk, unsigned char* data, int size) {
UploadCallbackData* cb = (UploadCallbackData*)user;
if (!cb || !cb->parent) return false;
if (McpCallCancelled()) { // P11:取消 → 停止发送
cb->cancelled = true;
cb->failed = true;
return false;
}
if (cb->deadline && (int)(GetTickCount() - cb->deadline) >= 0) { // 整体超时(DWORD 回绕安全)
cb->timedOut = true;
cb->failed = true;
return false;
}
context* ctx = cb->parent->FindHost(cb->clientID);
if (!ctx) { cb->failed = true; return false; }
BOOL sent = ctx->Send2Client(data, size);
if (!sent) cb->failed = true;
else if (chunk && chunk->dataLength) {
cb->bytesSent += chunk->dataLength;
// 进度按 1s 节流(EmitProgress 内部),大文件每片都会回调到这里。
if (cb->totalBytes > 0) McpCallProgress((double)cb->bytesSent, (double)cb->totalBytes);
else McpCallProgress((double)cb->bytesSent);
}
return sent != FALSE;
}
// 列远程目录一层,返回顶层名集合(小写原始 ANSI;客户端 ANSI=936 与主控本地名同编码)。
// 复用 list_files 的 COMMAND_LIST_DRIVE→TOKEN_DRIVE_LIST→COMMAND_LIST_FILES→TOKEN_FILE_LIST 链路。
static bool ListRemoteTopLevelNames(CMy2015RemoteDlg* parent, uint64_t devId,
const std::string& remoteDirAnsi,
std::set<std::string>& names,
bool foldCase = true) {
CMcpServer& mcp = CMcpServer::Instance();
if (!mcp.BeginPending(devId, "list_files", remoteDirAnsi)) return false;
context* ctx = FindMainContext(parent, devId);
if (!ctx) { mcp.ClearPending(devId); return false; }
BYTE cmd = COMMAND_LIST_DRIVE;
if (!ctx->Send2Client(&cmd, 1)) { mcp.ClearPending(devId); return false; }
std::vector<BYTE> data;
if (!mcp.WaitPending(devId, data, mcp.ToolTimeoutMs())) return false;
// upload_file 的 overwrite=false 判定:远程目录尚未创建(2/3)→ 视为「无同名项」,
// 不能因为新客户端开始报错就让「上传到新目录」失败;其他失败(如拒绝访问)仍按失败处理。
if (!data.empty() && data[0] == TOKEN_FILE_LIST_ERROR) {
DWORD e = ReadWin32Payload(data);
return e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND;
}
// TOKEN_FILE_LIST 布局:[token:1][attr:1][name\0][sizeHigh:4][sizeLow:4][ft:8]...
if (data.size() < 2) return true; // 空目录 → 无顶层名
const char* p = (const char*)data.data();
size_t len = data.size();
size_t off = 1; // 跳过 token 字节
while (off + 1 <= len) {
off += 1; // attr
const char* name = p + off;
size_t nlen = BoundedStrlen(name, len - off);
if (nlen == 0 || nlen >= len - off) break; // 空记录/越界 = 尾部零填充
off += nlen + 1;
if (off + 16 > len) break;
off += 16; // sizeHigh/sizeLow/ft(8)
names.insert(foldCase ? AsciiLower(std::string(name, nlen)) : std::string(name, nlen));
}
return true;
}
Json::Value BuildUploadFileInputSchema() {
Json::Value props(Json::objectValue);
Json::Value idProp(Json::objectValue);
idProp["type"] = "string";
idProp["description"] = u8"主机 id,取 list_online_hosts / search_hosts 返回的 id 字段";
props["id"] = idProp;
Json::Value lp(Json::objectValue);
lp["type"] = "string";
lp["description"] = u8"主控本机文件或目录的绝对路径(目录递归上传),如 C:\\Users\\foo\\Pictures";
props["local_path"] = lp;
Json::Value rd(Json::objectValue);
rd["type"] = "string";
rd["description"] = u8"远程主机的保存目录(不存在则自动创建)。Windows 主机如 C:\\uploads,Linux/macOS 主机用 /home/user/uploads 这类绝对 POSIX 路径";
props["remote_dir"] = rd;
Json::Value ow(Json::objectValue);
ow["type"] = "boolean";
ow["description"] = u8"是否覆盖 remote_dir 下已存在的同名顶层文件/目录;默认 false(跳过并计入 skipped)";
props["overwrite"] = ow;
Json::Value to(Json::objectValue);
to["type"] = "integer";
to["description"] = u8"超时毫秒(默认 600000=10 分钟,上限 3600000=1 小时)";
props["timeout_ms"] = to;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("id");
required.append("local_path");
required.append("remote_dir");
schema["required"] = required;
return schema;
}
Json::Value BuildUploadFileOutputSchema() {
Json::Value props(Json::objectValue);
Json::Value filesProp(Json::objectValue);
filesProp["type"] = "array";
Json::Value items(Json::objectValue);
items["type"] = "object";
Json::Value itemProps(Json::objectValue);
Json::Value pathProp(Json::objectValue); pathProp["type"] = "string"; itemProps["path"] = pathProp;
Json::Value sizeProp(Json::objectValue); sizeProp["type"] = "integer"; itemProps["size"] = sizeProp;
Json::Value shaProp(Json::objectValue); shaProp["type"] = "string"; itemProps["sha256"] = shaProp;
items["properties"] = itemProps;
filesProp["items"] = items;
props["files"] = filesProp;
Json::Value tb(Json::objectValue); tb["type"] = "integer"; props["total_bytes"] = tb;
Json::Value sk(Json::objectValue); sk["type"] = "integer"; props["skipped"] = sk;
Json::Value ra(Json::objectValue); ra["type"] = "boolean"; props["receiver_ack"] = ra;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
return schema;
}
// tools/call:upload_file(上传主控本机文件/目录到远程主机,V2 协议,主连接发送)
std::string BuildUploadFile(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
// 分派门控(McpFileTransfer=1 且 McpReadonly=0):即便绕过 tools/list 直调也拒绝。
if (!CMcpServer::Instance().IsFileTransferEnabled())
return BuildError(id, -32006, "File transfer is disabled: requires McpFileTransfer=1");
if (CMcpServer::Instance().IsReadonly())
return BuildError(id, -32006, "upload_file is disabled in read-only mode: requires McpReadonly=0");
uint64_t devId = 0;
std::string err;
if (!ParseHostIdArg(args, devId, err))
return BuildError(id, -32602, err);
context* ctx = FindMainContext(parent, devId);
if (!ctx)
return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId));
// 目标端类型决定 remote_dir 的写法:Windows 用盘符路径,LNX/MAC 用绝对 POSIX 路径。
// POSIX 接收端(common/FileTransferV2.h)按包里的 name 派生落盘路径,不需要专门指令。
CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
const bool posixTarget = (clientType == "LNX" || clientType == "MAC");
const bool dstAcks = ctx->SupportsC2CRecvAck(); // 目前仅 Linux 接收端会回执
if (!ctx->SupportsFileV2())
return BuildError(id, -32006, "Host does not support V2 file transfer");
std::string localPathUtf8 = GetStringArg(args, "local_path");
if (localPathUtf8.empty())
return BuildError(id, -32602, "Missing required parameter: local_path");
std::string remoteDirUtf8 = GetStringArg(args, "remote_dir");
if (remoteDirUtf8.empty())
return BuildError(id, -32602, "Missing required parameter: remote_dir");
bool overwrite = false;
if (args.isMember("overwrite") && args["overwrite"].isBool())
overwrite = args["overwrite"].asBool();
int timeoutMs = 600000;
if (args.isMember("timeout_ms")) {
int v = 0;
if (!GetIntArg(args, "timeout_ms", v) || v <= 0 || v > 3600000)
return BuildError(id, -32602, "timeout_ms must be in range 1..3600000");
timeoutMs = v;
}
// 主控本机路径:UTF-8 → 主控 ANSI,去尾斜杠。
std::string localPathAnsi = ToAnsi(localPathUtf8, CP_ACP);
if (localPathAnsi.empty())
return BuildError(id, -32602, "Invalid local_path encoding");
while (!localPathAnsi.empty() && (localPathAnsi.back() == '\\' || localPathAnsi.back() == '/'))
localPathAnsi.pop_back();
DWORD attr = GetFileAttributesA(localPathAnsi.c_str());
if (attr == INVALID_FILE_ATTRIBUTES)
return BuildError(id, -32602, "local_path not found: " + localPathUtf8);
// 收集本机文件 + 目录项(目录在前、子项随后),镜像 ExpandDirectories 的顺序语义。
std::vector<std::string> files;
files.push_back(localPathAnsi);
if (attr & FILE_ATTRIBUTE_DIRECTORY)
CollectLocalFiles(localPathAnsi, files);
// 远程保存目录:UTF-8 → 客户端 ANSI(936),去尾部分隔符。
std::string remoteDirAnsi = ToAnsi(remoteDirUtf8, 936);
if (remoteDirAnsi.empty())
return BuildError(id, -32602, "Invalid remote_dir encoding");
if (posixTarget) {
// 只接受绝对 POSIX 路径(单独的 "/" 也是合法目标)。
while (remoteDirAnsi.size() > 1 && remoteDirAnsi.back() == '/')
remoteDirAnsi.pop_back();
if (remoteDirAnsi[0] != '/')
return BuildError(id, -32602, "remote_dir must be an absolute POSIX path for Linux/macOS hosts, e.g. /home/user/uploads");
if (remoteDirAnsi.find('\\') != std::string::npos)
return BuildError(id, -32602, "remote_dir must not contain backslashes on Linux/macOS hosts; use '/'");
if (HasDotDotSegment(remoteDirAnsi))
return BuildError(id, -32602, "remote_dir must not contain '..' path segments");
} else {
while (!remoteDirAnsi.empty() && (remoteDirAnsi.back() == '\\' || remoteDirAnsi.back() == '/'))
remoteDirAnsi.pop_back();
if (remoteDirAnsi.empty())
return BuildError(id, -32602, "Invalid remote_dir: " + remoteDirUtf8);
if (HasDotDotSegment(remoteDirAnsi))
return BuildError(id, -32602, "remote_dir must not contain '..' path segments");
}
// 拼接前缀:Windows 用 '\';POSIX 用 '/'(根目录不再重复补分隔符)。
// relPath 里的 '\' 由接收端归一化成 '/',两条路都能落对。
std::string targetDir = posixTarget
? (remoteDirAnsi == "/" ? "/" : remoteDirAnsi + "/")
: (remoteDirAnsi + "\\");
// overwrite=false:预检 remote_dir 一层,跳过已存在的同名顶层项(单文件精确、目录整体跳过)。
int skipped = 0;
std::vector<std::string> sendFiles;
if (!overwrite) {
std::set<std::string> existing;
if (!ListRemoteTopLevelNames(parent, devId, remoteDirAnsi, existing))
return BuildError(id, -32001, "Failed to list remote_dir for overwrite check");
std::string rootDir = GetCommonRoot(files);
for (const std::string& f : files) {
DWORD a = GetFileAttributesA(f.c_str());
bool isDir = (a != INVALID_FILE_ATTRIBUTES && (a & FILE_ATTRIBUTE_DIRECTORY));
std::string rel = GetRelativePath(rootDir, f);
size_t sep = rel.find_first_of("\\/");
std::string top = (sep == std::string::npos) ? rel : rel.substr(0, sep);
if (existing.count(AsciiLower(top))) {
if (!isDir) skipped++; // 目录项不计入 skipped(与 download 一致)
continue;
}
sendFiles.push_back(f);
}
} else {
sendFiles = files;
}
// 全部被跳过:直接返回成功(不发起传输)。
if (sendFiles.empty()) {
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
structuredContent["files"] = Json::Value(Json::arrayValue);
structuredContent["total_bytes"] = (Json::UInt64)0;
structuredContent["skipped"] = skipped;
result["structuredContent"] = structuredContent;
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = std::string(u8"上传完成:所有文件均已存在,跳过 ") + std::to_string(skipped) + u8" 个。";
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
TransferOptionsV2 opts;
opts.transferID = GenerateTransferID(); // 先定下来:会话要用它匹配 POSIX 目标端回执
opts.srcClientID = 0; // 主控端
opts.dstClientID = devId;
opts.enableResume = false;
CMcpServer& mcp = CMcpServer::Instance();
if (!mcp.BeginFileUpload(devId, opts.transferID))
return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId));
std::string hash = GetPwdHash();
std::string hmac = GetHMAC(100);
UploadCallbackData cbData;
cbData.parent = parent;
cbData.clientID = devId;
cbData.deadline = GetTickCount() + (DWORD)timeoutMs; // DWORD 回绕由回调的 (int) 差值判断吸收
// 进度分母:待发送文件的数据字节总数(目录项不计)。取不到属性时保持 0 → 只报已发字节数。
for (const std::string& f : sendFiles) {
WIN32_FILE_ATTRIBUTE_DATA fad;
if (GetFileAttributesExA(f.c_str(), GetFileExInfoStandard, &fad) &&
!(fad.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
cbData.totalBytes += (((uint64_t)fad.nFileSizeHigh << 32) | fad.nFileSizeLow);
}
// 空文件:worker 对 0 字节文件不发数据块,只发 COMMAND_FILE_COMPLETE_V2,而完成包没有路径字段,
// POSIX 接收端无从创建文件(会「回执成功但文件不存在」)。这里替 POSIX 目标端补一个长度 0 的
// 收尾块(名字拼法与 worker 一致),接收端据此建空文件;随后 worker 的完成包只会被去重。
// Windows 目标端维持原行为不动。
std::string xferRoot = GetCommonRoot(sendFiles);
if (posixTarget) {
for (size_t i = 0; i < sendFiles.size(); ++i) {
DWORD a = GetFileAttributesA(sendFiles[i].c_str());
if (a == INVALID_FILE_ATTRIBUTES || (a & FILE_ATTRIBUTE_DIRECTORY)) continue;
WIN32_FILE_ATTRIBUTE_DATA fad;
if (!GetFileAttributesExA(sendFiles[i].c_str(), GetFileExInfoStandard, &fad)) continue;
if ((((uint64_t)fad.nFileSizeHigh << 32) | fad.nFileSizeLow) != 0) continue;
std::string name = targetDir + GetRelativePath(xferRoot, sendFiles[i]);
size_t packetSize = sizeof(FileChunkPacketV2) + name.size();
std::vector<uint8_t> packet(packetSize);
auto* pkt = (FileChunkPacketV2*)packet.data();
pkt->cmd = COMMAND_SEND_FILE_V2;
pkt->transferID = opts.transferID;
pkt->srcClientID = 0;
pkt->dstClientID = devId;
pkt->fileIndex = (uint32_t)i;
pkt->totalFiles = (uint32_t)sendFiles.size();
pkt->fileSize = 0;
pkt->offset = 0;
pkt->dataLength = 0;
pkt->nameLength = (uint32_t)name.size();
pkt->flags = FFV2_LAST_CHUNK;
pkt->checksum = 0;
memset(pkt->reserved, 0, sizeof(pkt->reserved));
if (!name.empty()) memcpy(packet.data() + sizeof(FileChunkPacketV2), name.data(), name.size());
UploadSendChunkHeadless(&cbData, pkt, packet.data(), (int)packetSize);
}
}
// 同步驱动发送(走主连接);无外来流,无需 WaitFileTransferDone / 收包计数。
int result = FileBatchTransferWorkerV2(sendFiles, targetDir, &cbData,
UploadSendChunkHeadless, nullptr, hash, hmac, opts);
bool clientOnline = (FindMainContext(parent, devId) != nullptr);
bool ok = (result == 0) && !cbData.failed && clientOnline;
// POSIX 目标端回执:接收端写完最后一包才回(Windows 客户端从不回,dstAcks 为 false)。
// 回执可能在上面的同步发送过程中就已到达并 latch 进会话,这里的等待通常立即返回。
CMcpServer::C2CResult ack;
if (ok && dstAcks) mcp.WaitC2CReceiver(devId, 5000, ack);
mcp.ClearFileTransfer(devId);
// 计算已发送文件(远程完整路径 = targetDir + relPath)与字节数;目录项不计入 files。
std::string outRoot = xferRoot;
std::vector<FileTransferEntry> outFiles;
uint64_t totalBytes = 0;
for (const std::string& f : sendFiles) {
DWORD a = GetFileAttributesA(f.c_str());
if (a == INVALID_FILE_ATTRIBUTES || (a & FILE_ATTRIBUTE_DIRECTORY)) continue;
std::string rel = GetRelativePath(outRoot, f);
FileTransferEntry e;
e.path = targetDir + rel;
if (posixTarget) {
for (char& c : e.path) if (c == '\\') c = '/'; // relPath 是 Windows 分隔符
}
WIN32_FILE_ATTRIBUTE_DATA fad;
if (GetFileAttributesExA(f.c_str(), GetFileExInfoStandard, &fad))
e.size = ((uint64_t)fad.nFileSizeHigh << 32) | fad.nFileSizeLow;
// §7.5:V2 无接收方→发送方 ACK,发送方自算 SHA-256 未由 worker 回传;P2 留空(延后 P3)。
e.sha256 = "";
totalBytes += e.size;
outFiles.push_back(std::move(e));
}
// 目标端回了回执但失败:发送端的「全部发出」不算完成,按目标端写入失败上报。
// 与 copy_files_c2c 的 -32011 同义(那两个 -32009/-32010 是发送端路径语义)。
if (ok && ack.recvAck && ack.recvStatus != (uint32_t)FEV2_OK) {
const char* why = "write failed";
if (ack.recvStatus == (uint32_t)FEV2_ACCESS_DENIED) why = "permission denied";
else if (ack.recvStatus == (uint32_t)FEV2_FILE_NOT_FOUND) why = "no such file or directory";
else if (ack.recvStatus == (uint32_t)FEV2_DISK_FULL) why = "no space left on device";
return BuildError(id, -32011, std::string("Destination host failed to write the files: ") + why
+ " (status=" + std::to_string(ack.recvStatus)
+ ", errno=" + std::to_string(ack.recvErrno)
+ ", files=" + std::to_string(ack.recvFileCount) + ")");
}
// 声明了会回执却不回:目标端可能中途掉线,发送端的「已发出」不能当成落盘成功。
// 例外:整包没有字节(全是空文件)——接收端无从回执。
if (ok && dstAcks && !ack.recvAck && totalBytes != 0)
return BuildError(id, -32001, "Upload finished sending but the destination did not confirm "
"the write (verify with list_files on the target host)");
if (ok) {
if (parent) {
std::string audit = "host " + std::to_string(devId) + " upload_file: "
+ localPathUtf8 + " -> " + remoteDirUtf8
+ " (" + std::to_string(outFiles.size()) + " files, "
+ std::to_string(totalBytes) + " bytes, skipped " + std::to_string(skipped) + ")";
parent->PostMessageA(WM_SHOWERRORMSG,
(WPARAM)new CString(ToAnsi(audit, 936).c_str()),
(LPARAM)new CString(_TR("MCP文件传输")));
}
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
Json::Value filesArr(Json::arrayValue);
for (auto& f : outFiles) {
Json::Value fo(Json::objectValue);
fo["path"] = ToUtf8(f.path.c_str(), 936);
fo["size"] = (Json::UInt64)f.size;
fo["sha256"] = f.sha256;
filesArr.append(fo);
}
structuredContent["files"] = filesArr;
structuredContent["total_bytes"] = (Json::UInt64)totalBytes;
structuredContent["skipped"] = skipped;
// receiver_ack=true 只可能来自 POSIX 接收端(Linux 客户端写完最后一包回执);
// Windows 目标与老客户端没有回执,false 时请用 list_files 在目标主机上复核。
structuredContent["receiver_ack"] = ack.recvAck;
result["structuredContent"] = structuredContent;
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = std::string(u8"上传完成:") + std::to_string(outFiles.size()) + u8" 个文件("
+ std::to_string(totalBytes) + u8" 字节),跳过 " + std::to_string(skipped) + u8" 个"
+ (ack.recvAck ? u8";目标端已确认写入。" : u8"。");
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
if (parent) {
std::string audit = "host " + std::to_string(devId) + " upload_file FAILED: "
+ localPathUtf8 + " -> " + remoteDirUtf8;
parent->PostMessageA(WM_SHOWERRORMSG,
(WPARAM)new CString(ToAnsi(audit, 936).c_str()),
(LPARAM)new CString(_TR("MCP文件传输")));
}
const char* msg = cbData.timedOut ? "Timeout waiting for upload to complete"
: "Upload failed (target offline or send error)";
return BuildError(id, -32001, msg);
}
// ========== C2C 文件传输:copy_files_c2c ==========
Json::Value BuildCopyFilesC2CInputSchema() {
Json::Value props(Json::objectValue);
Json::Value src(Json::objectValue);
src["type"] = "string";
src["description"] = u8"源主机 id(文件从这里发出),取 list_online_hosts / search_hosts 返回的 id";
props["src_id"] = src;
Json::Value dst(Json::objectValue);
dst["type"] = "string";
dst["description"] = u8"目标主机 id(文件落在这里),同上";
props["dst_id"] = dst;
Json::Value paths(Json::objectValue);
paths["type"] = "array";
Json::Value pathItems(Json::objectValue);
pathItems["type"] = "string";
paths["items"] = pathItems;
paths["description"] = u8"源主机上的绝对路径列表(文件或目录;目录递归发送,保留相对目录结构)";
props["paths"] = paths;
Json::Value dir(Json::objectValue);
dir["type"] = "string";
dir["description"] = u8"目标主机保存目录(绝对路径,不存在自动创建):Windows 目标如 D:\\Incoming,Linux/macOS 目标如 /home/user/incoming";
props["dst_dir"] = dir;
Json::Value to(Json::objectValue);
to["type"] = "integer";
to["description"] = u8"超时毫秒(默认 600000=10 分钟,上限 3600000=1 小时);超时不代表传输失败";
props["timeout_ms"] = to;
Json::Value ow(Json::objectValue);
ow["type"] = "boolean";
ow["description"] = u8"目标目录已存在同名顶层项时是否覆盖重传。默认 false:跳过并计入 skipped(不发起传输)。"
u8"目标端收包是无条件覆盖写,所以默认 false 才能避免重复调用时全量重发。";
props["overwrite"] = ow;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("src_id");
required.append("dst_id");
required.append("paths");
required.append("dst_dir");
schema["required"] = required;
return schema;
}
Json::Value BuildCopyFilesC2COutputSchema() {
Json::Value props(Json::objectValue);
Json::Value s1(Json::objectValue); s1["type"] = "string"; props["transfer_id"] = s1;
Json::Value s2(Json::objectValue); s2["type"] = "string"; props["src_id"] = s2;
Json::Value s3(Json::objectValue); s3["type"] = "string"; props["dst_id"] = s3;
Json::Value s4(Json::objectValue); s4["type"] = "string"; props["dst_dir"] = s4;
Json::Value s5(Json::objectValue); s5["type"] = "integer"; props["file_count"] = s5;
Json::Value s6(Json::objectValue); s6["type"] = "integer"; props["total_bytes"] = s6;
Json::Value s7(Json::objectValue); s7["type"] = "boolean"; props["receiver_ack"] = s7;
Json::Value s8(Json::objectValue); s8["type"] = "integer"; props["skipped"] = s8;
Json::Value s9(Json::objectValue); s9["type"] = "boolean"; props["skip_check_failed"] = s9;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
return schema;
}
// 取一个十进制主机 id 字符串字段(src_id / dst_id),与 ParseHostIdArg 同规则但不绑定 "id" 键。
static bool ParseIdField(const Json::Value& args, const char* key, uint64_t& out, std::string& err) {
std::string s = GetStringArg(args, key);
if (s.empty()) { err = std::string("Missing required parameter: ") + key; return false; }
for (char c : s) {
if (c < '0' || c > '9') {
err = std::string("Invalid ") + key + ": expected a decimal host id string";
return false;
}
}
out = strtoull(s.c_str(), nullptr, 10);
if (out == 0) { err = std::string("Invalid ") + key + ": host id must be non-zero"; return false; }
return true;
}
// tools/call:copy_files_c2c(源主机 → 目标主机直接传文件;服务端只做中继,不落盘)
// 报文:COMMAND_C2C_SEND_FILES(服务端 → 源主机主连接)→ 源端自开子连接上行
// → 服务端 COMMAND_SEND_FILE_V2 转发分支按 dstClientID 中继到目标主机主连接
// → 源端 TOKEN_C2C_SEND_RESULT 回传结果(本线程等的就是它)。
std::string BuildCopyFilesC2C(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
CMcpServer& mcp = CMcpServer::Instance();
if (!mcp.IsFileTransferEnabled())
return BuildError(id, -32006, "File transfer is disabled: requires McpFileTransfer=1");
if (mcp.IsReadonly())
return BuildError(id, -32006, "copy_files_c2c is disabled: MCP is in read-only mode (set McpReadonly=0 to enable)");
uint64_t srcId = 0, dstId = 0;
std::string err;
if (!ParseIdField(args, "src_id", srcId, err)) return BuildError(id, -32602, err);
if (!ParseIdField(args, "dst_id", dstId, err)) return BuildError(id, -32602, err);
if (srcId == dstId)
return BuildError(id, -32602, "src_id and dst_id must be different hosts");
context* srcCtx = FindMainContext(parent, srcId);
if (!srcCtx)
return BuildError(id, -32002, "Source host not found or offline: " + std::to_string(srcId));
context* dstCtx = FindMainContext(parent, dstId);
if (!dstCtx)
return BuildError(id, -32002, "Destination host not found or offline: " + std::to_string(dstId));
// 发送逻辑只在 Windows 客户端实现(client/KernelManager.cpp);目标端只按 V2 收包,无新能力位要求。
CString srcType = srcCtx->GetAdditionalData(RES_CLIENT_TYPE);
if (srcType == "LNX" || srcType == "MAC")
return BuildError(id, -32005, "copy_files_c2c requires a Windows source host");
if (!srcCtx->SupportsFileV2())
return BuildError(id, -32006, "Source host does not support V2 file transfer");
if (!srcCtx->SupportsC2CPaths())
return BuildError(id, -32005, "Source host client is too old: upgrade it to a build that supports copy_files_c2c");
if (!dstCtx->SupportsFileV2())
return BuildError(id, -32006, "Destination host does not support V2 file transfer");
// 目标端可以是 Windows,也可以是 Linux/macOS:dst_dir 由源端原样拼进每个块的 name 字段
// (纯字符串拼接,不经 Windows 路径 API),所以 Windows 目标吃绝对 Windows 路径,
// POSIX 目标吃绝对 POSIX 路径——接收端会把 '\' 归一化成 '/' 后按绝对路径落盘
// (common/FileTransferV2.h:224)。形态在下面按 dstType 分别校验。
CString dstType = dstCtx->GetAdditionalData(RES_CLIENT_TYPE);
const bool posixDst = (dstType == "LNX" || dstType == "MAC");
// 目标端是否会回落盘回执(目前只有新 Linux 客户端声明)。不会回的(Windows/老客户端)
// 不等回执,避免每次传输都白等几秒。
const bool dstAcks = dstCtx->SupportsC2CRecvAck();
std::string dstDirUtf8 = GetStringArg(args, "dst_dir");
if (dstDirUtf8.empty())
return BuildError(id, -32602, "Missing required parameter: dst_dir");
const Json::Value& paths = args["paths"];
if (!paths.isArray() || paths.size() == 0)
return BuildError(id, -32602, "Missing or invalid parameter: paths (non-empty string array)");
int timeoutMs = 600000;
if (args.isMember("timeout_ms")) {
int v = 0;
if (!GetIntArg(args, "timeout_ms", v) || v <= 0 || v > 3600000)
return BuildError(id, -32602, "timeout_ms must be in range 1..3600000");
timeoutMs = v;
}
// 目标目录:UTF-8 → 目标端 ANSI(936),去尾斜杠后统一补一个分隔符(作 targetDir 前缀,
// 源端是 targetDir + 相对路径的裸拼接,前缀必须以分隔符结尾)。
if (dstDirUtf8.find('\0') != std::string::npos) // 报文是 NUL 分隔的,内嵌 NUL 会截断并注入后续字段
return BuildError(id, -32602, "Invalid dst_dir: embedded NUL");
std::string dstDirAnsi;
if (posixDst) {
// 精确转换:CP936 表示不了字符(emoji/西里尔等)直接拒绝,而不是悄悄变成 '?'
// 把文件写进另一个目录。
if (!Utf8ToCpExact(dstDirUtf8, 936, dstDirAnsi) || dstDirAnsi.empty())
return BuildError(id, -32602, "Invalid dst_dir encoding (must be representable in CP936): "
+ dstDirUtf8);
} else {
dstDirAnsi = ToAnsi(dstDirUtf8, 936);
if (dstDirAnsi.empty())
return BuildError(id, -32602, "Invalid dst_dir encoding");
}
while (!dstDirAnsi.empty() && (dstDirAnsi.back() == '\\' || dstDirAnsi.back() == '/'))
dstDirAnsi.pop_back();
if (dstDirAnsi.empty() || HasDotDotSegment(dstDirAnsi))
return BuildError(id, -32602, "Invalid dst_dir: " + dstDirUtf8);
// 不带尾分隔符的形态,供 overwrite=false 的目录列举使用:客户端拼 "%s\*.*",
// 带尾分隔符会拼成 "C:\\*.*" 导致 FindFirstFile 失败(与 search_file 同一处坑)。
const std::string dstDirListAnsi = dstDirAnsi;
if (posixDst) {
// POSIX 目标:接收端把 '\' 当分隔符归一化,接 C:\x 会落成 /C:/x 之类;只收 '/' 根路径。
if (dstDirAnsi[0] != '/' || dstDirAnsi.find('\\') != std::string::npos)
return BuildError(id, -32602, "Invalid dst_dir for a Linux/macOS destination: use an "
"absolute POSIX path such as /home/user/incoming");
dstDirAnsi += "/";
} else {
dstDirAnsi += "\\";
}
std::vector<std::string> pathAnsi;
for (unsigned int i = 0; i < paths.size(); ++i) {
if (!paths[i].isString())
return BuildError(id, -32602, "paths must be an array of strings");
const std::string u8 = paths[i].asString();
if (u8.find('\0') != std::string::npos)
return BuildError(id, -32602, "Invalid path: embedded NUL");
std::string ansi = ToAnsi(u8, 936);
if (ansi.empty())
return BuildError(id, -32602, "Invalid path encoding: " + u8);
if (HasDotDotSegment(ansi))
return BuildError(id, -32602, "paths must not contain '..' segments: " + u8);
pathAnsi.push_back(ansi);
}
// ===== overwrite=false:先列目标目录一层,跳过已存在的同名顶层项 =====
// 目标端收包是无条件覆盖写,服务端不预检的话每次调用都会把整份文件重发一遍
// (实测同一份 11 MB 日志连传两次都重写,且两次返回值完全相同,调用方无从分辨)。
// 预检只在 overwrite=false 时做;目标目录尚不存在时 ListRemoteTopLevelNames 返回空集,
// 正好等价于「无同名项」。预检本身失败(主机忙/超时/拒绝访问)不回错误,退回全发并
// 置 skip_check_failed=true——不能让「检查失败」把一次本该成功的传输挡掉。
const bool overwrite = (args.isMember("overwrite") && args["overwrite"].isBool())
? args["overwrite"].asBool() : false;
int skipped = 0;
bool skipCheckFailed = false;
std::vector<std::string> sendPathAnsi;
if (overwrite) {
sendPathAnsi = pathAnsi;
} else {
std::set<std::string> existing;
// POSIX 目标区分大小写,Windows 目标不区分(与目标文件系统语义一致)。
if (!ListRemoteTopLevelNames(parent, dstId, dstDirListAnsi, existing, !posixDst)) {
skipCheckFailed = true;
sendPathAnsi = pathAnsi;
} else {
for (unsigned int i = 0; i < paths.size(); ++i) {
const std::string u8 = paths[i].asString();
const size_t sep = u8.find_last_of("\\/");
const std::string base = (sep == std::string::npos) ? u8 : u8.substr(sep + 1);
const std::string key = posixDst ? base : AsciiLower(base);
if (!base.empty() && existing.count(key)) { ++skipped; continue; }
sendPathAnsi.push_back(pathAnsi[i]);
}
}
}
// 全部被跳过:直接返回成功,不发起传输。
if (sendPathAnsi.empty()) {
Json::Value result(Json::objectValue);
Json::Value sc(Json::objectValue);
sc["transfer_id"] = std::string();
sc["src_id"] = std::to_string(srcId);
sc["dst_id"] = std::to_string(dstId);
sc["dst_dir"] = dstDirUtf8;
sc["file_count"] = (Json::UInt)0;
sc["total_bytes"] = (Json::UInt64)0;
sc["receiver_ack"] = false;
sc["skipped"] = skipped;
sc["skip_check_failed"] = false;
result["structuredContent"] = sc;
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = std::string(u8"C2C 未传输:") + std::to_string(skipped)
+ u8" 个顶层项在目标目录中已存在(overwrite=false),全部跳过。";
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
const uint64_t transferID = GenerateTransferID();
if (!mcp.BeginC2CTransfer(srcId, dstId, transferID))
return BuildError(id, -32003, "Device busy: source or destination host already has a transfer in flight");
// 组包:[C2CSendFilesPacket][dstDir\0][path1\0]...[pathN\0][\0]
C2CSendFilesPacket hdr = {};
hdr.cmd = (uint8_t)COMMAND_C2C_SEND_FILES;
hdr.transferID = transferID;
hdr.srcClientID = srcId;
hdr.dstClientID = dstId;
hdr.flags = 0;
strncpy_s(hdr.hash, sizeof(hdr.hash), GetPwdHash().c_str(), _TRUNCATE);
strncpy_s(hdr.hmac, sizeof(hdr.hmac), GetHMAC(100).c_str(), _TRUNCATE);
std::vector<BYTE> pkt;
pkt.reserve(sizeof(hdr) + dstDirAnsi.size() + 2);
pkt.insert(pkt.end(), (const BYTE*)&hdr, (const BYTE*)&hdr + sizeof(hdr));
pkt.insert(pkt.end(), dstDirAnsi.begin(), dstDirAnsi.end());
pkt.push_back(0);
for (const std::string& p : sendPathAnsi) {
pkt.insert(pkt.end(), p.begin(), p.end());
pkt.push_back(0);
}
pkt.push_back(0);
if (!srcCtx->Send2Client(pkt.data(), (ULONG)pkt.size())) {
mcp.ClearFileTransfer(srcId);
return BuildError(id, -32004, "Failed to send command to source host");
}
CMcpServer::C2CResult r;
bool ok = mcp.WaitC2CDone(srcId, timeoutMs, r);
// 源端说「全部发出」后再等目标端回执:只有声明 CLIENT_CAP_C2C_RECV_ACK 的端会回,
// 其余(Windows 目标、老 Linux 客户端、macOS)什么都不发,直接跳过等待。
if (ok && dstAcks) mcp.WaitC2CReceiver(srcId, 5000, r);
mcp.ClearFileTransfer(srcId);
if (!ok) {
// 1002 = 工具线程等超时(源端可能仍在发),其余是源端主动回报的失败。
if (r.error == 1002)
return BuildError(id, -32001, "Timeout waiting for the source host to finish sending (transfer may still be running; verify the destination with list_files)");
if (r.status == (uint32_t)FEV2_FILE_NOT_FOUND || r.status == (uint32_t)FEV2_ACCESS_DENIED) {
const bool denied = (r.win32err == 5) || (r.status == (uint32_t)FEV2_ACCESS_DENIED);
std::string msg = denied
? "Source path access denied (win32=" + std::to_string(r.win32err) + ")"
: "Source path not found or inaccessible (win32=" + std::to_string(r.win32err) + ")";
return BuildError(id, denied ? -32010 : -32009, msg);
}
std::string msg = "C2C transfer failed on the source host (status=" + std::to_string(r.status)
+ ", win32=" + std::to_string(r.win32err)
+ ", worker_rc=" + std::to_string((int)r.workerRc) + ")";
return BuildError(id, -32000, msg);
}
// 目标端回了回执但失败:源端的「全部发出」不算完成,按目标端写入失败上报。
if (r.recvAck && r.recvStatus != (uint32_t)FEV2_OK) {
const char* why = "write failed";
if (r.recvStatus == (uint32_t)FEV2_ACCESS_DENIED) why = "permission denied";
else if (r.recvStatus == (uint32_t)FEV2_FILE_NOT_FOUND) why = "no such file or directory";
else if (r.recvStatus == (uint32_t)FEV2_DISK_FULL) why = "no space left on device";
return BuildError(id, -32011, std::string("Destination host failed to write the files: ") + why
+ " (status=" + std::to_string(r.recvStatus)
+ ", errno=" + std::to_string(r.recvErrno)
+ ", files=" + std::to_string(r.recvFileCount) + ")");
}
// 声明了会回执却不回:目标端可能中途掉线或包被丢弃,源端的「已发出」不能当成落盘成功。
// 例外:整包没有字节(paths 全是空文件)——客户端不为空文件发任何数据块,也就无从回执。
if (dstAcks && !r.recvAck && r.totalBytes != 0)
return BuildError(id, -32001, "Source finished sending but the destination did not confirm "
"the write (verify with list_files on the destination host)");
// 审计(不可关闭;只记主机 id、目录与字节数,不落文件名以外的内容)
if (parent) {
std::string audit = "host " + std::to_string(srcId) + " -> host " + std::to_string(dstId)
+ " copy_files_c2c: " + dstDirUtf8 + " (" + std::to_string(r.fileCount)
+ " files, " + std::to_string(r.totalBytes) + " bytes)";
parent->PostMessageA(WM_SHOWERRORMSG,
(WPARAM)new CString(ToAnsi(audit, 936).c_str()),
(LPARAM)new CString(_TR("MCP文件传输")));
}
Json::Value result(Json::objectValue);
Json::Value sc(Json::objectValue);
sc["transfer_id"] = std::to_string(transferID);
sc["src_id"] = std::to_string(srcId);
sc["dst_id"] = std::to_string(dstId);
sc["dst_dir"] = dstDirUtf8;
sc["file_count"] = (Json::UInt)r.fileCount;
sc["total_bytes"] = (Json::UInt64)r.totalBytes;
// receiver_ack=true 只可能来自 POSIX 接收端(Linux 客户端写完最后一包回执);
// Windows 目标与老客户端没有回执,false 时请用 list_files 在目标主机上复核。
sc["receiver_ack"] = r.recvAck;
sc["skipped"] = skipped;
sc["skip_check_failed"] = skipCheckFailed;
result["structuredContent"] = sc;
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = std::string(u8"C2C 发送完成:") + std::to_string(r.fileCount) + u8" 个文件("
+ std::to_string(r.totalBytes) + u8" 字节),目标主机保存目录 " + dstDirUtf8
+ (skipped ? (std::string(u8";另有 ") + std::to_string(skipped) + u8" 个已存在被跳过")
: std::string())
+ (skipCheckFailed ? std::string(u8";未能预检目标目录(主机忙或超时),本次按全量发送")
: std::string())
+ (r.recvAck ? u8"。目标端已确认写入。"
: u8"。目标端无回执:请用 list_files 或 exec_command 在目标主机上复核。");
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
// ========== P7:设备管理控制 ==========
// kill_process:主连接 COMMAND_SYSTEM → 系统子连接 TOKEN_PSLIST(就绪)→ COMMAND_KILLPROCESS
// → 补发 COMMAND_PSLIST → 第二个 TOKEN_PSLIST(确认)。payload 与 SystemDlg::OnPlistKill 一致。
std::string BuildKillProcess(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
uint64_t devId = 0;
std::string err;
if (!ParseHostIdArg(args, devId, err))
return BuildError(id, -32602, err);
context* ctx = FindMainContext(parent, devId);
if (!ctx)
return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId));
CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
if (clientType == "MAC" || clientType == "APK")
return BuildError(id, -32005, "kill_process is only supported on Windows and Linux hosts");
CMcpServer& mcp = CMcpServer::Instance();
if (mcp.IsReadonly())
return BuildError(id, -32006, "kill_process is disabled: MCP is in read-only mode (set McpReadonly=0 to enable)");
if (!mcp.IsManageEnabled())
return BuildError(id, -32006, "kill_process is disabled: management operations are off (set McpManage=1 to enable)");
const Json::Value& pids = args["pids"];
if (!pids.isArray() || pids.size() == 0)
return BuildError(id, -32602, "Missing or invalid parameter: pids (non-empty integer array)");
std::vector<uint64_t> pidList;
std::vector<BYTE> followUp;
followUp.push_back((BYTE)COMMAND_KILLPROCESS);
for (unsigned int i = 0; i < pids.size(); ++i) {
uint64_t pid = 0;
if (!ReadUInt64(pids[i], pid) || pid == 0)
return BuildError(id, -32602, "pids must be non-zero integers");
pidList.push_back(pid);
DWORD d = (DWORD)pid;
followUp.push_back((BYTE)(d & 0xFF));
followUp.push_back((BYTE)((d >> 8) & 0xFF));
followUp.push_back((BYTE)((d >> 16) & 0xFF));
followUp.push_back((BYTE)((d >> 24) & 0xFF));
}
// ===== dry_run(§5.5):只取一次进程列表校验目标,不下发任何终止命令 =====
// MFC 侧不弹窗:挂起用「非写工具」的名称登记,TOKEN_PSLIST 首包会让 OnSystemReady
// 返回 false,由 TakeMainResponse + CancelIO 收走子链接。目标全部不存在时按 -32009 报错,
// 与 kill_network_connection 的 dry_run 口径一致。
bool dryRun = false;
if (args.isMember("dry_run")) {
if (!args["dry_run"].isBool())
return BuildError(id, -32602, "dry_run must be a boolean");
dryRun = args["dry_run"].asBool();
}
if (dryRun) {
if (!mcp.BeginPending(devId, "kill_process/dryrun"))
return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId));
BYTE cmd = COMMAND_SYSTEM;
if (!ctx->Send2Client(&cmd, 1)) {
mcp.ClearPending(devId);
return BuildError(id, -32004, "Failed to send command to host");
}
std::vector<BYTE> data;
if (!mcp.WaitPending(devId, data, mcp.ToolTimeoutMs()))
return BuildError(id, -32001, "Timeout waiting for process list (dry run)");
UINT cp = (clientType == "LNX" || clientType == "MAC") ? CP_UTF8 : 936;
Json::Value procs = ParseProcessList(data, cp);
Json::Value targets(Json::arrayValue);
Json::Value missing(Json::arrayValue);
for (size_t i = 0; i < pidList.size(); ++i) {
bool found = false;
for (unsigned int j = 0; j < procs.size(); ++j) {
if (procs[j]["pid"].asUInt64() == pidList[i]) {
Json::Value t(Json::objectValue);
t["pid"] = (Json::UInt64)pidList[i];
t["name"] = procs[j]["name"];
t["path"] = procs[j]["path"];
targets.append(t);
found = true;
break;
}
}
if (!found) missing.append((Json::UInt64)pidList[i]);
}
AuditManageAction(parent, devId, "kill_process",
"pids=" + std::to_string(pidList.size()) + " result=dry_run");
if (targets.empty())
return BuildError(id, -32009, "No matching process for any requested pid (dry run)");
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
structuredContent["ok"] = true;
structuredContent["dry_run"] = true;
structuredContent["targets"] = targets;
structuredContent["missing"] = missing;
result["structuredContent"] = structuredContent;
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = std::string(u8"试运行:将终止 ") + std::to_string(targets.size()) +
u8" 个进程(未发送任何命令)" +
(missing.empty() ? std::string()
: std::string(u8";") + std::to_string(missing.size()) +
u8" 个 PID 已不存在,已列入 missing") ;
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
if (!mcp.BeginPendingFollowUp(devId, "kill_process", followUp))
return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId));
BYTE cmd = COMMAND_SYSTEM;
if (!ctx->Send2Client(&cmd, 1)) {
mcp.ClearPending(devId);
return BuildError(id, -32004, "Failed to send command to host");
}
std::vector<BYTE> data;
if (!mcp.WaitPendingWrite(devId, data, mcp.ToolTimeoutMs()))
return BuildError(id, -32001, "Timeout waiting for process list after kill");
UINT cp = (clientType == "LNX" || clientType == "MAC") ? CP_UTF8 : 936;
Json::Value procs = ParseProcessList(data, cp);
Json::Value remaining(Json::arrayValue);
std::string detail = "pids=";
for (size_t i = 0; i < pidList.size(); ++i) {
if (i) detail += ",";
detail += std::to_string(pidList[i]);
bool stillAlive = false;
for (unsigned int j = 0; j < procs.size(); ++j) {
if (procs[j]["pid"].asUInt64() == pidList[i]) { stillAlive = true; break; }
}
if (stillAlive) remaining.append((Json::UInt64)pidList[i]);
}
AuditManageAction(parent, devId, "kill_process", detail);
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
structuredContent["remaining"] = remaining;
result["structuredContent"] = structuredContent;
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = remaining.empty()
? std::string(u8"目标进程已全部终止。")
: std::string(u8"仍有 ") + std::to_string((int)remaining.size()) + std::string(u8" 个进程存活(见 remaining)。");
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
// operate_window:主连接 COMMAND_WSLIST → 窗口子连接 TOKEN_WSLIST(就绪)→ CMD_WINDOW_CLOSE
// (close 客户端自动回 TOKEN_WSLIST)或 CMD_WINDOW_TEST(test 补发 COMMAND_WSLIST 索取)。
// 20 字节零填充 buffer 复刻 SystemDlg::OnWlistClose/OnWlistHide/Recover/Max/Min(hwnd 为 DWORD)。
std::string BuildOperateWindow(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
uint64_t devId = 0;
std::string err;
if (!ParseHostIdArg(args, devId, err))
return BuildError(id, -32602, err);
context* ctx = FindMainContext(parent, devId);
if (!ctx)
return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId));
CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
if (clientType == "LNX" || clientType == "MAC" || clientType == "APK")
return BuildError(id, -32005, "operate_window is only supported on Windows hosts");
CMcpServer& mcp = CMcpServer::Instance();
if (mcp.IsReadonly())
return BuildError(id, -32006, "operate_window is disabled: MCP is in read-only mode (set McpReadonly=0 to enable)");
if (!mcp.IsManageEnabled())
return BuildError(id, -32006, "operate_window is disabled: management operations are off (set McpManage=1 to enable)");
uint64_t hwnd = 0;
if (!ReadUInt64Arg(args, "hwnd", hwnd) || hwnd == 0)
return BuildError(id, -32602, "Missing or invalid parameter: hwnd (non-zero window handle)");
std::string action = Trim(GetStringArg(args, "action"));
BYTE lpMsgBuf[20] = { 0 };
DWORD h = (DWORD)hwnd;
if (action == "close") {
lpMsgBuf[0] = CMD_WINDOW_CLOSE;
memcpy(lpMsgBuf + 1, &h, sizeof(DWORD));
} else {
DWORD dHow;
if (action == "hide") dHow = SW_HIDE; // 0
else if (action == "show") dHow = SW_NORMAL; // 1
else if (action == "restore") dHow = SW_NORMAL; // 1
else if (action == "maximize") dHow = SW_MAXIMIZE; // 3
else if (action == "minimize") dHow = SW_MINIMIZE; // 6
else return BuildError(id, -32602,
"Invalid action: " + action + " (expect close|show|hide|minimize|maximize|restore)");
lpMsgBuf[0] = CMD_WINDOW_TEST;
memcpy(lpMsgBuf + 1, &h, sizeof(DWORD));
memcpy(lpMsgBuf + 1 + sizeof(DWORD), &dHow, sizeof(DWORD));
}
std::vector<BYTE> followUp(lpMsgBuf, lpMsgBuf + sizeof(lpMsgBuf));
// ===== dry_run(§5.5):只取一次窗口列表校验 hwnd,不下发任何窗口命令 =====
// 与 kill_process 的 dry_run 同构:用非写工具名登记,首包直接由 TakeMainResponse 收走。
bool dryRun = false;
if (args.isMember("dry_run")) {
if (!args["dry_run"].isBool())
return BuildError(id, -32602, "dry_run must be a boolean");
dryRun = args["dry_run"].asBool();
}
if (dryRun) {
if (!mcp.BeginPending(devId, "operate_window/dryrun"))
return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId));
BYTE cmd = COMMAND_WSLIST;
if (!ctx->Send2Client(&cmd, 1)) {
mcp.ClearPending(devId);
return BuildError(id, -32004, "Failed to send command to host");
}
std::vector<BYTE> data;
if (!mcp.WaitPending(devId, data, mcp.ToolTimeoutMs()))
return BuildError(id, -32001, "Timeout waiting for window list (dry run)");
// 窗口标题编码由客户端能力位决定(新客户端 UTF-8,老客户端 CP_ACP),与 list_windows 同口径。
Json::Value windows = ParseWindowList(data, GetClientEncoding(ctx));
Json::Value target(Json::objectValue);
for (unsigned int i = 0; i < windows.size(); ++i) {
if (windows[i]["hwnd"].asUInt64() == hwnd) { target = windows[i]; break; }
}
AuditManageAction(parent, devId, "operate_window",
"action=" + action + " hwnd=" + std::to_string(hwnd) + " result=dry_run");
if (target.isNull() || !target.isObject())
return BuildError(id, -32009, "Window hwnd=" + std::to_string(hwnd) +
" is not in the current visible window list (dry run)");
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
structuredContent["ok"] = true;
structuredContent["dry_run"] = true;
structuredContent["action"] = action;
structuredContent["window"] = target;
result["structuredContent"] = structuredContent;
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = std::string(u8"试运行:将对窗口「") + target["title"].asString() +
u8"」执行 " + action + u8"(未发送任何命令)";
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
if (!mcp.BeginPendingFollowUp(devId, "operate_window", followUp))
return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId));
BYTE cmd = COMMAND_WSLIST;
if (!ctx->Send2Client(&cmd, 1)) {
mcp.ClearPending(devId);
return BuildError(id, -32004, "Failed to send command to host");
}
std::vector<BYTE> data;
if (!mcp.WaitPendingWrite(devId, data, mcp.ToolTimeoutMs()))
return BuildError(id, -32001, "Timeout waiting for window operation");
AuditManageAction(parent, devId, "operate_window",
"action=" + action + " hwnd=" + std::to_string(hwnd));
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
structuredContent["ok"] = true;
result["structuredContent"] = structuredContent;
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = std::string(u8"已下发窗口操作:") + action;
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
// control_service:主连接 COMMAND_SERVICES → 服务子连接 TOKEN_SERVERLIST(就绪)→
// COMMAND_SERVICECONFIG → 客户端写后自动 SendServicesList(确认,无需补发)。
std::string BuildControlService(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
uint64_t devId = 0;
std::string err;
if (!ParseHostIdArg(args, devId, err))
return BuildError(id, -32602, err);
context* ctx = FindMainContext(parent, devId);
if (!ctx)
return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId));
CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
if (clientType == "LNX" || clientType == "MAC" || clientType == "APK")
return BuildError(id, -32005, "control_service is only supported on Windows hosts");
CMcpServer& mcp = CMcpServer::Instance();
if (mcp.IsReadonly())
return BuildError(id, -32006, "control_service is disabled: MCP is in read-only mode (set McpReadonly=0 to enable)");
if (!mcp.IsManageEnabled())
return BuildError(id, -32006, "control_service is disabled: management operations are off (set McpManage=1 to enable)");
std::string serviceName = Trim(GetStringArg(args, "service_name"));
if (serviceName.empty())
return BuildError(id, -32602, "Missing required parameter: service_name");
std::string action = Trim(GetStringArg(args, "action"));
BYTE bCmd;
if (action == "start") bCmd = 1;
else if (action == "stop") bCmd = 2;
else if (action == "set_auto") bCmd = 3;
else if (action == "set_manual") bCmd = 4;
else return BuildError(id, -32602,
"Invalid action: " + action + " (expect start|stop|set_auto|set_manual)");
// 服务名来自 Windows A 接口(GBK/936),下发前转 ANSI。payload 与 MachineDlg 一致:
// [COMMAND_SERVICECONFIG:1][bCmd:1][serviceName\0]。
std::string ansiName = ToAnsi(serviceName, 936);
std::vector<BYTE> followUp;
followUp.reserve(2 + ansiName.size() + 1);
followUp.push_back((BYTE)COMMAND_SERVICECONFIG);
followUp.push_back(bCmd);
followUp.insert(followUp.end(), ansiName.begin(), ansiName.end());
followUp.push_back(0);
if (!mcp.BeginPendingFollowUp(devId, "control_service", followUp))
return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId));
BYTE cmd = COMMAND_SERVICES;
if (!ctx->Send2Client(&cmd, 1)) {
mcp.ClearPending(devId);
return BuildError(id, -32004, "Failed to send command to host");
}
std::vector<BYTE> data;
if (!mcp.WaitPendingWrite(devId, data, mcp.ToolTimeoutMs()))
return BuildError(id, -32001, "Timeout waiting for service operation");
AuditManageAction(parent, devId, "control_service",
"service=" + serviceName + " action=" + action);
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
structuredContent["ok"] = true;
result["structuredContent"] = structuredContent;
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = std::string(u8"已下发服务操作:") + action + std::string(u8" ") + serviceName;
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
// power_action:主连接 TOKEN_MACHINE_MANAGE,发完即走(无响应);主机立即离线。
// power_action 的结果验证(§5.4):电源命令是「发完即走、无响应」,服务端唯一能观察到的
// 事实是主连接在不在线。wait=true 时先等主机下线(连接消失),再等它重新上线(重启后客户端
// 用同一个 id 重连)。两个阶段各自以 wait_ms 为上界;等不到不是错误,交给调用方判断。
static bool WaitHostOnlineState(CMy2015RemoteDlg* parent, uint64_t devId, bool wantOnline,
int timeoutMs) {
const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutMs);
while (true) {
if ((FindMainContext(parent, devId) != nullptr) == wantOnline) return true;
if (McpCallCancelled()) return false; // 取消后按「没等到」返回,由调用方如实回报
const auto now = std::chrono::steady_clock::now();
if (now >= deadline) return false;
std::this_thread::sleep_for(std::chrono::milliseconds(200));
}
}
std::string BuildPowerAction(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
uint64_t devId = 0;
std::string err;
if (!ParseHostIdArg(args, devId, err))
return BuildError(id, -32602, err);
context* ctx = FindMainContext(parent, devId);
if (!ctx)
return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId));
CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
if (clientType == "LNX" || clientType == "MAC" || clientType == "APK")
return BuildError(id, -32005, "power_action is only supported on Windows hosts");
CMcpServer& mcp = CMcpServer::Instance();
if (mcp.IsReadonly())
return BuildError(id, -32006, "power_action is disabled: MCP is in read-only mode (set McpReadonly=0 to enable)");
if (!mcp.IsManageEnabled())
return BuildError(id, -32006, "power_action is disabled: management operations are off (set McpManage=1 to enable)");
std::string action = Trim(GetStringArg(args, "action"));
BYTE type;
if (action == "logout") type = MACHINE_LOGOUT;
else if (action == "shutdown") type = MACHINE_SHUTDOWN;
else if (action == "reboot") type = MACHINE_REBOOT;
else return BuildError(id, -32602,
"Invalid action: " + action + " (expect logout|shutdown|reboot)");
// 结果验证参数(§5.4):wait 默认 false(保持「发完即走」的旧行为与旧耗时)。
// wait_ms 即使 wait=false 也校验,避免调用方以为传了有效值、实际被静默忽略。
bool wait = false;
if (args.isMember("wait")) {
if (!args["wait"].isBool())
return BuildError(id, -32602, "wait must be a boolean");
wait = args["wait"].asBool();
}
int waitMs = 60000;
if (args.isMember("wait_ms")) {
int v = 0;
if (!GetIntArg(args, "wait_ms", v) || v < 1000 || v > 600000)
return BuildError(id, -32602, "wait_ms must be in range 1000..600000");
waitMs = v;
}
// 主连接、发完即走、无响应(客户端 KernelManager 只校验 ulLength>1 并读 szBuffer[1])。
BYTE token[2] = { (BYTE)TOKEN_MACHINE_MANAGE, type };
if (!ctx->Send2Client(token, 2))
return BuildError(id, -32004, "Failed to send command to host");
bool wentOffline = false;
bool cameBack = false;
long long elapsedMs = 0;
if (wait) {
const auto t0 = std::chrono::steady_clock::now();
wentOffline = WaitHostOnlineState(parent, devId, false, waitMs);
if (wentOffline) cameBack = WaitHostOnlineState(parent, devId, true, waitMs);
elapsedMs = (long long)std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - t0).count();
}
AuditManageAction(parent, devId, "power_action",
"action=" + action + (wait ? " wait=1" : "") +
(wait ? (wentOffline ? (cameBack ? " went_offline=1 came_back=1"
: " went_offline=1 came_back=0")
: " went_offline=0") : ""));
// 取消优先于「没等到」:命令已经发出去了,不能伪装成「主机没反应」。用 -32800 说明是
// 调用方自己取消了等待,正文里点明命令可能已生效(重试前先读一次在线列表)。
// 已经看到下线的(wentOffline)继续按成功回报——那是真实发生的事实。
if (wait && !wentOffline && McpCallCancelled())
return BuildError(id, kErrCancelled,
"Cancelled while waiting for the host to go offline; the power command "
"was already sent, so check the host list before retrying");
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
structuredContent["ok"] = true;
structuredContent["sent"] = true;
structuredContent["went_offline"] = wentOffline;
structuredContent["came_back"] = cameBack;
structuredContent["elapsed_ms"] = (Json::Int64)elapsedMs;
result["structuredContent"] = structuredContent;
std::string text = std::string(u8"已下发电源操作:") + action;
if (!wait) {
text += u8"(未等待结果;要确认主机真的下线/回线请传 wait=true)";
} else if (!wentOffline) {
text += std::string(u8";在 ") + std::to_string(waitMs) +
u8" ms 内主机仍在在线列表里——命令可能没有生效"
u8"(客户端无管理员权限时关机/重启会被拒绝),也可能还在关机流程中。";
} else if (!cameBack) {
text += std::string(u8";主机已下线(") + std::to_string(elapsedMs) +
std::string(u8" ms),但未在 ") + std::to_string(waitMs) +
u8" ms 内重新上线(注销不会自动回线;关机后需人工开机)。";
} else {
text += std::string(u8";主机已下线并重新上线,共耗时 ") + std::to_string(elapsedMs) + u8" ms。";
}
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = text;
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
// ===== B1:主机库元数据(备注 / 关注等级)=====
//
// 写的是服务端本机的 _ClientList(MAP_NOTE / MAP_LEVEL),只影响主控端自己的展示:
// 不向客户端下发任何命令,也不改远端状态。所以门控只要 McpReadonly=0(这不是对设备的
// 操作,不要求 McpManage),审计仍走 AuditManageAction(只记字节数,绝不记备注内容)。
// 在线与离线(历史记录)主机都能写:id 在主机库里存在即可。
static bool HostStoreHas(CMy2015RemoteDlg* parent, uint64_t devId) {
if (!parent || !parent->m_ClientMap) return false;
EnterCriticalSection(&parent->m_cs);
bool exists = parent->m_ClientMap->Exists(devId);
LeaveCriticalSection(&parent->m_cs);
return exists;
}
// 备注/关注等级改完,UI 行要重绘才能立刻看到。MCP 线程不能直接碰 CListCtrl,
// 用 LVM_REDRAWITEMS 投递到列表控件(回到 UI 线程处理,触发 LVN_GETDISPINFO 重取文本)。
static void PostRepaintHostRow(CMy2015RemoteDlg* parent, uint64_t devId) {
if (!parent || !parent->m_CList_Online.GetSafeHwnd()) return;
int row = -1;
EnterCriticalSection(&parent->m_cs);
auto it = parent->m_ClientIndex.find(devId);
if (it != parent->m_ClientIndex.end()) {
for (size_t fi = 0; fi < parent->m_FilteredIndices.size(); ++fi) {
if (parent->m_FilteredIndices[fi] == it->second) { row = (int)fi; break; }
}
}
LeaveCriticalSection(&parent->m_cs);
if (row >= 0)
parent->m_CList_Online.PostMessage(LVM_REDRAWITEMS, (WPARAM)row, (LPARAM)row);
}
std::string BuildHostSetRemark(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
uint64_t devId = 0;
std::string err;
if (!ParseHostIdArg(args, devId, err))
return BuildError(id, -32602, err);
if (!args.isMember("remark") || !args["remark"].isString())
return BuildError(id, -32602,
"Missing required parameter: remark (string; empty string clears the remark)");
const std::string remarkU8 = args["remark"].asString();
CMcpServer& mcp = CMcpServer::Instance();
if (mcp.IsReadonly())
return BuildError(id, -32006,
"host_set_remark is disabled: MCP is in read-only mode (set McpReadonly=0 to enable)");
if (!HostStoreHas(parent, devId))
return BuildError(id, -32002, "Unknown host id (not in host store): " + std::to_string(devId));
// 主机库的备注列是 char Note[64](_ClientValue),存的是 GBK。严格转换:不可表示
// 的字符(emoji、ö 等)直接报错,而不是静默变成 '?';长度按 GBK 字节算,留 1 字节 NUL。
std::string remarkGbk;
if (!Utf8ToCpExact(remarkU8, 936, remarkGbk))
return BuildError(id, -32602,
"Remark contains characters that GBK (client ANSI) cannot represent");
if (remarkGbk.size() >= 64)
return BuildError(id, -32602,
"Remark too long: " + std::to_string(remarkGbk.size()) +
" GBK bytes (max 63)");
EnterCriticalSection(&parent->m_cs);
parent->m_ClientMap->SetClientMapData(devId, MAP_NOTE, remarkGbk.c_str());
parent->m_ClientMap->SaveToFile(GetDbPath());
LeaveCriticalSection(&parent->m_cs);
PostRepaintHostRow(parent, devId);
AuditManageAction(parent, devId, "host_set_remark",
std::string("remark ") + (remarkGbk.empty() ? "cleared" : "set") +
" bytes=" + std::to_string(remarkGbk.size()));
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
structuredContent["id"] = std::to_string(devId);
structuredContent["remark"] = remarkU8;
result["structuredContent"] = structuredContent;
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = remarkGbk.empty()
? std::string(u8"已清除该主机的备注。")
: std::string(u8"已更新该主机的备注(") +
std::to_string(remarkGbk.size()) + std::string(u8" 字节)。");
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
std::string BuildHostSetWatchLevel(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
uint64_t devId = 0;
std::string err;
if (!ParseHostIdArg(args, devId, err))
return BuildError(id, -32602, err);
int level = -1;
if (!GetIntArg(args, "level", level))
return BuildError(id, -32602, "Missing required parameter: level (integer 0-3)");
if (level < 0 || level > 3)
return BuildError(id, -32602,
"Invalid level: " + std::to_string(level) + " (expect 0-3)");
CMcpServer& mcp = CMcpServer::Instance();
if (mcp.IsReadonly())
return BuildError(id, -32006,
"host_set_watch_level is disabled: MCP is in read-only mode (set McpReadonly=0 to enable)");
if (!HostStoreHas(parent, devId))
return BuildError(id, -32002, "Unknown host id (not in host store): " + std::to_string(devId));
EnterCriticalSection(&parent->m_cs);
parent->m_ClientMap->SetClientMapInteger(devId, MAP_LEVEL, level);
parent->m_ClientMap->SaveToFile(GetDbPath());
LeaveCriticalSection(&parent->m_cs);
PostRepaintHostRow(parent, devId);
AuditManageAction(parent, devId, "host_set_watch_level",
"level=" + std::to_string(level));
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
structuredContent["id"] = std::to_string(devId);
structuredContent["level"] = level;
result["structuredContent"] = structuredContent;
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = std::string(u8"关注等级已设为 ") + std::to_string(level) +
std::string(u8"(0=无、1=蓝字、2=红字、3=红底)。");
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
// ===== N3:get_keylog =====
//
// 复用客户端既有键盘记录链路:主连接下发 COMMAND_KEYBOARD → 客户端新建子连接并回
// TOKEN_KEYBOARD_START(就绪)→ 之后客户端每约 1 秒推一包 TOKEN_KEYBOARD_DATA
// (击键文本,客户端编码)。服务端在窗口期内累积,到时间/字节上限即关闭子连接
// (关连接就是让客户端停止记录,与 MFC 关对话框同一路径)。
// 隐私:击键内容只进本次响应;审计日志只有 tool/耗时/字节数(CALL_OK 那一行)。
std::string BuildGetKeylog(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
CMcpServer& mcp = CMcpServer::Instance();
if (!mcp.IsKeylogEnabled())
return BuildError(id, -32006, "Keyboard log is disabled (McpKeylog=0)");
uint64_t devId = 0;
std::string err;
if (!ParseHostIdArg(args, devId, err))
return BuildError(id, -32602, err);
int durationMs = 4000; // 采集窗口:默认 4s,1-15s
GetIntArg(args, "duration_ms", durationMs);
if (durationMs < 1000) durationMs = 1000;
if (durationMs > 15000) durationMs = 15000;
int maxBytes = 64 * 1024; // 返回上限:默认 64 KiB,1-256 KiB
GetIntArg(args, "max_bytes", maxBytes);
if (maxBytes < 1024) maxBytes = 1024;
if (maxBytes > 256 * 1024) maxBytes = 256 * 1024;
// 两个写动作在开会话之前就要判定完:否则先下发 COMMAND_KEYBOARD、建好子连接,
// 再因为参数/权限问题返回错误,客户端那边已经弹起记录了。
bool setOffline = false;
const bool wantSetOffline = args.isMember("set_offline");
if (wantSetOffline) {
if (!args["set_offline"].isBool())
return BuildError(id, -32602, "set_offline must be a boolean");
setOffline = args["set_offline"].asBool();
}
bool wantClear = false;
if (args.isMember("clear")) {
if (!args["clear"].isBool())
return BuildError(id, -32602, "clear must be a boolean");
wantClear = args["clear"].asBool(); // clear=false 视为不要求
}
if ((wantSetOffline || wantClear) && mcp.IsReadonly())
return BuildError(id, -32006,
"clear / set_offline change client state: set McpReadonly=0 to use them");
context* ctx = FindMainContext(parent, devId);
if (!ctx)
return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId));
CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
if (clientType == "LNX" || clientType == "MAC" || clientType == "APK")
return BuildError(id, -32005, "get_keylog is only supported on Windows hosts");
if (!mcp.BeginKeylogSession(devId, "get_keylog", ctx))
return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId));
BYTE cmd = COMMAND_KEYBOARD;
if (!ctx->Send2Client(&cmd, 1)) {
mcp.EndManagedSession(devId, false, false);
return BuildError(id, -32004, "Failed to send command to host");
}
// 等子连接就绪包(TOKEN_KEYBOARD_START)。客户端建连很快,给 10s 余量。
std::vector<BYTE> ready;
context* sub = nullptr;
std::string clientErr;
CMcpServer::ManagedWaitResult wr = mcp.WaitManagedPacket(
devId, (BYTE)TOKEN_KEYBOARD_START, ready, sub, 10000, clientErr);
if (wr != CMcpServer::ManagedWaitResult::Ok) {
mcp.EndManagedSession(devId, sub != nullptr,
wr == CMcpServer::ManagedWaitResult::Timeout);
if (wr == CMcpServer::ManagedWaitResult::ClientError)
return BuildError(id, -32004, "Client error: " + clientErr);
if (wr == CMcpServer::ManagedWaitResult::Closed)
return BuildError(id, -32002, "Sub-connection closed before keyboard log started");
return BuildError(id, -32001, "Timeout waiting for keyboard log sub-connection");
}
// 通知「窗口已打开」:客户端 `WaitForDialogOpen` 收到 COMMAND_NEXT 立即返回,
// 不再空等 8s。本工具不开 UI,这一步只是让客户端线程别阻塞。
if (sub) {
BYTE next = COMMAND_NEXT;
sub->Send2Client(&next, 1);
}
// 就绪包格式 [TOKEN_KEYBOARD_START, offline, WORD caps, TextReplace...](client/
// KeyboardManager.cpp:162-169):byte 1 是客户端常驻记录开关的现值。老客户端也带
// 这一字节;长度不足视为没上报,响应里就不出 offlineRecord。
const bool haveOfflineFlag = ready.size() >= 2;
const bool offlineRecord = haveOfflineFlag && ready[1] != 0;
// Ok 一定带 subCtx(OnManagedSubPacket 先绑连接再置 hasResponse)。真为空说明状态机
// 出了问题:宁可报错,也不能让写动作被静默跳过、却回一份「已经清过」的结果。
if (!sub) {
mcp.EndManagedSession(devId, false, false);
return BuildError(id, -32004, "Keyboard sub-connection not bound");
}
// 写动作在采集窗口之前下发(与 MFC 的 CKeyBoardDlg 同一组命令、同一条子连接)。
// 二者都没有回执,Send2Client 只表示写进了 socket;失败就中止本次会话,别让模型
// 以为「清过了」而拿到一份其实没清的记录。
if (wantClear) {
BYTE b = COMMAND_KEYBOARD_CLEAR;
if (!sub->Send2Client(&b, 1)) {
mcp.EndManagedSession(devId, true, false);
return BuildError(id, -32004, "Failed to send clear to host");
}
}
if (wantSetOffline) {
BYTE b[2] = { COMMAND_KEYBOARD_OFFLINE, (BYTE)(setOffline ? 1 : 0) };
if (!sub->Send2Client(b, sizeof(b))) {
mcp.EndManagedSession(devId, true, false);
return BuildError(id, -32004, "Failed to send set_offline to host");
}
}
if (wantClear || wantSetOffline) {
std::string detail = std::string("clear=") + (wantClear ? "1" : "0") +
" set_offline=" + (wantSetOffline ? (setOffline ? "1" : "0") : "-");
AuditManageAction(parent, devId, "get_keylog", detail);
}
std::string collected;
bool truncated = false;
auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(durationMs);
for (;;) {
auto now = std::chrono::steady_clock::now();
if (now >= deadline) break;
int remain = (int)std::chrono::duration_cast<std::chrono::milliseconds>(
deadline - now).count();
std::string chunk;
bool chunkTrunc = false;
CMcpServer::KeylogWaitResult r =
mcp.WaitKeylogData(devId, chunk, remain > 0 ? remain : 1, chunkTrunc);
if (chunkTrunc) truncated = true;
if (!chunk.empty()) {
if (collected.size() + chunk.size() > (size_t)maxBytes) {
collected.append(chunk, 0, (size_t)maxBytes - collected.size());
truncated = true;
break;
}
collected += chunk;
if (collected.size() >= (size_t)maxBytes) { truncated = true; break; }
}
if (r == CMcpServer::KeylogWaitResult::Closed) break;
}
// 关子连接 = 让客户端停止键盘记录(与 MFC 关闭对话框同路径)。
mcp.EndManagedSession(devId, true, false);
// 编码:主连接的代码页(老客户端 GBK,新客户端可能 UTF-8)。
// 去掉夹带的 NUL,避免截断转换;按行切分并去掉行尾 '\r'。
std::string raw;
raw.reserve(collected.size());
for (char c : collected) if (c != '\0') raw.push_back(c);
std::string utf8 = ToUtf8(raw.c_str(), GetClientEncoding(ctx));
Json::Value lines(Json::arrayValue);
size_t pos = 0;
std::string joined;
while (pos < utf8.size()) {
size_t nl = utf8.find('\n', pos);
std::string line = (nl == std::string::npos) ? utf8.substr(pos)
: utf8.substr(pos, nl - pos);
if (!line.empty() && line[line.size() - 1] == '\r') line.erase(line.size() - 1);
if (!line.empty()) {
lines.append(line);
if (joined.size() < 16 * 1024) joined += line + "\n";
}
if (nl == std::string::npos) break;
pos = nl + 1;
}
Json::Value structuredContent(Json::objectValue);
structuredContent["id"] = std::to_string(devId);
structuredContent["duration_ms"] = durationMs;
structuredContent["bytes"] = (Json::Int)collected.size();
structuredContent["lines"] = lines;
structuredContent["lineCount"] = (int)lines.size();
structuredContent["truncated"] = truncated;
if (haveOfflineFlag) structuredContent["offlineRecord"] = offlineRecord;
Json::Value result(Json::objectValue);
result["structuredContent"] = structuredContent;
// 行内容已随正文外露(joined 最多 16 KB),正文外只补元数据,不再重复整份行记录。
Json::Value textPayload(Json::objectValue);
textPayload["id"] = std::to_string(devId);
textPayload["duration_ms"] = durationMs;
textPayload["bytes"] = (Json::Int)collected.size();
textPayload["lineCount"] = (int)lines.size();
textPayload["truncated"] = truncated;
SetStructuredTextPayload(result, textPayload);
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
std::string text = std::string(u8"键盘记录 ") + std::to_string(durationMs / 1000) +
std::string(u8" 秒:收到 ") + std::to_string(collected.size()) +
std::string(u8" 字节、") + std::to_string(lines.size()) +
std::string(u8" 行");
text += truncated ? std::string(u8"(已到上限,后续内容未取)。")
: std::string(u8"。");
if (!joined.empty()) text += "\n" + joined;
item["text"] = text;
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
// ===== B2:search_file(远程文件搜索,仅 Windows)=====
//
// 链路:主连接 COMMAND_LIST_DRIVE → 子连接回 TOKEN_DRIVE_LIST(OnDriveList 转下发)
// → 子连接 COMMAND_SEARCH_FILE → N×TOKEN_SEARCH_FILE_LIST → TOKEN_SEARCH_FILE_FINISH。
//
// 协议来自 client/FileManager.cpp(COMMAND_LIST_DRIVE → LoopFileManager → 这个 CFileManager),
// 不是 client/file/FileManager.cpp(那是 SimplePlugins 版,走 COMMAND_FILE_MANAGER_PLUGIN,
// MCP 的 list_files 不走那条链路)。客户端工程是 MultiByte,全部字段都是 ANSI(GBK):
// * 请求 = [COMMAND_SEARCH_FILE][根目录 \0][模式 \0](两个 NUL 结尾的字符串,无定长结构)。
// 模式里没有 * / ? 时客户端自动包成 "*模式*",即「子串、不区分大小写」;
// 含通配符则按通配符匹配(WildcardMatch)。
// * 结果 = [TOKEN_SEARCH_FILE_LIST]{ [attr:1][全路径 \0][sizeHi:4][sizeLo:4][FILETIME:8] }*,
// 一个包里可以有多条(客户端按 64KB 批量发),attr = dwFileAttributes & 0x10 → 0 或 16。
// * 客户端行为:总是递归(深度 32、最多 10000 条),跳过隐藏+系统目录与重解析点;
// COMMAND_FILES_SEARCH_STOP 只置 m_bSearching=false,搜索线程随后自然结束并发 FINISH。
// ~CFileManager 会 m_bSearching=false + WaitForSingleObject(5000) 再离开,所以即使连接
// 在搜索中途断开,旧版这个管理器也不会 UAF;我们仍然只在 FINISH 后关连接,保持保守。
//
// 协议上限约束:客户端用 char[MAX_PATH] 缓冲拼路径(ExpandEnvironmentStrings/wsprintf),
// 服务端把 path/pattern 限在 200 字节 GBK 内,给客户端留余量(见 kSearchMaxPathBytes)。
namespace {
// 客户端 SearchFilesRecursive 的 strPath[MAX_PATH]/szFullPath[MAX_PATH] 都要再拼子路径。
const size_t kSearchMaxPathBytes = 200;
const size_t kSearchMaxPatternBytes = 200;
// 去掉末尾的 '\' 或 '/'("C:\" 保留成 "C:",比较时再容忍这种差异)。
std::string StripTrailingSlashes(std::string s) {
while (s.size() > 2 && (s.back() == '\\' || s.back() == '/')) s.pop_back();
if (s.size() == 3 && s[1] == ':' && (s[2] == '\\' || s[2] == '/')) s.pop_back(); // "C:\" → "C:"
return s;
}
// Windows 路径比较:ASCII 不区分大小写(GBK 双字节按原字节比,中文本就无大小写)。
bool EqualsPathNoCase(const std::string& a, const std::string& b) {
if (a.size() != b.size()) return false;
for (size_t i = 0; i < a.size(); ++i) {
char ca = a[i], cb = b[i];
if (ca >= 'A' && ca <= 'Z') ca = (char)(ca - 'A' + 'a');
if (cb >= 'A' && cb <= 'Z') cb = (char)(cb - 'A' + 'a');
if (ca != cb) return false;
}
return true;
}
std::string FormatFileTimeLocal(const FILETIME& ftIn) {
if (ftIn.dwLowDateTime == 0 && ftIn.dwHighDateTime == 0) return "";
FILETIME local;
if (!FileTimeToLocalFileTime(&ftIn, &local)) return "";
SYSTEMTIME st;
if (!FileTimeToSystemTime(&local, &st)) return "";
char buf[32];
_snprintf_s(buf, sizeof(buf), _TRUNCATE, "%04d-%02d-%02d %02d:%02d:%02d",
st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
return buf;
}
// 一个 TOKEN_SEARCH_FILE_LIST 包里有多条记录(客户端按 64KB 批量发)。
// 客户端用 LocalReAlloc(LMEM_ZEROINIT) 扩缓冲,包尾可能带 0 填充;读到空路径即视为结束。
void AppendSearchRecords(const std::vector<BYTE>& pkt, Json::Value& out) {
if (pkt.size() < 2) return;
const size_t len = pkt.size();
size_t off = 1; // 跳过 token 字节
while (off + 1 <= len) {
const BYTE attr = pkt[off];
++off;
std::string path; // GBK 原始字节
bool terminated = false;
while (off < len) {
const char ch = (char)pkt[off++];
if (ch == 0) { terminated = true; break; }
path.push_back(ch);
}
if (!terminated || off + 16 > len) return; // 尾部截断/零填充
if (path.empty()) return; // LocalSize 的零填充
DWORD sizeHi = 0, sizeLo = 0;
memcpy(&sizeHi, pkt.data() + off, 4);
memcpy(&sizeLo, pkt.data() + off + 4, 4);
off += 8;
FILETIME ft;
memcpy(&ft, pkt.data() + off, sizeof(ft));
off += 8;
size_t slash = path.find_last_of("\\/");
const std::string name = (slash == std::string::npos) ? path : path.substr(slash + 1);
Json::Value rec(Json::objectValue);
rec["path"] = ToUtf8(path.c_str(), 936);
rec["name"] = ToUtf8(name.c_str(), 936);
rec["dir"] = (attr & FILE_ATTRIBUTE_DIRECTORY) != 0;
rec["size"] = (Json::UInt64)(((uint64_t)sizeHi << 32) | sizeLo);
std::string modified = FormatFileTimeLocal(ft);
if (!modified.empty()) rec["modified"] = modified;
out.append(rec);
}
}
} // namespace
Json::Value BuildSearchFileInputSchema() {
Json::Value props(Json::objectValue);
Json::Value idProp(Json::objectValue);
idProp["type"] = "string";
idProp["description"] = u8"主机 id(Windows 客户端)。";
props["id"] = idProp;
Json::Value pathProp(Json::objectValue);
pathProp["type"] = "string";
pathProp["description"] = u8"搜索的根目录,例如 C:\\Users 或 D:\\Data(必须是完整路径)。";
props["path"] = pathProp;
Json::Value patProp(Json::objectValue);
patProp["type"] = "string";
patProp["description"] = u8"文件名匹配串(不区分大小写),例如 report、.log、setup.exe;不含通配符时按子串匹配,含 * 或 ? 时按通配符匹配(如 *.log)。";
props["pattern"] = patProp;
Json::Value recProp(Json::objectValue);
recProp["type"] = "boolean";
recProp["description"] = u8"是否包含子目录,默认 true。客户端只支持递归搜索,传 false 时由服务端过滤出根目录下的直接子项(搜索耗时不变)。";
props["recursive"] = recProp;
Json::Value toProp(Json::objectValue);
toProp["type"] = "integer";
toProp["description"] = u8"搜索时限(毫秒),默认 20000,范围 1000-120000。到时限会通知客户端停止搜索,返回已收到的部分结果(finished=false)。";
props["timeout_ms"] = toProp;
// ===== C4:结果侧过滤 =====
Json::Value minProp(Json::objectValue);
minProp["type"] = "integer";
minProp["description"] = u8"只保留大小不小于该字节数的条目。目录项也会参与比较(客户端上报的目录 size 恒为 0),只想看文件时用 min_size=1。";
props["min_size"] = minProp;
Json::Value maxProp(Json::objectValue);
maxProp["type"] = "integer";
maxProp["description"] = u8"只保留不大于该字节数的条目。与 min_size 同时给出时区间取交集。";
props["max_size"] = maxProp;
Json::Value maProp(Json::objectValue);
maProp["type"] = "string";
maProp["description"] = u8"只保留修改时间晚于该时刻的条目,格式 YYYY-MM-DD 或 YYYY-MM-DD HH:MM:SS(主机本地时间)。只给日期时按「该日 00:00:00 之后」理解。";
props["modified_after"] = maProp;
Json::Value nameOnlyProp(Json::objectValue);
nameOnlyProp["type"] = "boolean";
nameOnlyProp["description"] = u8"true 时每条只返回 path 与 name,省略 dir/size/modified,用于结果集很大时省流量。默认 false。";
props["name_only"] = nameOnlyProp;
AppendPagingProps(props);
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("id");
required.append("path");
required.append("pattern");
schema["required"] = required;
return schema;
}
Json::Value BuildSearchFileOutputSchema() {
Json::Value props(Json::objectValue);
Json::Value filesProp(Json::objectValue);
filesProp["type"] = "array";
Json::Value items(Json::objectValue);
items["type"] = "object";
filesProp["items"] = items;
props["files"] = filesProp;
Json::Value finProp(Json::objectValue);
finProp["type"] = "boolean";
props["finished"] = finProp;
Json::Value truncProp(Json::objectValue);
truncProp["type"] = "boolean";
props["truncated"] = truncProp;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
return schema;
}
std::string BuildSearchFile(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
uint64_t devId = 0;
std::string err;
if (!ParseHostIdArg(args, devId, err))
return BuildError(id, -32602, err);
context* ctx = FindMainContext(parent, devId);
if (!ctx)
return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId));
// 该协议只在 Windows 客户端的 CFileManager 里实现(请求体是两个 GBK C 串)。
CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
if (clientType == "LNX" || clientType == "MAC" || clientType == "APK")
return BuildError(id, -32005, "search_file is only supported on Windows hosts");
std::string path = Trim(GetStringArg(args, "path"));
std::string pattern = Trim(GetStringArg(args, "pattern"));
if (path.empty())
return BuildError(id, -32602, "Missing required parameter: path (e.g. C:\\\\Users)");
if (pattern.empty())
return BuildError(id, -32602, "Missing required parameter: pattern (file name substring)");
// 客户端枚举用的是 wsprintf("%s\\*.*"):根目录带尾部反斜杠会拼成 "C:\\*.*",
// FindFirstFile 直接失败,搜索秒回 0 条。统一去尾斜杠("C:\" → "C:",客户端拼回 "C:\*.*"),
// 顺便把分隔符统一成反斜杠(记录里的全路径也是反斜杠拼的)。
for (char& c : path) if (c == '/') c = '\\';
path = StripTrailingSlashes(path);
if (path.empty() || path == "\\")
return BuildError(id, -32602,
"Invalid path: expected a directory such as C:\\ or C:\\Users");
bool recursive = true;
if (args.isMember("recursive") && args["recursive"].isBool())
recursive = args["recursive"].asBool();
int timeoutMs = 20000;
int v = 0;
if (GetIntArg(args, "timeout_ms", v)) {
if (v < 1000) v = 1000;
if (v > 120000) v = 120000;
timeoutMs = v;
}
// ===== C4:结果侧过滤参数(全部在服务端做,客户端仍只做「按名字匹配 + 递归」)=====
// 读可选的字节数参数:0=未给出;1=已给出;-1=非法(负数/非数字)。
auto readSizeArg = [](const Json::Value& a, const char* key, uint64_t& out) -> int {
if (!a.isMember(key)) return 0;
const Json::Value& val = a[key];
if (val.isNumeric() && val.asDouble() < 0) return -1;
if (!ReadUInt64(val, out)) return -1;
return 1;
};
uint64_t minSize = 0, maxSize = 0;
int hasMinSize = readSizeArg(args, "min_size", minSize);
int hasMaxSize = readSizeArg(args, "max_size", maxSize);
if (hasMinSize < 0)
return BuildError(id, -32602, "min_size must be a non-negative integer (bytes)");
if (hasMaxSize < 0)
return BuildError(id, -32602, "max_size must be a non-negative integer (bytes)");
if (hasMinSize == 1 && hasMaxSize == 1 && minSize > maxSize)
return BuildError(id, -32602, "min_size must not be greater than max_size");
// 客户端 modified 是固定宽度的 "YYYY-MM-DD HH:MM:SS",所以边界值可直接按字典序比较。
std::string modifiedAfter;
if (args.isMember("modified_after")) {
if (!args["modified_after"].isString())
return BuildError(id, -32602, "modified_after must be a string");
modifiedAfter = Trim(args["modified_after"].asString());
if (!modifiedAfter.empty()) {
bool shaped = (modifiedAfter.size() == 10 || modifiedAfter.size() == 19);
for (size_t i = 0; shaped && i < modifiedAfter.size(); ++i) {
const char c = modifiedAfter[i];
if (i == 4 || i == 7) shaped = (c == '-');
else if (i == 10) shaped = (c == ' ');
else if (i == 13 || i == 16) shaped = (c == ':'); // 19 位形式才有
else shaped = (c >= '0' && c <= '9');
}
if (!shaped)
return BuildError(id, -32602,
"modified_after must look like YYYY-MM-DD or YYYY-MM-DD HH:MM:SS");
}
}
bool nameOnly = args.isMember("name_only") && args["name_only"].isBool() &&
args["name_only"].asBool();
const bool hasResultFilter = hasMinSize == 1 || hasMaxSize == 1 ||
!modifiedAfter.empty() || nameOnly;
std::string ansiPath, ansiPattern;
if (!Utf8ToCpExact(path, 936, ansiPath))
return BuildError(id, -32602,
"path cannot be encoded in the client's ANSI code page (GBK); use ASCII-safe paths");
if (!Utf8ToCpExact(pattern, 936, ansiPattern))
return BuildError(id, -32602,
"pattern cannot be encoded in the client's ANSI code page (GBK)");
if (ansiPath.size() > kSearchMaxPathBytes)
return BuildError(id, -32602,
"path too long (max " + std::to_string(kSearchMaxPathBytes) + " bytes in GBK)");
if (ansiPattern.size() > kSearchMaxPatternBytes)
return BuildError(id, -32602,
"pattern too long (max " + std::to_string(kSearchMaxPatternBytes) + " bytes in GBK)");
// 请求体 = [根目录 \0][模式 \0](OnDriveList 前面再加 COMMAND_SEARCH_FILE)。
std::string payload;
payload.reserve(ansiPath.size() + ansiPattern.size() + 2);
payload.append(ansiPath);
payload.push_back('\0');
payload.append(ansiPattern);
payload.push_back('\0');
CMcpServer& mcp = CMcpServer::Instance();
if (!mcp.BeginPending(devId, "search_file", payload))
return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId));
BYTE cmd = COMMAND_LIST_DRIVE;
if (!ctx->Send2Client(&cmd, 1)) {
mcp.ClearPending(devId);
return BuildError(id, -32004, "Failed to send command to host");
}
std::vector<std::vector<BYTE>> packets;
bool finished = false, truncated = false;
context* subCtx = nullptr;
if (!mcp.WaitSearchFile(devId, packets, finished, truncated, subCtx, timeoutMs)) {
mcp.ClearPending(devId);
return BuildError(id, -32001, "Timeout waiting for the file manager session");
}
if (!finished) {
if (!subCtx) {
// 客户端连文件管理器子连接都没建起来(离线/拒绝/过载),不是「搜索慢」。
mcp.ClearPending(devId);
return BuildError(id, -32001, "Timeout waiting for the file manager session");
}
// 到时限:让客户端停搜(客户端搜索线程下一次循环即退出,随后回 FINISH),再给 5s 收尾。
// 收不到 FINISH 也照样返回部分结果;子连接留给 FINISH 分支关闭。
mcp.StopSearchFile(devId);
std::vector<std::vector<BYTE>> more;
bool finished2 = false, truncated2 = truncated;
context* subCtx2 = nullptr;
if (mcp.WaitSearchFile(devId, more, finished2, truncated2, subCtx2, 5000)) {
packets.insert(packets.end(), more.begin(), more.end());
finished = finished2;
truncated = truncated || truncated2;
}
}
mcp.ClearPending(devId);
Json::Value all(Json::arrayValue);
for (const auto& pkt : packets) AppendSearchRecords(pkt, all);
// 客户端只有递归搜索(深度 32),非递归请求在这里按「父目录 == 根目录」服务端过滤。
if (!recursive) {
Json::Value filtered(Json::arrayValue);
const std::string root = StripTrailingSlashes(path);
for (const Json::Value& rec : all) {
std::string p = rec["path"].asString();
size_t slash = p.find_last_of("\\/");
if (slash == std::string::npos) continue;
if (EqualsPathNoCase(StripTrailingSlashes(p.substr(0, slash)), root))
filtered.append(rec);
}
all = filtered;
}
// C4:结果侧过滤。注意它发生在收集之后——客户端的 5000 条 / 4 MB 收集上限
// 仍在过滤之前生效,命中太多时该 truncated 还是会 truncated。
const int collected = (int)all.size();
if (hasResultFilter) {
Json::Value filtered(Json::arrayValue);
for (const Json::Value& rec : all) {
if (hasMinSize == 1 || hasMaxSize == 1) {
uint64_t sz = rec["size"].asUInt64();
if (hasMinSize == 1 && sz < minSize) continue;
if (hasMaxSize == 1 && sz > maxSize) continue;
}
if (!modifiedAfter.empty()) {
std::string m = JsonStrField(rec, "modified");
if (m.empty() || m <= modifiedAfter) continue; // 字典序即时间序(格式固定)
}
if (nameOnly) {
Json::Value slim(Json::objectValue);
slim["path"] = rec["path"];
slim["name"] = rec["name"];
filtered.append(slim);
} else {
filtered.append(rec);
}
}
all = filtered;
}
PageWindow page = ResolvePageWindow(args);
Json::Value pageItems;
ApplyPageWindow(all, page, pageItems);
if (hasResultFilter) page.totalAll = collected; // total 是命中数,totalAll 是过滤前条数
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
structuredContent["files"] = pageItems;
structuredContent["finished"] = finished;
structuredContent["truncated"] = truncated;
WritePageFields(structuredContent, page);
result["structuredContent"] = structuredContent;
std::string text = PageSummary(page, u8"个匹配项");
if (hasResultFilter)
text += std::string(u8"过滤前共 ") + std::to_string(collected) +
std::string(u8" 条(大小/修改时间/精简字段过滤在服务端进行,不减少客户端搜索耗时)。");
if (!finished)
text += u8" 搜索在时限内未完成,以上为已收到的部分结果(可加大 timeout_ms 重试)。";
if (truncated)
text += u8" 命中数超过服务端收集上限(5000 条 / 4 MB),后续匹配已停止收集,请缩小 path 或 pattern 再搜。";
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = text;
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
// ===== P10-B:文件系统写操作(delete_path / move_path / create_folder)=====
//
// 链路:
// 主连接 COMMAND_LIST_DRIVE → 子连接首包 TOKEN_DRIVE_LIST(OnDriveList 转下发写命令)
// → 子连接回 TOKEN_DELETE_FINISH / TOKEN_RENAME_FINISH / TOKEN_CREATEFOLDER_FINISH
// (TakeFileOpFinish 转入复核:在同一子连接上补发 COMMAND_LIST_FILES 列父目录)
// → TOKEN_FILE_LIST(MessageHandle 现有分支投递数据并 CancelIO 收尾)
//
// 为什么必须复核:客户端四个写命令都是「做完就无条件 SendToken」,DeleteFile / MoveFile /
// MakeSureDirectoryPathExists 的返回值一概不看(也没有错误包)。所以完成包只证明「命令到了」,
// 不证明「做成了」。复核复用同一条已开的子连接再列一次父目录,代价只有一次往返。
//
// 编码:路径按客户端 ANSI(GBK) 上线(CFileManager 走 A 接口),UTF-8 → GBK 严格转换,
// 转不了直接 -32602(同 search_file),不做「转不了就传原样」的猜测。
namespace {
// 客户端用 char[MAX_PATH] 缓冲拼路径(ExpandPath / wsprintf "%s\\*.*"),
// 与 search_file 同一约束:单条路径限 200 字节 GBK,给「父目录 + 反斜杠 + 文件名」留余量。
const size_t kFileOpMaxPathBytes = 200;
bool IsFileWriteToolName(const std::string& tool) {
return tool == "delete_path" || tool == "move_path" || tool == "create_folder";
}
inline bool IsAsciiLetter(char c) { return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'); }
// 规范化 UTF-8 路径:去掉 \\?\ 前缀、分隔符统一 '\'、折叠 . 与 ..、去掉尾部分隔符。
// 只接受绝对路径(盘符 / UNC / 卷根相对):相对路径由目标机的当前目录解析,服务端既没法
// 校验保护目录,也就算不出复核用的父目录。折叠 .. 是为了保护判定不被人为的 "C:\x\..\Windows" 绕过。
bool NormalizePathUtf8(const std::string& raw, std::string& out) {
std::string in = raw;
if (in.rfind("\\\\?\\", 0) == 0 || in.rfind("\\\\.\\", 0) == 0) in = in.substr(4);
for (char& c : in) if (c == '/') c = '\\';
// 前缀:盘符 "X:"、UNC 的 "\\server\share",或卷根相对("\Windows\..." → 前缀为空)
std::string prefix;
size_t i = 0;
if (in.size() >= 2 && IsAsciiLetter(in[0]) && in[1] == ':') {
prefix = in.substr(0, 2);
i = 2;
} else if (in.rfind("\\\\", 0) == 0) {
const size_t a = in.find('\\', 2);
if (a == std::string::npos) return false; // "\\" 或 "\\server"
const size_t b = in.find('\\', a + 1);
prefix = (b == std::string::npos) ? in : in.substr(0, b);
i = prefix.size();
} else if (!in.empty() && in[0] == '\\') {
i = 1;
} else {
return false; // 相对路径
}
std::vector<std::string> segs;
while (i <= in.size()) {
size_t j = in.find('\\', i);
if (j == std::string::npos) j = in.size();
const std::string seg = in.substr(i, j - i);
if (!seg.empty() && seg != ".") {
if (seg == "..") {
if (segs.empty()) return false; // 试图越过根
segs.pop_back();
} else {
segs.push_back(seg);
}
}
i = j + 1;
}
out = prefix;
for (const std::string& s : segs) {
out += '\\';
out += s;
}
return !out.empty();
}
// 盘符根 / 卷根 / 共享根(C:、\、\\server\share):任何写操作都不能拿它当目标。
bool IsPathRoot(const std::string& p) {
if (p.size() == 2 && IsAsciiLetter(p[0]) && p[1] == ':') return true;
if (p.empty() || p.find_first_not_of('\\') == std::string::npos) return true;
if (p.rfind("\\\\", 0) == 0) {
const size_t a = p.find('\\', 2);
if (a == std::string::npos) return true; // \\server
return p.find('\\', a + 1) == std::string::npos; // \\server\share
}
return false;
}
std::string UpperAscii(std::string s) {
for (char& c : s) if (c >= 'a' && c <= 'z') c = (char)(c - 'a' + 'A');
return s;
}
// 系统目录保护。删除/改名是「毁灭」,不允许落在这些位置;建目录不受限(安装前建目录是正经用法)。
// 按整段比较:C:\Windows.old 不算 C:\Windows,C:\Program Files (x86) 单独一条。
// 带子树的是「整棵都不能动」;kProtectedExact 只挡目录本身(C:\Users\bob\... 仍是合法目标)。
const char* const kProtectedTree[] = {
"\\WINDOWS", "\\PROGRAM FILES", "\\PROGRAM FILES (X86)", "\\PROGRAMDATA",
"\\SYSTEM VOLUME INFORMATION", "\\$RECYCLE.BIN",
};
const char* const kProtectedExact[] = { "\\USERS", "\\PERFLOGS", "\\RECOVERY" };
// 入参必须是 NormalizePathUtf8 的结果。
bool IsProtectedSystemPath(const std::string& normalized) {
const std::string up = UpperAscii(normalized);
size_t i = 0;
if (up.size() >= 2 && IsAsciiLetter(up[0]) && up[1] == ':') {
i = 2;
} else if (up.rfind("\\\\", 0) == 0) {
const size_t a = up.find('\\', 2);
if (a == std::string::npos) return true; // 只有服务器名
const size_t b = up.find('\\', a + 1);
if (b == std::string::npos) return true; // 共享根本身
i = b;
}
const std::string rel = up.substr(i);
for (const char* p : kProtectedTree) {
const std::string tree = p;
if (rel == tree || rel.rfind(tree + "\\", 0) == 0) return true;
}
for (const char* p : kProtectedExact) {
if (rel == std::string(p)) return true;
}
return false;
}
// 校验一条写操作目标路径,产出上线用的 GBK 字节、复核用的父目录与末段名字。
// protectSystemDirs=true:目标本身落在系统目录内就拒绝(删除、改名的来源);
// false:只拒绝根路径(改名的去向、建目录——写到 Program Files 与 upload_file 同权限,不额外收紧)。
bool PrepareFileOpPath(const std::string& raw, bool protectSystemDirs, bool needParent,
const std::string& tool, std::string& normalized,
std::string& ansi, std::string& parentAnsi, std::string& leafUtf8,
std::string& err) {
const std::string trimmed = Trim(raw);
if (trimmed.empty()) {
err = tool + ": missing or empty path";
return false;
}
// 客户端会对路径做 ExpandEnvironmentStrings:%SystemRoot%\System32 之类的写法在服务端
// 看起来不在保护目录里,到目标机却会展开过去。服务端无从预知目标机环境,一律拒绝。
if (trimmed.find('%') != std::string::npos) {
err = tool + ": path must not contain environment variables (%VAR%): the client expands "
"them and the server cannot validate the real target. Resolve the variable first";
return false;
}
if (!NormalizePathUtf8(trimmed, normalized)) {
err = tool + ": invalid path (expected an absolute path such as C:\\\\Temp\\\\work): " + trimmed;
return false;
}
if (IsPathRoot(normalized)) {
err = tool + ": refusing to operate on a drive root or share root: " + normalized;
return false;
}
if (protectSystemDirs && IsProtectedSystemPath(normalized)) {
err = tool + ": refusing to modify a protected system location: " + normalized +
" (Windows, Program Files, ProgramData, $Recycle.Bin and their subtrees are off "
"limits; use exec_command if you really need to touch them)";
return false;
}
if (!Utf8ToCpExact(normalized, 936, ansi)) {
err = tool + ": path cannot be encoded in the client's ANSI code page (GBK): " + normalized;
return false;
}
if (ansi.size() > kFileOpMaxPathBytes) {
err = tool + ": path too long (max " + std::to_string(kFileOpMaxPathBytes) +
" bytes in GBK): " + normalized;
return false;
}
if (!needParent) return true;
const size_t slash = normalized.find_last_of('\\');
if (slash == std::string::npos) {
err = tool + ": cannot derive a parent directory from " + normalized;
return false;
}
leafUtf8 = normalized.substr(slash + 1);
// 父目录一定比整条路径短,前面已确认整条能转 GBK;这里再转一次是因为要单独上线。
if (leafUtf8.empty() || !Utf8ToCpExact(normalized.substr(0, slash), 936, parentAnsi)) {
err = tool + ": cannot derive a parent directory from " + normalized;
return false;
}
return true;
}
// 复核结果:在 TOKEN_FILE_LIST 里找末段名字。
enum class ListingLookup { Unknown, Present, Absent };
ListingLookup LookupInListing(const std::vector<BYTE>& data, const std::string& leafUtf8, bool& isDir) {
isDir = false;
if (data.empty()) return ListingLookup::Unknown;
if (data[0] == TOKEN_FILE_LIST_ERROR) {
// 新客户端的结构化失败:[token][win32err:4]。只有「不存在」能当否定结论;
// 拒绝访问说明复核本身没做成,不能据此判定操作失败。
const DWORD e = ReadWin32Payload(data);
if (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND) return ListingLookup::Absent;
return ListingLookup::Unknown;
}
if (data[0] != TOKEN_FILE_LIST) return ListingLookup::Unknown;
// 不在服务端截断:默认那 500 条是给界面用的窗口,这里要扫全(大小仍由客户端单包上限约束)。
const Json::Value items = ParseFileList(data, 1000000, 936);
for (unsigned int i = 0; i < items.size(); ++i) {
const std::string name = JsonStrField(items[i], "name");
if (EqualsPathNoCase(name, leafUtf8)) {
isDir = items[i]["isDir"].asBool();
return ListingLookup::Present;
}
}
return ListingLookup::Absent;
}
// want:0=期望目标不存在(删除);1=期望存在(改名目标);2=期望存在且是目录(建目录)。
// 返回 1=确认生效,0=确认未生效,-1=无法确认(不谎报 false)。
int ResolveFileOpVerified(ListingLookup lk, bool isDir, int want) {
if (lk == ListingLookup::Unknown) return -1;
if (lk == ListingLookup::Absent) return want == 0 ? 1 : 0;
if (want == 0) return 0; // 还在
if (want == 2) return isDir ? 1 : 0; // 同名文件挡着,目录没建成
return 1;
}
struct FileOpWait {
bool acked = false; // 收到客户端完成包(命令已送达)
bool dataIsListing = false; // 最终拿到的是复核列表(false = 完成包本身)
std::vector<BYTE> data;
};
// 等两阶段收尾。返回 false = 连完成包都没等到(超时/断线),调用方按 -32001 处理。
// phase 1 超时是特例:命令已送到客户端、只是复核没回来——结果未知,不算失败。
bool WaitFileOp(CMcpServer& mcp, uint64_t devId, FileOpWait& out) {
int phase = 0;
if (!mcp.WaitPendingWrite(devId, out.data, mcp.ToolTimeoutMs(), &phase)) {
out.acked = (phase == 1);
out.dataIsListing = false;
return out.acked;
}
out.acked = true;
out.dataIsListing = (phase == 1);
return true;
}
// 门控 + 平台检查。返回空串 = 放行;否则是完整的错误响应。
std::string GateFileWriteTool(const Json::Value& id, const std::string& tool, const Json::Value& args,
CMy2015RemoteDlg* parent, uint64_t& devId, context*& ctx) {
std::string err;
if (!ParseHostIdArg(args, devId, err)) return BuildError(id, -32602, err);
ctx = FindMainContext(parent, devId);
if (!ctx) return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId));
// 这几个命令只在 Windows 客户端的 CFileManager 里实现(GBK + A 接口);LNX/MAC 的
// FileManager.h 虽然也有同名分支,但收包按 GBK→UTF-8 解,和 list_files 的 UTF-8 口径
// 不一致,非 ASCII 路径会互相打脸,暂不开放。
const CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
if (clientType == "LNX" || clientType == "MAC" || clientType == "APK")
return BuildError(id, -32005, tool + " is only supported on Windows hosts");
CMcpServer& mcp = CMcpServer::Instance();
if (mcp.IsReadonly())
return BuildError(id, -32006, tool + " is disabled: MCP is in read-only mode (set McpReadonly=0 to enable)");
if (!mcp.IsFileWriteEnabled())
return BuildError(id, -32006, tool + " is disabled: file writes are off (set McpFileWrite=1 to enable)");
return std::string();
}
// 开子连接 + 两阶段等待。返回空串 = 结果在 out 里;否则是完整的错误响应。
std::string RunFileOp(const Json::Value& id, const std::string& tool, context* ctx, uint64_t devId,
const std::vector<BYTE>& followUp, const std::string& verifyPathAnsi,
FileOpWait& out) {
CMcpServer& mcp = CMcpServer::Instance();
if (!mcp.BeginPendingFileOp(devId, tool, followUp, verifyPathAnsi))
return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId));
BYTE cmd = COMMAND_LIST_DRIVE;
if (!ctx->Send2Client(&cmd, 1)) {
mcp.ClearPending(devId);
return BuildError(id, -32004, "Failed to send command to host");
}
if (!WaitFileOp(mcp, devId, out))
return BuildError(id, -32001,
"Timeout waiting for the client to acknowledge " + tool +
" (the command may still be executed later; re-check with list_files)");
return std::string();
}
// 统一输出:{..., ok, verified:true|false|null} + 一句可读摘要。
// 复核通过时的文案必须只描述「复核看到的状态」,不能写成「已完成删除」:客户端对不存在的
// 目标也会回完成包,而复核只能看到「现在没有这个名字」,两者无法区分(见 delete_path 描述)。
std::string BuildFileOpResult(const Json::Value& id, Json::Value structured,
const std::string& confirmedText,
const std::string& failedHint, const FileOpWait& w, int verified) {
structured["ok"] = w.acked;
if (verified == 1) structured["verified"] = true;
else if (verified == 0) structured["verified"] = false;
else structured["verified"] = Json::Value(Json::nullValue);
std::string text;
if (verified == 1) {
text = std::string(u8"复核通过:") + confirmedText;
} else if (verified == 0) {
text = std::string(u8"命令已送达客户端,但复核显示未生效:") + failedHint;
} else {
text = std::string(u8"命令已送达客户端(已收到完成包),但复核没能完成"
u8"(列目录超时或断线),结果未知;请用 list_files 再确认一次。");
}
Json::Value result(Json::objectValue);
result["structuredContent"] = structured;
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = text;
content.append(item);
result["content"] = content;
// verified=false 是「确认没成」→ 调用失败;null 只是「不知道」,不判失败。
result["isError"] = (verified == 0);
return BuildResult(id, result);
}
// 三个写工具共享的路径字段 schema
void AppendFileOpResultProps(Json::Value& props) {
Json::Value okProp(Json::objectValue);
okProp["type"] = "boolean";
okProp["description"] = u8"命令已送达客户端并收到完成回包。客户端的完成包是无条件回包,不代表操作成功。";
props["ok"] = okProp;
Json::Value verProp(Json::objectValue);
// 三态:true / false / null。声明成 ["boolean","null"],别让严格校验的客户端
// 把「复核没做成」误判成 schema 违规。
Json::Value verType(Json::arrayValue);
verType.append("boolean");
verType.append("null");
verProp["type"] = verType;
verProp["description"] = u8"复核结果:true=确认已生效,false=确认未生效,null=复核没做成(结果未知)。";
props["verified"] = verProp;
}
} // namespace
Json::Value BuildDeletePathInputSchema() {
Json::Value props(Json::objectValue);
Json::Value idProp(Json::objectValue);
idProp["type"] = "string";
idProp["description"] = u8"主机 id(Windows 客户端)。";
props["id"] = idProp;
Json::Value pathProp(Json::objectValue);
pathProp["type"] = "string";
pathProp["description"] = u8"要删除的绝对路径(文件或目录),例如 C:\\Temp\\old.log;不能含 %VAR%,不能是盘符根。";
props["path"] = pathProp;
Json::Value recProp(Json::objectValue);
recProp["type"] = "boolean";
recProp["description"] = u8"true=按目录递归删除(COMMAND_DELETE_DIRECTORY,连同子目录内容一起删);默认 false=按单个文件删除。目标其实是目录却传 false 时,客户端 DeleteFile 会失败(复核会返回 verified=false)。";
props["recursive"] = recProp;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("id");
required.append("path");
schema["required"] = required;
return schema;
}
Json::Value BuildDeletePathOutputSchema() {
Json::Value props(Json::objectValue);
AppendFileOpResultProps(props);
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
return schema;
}
Json::Value BuildMovePathInputSchema() {
Json::Value props(Json::objectValue);
Json::Value idProp(Json::objectValue);
idProp["type"] = "string";
idProp["description"] = u8"主机 id(Windows 客户端)。";
props["id"] = idProp;
Json::Value fromProp(Json::objectValue);
fromProp["type"] = "string";
fromProp["description"] = u8"原来的绝对路径(文件或目录),例如 C:\\Temp\\a.txt。";
props["from"] = fromProp;
Json::Value toProp(Json::objectValue);
toProp["type"] = "string";
toProp["description"] = u8"新的完整路径(含新名字),例如 C:\\Temp\\b.txt;必须在同一卷内。";
props["to"] = toProp;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("id");
required.append("from");
required.append("to");
schema["required"] = required;
return schema;
}
Json::Value BuildMovePathOutputSchema() {
Json::Value props(Json::objectValue);
AppendFileOpResultProps(props);
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
return schema;
}
Json::Value BuildCreateFolderInputSchema() {
Json::Value props(Json::objectValue);
Json::Value idProp(Json::objectValue);
idProp["type"] = "string";
idProp["description"] = u8"主机 id(Windows 客户端)。";
props["id"] = idProp;
Json::Value pathProp(Json::objectValue);
pathProp["type"] = "string";
pathProp["description"] = u8"要创建的目录绝对路径,例如 C:\\Temp\\report\\2026;缺失的中间层会一并创建。";
props["path"] = pathProp;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("id");
required.append("path");
schema["required"] = required;
return schema;
}
Json::Value BuildCreateFolderOutputSchema() {
Json::Value props(Json::objectValue);
AppendFileOpResultProps(props);
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
return schema;
}
std::string BuildDeletePath(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
const std::string tool = "delete_path";
uint64_t devId = 0;
context* ctx = nullptr;
std::string err = GateFileWriteTool(id, tool, args, parent, devId, ctx);
if (!err.empty()) return err;
const bool recursive = args.isMember("recursive") && args["recursive"].isBool() &&
args["recursive"].asBool();
std::string normalized, ansi, parentAnsi, leafUtf8;
if (!PrepareFileOpPath(GetStringArg(args, "path"), true, true, tool,
normalized, ansi, parentAnsi, leafUtf8, err))
return BuildError(id, -32602, err);
// 递归删除走 COMMAND_DELETE_DIRECTORY(客户端 DeleteDirectory 会先清子项再删目录)。
// path 后必须补 '\0':客户端按 C 串取路径。
std::vector<BYTE> followUp;
followUp.reserve(2 + ansi.size());
followUp.push_back(recursive ? (BYTE)COMMAND_DELETE_DIRECTORY : (BYTE)COMMAND_DELETE_FILE);
followUp.insert(followUp.end(), ansi.begin(), ansi.end());
followUp.push_back(0);
FileOpWait w;
err = RunFileOp(id, tool, ctx, devId, followUp, parentAnsi, w);
if (!err.empty()) return err;
AuditManageAction(parent, devId, tool,
std::string("path=") + normalized + (recursive ? " recursive=1" : " recursive=0"));
int verified = -1;
if (w.dataIsListing) {
bool isDir = false;
// isDir 是 LookupInListing 的出参,必须先单独调用:写成
// ResolveFileOpVerified(LookupInListing(..., isDir), isDir, ...) 会读到未赋值的 false
// (实参求值顺序未指定,MSVC 从右往左先算 isDir)。
const ListingLookup lk = LookupInListing(w.data, leafUtf8, isDir);
verified = ResolveFileOpVerified(lk, isDir, 0);
}
Json::Value sc(Json::objectValue);
sc["id"] = std::to_string(devId);
sc["path"] = normalized;
sc["recursive"] = recursive;
return BuildFileOpResult(id, sc,
u8"\"" + normalized + u8"\" 已不在父目录列表里"
u8"(目标本来就不存在时也是这个结果——客户端不回错误包)。",
u8"目标仍在(只读文件、被占用或权限不足都会静默失败;"
u8"也可能是 recursive=false 落在了目录上:" + normalized + u8")。",
w, verified);
}
std::string BuildMovePath(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
const std::string tool = "move_path";
uint64_t devId = 0;
context* ctx = nullptr;
std::string err = GateFileWriteTool(id, tool, args, parent, devId, ctx);
if (!err.empty()) return err;
// 来源按「会被拿走」对待,受系统目录保护;去向只拒绝根路径(写入 Program Files 的权限
// 与 upload_file 相同,不额外收紧)。
std::string fromNorm, fromAnsi, ignored1, ignored2;
if (!PrepareFileOpPath(GetStringArg(args, "from"), true, false, tool,
fromNorm, fromAnsi, ignored1, ignored2, err))
return BuildError(id, -32602, err);
std::string toNorm, toAnsi, toParentAnsi, toLeafUtf8;
if (!PrepareFileOpPath(GetStringArg(args, "to"), false, true, tool,
toNorm, toAnsi, toParentAnsi, toLeafUtf8, err))
return BuildError(id, -32602, err);
if (EqualsPathNoCase(fromNorm, toNorm))
return BuildError(id, -32602, "move_path: from and to are the same path: " + fromNorm);
// 请求体 = [from\0][to\0](首字节是命令)。客户端用 ::MoveFile,同卷内文件与目录都能搬。
std::vector<BYTE> followUp;
followUp.reserve(3 + fromAnsi.size() + toAnsi.size());
followUp.push_back((BYTE)COMMAND_RENAME_FILE);
followUp.insert(followUp.end(), fromAnsi.begin(), fromAnsi.end());
followUp.push_back(0);
followUp.insert(followUp.end(), toAnsi.begin(), toAnsi.end());
followUp.push_back(0);
FileOpWait w;
err = RunFileOp(id, tool, ctx, devId, followUp, toParentAnsi, w);
if (!err.empty()) return err;
AuditManageAction(parent, devId, tool, "from=" + fromNorm + " to=" + toNorm);
int verified = -1;
if (w.dataIsListing) {
bool isDir = false;
// 同 delete_path:先调用再取值,别把出参和调用写进同一句实参表。
const ListingLookup lk = LookupInListing(w.data, toLeafUtf8, isDir);
verified = ResolveFileOpVerified(lk, isDir, 1);
}
Json::Value sc(Json::objectValue);
sc["id"] = std::to_string(devId);
sc["from"] = fromNorm;
sc["to"] = toNorm;
return BuildFileOpResult(id, sc,
u8"\"" + toNorm + u8"\" 已出现在父目录列表里(原路径 \""
+ fromNorm + u8"\" 是否已消失不在复核范围内)。",
u8"新名字没有出现在目标目录里(目标已存在、跨卷、只读或被占用都会"
u8"让 ::MoveFile 静默失败):\"" + toNorm + u8"\"。",
w, verified);
}
std::string BuildCreateFolder(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
const std::string tool = "create_folder";
uint64_t devId = 0;
context* ctx = nullptr;
std::string err = GateFileWriteTool(id, tool, args, parent, devId, ctx);
if (!err.empty()) return err;
std::string normalized, ansi, parentAnsi, leafUtf8;
if (!PrepareFileOpPath(GetStringArg(args, "path"), false, true, tool,
normalized, ansi, parentAnsi, leafUtf8, err))
return BuildError(id, -32602, err);
// 结尾必须补一个 '\\':客户端 CFileManager::CreateFolder 直接把这段字节丢给
// MakeSureDirectoryPathExists,而它是「路径里每个以反斜杠结尾的片段都要存在」的语义
// ——不带尾部反斜杠时最后一级被当成文件名,压根不会被创建(MFC 的 OnRemoteNewfolder
// 也是拼 m_Remote_Path + name + "\\")。delete 恰好相反:RemoveDirectory 不接受尾部
// 反斜杠,所以那边保持去掉分隔符的写法。
std::vector<BYTE> followUp;
followUp.reserve(3 + ansi.size());
followUp.push_back((BYTE)COMMAND_CREATE_FOLDER);
followUp.insert(followUp.end(), ansi.begin(), ansi.end());
followUp.push_back('\\');
followUp.push_back(0);
FileOpWait w;
err = RunFileOp(id, tool, ctx, devId, followUp, parentAnsi, w);
if (!err.empty()) return err;
AuditManageAction(parent, devId, tool, "path=" + normalized);
int verified = -1;
if (w.dataIsListing) {
bool isDir = false;
// 这一处最要命:want=2 会读 isDir,写成一行时 isDir 永远是初始的 false,
// 于是「建目录」永远自评「未生效」(同 delete_path 的注释)。
const ListingLookup lk = LookupInListing(w.data, leafUtf8, isDir);
verified = ResolveFileOpVerified(lk, isDir, 2);
}
Json::Value sc(Json::objectValue);
sc["id"] = std::to_string(devId);
sc["path"] = normalized;
return BuildFileOpResult(id, sc,
u8"\"" + normalized + u8"\" 已存在且确实是目录。",
u8"复核时没看到这个目录,或同名条目是文件而不是目录(权限不足、"
u8"路径被占用等都会静默失败):\"" + normalized + u8"\"。",
w, verified);
}
// ===== B1:主机库元数据 schema =====
Json::Value BuildHostSetRemarkInputSchema() {
Json::Value props(Json::objectValue);
Json::Value idProp(Json::objectValue);
idProp["type"] = "string";
idProp["description"] = u8"主机 id(list_online_hosts / list_all_hosts 返回的十进制字符串)。";
props["id"] = idProp;
Json::Value remarkProp(Json::objectValue);
remarkProp["type"] = "string";
remarkProp["description"] = u8"备注文本(UTF-8);空字符串表示清除备注;GBK 编码后最长 63 字节。";
props["remark"] = remarkProp;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("id");
required.append("remark");
schema["required"] = required;
return schema;
}
Json::Value BuildHostSetRemarkOutputSchema() {
Json::Value props(Json::objectValue);
Json::Value idProp(Json::objectValue);
idProp["type"] = "string";
props["id"] = idProp;
Json::Value remarkProp(Json::objectValue);
remarkProp["type"] = "string";
props["remark"] = remarkProp;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
return schema;
}
Json::Value BuildHostSetWatchLevelInputSchema() {
Json::Value props(Json::objectValue);
Json::Value idProp(Json::objectValue);
idProp["type"] = "string";
idProp["description"] = u8"主机 id(在线或离线历史记录均可)。";
props["id"] = idProp;
Json::Value levelProp(Json::objectValue);
levelProp["type"] = "integer";
levelProp["minimum"] = 0;
levelProp["maximum"] = 3;
levelProp["description"] = u8"关注等级:0=无、1=蓝字、2=红字、3=红底(服务端在线列表现色)。";
props["level"] = levelProp;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("id");
required.append("level");
schema["required"] = required;
return schema;
}
Json::Value BuildHostSetWatchLevelOutputSchema() {
Json::Value props(Json::objectValue);
Json::Value idProp(Json::objectValue);
idProp["type"] = "string";
props["id"] = idProp;
Json::Value levelProp(Json::objectValue);
levelProp["type"] = "integer";
props["level"] = levelProp;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
return schema;
}
// ===== N2:批量只读调用(ids[]) =====
//
// 只读工具支持一次传多个主机 id(args.ids),服务端逐个调用单机实现并把结果汇总到
// structuredContent.results。写操作工具一律不支持批量(避免一次误操作波及多台)。
// 每个 id 的单机结果仍带各自的 limit/offset/total/hasMore —— 分页是「每台主机各自的」。
static const size_t kBatchMaxIds = 50;
// 批量整体时限:50 台 × 单机 20s 最坏能拖到 1000s,远超 MCP 客户端自身的工具超时。
// 到了时限就不再对剩余 id 下发(标 skipped),保证响应在客户端放弃之前返回。
// 注意:时限只在「下一台开始前」检查,正在跑的那一台仍会跑完它自己的超时,
// 所以真实上限约为 50s + 单机超时(20s)。要更紧就得把 deadline 一路传进各工具。
static const long long kBatchDeadlineMs = 50000;
// IsBatchReadOnlyTool 定义在 McpInternal.cpp:tools/list 要用它补 outputSchema,
// tools/call 要用它做批量入口判定,两处必须共用同一份清单,故不再在此重复定义。
// ===== 平台门禁:调用前拦掉「该客户端根本没实现」的组合 =====
//
// 判据来自各平台客户端对相应 COMMAND_ 的处理实现,不能看「是否引用了常量」:
// - android/.../main.cpp:534-540 的 COMMAND_SYSTEM / COMMAND_SHELL 都是空实现
// - macOS 能处理 SEND_FILE_V2,但 DefaultCaps() 不给 SCREEN_PREVIEW,截屏仍不可用
// 表内容与 mcp/tools.json 的 platforms 字段一一对应,
// tools/mcp_tools/check_platform_table.py 会校验两边一致。
//
// 这里只做平台级粗筛。能力位门槛(SCREEN_PREVIEW / V2 / C2C_PATHS)仍留在各工具内部,
// 因为像「Linux 这台机器有没有 X11 桌面」只有运行时才知道。
enum : uint8_t {
kPlatWin = 1,
kPlatLnx = 2,
kPlatMac = 4,
kPlatApk = 8,
};
struct ToolPlatform {
const char* name;
uint8_t mask;
};
// mask 为 0 或表里查不到 = 不限制。新增工具忘了登记时按放行处理(宁可漏拦,不可误拒),
// 遗漏由 check_platform_table.py 的工具数比对发现。
const ToolPlatform kToolPlatforms[] = {
// ---- win+lnx+mac+apk ---- 只读写服务端本地数据,与客户端平台无关
{ "list_online_hosts", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
{ "search_hosts", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
{ "list_all_hosts", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
{ "get_host_detail", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
{ "get_audit_log", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
{ "get_server_status", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
{ "mcp_list_sessions", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
{ "mcp_cancel_session", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
{ "host_set_remark", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
{ "host_set_watch_level", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
// ---- win+lnx+mac ---- SYSTEM / LIST_DRIVE / QUERY_LOG / V2 文件传输
{ "list_processes", kPlatWin|kPlatLnx|kPlatMac },
{ "list_files", kPlatWin|kPlatLnx|kPlatMac },
{ "get_client_log", kPlatWin|kPlatLnx|kPlatMac },
{ "download_file", kPlatWin|kPlatLnx|kPlatMac },
{ "upload_file", kPlatWin|kPlatLnx|kPlatMac },
// ---- win+lnx ---- 远程控制全族 + 需 SCREEN_PREVIEW 的截屏 + macOS 未开放项
{ "get_screenshot", kPlatWin|kPlatLnx },
{ "remote_open", kPlatWin|kPlatLnx },
{ "remote_close", kPlatWin|kPlatLnx },
{ "remote_keyboard", kPlatWin|kPlatLnx },
{ "remote_mouse", kPlatWin|kPlatLnx },
{ "remote_clipboard", kPlatWin|kPlatLnx },
// macOS 客户端有 PTY 实现(macos/main.mm:753),但服务端刻意不开放
// (McpServer.cpp:3652「macOS 本轮不开放」),故实际不可用
{ "exec_command", kPlatWin|kPlatLnx },
{ "terminal_open", kPlatWin|kPlatLnx },
{ "terminal_exec", kPlatWin|kPlatLnx },
{ "terminal_close", kPlatWin|kPlatLnx },
// macOS 客户端有 COMMAND_KILLPROCESS 分支,服务端同样拦着(McpServer.cpp:6870)
{ "kill_process", kPlatWin|kPlatLnx },
// ---- win ---- 服务 / 注册表 / 键日志 / 文件写 / host_* / chat_* / power_action
// list_windows 单列:BuildListWindows 把 COMMAND_WSLIST 发在**主连接**上
// (McpServer.cpp:2931 的 Send2Client),而 Linux/macOS 主循环只处理 COMMAND_SYSTEM
// (起 SystemManager 子连接),WSLIST 只在子连接里处理 —— 走不到,实测 Linux 上
// 直接超时 -32001。Windows 是在主循环里处理的(client/KernelManager.cpp:1491)。
// 注意别被 linux/SystemManager.h:38 和 macos/SystemManager.mm:39 的 case 骗到,
// 那是给 SystemDlg 窗口管理用的,不是 MCP 这条路径。
{ "list_windows", kPlatWin },
// Linux 客户端已实现 COMMAND_QUERY_ACTIVITY → TOKEN_REPORT_ACTIVITY(linux/LinuxActivityHistory.h,
// 有桌面走 X11 窗口采样,无桌面走 last + shell 历史),与 Windows 同为主连接 RPC
{ "get_activity_history", kPlatWin|kPlatLnx },
{ "list_services", kPlatWin },
{ "get_keylog", kPlatWin },
{ "list_registry", kPlatWin },
{ "remote_block_input", kPlatWin },
// 两端并集。方向性差异由 CollectTargetReqs 精确处理:源端必须 win,目标端 win/lnx/mac
{ "copy_files_c2c", kPlatWin|kPlatLnx|kPlatMac },
{ "operate_window", kPlatWin },
{ "control_service", kPlatWin },
{ "power_action", kPlatWin },
{ "search_file", kPlatWin },
{ "delete_path", kPlatWin },
{ "move_path", kPlatWin },
{ "create_folder", kPlatWin },
{ "list_network_connections", kPlatWin },
{ "kill_network_connection", kPlatWin },
{ "host_list_processes", kPlatWin },
{ "host_list_windows", kPlatWin },
{ "host_list_network_state", kPlatWin },
{ "host_list_software", kPlatWin },
{ "host_list_browser_history", kPlatWin },
{ "host_list_favorites", kPlatWin },
{ "host_list_win32_services", kPlatWin },
{ "host_list_driver_services", kPlatWin },
{ "host_list_scheduled_tasks", kPlatWin },
{ "host_get_hosts_file", kPlatWin },
{ "host_control_process", kPlatWin },
{ "host_control_window", kPlatWin },
{ "host_control_service", kPlatWin },
{ "host_control_task", kPlatWin },
{ "chat_open", kPlatWin },
{ "chat_send", kPlatWin },
{ "chat_wait", kPlatWin },
{ "chat_close", kPlatWin },
};
// 未知的 clientType 一律按 Windows:EXE/DLL/MEXE/SC/MDLL 都走这个分支,
// 将来新增平台在没有明确登记前也不会被误拦。
uint8_t CurrentClientPlatform(context* ctx) {
CString t = ctx->GetAdditionalData(RES_CLIENT_TYPE);
if (t == "LNX") return kPlatLnx;
if (t == "MAC") return kPlatMac;
if (t == "APK") return kPlatApk;
return kPlatWin;
}
const char* PlatformName(uint8_t p) {
switch (p) {
case kPlatLnx: return "lnx";
case kPlatMac: return "mac";
case kPlatApk: return "apk";
default: return "win";
}
}
std::string PlatformNames(uint8_t mask) {
std::string s;
if (mask & kPlatWin) s += "win ";
if (mask & kPlatLnx) s += "lnx ";
if (mask & kPlatMac) s += "mac ";
if (mask & kPlatApk) s += "apk ";
if (!s.empty()) s.pop_back();
return s;
}
// 一台主机 + 它在这个工具里被允许的平台集合。
struct TargetReq {
uint64_t id;
uint8_t mask;
};
bool AddIdReq(const Json::Value& args, const char* key, uint8_t mask,
std::vector<TargetReq>& reqs) {
if (!args[key].isString()) return false;
const std::string sid = args[key].asString();
if (sid.empty() || sid.find_first_not_of("0123456789") != std::string::npos) return false;
reqs.push_back({ strtoull(sid.c_str(), nullptr, 10), mask });
return true;
}
// 取出这个工具真正要操作的主机,以及每台主机各自的平台要求。
// 绝大多数工具只有一个目标、用统一的 defaultMask;copy_files_c2c 是唯一的
// 非对称工具,源端和目标端的平台要求不同,必须分开查:
// src_id —— 只有 Windows 实现了 C2C 发送逻辑(client/KernelManager.cpp)
// dst_id —— 只需 CLIENT_CAP_V2 收包,Windows / Linux / macOS 都行
// 反过来 Linux → Windows 不支持:POSIX 客户端没有 C2C_PATHS 发送实现。
// 返回 false = 这个工具不针对某台主机(服务端本地工具),不需要门禁。
bool CollectTargetReqs(const std::string& toolName, const Json::Value& args,
uint8_t defaultMask, std::vector<TargetReq>& reqs) {
// 多主机工具必须先判断:它的 schema 里没有 "id",但调用方可以多塞一个 id 进来。
// 若先走 ParseHostIdArg,就只会检查那一台主机,真正的 src_id / dst_id 反而漏过去。
if (toolName == "copy_files_c2c") {
AddIdReq(args, "src_id", kPlatWin, reqs);
AddIdReq(args, "dst_id", kPlatWin|kPlatLnx|kPlatMac, reqs);
return !reqs.empty();
}
uint64_t devId = 0;
std::string err;
if (!ParseHostIdArg(args, devId, err)) return false; // 无 id:服务端本地工具
reqs.push_back({ devId, defaultMask });
return true;
}
// 返回空串 = 放行;非空 = 可直接作为 tools/call 结果返回的错误 JSON。
// 主机不存在/离线时跳过该 id,把 -32002 留给工具自己报,避免同一问题出现两种错误码。
std::string CheckToolPlatform(const Json::Value& id, const std::string& toolName,
const Json::Value& args, CMy2015RemoteDlg* parent) {
if (!CMcpServer::Instance().IsPlatformGuardEnabled()) return "";
uint8_t mask = 0;
for (const ToolPlatform& e : kToolPlatforms) {
if (toolName == e.name) { mask = e.mask; break; }
}
if (mask == 0) return "";
std::vector<TargetReq> reqs;
if (!CollectTargetReqs(toolName, args, mask, reqs)) return ""; // 无 id:服务端本地工具
for (const TargetReq& req : reqs) {
context* ctx = FindMainContext(parent, req.id);
if (!ctx) continue;
const uint8_t cur = CurrentClientPlatform(ctx);
if (req.mask & cur) continue;
CString ct = ctx->GetAdditionalData(RES_CLIENT_TYPE);
std::string msg;
msg += std::string(u8"该主机平台是 ");
msg += PlatformName(cur);
msg += std::string(u8"(clientType=");
msg += std::string((LPCSTR)ct);
msg += std::string(u8"),");
msg += toolName;
msg += std::string(u8" 在此主机上仅支持 ");
msg += PlatformNames(req.mask);
msg += std::string(u8"。按 instructions 第 5 节换用该平台支持的等价工具。");
return BuildError(id, -32005, msg);
}
return "";
}
// 单主机分派:批量路径复用它,保证批量与单机走同一套实现。
std::string DispatchSingleHostTool(const Json::Value& id, const std::string& toolName,
const Json::Value& args, CMy2015RemoteDlg* parent);
Json::Value MakeBatchErrorEntry(const std::string& hostId, int code, const std::string& msg) {
Json::Value entry(Json::objectValue);
entry["id"] = hostId;
entry["ok"] = false;
Json::Value err(Json::objectValue);
err["code"] = code;
err["message"] = msg;
entry["error"] = err;
return entry;
}
// 批量整体时限用尽后,剩余 id 的占位结果:明确标 skipped(未下发),
// 与「试过但失败」区分开,避免调用方误以为这些都是主机侧错误。
Json::Value MakeBatchSkippedEntry(const std::string& hostId) {
Json::Value entry = MakeBatchErrorEntry(hostId, -32001,
"Batch deadline exceeded (" + std::to_string(kBatchDeadlineMs / 1000) +
" s): not attempted");
entry["skipped"] = true;
return entry;
}
std::string BuildBatchCall(const Json::Value& id, const std::string& toolName,
const Json::Value& args, CMy2015RemoteDlg* parent) {
const Json::Value& ids = args["ids"];
if (ids.size() > kBatchMaxIds) {
return BuildError(id, -32602,
"Too many ids: " + std::to_string(ids.size()) + " (max " +
std::to_string(kBatchMaxIds) + " per batch)");
}
Json::Value results(Json::arrayValue);
int okCount = 0, failCount = 0, skipCount = 0;
std::string failLines;
const auto batchDeadline =
std::chrono::steady_clock::now() + std::chrono::milliseconds(kBatchDeadlineMs);
bool deadlineHit = false;
for (const Json::Value& v : ids) {
std::string hostId;
if (v.isString()) hostId = v.asString();
else if (v.isNumeric()) hostId = std::to_string(v.asUInt64());
if (!IsDigits(hostId)) {
results.append(MakeBatchErrorEntry(hostId, -32602,
"Invalid id: expected a decimal host id string"));
++failCount;
if (failLines.size() < 1200)
failLines += "\n - " + (hostId.empty() ? std::string("(empty)") : hostId) +
": Invalid id: expected a decimal host id string";
continue;
}
// 整体时限:一旦命中,后面所有 id 都不再下发(只记 skipped,不等待)。
if (deadlineHit || std::chrono::steady_clock::now() >= batchDeadline) {
deadlineHit = true;
results.append(MakeBatchSkippedEntry(hostId));
++skipCount;
continue;
}
Json::Value oneArgs = args;
oneArgs.removeMember("ids");
oneArgs["id"] = hostId;
std::string raw = DispatchSingleHostTool(id, toolName, oneArgs, parent);
Json::Value parsed;
Json::CharReaderBuilder rb;
std::string parseErrs;
std::istringstream iss(raw);
if (!Json::parseFromStream(rb, iss, &parsed, &parseErrs) || !parsed.isObject()) {
results.append(MakeBatchErrorEntry(hostId, -32603,
"Internal error: failed to parse host result"));
++failCount;
continue;
}
if (parsed.isMember("error")) {
Json::Value entry = MakeBatchErrorEntry(hostId, -32603, "");
entry["error"] = parsed["error"];
results.append(entry);
++failCount;
std::string msg = JsonStrField(parsed["error"], "message");
if (failLines.size() < 1200)
failLines += "\n - " + hostId + ": " + msg;
continue;
}
const Json::Value& r = parsed["result"];
bool isError = r.isMember("isError") && r["isError"].isBool() && r["isError"].asBool();
Json::Value entry(Json::objectValue);
entry["id"] = hostId;
entry["ok"] = !isError;
if (r.isMember("structuredContent")) entry["data"] = r["structuredContent"];
std::string firstText;
if (r.isMember("content") && r["content"].isArray() && !r["content"].empty())
firstText = JsonStrField(r["content"][0], "text");
if (!firstText.empty()) entry["text"] = firstText;
results.append(entry);
if (isError) {
++failCount;
if (failLines.size() < 1200)
failLines += "\n - " + hostId + ": " + firstText;
} else {
++okCount;
}
}
Json::Value structuredContent(Json::objectValue);
structuredContent["tool"] = toolName;
structuredContent["total"] = (int)ids.size();
structuredContent["succeeded"] = okCount;
structuredContent["failed"] = failCount;
structuredContent["skipped"] = skipCount;
structuredContent["results"] = results;
Json::Value result(Json::objectValue);
result["structuredContent"] = structuredContent;
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = std::string(u8"批量调用 ") + toolName + std::string(u8":共 ") +
std::to_string(ids.size()) + std::string(u8" 台,成功 ") +
std::to_string(okCount) + std::string(u8" 台,失败 ") +
std::to_string(failCount) + std::string(u8" 台") +
(skipCount > 0
? std::string(u8",超时跳过 ") + std::to_string(skipCount) + std::string(u8" 台")
: std::string()) +
std::string(u8"。") + failLines;
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
// tools/call 分派
std::string BuildToolsCall(const Json::Value& root, CMy2015RemoteDlg* parent) {
const Json::Value& id = root["id"];
Json::Value params = root.isMember("params") ? root["params"] : Json::Value(Json::objectValue);
std::string toolName;
if (params.isObject() && params.isMember("name") && params["name"].isString()) {
toolName = params["name"].asString();
}
const Json::Value args = GetCallArguments(params);
// N2:带 ids[] 即走批量只读路径。
if (args.isObject() && args.isMember("ids") && args["ids"].isArray()) {
if (!IsBatchReadOnlyTool(toolName)) {
return BuildError(id, -32602,
"Batch calls are only supported for read-only tools, and " + toolName +
" is not one of them.");
}
return BuildBatchCall(id, toolName, args, parent);
}
return DispatchSingleHostTool(id, toolName, args, parent);
}
std::string DispatchSingleHostTool(const Json::Value& id, const std::string& toolName,
const Json::Value& args, CMy2015RemoteDlg* parent) {
// 平台门禁:放在所有分派之前,批量路径也会经过这里(BuildBatchCall 循环调用本函数),
// 所以不需要在批量入口重复一次。主机不存在/离线时放行,让各工具自己报 -32002。
{
std::string platErr = CheckToolPlatform(id, toolName, args, parent);
if (!platErr.empty()) return platErr;
}
// P8:连接管理 / 主机管理工具族(独立分发;门控在 McpMachine::Call 内复核)。
if (McpMachine::Handles(toolName)) return McpMachine::Call(id, toolName, args, parent);
// P9:远程交谈工具族(独立开关 McpChat;门控在 McpChat::Call 内复核)。
if (McpChat::Handles(toolName)) return McpChat::Call(id, toolName, args, parent);
if (toolName == "list_online_hosts") return BuildListOnlineHosts(id, args, parent);
if (toolName == "list_all_hosts") return BuildListAllHosts(id, args, parent);
if (toolName == "search_hosts") return BuildSearchHosts(id, args, parent);
if (toolName == "get_host_detail") return BuildGetHostDetail(id, args, parent);
if (toolName == "list_processes") return BuildListProcesses(id, args, parent);
if (toolName == "list_windows") return BuildListWindows(id, args, parent);
if (toolName == "get_activity_history") return BuildGetActivityHistory(id, args, parent);
if (toolName == "get_screenshot") return BuildGetScreenshot(id, args, parent);
if (toolName == "list_files") return BuildListFiles(id, args, parent);
if (toolName == "list_services") return BuildListServices(id, args, parent);
if (toolName == "get_client_log") return BuildGetClientLog(id, args, parent);
if (toolName == "get_keylog") return BuildGetKeylog(id, args, parent);
if (toolName == "get_audit_log") return BuildGetAuditLog(id, args, parent);
if (toolName == "get_server_status") return BuildGetServerStatus(id, parent);
// P11:服务端自身会话的观测 / 取消(无主机、纯本地;不受功能开关与只读限制)。
if (toolName == "mcp_list_sessions") return BuildMcpListSessions(id, args);
if (toolName == "mcp_cancel_session") return BuildMcpCancelSession(id, args);
if (toolName == "list_registry") return BuildListRegistry(id, args, parent);
if (toolName == "exec_command") return BuildExecCommand(id, args, parent);
if (toolName == "terminal_open") return BuildTerminalOpen(id, args, parent);
if (toolName == "terminal_exec") return BuildTerminalExec(id, args, parent);
if (toolName == "terminal_close") return BuildTerminalClose(id, args, parent);
if (toolName == "remote_open") return BuildRemoteOpen(id, args, parent);
if (toolName == "remote_close") return BuildRemoteClose(id, args, parent);
if (toolName == "remote_keyboard") return BuildRemoteKeyboard(id, args, parent);
if (toolName == "remote_mouse") return BuildRemoteMouse(id, args, parent);
if (toolName == "remote_clipboard") return BuildRemoteClipboard(id, args, parent);
if (toolName == "remote_block_input") return BuildRemoteBlockInput(id, args, parent);
if (toolName == "download_file") return BuildDownloadFile(id, args, parent);
if (toolName == "upload_file") return BuildUploadFile(id, args, parent);
if (toolName == "copy_files_c2c") return BuildCopyFilesC2C(id, args, parent);
if (toolName == "kill_process") return BuildKillProcess(id, args, parent);
if (toolName == "operate_window") return BuildOperateWindow(id, args, parent);
if (toolName == "control_service") return BuildControlService(id, args, parent);
if (toolName == "power_action") return BuildPowerAction(id, args, parent);
if (toolName == "host_set_remark") return BuildHostSetRemark(id, args, parent);
if (toolName == "host_set_watch_level") return BuildHostSetWatchLevel(id, args, parent);
if (toolName == "search_file") return BuildSearchFile(id, args, parent);
if (toolName == "delete_path") return BuildDeletePath(id, args, parent);
if (toolName == "move_path") return BuildMovePath(id, args, parent);
if (toolName == "create_folder") return BuildCreateFolder(id, args, parent);
return BuildError(id, -32602,
"Unknown tool: " + (toolName.empty() ? std::string("(empty)") : toolName));
}
} // namespace
// ===== P3:exec_command 哨兵检测与终端会话 =====
// 在原始 shell 输出字节流中定位哨兵(纯 ASCII,编码无关)。哨兵后紧跟退出码数字(可带负号)。
//
// ConPTY 会把输入整行回显进输出流,因此「哨兵必须独占行首」这条旧规则反而会把真实哨兵
// 排除掉(命令最后一行没有换行时哨兵会接在其后),再往前命中回显里的 &&/|| 片段,得到
// 错误的退出码(评审 P3,`ver` → exit_code=1)。现在两种哨兵形态都能安全地不依赖行首:
// - 新形态(ConPTY):回显文本里是字面 "%errorlevel%",不是数字,天然不可能命中;
// - 老形态(非 PTY):回显由客户端按写入长度跳过,且回显中的片段在真实哨兵之前。
// 故从后往前找第一个「标记 + 数字」即可。
static bool FindSentinel(const std::vector<BYTE>& buf, const std::string& nonce,
size_t& pos, int& exitCode) {
std::string marker = "__MCP_DONE_" + nonce + "__";
if (marker.size() + 1 > buf.size()) return false;
std::string s((const char*)buf.data(), buf.size());
size_t from = std::string::npos;
while (true) {
size_t p = s.rfind(marker, from);
if (p == std::string::npos) return false;
size_t q = p + marker.size();
bool neg = false;
if (q < s.size() && s[q] == '-') { neg = true; ++q; }
size_t digits = q;
long long v = 0;
while (q < s.size() && s[q] >= '0' && s[q] <= '9' && q - digits < 9) {
v = v * 10 + (s[q] - '0');
++q;
}
if (q > digits) {
exitCode = (int)(neg ? -v : v);
pos = p;
return true;
}
if (p == 0) return false;
from = p - 1;
}
}
bool CMcpServer::IsTermPending(uint64_t device_id) {
std::lock_guard<std::mutex> lk(m_TermMutex);
auto it = m_TermSessions.find(device_id);
return it != m_TermSessions.end() && !it->second.started;
}
void CMcpServer::RegisterTerminalContext(uint64_t device_id, context* subCtx, bool isPty) {
{
std::lock_guard<std::mutex> lk(m_TermMutex);
auto it = m_TermSessions.find(device_id);
if (it == m_TermSessions.end() || it->second.started) return; // 没有等它的会话
TermSession& s = it->second;
s.started = true;
s.subCtx = subCtx;
s.isPty = isPty;
m_TermContextToDevice[subCtx] = device_id;
}
// 关键步骤:告知客户端「启动 shell 输出回流」。客户端读线程靠 COMMAND_NEXT 才启动,
// 漏发会导致 shell 在跑但输出永不送回。PTY 还要先告知初始 80x24,否则 TUI 尺寸错乱。
if (isPty) {
BYTE resizeBuf[5];
resizeBuf[0] = CMD_TERMINAL_RESIZE;
*(short*)(resizeBuf + 1) = (short)80;
*(short*)(resizeBuf + 3) = (short)24;
subCtx->Send2Client(resizeBuf, 5);
}
BYTE startCmd = COMMAND_NEXT;
subCtx->Send2Client(&startCmd, 1);
m_TermCv.notify_all();
}
bool CMcpServer::IsTerminalContext(context* subCtx) {
std::lock_guard<std::mutex> lk(m_TermMutex);
return m_TermContextToDevice.find(subCtx) != m_TermContextToDevice.end();
}
void CMcpServer::OnTerminalData(context* subCtx, const BYTE* data, ULONG len) {
std::lock_guard<std::mutex> lk(m_TermMutex);
auto it = m_TermContextToDevice.find(subCtx);
if (it == m_TermContextToDevice.end()) return;
auto sit = m_TermSessions.find(it->second);
if (sit == m_TermSessions.end()) return;
TermSession& s = sit->second;
if (s.done || s.closed) return; // 已结束,忽略迟到数据
s.data.insert(s.data.end(), data, data + len);
if (FindSentinel(s.data, s.nonce, s.sentPos, s.exitCode)) {
s.done = true;
m_TermCv.notify_all();
}
}
void CMcpServer::OnTerminalClosed(context* subCtx) {
std::lock_guard<std::mutex> lk(m_TermMutex);
auto it = m_TermContextToDevice.find(subCtx);
if (it == m_TermContextToDevice.end()) return;
auto sit = m_TermSessions.find(it->second);
if (sit == m_TermSessions.end()) return;
TermSession& s = sit->second;
s.closed = true;
if (s.persistent && !s.busy && s.started) {
// 空闲持久会话:shell 已退、无等待线程会清理,直接擦路由+会话(无需 CancelIO,已死)。
m_TermContextToDevice.erase(subCtx);
m_TermSessions.erase(sit);
}
m_TermCv.notify_all(); // busy 场景唤醒等待线程由其清理;一次性 exec 路径不变
}
bool CMcpServer::BeginTermPending(uint64_t device_id, const std::string& command, const std::string& nonce) {
std::lock_guard<std::mutex> lk(m_TermMutex);
if (m_TermSessions.find(device_id) != m_TermSessions.end()) return false; // 已有会话
TermSession s;
s.command = command;
s.nonce = nonce;
m_TermSessions[device_id] = std::move(s);
return true;
}
bool CMcpServer::WaitTerminalReady(uint64_t device_id, context*& subCtx, bool& isPty, int timeoutMs) {
std::unique_lock<std::mutex> lk(m_TermMutex);
auto it = m_TermSessions.find(device_id);
if (it == m_TermSessions.end()) return false;
bool signaled = WaitWithCancel(lk, m_TermCv, DeadlineAfter(timeoutMs),
[&] { return it->second.started; });
if (!signaled) {
// 放弃:迟到的 shell 子连接就绪包(TOKEN_SHELL_START/TOKEN_TERMINAL_START)不能弹终端窗口。
MarkLateFirstPacket(device_id, { (BYTE)TOKEN_SHELL_START, (BYTE)TOKEN_TERMINAL_START });
m_TermSessions.erase(it); // 超时/取消 → 清理
return false;
}
subCtx = it->second.subCtx;
isPty = it->second.isPty;
return true;
}
bool CMcpServer::WaitTerminalDone(uint64_t device_id, std::vector<BYTE>& out,
int& exitCode, bool& closed, int timeoutMs) {
std::unique_lock<std::mutex> lk(m_TermMutex);
auto it = m_TermSessions.find(device_id);
if (it == m_TermSessions.end()) return false;
bool signaled = WaitWithCancel(lk, m_TermCv, DeadlineAfter(timeoutMs),
[&] { return it->second.done || it->second.closed; });
if (!signaled) { // 超时/取消 → 清理(含路由表)
m_TermContextToDevice.erase(it->second.subCtx);
m_TermSessions.erase(it);
return false;
}
TermSession s = it->second; // 拷贝出,避免擦除后悬空
m_TermContextToDevice.erase(s.subCtx);
m_TermSessions.erase(it);
closed = s.closed;
exitCode = s.exitCode;
if (s.done && s.sentPos <= s.data.size())
out.assign(s.data.begin(), s.data.begin() + s.sentPos); // 截断到哨兵前
else
out = s.data; // 进程退出无哨兵:返回已收集的原始输出
return true;
}
void CMcpServer::ClearTermPending(uint64_t device_id) {
std::lock_guard<std::mutex> lk(m_TermMutex);
auto it = m_TermSessions.find(device_id);
if (it != m_TermSessions.end()) m_TermSessions.erase(it);
}
// ===== P4:持久远程终端(状态机方法)=====
bool CMcpServer::BeginTermOpen(uint64_t device_id, const std::string& sessionId) {
std::lock_guard<std::mutex> lk(m_TermMutex);
if (m_TermSessions.find(device_id) != m_TermSessions.end()) return false; // 单设备单终端
TermSession s;
s.sessionId = sessionId;
s.persistent = true;
s.lastActiveAt = time(nullptr);
m_TermSessions[device_id] = std::move(s);
return true;
}
// 墓碑:记下会话被销毁的原因,供后续 terminal_exec 给出可区分文案。
// 调用方必须持有 m_TermMutex。会话不存在时记录是为了让「上一次超时后用户重试」能看懂。
void CMcpServer::MarkTermDestroyedLocked(uint64_t device_id, const std::string& sessionId,
const std::string& reason) {
if (sessionId.empty()) return;
TermDestroyedInfo info;
info.sessionId = sessionId;
info.reason = reason;
info.expiry = std::chrono::steady_clock::now() + std::chrono::seconds(kTermTombstoneSec);
m_TermDestroyed[device_id] = std::move(info);
// 顺手清理过期项(条目极少,线性清一遍即可)
auto now = std::chrono::steady_clock::now();
for (auto it = m_TermDestroyed.begin(); it != m_TermDestroyed.end(); ) {
if (it->second.expiry <= now) it = m_TermDestroyed.erase(it);
else ++it;
}
}
std::string CMcpServer::DescribeTermDestroyed(uint64_t device_id, const std::string& sessionId) {
std::lock_guard<std::mutex> lk(m_TermMutex);
auto it = m_TermDestroyed.find(device_id);
if (it == m_TermDestroyed.end()) return "";
if (std::chrono::steady_clock::now() >= it->second.expiry) {
m_TermDestroyed.erase(it);
return "";
}
if (it->second.sessionId != sessionId) return ""; // 是「id 写错」,不是「已销毁」
return it->second.reason;
}
int CMcpServer::BeginTermCommand(uint64_t device_id, const std::string& sessionId,
const std::string& command, const std::string& nonce,
context*& subCtx, bool& isPty) {
std::lock_guard<std::mutex> lk(m_TermMutex);
auto it = m_TermSessions.find(device_id);
if (it == m_TermSessions.end()) return 1; // 不存在(含已销毁)
TermSession& s = it->second;
if (!s.persistent || s.sessionId != sessionId) return 2; // 非持久或 token 不匹配
if (!s.started) return 3; // 未就绪
if (s.busy) return 4; // 已有命令在飞
if (s.closed) return 5; // 已关闭
s.busy = true;
s.command = command;
s.nonce = nonce;
s.data.clear();
s.sentPos = 0;
s.exitCode = -1;
s.done = false;
s.closed = false;
s.lastActiveAt = time(nullptr);
subCtx = s.subCtx;
isPty = s.isPty;
return 0;
}
bool CMcpServer::WaitTermCommand(uint64_t device_id, std::vector<BYTE>& out,
int& exitCode, bool& closed, int timeoutMs) {
std::unique_lock<std::mutex> lk(m_TermMutex);
auto it = m_TermSessions.find(device_id);
if (it == m_TermSessions.end()) return false;
bool signaled = WaitWithCancel(lk, m_TermCv, DeadlineAfter(timeoutMs),
[&] { return it->second.done || it->second.closed; });
if (!signaled) { // 超时/取消 → 清理会话+路由(调用方负责 CancelIO)
context* subCtx = it->second.subCtx;
MarkTermDestroyedLocked(device_id, it->second.sessionId,
McpCallCancelled()
? std::string("Terminal session was destroyed because the request was cancelled; "
"call terminal_open again")
: "Terminal session was destroyed after this command timed out (waited "
+ std::to_string(timeoutMs) + " ms); call terminal_open again");
m_TermContextToDevice.erase(subCtx);
m_TermSessions.erase(it);
return false;
}
if (it->second.closed) { // 进程退出 → 清理,返回已收集输出(无哨兵)
context* subCtx = it->second.subCtx;
out = it->second.data;
exitCode = -1;
closed = true;
MarkTermDestroyedLocked(device_id, it->second.sessionId,
"Terminal session ended: the shell process exited; call terminal_open again");
m_TermContextToDevice.erase(subCtx);
m_TermSessions.erase(it);
return true;
}
// 哨兵命中 → 保持会话,复位 busy;刷新 lastActiveAt,避免「长命令刚完成即被 idle 回收」
// (idle 语义应为「距上次活动」,而非「距上次命令开始」)。
it->second.busy = false;
it->second.lastActiveAt = time(nullptr);
exitCode = it->second.exitCode;
closed = false;
if (it->second.sentPos <= it->second.data.size())
out.assign(it->second.data.begin(), it->second.data.begin() + it->second.sentPos);
return true;
}
int CMcpServer::CloseTermSession(uint64_t device_id, const std::string& sessionId) {
context* subCtx = nullptr;
{
std::lock_guard<std::mutex> lk(m_TermMutex);
auto it = m_TermSessions.find(device_id);
if (it == m_TermSessions.end()) return 1; // 不存在(幂等)
TermSession& s = it->second;
if (!s.persistent || s.sessionId != sessionId) return 2; // token 不匹配
if (s.busy) {
// 有命令在飞:置 closed 唤醒等待线程,由其清理(避免双重擦除)。
s.closed = true;
MarkTermDestroyedLocked(device_id, sessionId,
"Terminal session was closed by terminal_close while a command was running");
m_TermCv.notify_all();
return 0;
}
subCtx = s.subCtx;
MarkTermDestroyedLocked(device_id, sessionId, "Terminal session was closed by terminal_close");
m_TermContextToDevice.erase(s.subCtx);
m_TermSessions.erase(it);
}
if (subCtx) subCtx->CancelIO(); // 锁外取消 IO,触发客户端 shell 退出
return 0;
}
int CMcpServer::SweepIdleTerminals(time_t idleTimeoutSec) {
time_t now = time(nullptr);
std::vector<context*> toCancel;
{
std::lock_guard<std::mutex> lk(m_TermMutex);
for (auto it = m_TermSessions.begin(); it != m_TermSessions.end(); ) {
TermSession& s = it->second;
if (s.persistent && !s.busy && difftime(now, s.lastActiveAt) > (double)idleTimeoutSec) {
if (s.subCtx) { m_TermContextToDevice.erase(s.subCtx); toCancel.push_back(s.subCtx); }
MarkTermDestroyedLocked(it->first, s.sessionId,
"Terminal session was reclaimed after " + std::to_string((int)idleTimeoutSec)
+ "s of inactivity; call terminal_open again");
it = m_TermSessions.erase(it);
} else {
++it;
}
}
}
for (context* c : toCancel) if (c) c->CancelIO(); // 锁外 CancelIO
return (int)toCancel.size();
}
// ===== P5:MCP 远程控制(状态机方法)=====
bool CMcpServer::IsScreenCtrlContext(context* subCtx) {
std::lock_guard<std::mutex> lk(m_ScreenCtrlMutex);
return m_ScreenCtrlContextToDevice.find(subCtx) != m_ScreenCtrlContextToDevice.end();
}
bool CMcpServer::BeginScreenCtrlOpen(uint64_t device_id, const std::string& sessionId) {
std::lock_guard<std::mutex> lk(m_ScreenCtrlMutex);
if (m_ScreenCtrlSessions.find(device_id) != m_ScreenCtrlSessions.end()) return false; // 单设备单会话
ScreenCtrlSession s;
s.sessionId = sessionId;
s.lastActiveAt = time(nullptr);
m_ScreenCtrlSessions[device_id] = std::move(s);
// 双向互斥(方向二):标记该设备屏幕子连接归 MCP 会话独占,人类 Web 观看期间被拒绝
// (HandleConnect 查 IsMcpTriggered)。会话擦除点(CloseScreenCtrlSession /
// SweepIdleScreenCtrl / OnScreenControlClosed / EndScreenCtrlAction)同步 ClearMcpTriggered。
WebService().SetMcpTriggered(device_id);
return true;
}
bool CMcpServer::MarkScreenCtrlReady(uint64_t device_id, const std::string& sessionId,
context* subCtx, int screenW, int screenH) {
std::lock_guard<std::mutex> lk(m_ScreenCtrlMutex);
auto it = m_ScreenCtrlSessions.find(device_id);
if (it == m_ScreenCtrlSessions.end() || it->second.sessionId != sessionId) return false;
ScreenCtrlSession& s = it->second;
s.subCtx = subCtx;
s.started = true;
s.screenW = screenW;
s.screenH = screenH;
s.lastActiveAt = time(nullptr);
m_ScreenCtrlContextToDevice[subCtx] = device_id;
return true;
}
int CMcpServer::CloseScreenCtrlSession(uint64_t device_id, const std::string& sessionId) {
context* unblockCtx = nullptr;
int rc = 1;
{
std::lock_guard<std::mutex> lk(m_ScreenCtrlMutex);
auto it = m_ScreenCtrlSessions.find(device_id);
if (it != m_ScreenCtrlSessions.end()) {
if (it->second.sessionId != sessionId) {
rc = 2; // token 不匹配
} else {
rc = 0;
ScreenCtrlSession& s = it->second;
// 关会话前必须解除键鼠锁定:子连接一断,服务端就再没有下发通道,
// 客户端进程还活着的话人会被锁在电脑外(P10-C)。
if (s.inputBlocked && s.subCtx) unblockCtx = s.subCtx;
if (s.busy) {
// 注入在飞:置 closed 交注入线程收尾,避免与注入并发擦会话(镜像终端 busy 模式)。
s.closed = true;
} else {
if (s.subCtx) m_ScreenCtrlContextToDevice.erase(s.subCtx);
m_ScreenCtrlSessions.erase(it);
WebService().ClearMcpTriggered(device_id);
}
}
}
}
// 锁外发(Send2Client 持该上下文的 SendLock,不在 MCP 锁内做 socket 发送)。
if (unblockCtx) SendScreenBlockInput(unblockCtx, false);
return rc;
}
int CMcpServer::SweepIdleScreenCtrl(time_t idleTimeoutSec) {
time_t now = time(nullptr);
std::vector<uint64_t> toClose;
struct Blocked { uint64_t devId; std::string sessionId; context* subCtx; };
std::vector<Blocked> toUnblock;
{
std::lock_guard<std::mutex> lk(m_ScreenCtrlMutex);
for (auto it = m_ScreenCtrlSessions.begin(); it != m_ScreenCtrlSessions.end(); ) {
ScreenCtrlSession& s = it->second;
if (!s.busy && difftime(now, s.lastActiveAt) > (double)idleTimeoutSec) {
// 回收前强制解除键鼠锁定(P10-C):下面就要关子连接了,之后无从下发。
if (s.inputBlocked && s.subCtx)
toUnblock.push_back({ it->first, s.sessionId, s.subCtx });
if (s.subCtx) m_ScreenCtrlContextToDevice.erase(s.subCtx);
uint64_t devId = it->first;
toClose.push_back(devId);
it = m_ScreenCtrlSessions.erase(it);
WebService().ClearMcpTriggered(devId); // 锁内清除,避免与并发 remote_open 竞态
} else {
++it;
}
}
}
// 锁外解锁,且必须排在关对话框之前:先让客户端丢掉锁定,再拆子连接。
for (const Blocked& b : toUnblock) {
SendScreenBlockInput(b.subCtx, false);
// 审计(不可关闭):闲置回收顺带解了锁,人类看不到这一步,必须留痕。
if (m_parent) {
std::string audit = "host " + std::to_string(b.devId) + " remote-block-input: session "
+ b.sessionId + " input lock forced off by idle reclaim";
m_parent->PostMessageA(WM_SHOWERRORMSG,
(WPARAM)new CString(ToAnsi(audit, 936).c_str()),
(LPARAM)new CString(_TR("MCP远程控制")));
}
}
// 锁外关闭隐藏对话框(WM_CLOSE → CScreenSpyDlg 析构 → UnregisterScreenContext)。
for (uint64_t devId : toClose) {
if (m_parent) m_parent->CloseWebRemoteDesktopByClientID(devId);
WebService().ClearWebTriggered(devId);
}
return (int)toClose.size();
}
void CMcpServer::OnScreenControlClosed(context* subCtx) {
std::lock_guard<std::mutex> lk(m_ScreenCtrlMutex);
auto it = m_ScreenCtrlContextToDevice.find(subCtx);
if (it == m_ScreenCtrlContextToDevice.end()) return;
auto sit = m_ScreenCtrlSessions.find(it->second);
if (sit == m_ScreenCtrlSessions.end()) { // 路由在但会话已擦(防御)
m_ScreenCtrlContextToDevice.erase(it);
return;
}
if (sit->second.busy) {
// 注入在飞:不擦会话(注入线程仍持 subCtx),仅置 closed,由 EndScreenCtrlAction 收尾。
sit->second.closed = true;
} else {
uint64_t devId = it->second;
m_ScreenCtrlSessions.erase(sit);
m_ScreenCtrlContextToDevice.erase(it);
WebService().ClearMcpTriggered(devId);
}
}
int CMcpServer::BeginScreenCtrlAction(uint64_t device_id, const std::string& sessionId,
context*& subCtx, int& screenW, int& screenH) {
std::lock_guard<std::mutex> lk(m_ScreenCtrlMutex);
auto it = m_ScreenCtrlSessions.find(device_id);
if (it == m_ScreenCtrlSessions.end()) return 1; // 会话不存在
ScreenCtrlSession& s = it->second;
if (s.sessionId != sessionId) return 1; // token 不匹配
if (!s.started) return 1; // 未就绪
if (s.busy) return 2; // 已有注入在飞
if (s.closed) return 1; // 子连接已断
s.busy = true;
s.lastActiveAt = time(nullptr);
subCtx = s.subCtx;
screenW = s.screenW;
screenH = s.screenH;
return 0;
}
void CMcpServer::EndScreenCtrlAction(uint64_t device_id, const std::string& sessionId) {
std::lock_guard<std::mutex> lk(m_ScreenCtrlMutex);
auto it = m_ScreenCtrlSessions.find(device_id);
if (it == m_ScreenCtrlSessions.end()) return;
if (it->second.sessionId != sessionId) return;
it->second.busy = false;
it->second.lastActiveAt = time(nullptr);
if (it->second.closed) { // 注入期间子连接已断:擦会话+路由
if (it->second.subCtx) m_ScreenCtrlContextToDevice.erase(it->second.subCtx);
m_ScreenCtrlSessions.erase(it);
WebService().ClearMcpTriggered(device_id);
}
}
// ===== P10-C:键鼠锁定的状态维护与自动解除 =====
bool CMcpServer::ScreenCtrlSetBlock(uint64_t device_id, const std::string& sessionId, bool block,
int maxBlockMs, bool& autoUnblocked) {
autoUnblocked = false;
std::lock_guard<std::mutex> lk(m_ScreenCtrlMutex);
auto it = m_ScreenCtrlSessions.find(device_id);
if (it == m_ScreenCtrlSessions.end() || it->second.sessionId != sessionId) return false;
ScreenCtrlSession& s = it->second;
// 上一次锁定被看门狗自动解除的通知:随本次结果取走(每条 remote_block_input 都能看到)。
autoUnblocked = s.blockAutoReleased;
s.blockAutoReleased = false;
s.inputBlocked = block;
s.blockUntil = block
? std::chrono::steady_clock::now() + std::chrono::milliseconds(maxBlockMs)
: std::chrono::steady_clock::time_point{};
return true;
}
bool CMcpServer::IsScreenCtrlBlocked(uint64_t device_id, const std::string& sessionId) {
std::lock_guard<std::mutex> lk(m_ScreenCtrlMutex);
auto it = m_ScreenCtrlSessions.find(device_id);
return it != m_ScreenCtrlSessions.end() && it->second.sessionId == sessionId
&& it->second.inputBlocked;
}
// 扫一遍会话,把超过 blockUntil 的锁定解除。busy 的会话本轮跳过(下一轮再试,注入都很短);
// 发送失败(多半是子连接已断)时保持锁定并把期限推后 5 秒,避免每 500ms 空转打已死的连接。
void CMcpServer::WatchdogScreenBlock() {
struct Hit { uint64_t devId; std::string sessionId; context* subCtx; };
std::vector<Hit> hits;
{
std::lock_guard<std::mutex> lk(m_ScreenCtrlMutex);
auto now = std::chrono::steady_clock::now();
for (auto& kv : m_ScreenCtrlSessions) {
ScreenCtrlSession& s = kv.second;
if (!s.inputBlocked || s.busy || s.closed || !s.started || !s.subCtx) continue;
if (now < s.blockUntil) continue;
s.busy = true; // 占位:注入 / close 会等这次解锁收尾
s.lastActiveAt = time(nullptr);
hits.push_back({ kv.first, s.sessionId, s.subCtx });
}
}
for (const Hit& h : hits) {
const bool ok = SendScreenBlockInput(h.subCtx, false); // 锁外发送
bool erased = false;
{
std::lock_guard<std::mutex> lk(m_ScreenCtrlMutex);
auto it = m_ScreenCtrlSessions.find(h.devId);
if (it != m_ScreenCtrlSessions.end() && it->second.sessionId == h.sessionId) {
ScreenCtrlSession& s = it->second;
if (ok) {
s.inputBlocked = false;
s.blockAutoReleased = true; // 等下一次 remote_block_input 上报
s.blockUntil = std::chrono::steady_clock::time_point{};
} else {
s.blockUntil = std::chrono::steady_clock::now() + std::chrono::seconds(5);
}
s.busy = false;
s.lastActiveAt = time(nullptr);
if (s.closed) { // 占位期间子连接断了:擦会话(镜像 EndScreenCtrlAction)
if (s.subCtx) m_ScreenCtrlContextToDevice.erase(s.subCtx);
m_ScreenCtrlSessions.erase(it);
WebService().ClearMcpTriggered(h.devId);
erased = true;
}
}
}
// 审计(不可关闭):自动解除是人类看不见的安全事件,必须留痕。
if (ok && !erased && m_parent) {
std::string audit = "host " + std::to_string(h.devId) + " remote-block-input: session "
+ h.sessionId + " auto-unblocked (max_block_ms elapsed)";
m_parent->PostMessageA(WM_SHOWERRORMSG,
(WPARAM)new CString(ToAnsi(audit, 936).c_str()),
(LPARAM)new CString(_TR("MCP远程控制")));
}
}
}
void CMcpServer::BlockWatchdogLoop() {
// 100ms 切片:Stop 时最多等一个切片,不拖慢退出。
while (!m_blockStop.load()) {
for (int i = 0; i < 5 && !m_blockStop.load(); ++i)
std::this_thread::sleep_for(std::chrono::milliseconds(100));
if (m_blockStop.load()) break;
WatchdogScreenBlock();
}
}
//////////////////////////////////////////////////////////////////////////
// CMcpServer Implementation
//////////////////////////////////////////////////////////////////////////
CMcpServer& CMcpServer::Instance() {
static CMcpServer instance;
return instance;
}
CMcpServer::CMcpServer() {
m_server.Post("/mcp", [this](const httplib::Request& req, httplib::Response& res) {
HandleMcp(req, res);
});
}
CMcpServer::~CMcpServer() {
Stop(); // 兜底:确保监听线程 join,避免 std::thread 析构触发 terminate
}
bool CMcpServer::Start(const std::string& bind, int port) {
if (m_running.load()) return true; // 已在运行
// ===== 传输层加固(A1)=====
// httplib 默认:请求体不限长(SIZE_MAX)、读写超时各 5s、线程池 max(8, 核数-1)。
// 1) 请求体上限 2 MB:本服务只收 JSON-RPC 参数(文件内容走子连接分块,不进 HTTP body),
// 2 MB 足够 chat_send(4 KB)/remote_clipboard 文本,又能挡住超大 body 打爆内存。
// 2) 读超时 15s:经 frp 隧道上传参数时单次 recv 不至于 5s 就被掐断。
// 3) 写超时 60s:get_screenshot 的大图 base64 或慢链路下,5s 会把半个响应写断。
// 4) 线程池显式 32:chat_wait(最长 55s)/批量只读会长时间占线程,默认 8~15 个不够;
// 每个线程约 1 MB 栈,32 个约 32 MB,可接受。
m_server.set_payload_max_length(2 * 1024 * 1024);
m_server.set_read_timeout(15, 0);
m_server.set_write_timeout(60, 0);
m_server.new_task_queue = []() { return new httplib::ThreadPool(32); };
m_bind = bind;
m_port = port;
// HTTPS 时 httplib 只监听回环内部端口,对外端口由 McpTlsProxy 占据。
const bool https = m_httpsEnabled;
const int backendPort = (https && m_internalPort > 0) ? m_internalPort : (https ? port + 1 : port);
// 只在 HTTPS 下记住内部端口:明文模式下把它写成 port,会让「先明文启动、再改 HTTPS
// 重启」这条路径拿到 backendPort == port,后端和前端抢同一个端口、MCP 直接起不来。
if (https) m_internalPort = backendPort;
const std::string backendBind = https ? "127.0.0.1" : bind;
m_thread = std::thread([this, backendBind, backendPort]() {
m_server.listen(backendBind, backendPort);
});
// 给 listen 一点时间绑定端口;httplib::Server::is_running() 在 listen 内部置位。
std::this_thread::sleep_for(std::chrono::milliseconds(100));
m_running.store(m_server.is_running());
if (!m_running.load()) return false;
if (https) {
// fail-closed:TLS 前端起不来(证书/私钥坏、端口被占)就整体停掉,
// 绝不让 MCP 以「以为在跑 HTTPS 其实没在监听」的状态存在。
if (!m_tlsProxy.Start(bind, port, backendPort, m_certPath, m_keyPath)) {
Mprintf("[MCP] HTTPS front-end failed to start; MCP server disabled\n");
m_server.stop();
if (m_thread.joinable()) m_thread.join();
m_running.store(false);
return false;
}
}
// 键鼠锁定看门狗(P10-C):remote_block_input 的 auto-unblock 期限靠它兑现。
// 防御:上一次 Start 没 Stop 就再 Start(正常路径由顶部 m_running 拦下)时先收掉旧线程,
// 必须先置停止位再 join,否则旧线程永远不退出。
if (m_blockThread.joinable()) {
m_blockStop.store(true);
m_blockThread.join();
}
m_blockStop.store(false);
m_blockThread = std::thread([this]() { BlockWatchdogLoop(); });
return true;
}
void CMcpServer::Stop() {
// P11:先取消所有在飞调用——长任务(下载 / 搜索 / 挂起等待)的等待循环会在 ≤1s
// 内退出并走超时清理路径,不给 Stop 留下还在用连接、还在改表的工具线程。
CancelCalls(0, std::string());
// 再停看门狗:它会对屏幕子连接发报文,必须在后端服务拆除之前停止。
m_blockStop.store(true);
if (m_blockThread.joinable()) m_blockThread.join();
// 再停前端:不再接入新连接,再停后端。Stop 内部会 join 前端线程。
m_tlsProxy.Stop();
m_server.stop();
if (m_thread.joinable()) {
m_thread.join();
}
m_running.store(false);
}
// get_server_status:各类在飞会话 + 当前被封禁的来源 IP 计数。
// 每类只取自己的锁且立刻释放,不跨锁持有一致性(这些数字只作观测用)。
void CMcpServer::GetRuntimeCounters(int& pending, int& terminal, int& screenCtrl,
int& fileXfer, int& chat, int& blockedIps) {
{
std::lock_guard<std::mutex> lk(m_PendingMutex);
pending = (int)m_Pending.size();
}
{
std::lock_guard<std::mutex> lk(m_TermMutex);
terminal = (int)m_TermSessions.size();
}
{
std::lock_guard<std::mutex> lk(m_ScreenCtrlMutex);
screenCtrl = (int)m_ScreenCtrlSessions.size();
}
{
std::lock_guard<std::mutex> lk(m_FileXferMutex);
fileXfer = (int)m_FileXferSessions.size();
}
{
std::lock_guard<std::mutex> lk(m_ChatMutex);
chat = (int)m_ChatSessions.size();
}
blockedIps = 0;
auto now = std::chrono::steady_clock::now();
std::lock_guard<std::mutex> lk(m_AuthMutex);
for (const auto& kv : m_AuthFails) {
if (kv.second.blockedUntil > now) blockedIps++;
}
}
// ===== P11:在飞调用登记 / 取消 / 会话快照 =====
//
// 三张表各自持锁、只读遍历,绝不嵌套(与 GetRuntimeCounters 同一约定):调用方拿到的
// 是「大致同一时刻」的快照,仅用于观测与取消,不用来同步。
namespace {
long long ElapsedMsSince(std::chrono::steady_clock::time_point tp) {
if (tp.time_since_epoch().count() == 0) return -1;
return (long long)std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - tp).count();
}
long long IdleMsSince(time_t t) {
if (t <= 0) return -1;
return (long long)(time(NULL) - t) * 1000;
}
} // namespace
std::shared_ptr<McpCallContext> CMcpServer::BeginCall(const std::string& idKey, const std::string& idText,
const std::string& tool,
uint64_t device, const std::string& sessionId) {
auto call = std::make_shared<McpCallContext>();
call->idKey = idKey;
call->idText = idText;
call->tool = tool;
call->device = device;
call->sessionId = sessionId;
call->startedAt = std::chrono::steady_clock::now();
std::lock_guard<std::mutex> lk(m_CallMutex);
m_Calls.push_back(call);
return call;
}
void CMcpServer::EndCall(const std::shared_ptr<McpCallContext>& call) {
if (!call) return;
std::lock_guard<std::mutex> lk(m_CallMutex);
for (auto it = m_Calls.begin(); it != m_Calls.end(); ++it) {
if (*it == call) { m_Calls.erase(it); return; }
}
}
bool CMcpServer::CancelCallById(const std::string& idKey, const std::string& idText) {
std::lock_guard<std::mutex> lk(m_CallMutex);
// 先按精确写法找:"41"(字符串)与 41(数字)是两个不同的 id,不能混。
for (const auto& c : m_Calls) {
if (c->idKey == idKey) { c->cancelled.store(true); return true; }
}
// 再退回展示文本:调用方常把列表里的 request_id 当字符串原样传回来,
// 而原调用用的是数字 id —— 这是同一意图,容忍。
if (!idText.empty()) {
for (const auto& c : m_Calls) {
if (c->idText == idText) { c->cancelled.store(true); return true; }
}
}
return false;
}
int CMcpServer::CancelCalls(uint64_t device, const std::string& sessionId) {
int n = 0;
std::lock_guard<std::mutex> lk(m_CallMutex);
for (const auto& c : m_Calls) {
if (device != 0 && c->device != device) continue;
if (!sessionId.empty() && c->sessionId != sessionId) continue;
c->cancelled.store(true);
++n;
}
return n;
}
std::vector<CMcpServer::SessionSnapshot> CMcpServer::ListSessions() {
std::vector<SessionSnapshot> out;
{
std::lock_guard<std::mutex> lk(m_CallMutex);
for (const auto& c : m_Calls) {
SessionSnapshot s;
s.device = c->device;
s.kind = "call";
s.tool = c->tool;
s.sessionId = c->sessionId;
s.idKey = c->idKey;
s.requestId = c->idText;
s.busy = true;
s.elapsedMs = ElapsedMsSince(c->startedAt);
out.push_back(s);
}
}
{
std::lock_guard<std::mutex> lk(m_PendingMutex);
for (const auto& kv : m_Pending) {
SessionSnapshot s;
s.device = kv.first;
s.kind = "pending";
s.tool = kv.second.tool;
s.busy = true;
s.elapsedMs = ElapsedMsSince(kv.second.startedAt);
out.push_back(s);
}
}
{
std::lock_guard<std::mutex> lk(m_TermMutex);
for (const auto& kv : m_TermSessions) {
const TermSession& t = kv.second;
SessionSnapshot s;
s.device = kv.first;
s.kind = "terminal";
s.tool = t.persistent ? "terminal" : "exec_command";
s.sessionId = t.sessionId;
s.busy = t.busy || !t.started;
s.elapsedMs = ElapsedMsSince(t.startedAt);
s.idleMs = IdleMsSince(t.lastActiveAt);
out.push_back(s);
}
}
{
std::lock_guard<std::mutex> lk(m_ScreenCtrlMutex);
for (const auto& kv : m_ScreenCtrlSessions) {
const ScreenCtrlSession& c = kv.second;
SessionSnapshot s;
s.device = kv.first;
s.kind = "remote_control";
s.tool = "remote_control";
s.sessionId = c.sessionId;
s.busy = c.busy || !c.started;
s.elapsedMs = ElapsedMsSince(c.startedAt);
s.idleMs = IdleMsSince(c.lastActiveAt);
out.push_back(s);
}
}
{
std::lock_guard<std::mutex> lk(m_FileXferMutex);
for (const auto& kv : m_FileXferSessions) {
const FileTransferSession& f = kv.second;
SessionSnapshot s;
s.device = kv.first;
s.kind = "file_transfer";
s.tool = f.tool;
s.busy = true; // 文件传输会话在表里就是「在飞」,结束时删除
s.elapsedMs = ElapsedMsSince(f.startedAt);
s.idleMs = ElapsedMsSince(f.lastDataAt);
out.push_back(s);
}
}
{
std::lock_guard<std::mutex> lk(m_ChatMutex);
for (const auto& kv : m_ChatSessions) {
const ChatSession& c = *kv.second;
SessionSnapshot s;
s.device = kv.first;
s.kind = "chat";
s.tool = "chat";
s.sessionId = c.sessionId;
s.busy = c.sendBusy || c.waitBusy || !c.started;
s.elapsedMs = ElapsedMsSince(c.startedAt);
s.idleMs = IdleMsSince(c.lastActiveAt);
out.push_back(s);
}
}
return out;
}
// -32003 文案后缀:优先报「正在跑的长任务」(调用 / 挂起 / 文件传输),其次报持久会话。
std::string CMcpServer::DescribeBusy(uint64_t device_id) {
auto describe = [](const std::string& tool, long long ms) {
std::string s = " (tool=" + (tool.empty() ? std::string("?") : tool);
if (ms >= 0) s += ", elapsed=" + std::to_string(ms / 1000) + "s";
return s + ")";
};
{
std::lock_guard<std::mutex> lk(m_CallMutex);
const McpCallContext* self = CurrentMcpCall().get();
for (const auto& c : m_Calls) {
if (c.get() == self) continue; // 发起 -32003 的就是这次调用,不能算「占用者」
if (c->device == device_id)
return describe(c->tool + (c->sessionId.empty() ? "" : " session_id=" + c->sessionId),
ElapsedMsSince(c->startedAt));
}
}
{
std::lock_guard<std::mutex> lk(m_PendingMutex);
auto it = m_Pending.find(device_id);
if (it != m_Pending.end()) return describe(it->second.tool, ElapsedMsSince(it->second.startedAt));
}
{
std::lock_guard<std::mutex> lk(m_FileXferMutex);
auto it = m_FileXferSessions.find(device_id);
if (it != m_FileXferSessions.end())
return describe(it->second.tool, ElapsedMsSince(it->second.startedAt));
}
{
std::lock_guard<std::mutex> lk(m_TermMutex);
auto it = m_TermSessions.find(device_id);
if (it != m_TermSessions.end() && it->second.busy)
return describe(it->second.sessionId.empty() ? "exec_command" : "terminal",
ElapsedMsSince(it->second.startedAt));
}
{
std::lock_guard<std::mutex> lk(m_ScreenCtrlMutex);
auto it = m_ScreenCtrlSessions.find(device_id);
if (it != m_ScreenCtrlSessions.end() && it->second.busy)
return describe("remote_control", ElapsedMsSince(it->second.startedAt));
}
{
std::lock_guard<std::mutex> lk(m_ChatMutex);
auto it = m_ChatSessions.find(device_id);
if (it != m_ChatSessions.end() && (it->second->sendBusy || it->second->waitBusy))
return describe("chat", ElapsedMsSince(it->second->startedAt));
}
return std::string();
}
// -32003 的正文:通用句 + 「谁占着这台主机、已持续多久」。McpMachine.cpp 也用它。
std::string BusyMessage(const std::string& base, uint64_t devId) {
const std::string who = CMcpServer::Instance().DescribeBusy(devId);
return who.empty() ? base : base + who;
}
// ===== 鉴权加固(N4)=====
// 两件事:
// 1) 同一 IP 在 60 s 内鉴权失败 10 次 → 封禁 15 min(封禁期内直接 429,不比对 token)。
// 正常客户端只有在 token 配错时才会连续 401,10 次足够覆盖改配置重试;爆破工具一分钟
// 就能打出上千次,阈值远在安全侧。例外:环回来源(frp 隧道)只记账不封禁,见
// IsProxySourceAddress——封 127.0.0.1 会误伤隧道后面所有客户端。
// 2) 所有鉴权失败与工具调用写入 <exe>\logs\mcp_audit.log。审计只含时间/IP/UA/工具名/
// 耗时/字节数等元数据——绝不写 token、Authorization 头、请求参数或返回正文。
namespace {
const int kAuthWindowSec = 60;
const int kAuthMaxFailures = 10;
const int kAuthBlockSec = 900;
const size_t kAuthMapMax = 1024; // 跟踪表上限,防止被扫描器撑爆内存
const long long kAuditMaxBytes = 5LL * 1024 * 1024;
std::string AuditStamp() {
SYSTEMTIME st;
GetLocalTime(&st);
char buf[32];
_snprintf_s(buf, sizeof(buf), _TRUNCATE, "%04d-%02d-%02d %02d:%02d:%02d.%03d",
st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
return buf;
}
// 经本机代理转发的请求源地址恒为环回:内置 frpc 把 MCP 端口映射出去时是「本机连本机」,
// 且这条转发没开 Proxy Protocol(httplib 不解析),所以远端客户端的真实 IP 拿不到。
// 这类来源一律不封禁——封 127.0.0.1 等于把经隧道连进来的所有客户端(含用户自己)一起封掉,
// 而攻击者要过 token 这一关本来也过不去。失败照样计数并写审计,便于事后发现扫描。
bool IsProxySourceAddress(const std::string& ip) {
return ip == "127.0.0.1" || ip == "::1" || ip == "::ffff:127.0.0.1";
}
// 头部值可能很长且含引号/控制字符:压成单行并截断,避免破坏日志行结构。
std::string SanitizeHeaderValue(const std::string& s, size_t maxLen = 120) {
std::string out;
for (char c : s) {
if (out.size() >= maxLen) break;
out += (c < 0x20 || c == 0x7f || c == '"') ? '_' : c;
}
return out;
}
} // namespace
void CMcpServer::AppendAuditFile(const std::string& line) {
static std::mutex s_mutex;
static std::string s_path;
static bool s_init = false;
std::lock_guard<std::mutex> lk(s_mutex);
if (!s_init) {
char exe[MAX_PATH] = {0};
if (GetModuleFileNameA(NULL, exe, MAX_PATH) == 0) return;
std::string dir(exe);
size_t pos = dir.find_last_of("\\/");
if (pos == std::string::npos) return;
dir.resize(pos);
std::string logDir = dir + "\\logs";
CreateDirectoryA(logDir.c_str(), NULL); // 已存在时失败,忽略
s_path = logDir + "\\mcp_audit.log";
s_init = true;
}
// 超限滚动一代(mcp_audit.log → mcp_audit.log.1),避免无限增长。
WIN32_FILE_ATTRIBUTE_DATA fad;
if (GetFileAttributesExA(s_path.c_str(), GetFileExInfoStandard, &fad)) {
long long size = ((long long)fad.nFileSizeHigh << 32) | fad.nFileSizeLow;
if (size > kAuditMaxBytes) {
std::string old = s_path + ".1";
DeleteFileA(old.c_str());
MoveFileA(s_path.c_str(), old.c_str());
}
}
FILE* f = nullptr;
if (fopen_s(&f, s_path.c_str(), "ab") != 0 || !f) return;
fputs(line.c_str(), f);
fputc('\n', f);
fclose(f);
}
void CMcpServer::AuditMcpEvent(const char* event, const std::string& ip, const std::string& detail) {
std::string line = AuditStamp();
line += ' ';
line += event;
line += " ip=";
line += ip.empty() ? std::string("-") : ip;
if (!detail.empty()) { line += ' '; line += detail; }
AppendAuditFile(line);
}
bool CMcpServer::IsAuthBlocked(const std::string& ip) {
auto now = std::chrono::steady_clock::now();
std::lock_guard<std::mutex> lk(m_AuthMutex);
auto it = m_AuthFails.find(ip);
if (it == m_AuthFails.end()) return false;
if (it->second.blockedUntil > now) return true;
// 封禁已到期、且失败窗口也已过期 → 清掉,防止表无限增长
if (now - it->second.windowStart > std::chrono::seconds(kAuthWindowSec)) m_AuthFails.erase(it);
return false;
}
bool CMcpServer::RecordAuthFailure(const std::string& ip) {
auto now = std::chrono::steady_clock::now();
std::lock_guard<std::mutex> lk(m_AuthMutex);
if (m_AuthFails.size() >= kAuthMapMax) {
// 表满:先清扫彻底过期的项;仍然满就不再新增(宁可少统计也不无限增长)
for (auto it = m_AuthFails.begin(); it != m_AuthFails.end(); ) {
bool stale = it->second.blockedUntil <= now &&
now - it->second.windowStart > std::chrono::seconds(kAuthWindowSec);
if (stale) it = m_AuthFails.erase(it); else ++it;
}
if (m_AuthFails.size() >= kAuthMapMax) return false;
}
AuthFailRecord& r = m_AuthFails[ip];
if (r.count == 0 || now - r.windowStart > std::chrono::seconds(kAuthWindowSec)) {
r.count = 1;
r.windowStart = now;
return false;
}
r.count++;
if (r.count >= kAuthMaxFailures && r.blockedUntil <= now) {
r.blockedUntil = now + std::chrono::seconds(kAuthBlockSec);
return true;
}
return false;
}
void CMcpServer::ClearAuthFailures(const std::string& ip) {
std::lock_guard<std::mutex> lk(m_AuthMutex);
m_AuthFails.erase(ip);
}
void CMcpServer::HandleMcp(const httplib::Request& req, httplib::Response& res) {
// 注意:这里不预置 Content-Type —— set_content / set_chunked_content_provider 各自
// 会写,预置会让 SSE 响应带上两个 Content-Type(application/json 在前)。
const std::string clientIp = req.remote_addr;
// 环回来源(本机 / frp 隧道)不参与封禁,理由见 IsProxySourceAddress。
const bool proxySource = IsProxySourceAddress(clientIp);
// 封禁期内直接拒绝:不比对 token,也不解析请求体
if (!proxySource && IsAuthBlocked(clientIp)) {
res.status = 429;
res.set_header("Retry-After", std::to_string(kAuthBlockSec));
res.set_content(BuildError(Json::nullValue, -32000,
"Too many failed authentication attempts"), "application/json");
return;
}
// 静态 token 校验:Authorization: Bearer <token>(Start 前经 SetToken 保证非空)
if (req.get_header_value("Authorization") != ("Bearer " + m_token)) {
bool blocked = RecordAuthFailure(clientIp);
std::string ua = SanitizeHeaderValue(req.get_header_value("User-Agent"));
AuditMcpEvent("AUTH_FAIL", clientIp,
"ua=\"" + ua + "\" bytes=" + std::to_string(req.body.size()) +
" blocked=" + (blocked ? "1" : "0"));
if (blocked) {
AuditMcpEvent("AUTH_BLOCK", clientIp,
"window=" + std::to_string(kAuthWindowSec) + "s fail=" +
std::to_string(kAuthMaxFailures) + " block=" +
std::to_string(kAuthBlockSec) + "s" +
(proxySource ? " scope=proxy-source-exempt" : ""));
if (!proxySource) {
res.status = 429;
res.set_header("Retry-After", std::to_string(kAuthBlockSec));
res.set_content(BuildError(Json::nullValue, -32000,
"Too many failed authentication attempts"), "application/json");
return;
}
}
res.status = 401;
res.set_content(BuildError(Json::nullValue, -32000, "Unauthorized"), "application/json");
return;
}
ClearAuthFailures(clientIp);
// 解析 JSON-RPC 请求体
Json::Value root;
Json::CharReaderBuilder rbuilder;
std::string errs;
std::istringstream iss(req.body);
if (!Json::parseFromStream(rbuilder, iss, &root, &errs) || !root.isObject()) {
res.set_content(BuildError(Json::nullValue, -32700, "Parse error"), "application/json");
return;
}
// 通知(无 id)→ 不返回 JSON-RPC 响应(如 notifications/initialized)
if (!root.isMember("id")) {
// P11:notifications/cancelled → 置对应在飞调用的取消位。工具层的等待循环会在
// ≤1s 内退出并走既有的超时清理路径(不发多余报文、不留下悬空挂起项),
// 该请求自己的 SSE 流(若有)随即以 -32800 结束。
const Json::Value& m = root["method"];
if (m.isString() && m.asString() == "notifications/cancelled") {
const Json::Value& params = root["params"];
if (params.isObject() && params.isMember("requestId")) {
const Json::Value& rid = params["requestId"];
const bool hit = CancelCallById(JsonToString(rid), McpRequestIdText(rid));
AuditMcpEvent("NOTIFY_CANCEL", clientIp,
"requestId=" + SanitizeHeaderValue(McpRequestIdText(rid), 64) +
" hit=" + (hit ? "1" : "0"));
}
}
res.status = 202;
res.set_content("", "application/json");
return;
}
// 结构校验:缺 method
if (!root.isMember("method") || !root["method"].isString()) {
res.set_content(BuildError(root["id"], -32600, "Invalid Request"), "application/json");
return;
}
std::string method = root["method"].asString();
if (method == "initialize") {
res.set_content(BuildInitializeResult(root["id"]), "application/json");
return;
}
if (method == "ping") {
res.set_content(BuildPingResult(root["id"]), "application/json");
return;
}
if (method == "tools/list") {
res.set_content(BuildToolsListResult(root["id"]), "application/json");
return;
}
if (method == "tools/call") {
const Json::Value params =
root.isMember("params") ? root["params"] : Json::Value(Json::objectValue);
std::string toolName;
if (params.isObject() && params.isMember("name") && params["name"].isString())
toolName = params["name"].asString();
// 登记在飞调用:devId / session_id 只用于观测与 mcp_cancel_session,
// 解析不出来(非主机工具、参数非法)就按 0 / 空处理,不影响工具自身的行为。
const Json::Value args = GetCallArguments(params);
uint64_t devId = 0;
std::string ignored;
ParseHostIdArg(args, devId, ignored);
std::string sessionId;
if (args.isObject() && args.isMember("session_id") && args["session_id"].isString())
sessionId = args["session_id"].asString();
auto call = BeginCall(JsonToString(root["id"]), McpRequestIdText(root["id"]),
toolName, devId, sessionId);
// _meta.progressToken(MCP 2025-06-18):字符串或整数,原样回显。
if (params.isObject() && params.isMember("_meta") && params["_meta"].isObject() &&
params["_meta"].isMember("progressToken")) {
const Json::Value& tok = params["_meta"]["progressToken"];
if (tok.isString() || tok.isInt() || tok.isUInt() || tok.isInt64() || tok.isUInt64()) {
call->hasProgressToken = true;
call->progressTokenJson = JsonToString(tok);
}
}
// 审计一条 tools/call 结果(SSE 路径的工具线程与普通路径共用同一份判定)。
auto auditResult = [this, clientIp, toolName](const std::string& resp, long long ms) {
// 成败以返回体顶层是否有 "error" 成员为准(解析一次,避免正文里出现 "error" 字样时误判)
bool failed = false;
int errCode = 0;
std::string errMsg;
{
Json::Value parsed;
Json::CharReaderBuilder rb;
std::string perrs;
std::istringstream pis(resp);
if (Json::parseFromStream(rb, pis, &parsed, &perrs) &&
parsed.isObject() && parsed.isMember("error")) {
failed = true;
const Json::Value& err = parsed["error"];
if (err.isObject()) {
if (err["code"].isInt()) errCode = err["code"].asInt();
if (err["message"].isString()) errMsg = err["message"].asString();
}
}
}
// 单行不变量:工具名来自请求参数,控制字符一律换成空格,避免伪造出额外审计行
auto oneLine = [](std::string v) {
for (char& c : v)
if ((unsigned char)c < 0x20) c = ' ';
return v;
};
const std::string toolTag =
"tool=" + oneLine(toolName.empty() ? std::string("(empty)") : toolName);
AuditMcpEvent(failed ? "CALL_FAIL" : "CALL_OK", clientIp,
toolTag + " ms=" + std::to_string(ms) + " bytes=" + std::to_string(resp.size()));
// 策略拒绝(-32006:只读模式、功能开关关闭、主机不支持)另记一条 CALL_DENIED,
// 事后才分得清「没人调用」和「被策略拦下」。reason 全是固定的英文句式,不含
// 调用参数或用户输入,可以直接落盘。
if (errCode == -32006)
AuditMcpEvent("CALL_DENIED", clientIp, toolTag + " reason=" + oneLine(errMsg));
};
// 取消后的收尾:工具因取消而失败时,把错误统一改写成 -32800,让调用方知道
// 「这是自己取消的」而不是主机故障;已经拿到成功结果就照实返回。
auto finalize = [id = root["id"], call](std::string resp) {
if (!call->IsCancelled()) return resp;
Json::Value parsed;
Json::CharReaderBuilder rb;
std::string perrs;
std::istringstream pis(resp);
if (!Json::parseFromStream(rb, pis, &parsed, &perrs) || !parsed.isObject() ||
!parsed.isMember("error"))
return resp;
return BuildError(id, kErrCancelled,
"Request cancelled: the in-flight work was aborted and cleaned up");
};
if (call->hasProgressToken) {
// 带 _meta.progressToken:按 MCP Streamable HTTP 的要求以 text/event-stream
// 回应同一个 POST。工具在独立线程执行,进度通知与最终响应都从这个流写出。
auto ch = std::make_shared<McpProgressChannel>();
ch->call = call;
call->channel = ch;
const Json::Value rootCopy = root; // 请求体在栈上,工具线程必须持有副本
std::thread([this, rootCopy, call, ch, clientIp, toolName, auditResult, finalize]() {
McpCallScope scope(call);
auto t0 = std::chrono::steady_clock::now();
std::string resp = finalize(BuildToolsCall(rootCopy, m_parent));
const long long ms = (long long)std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - t0).count();
auditResult(resp, ms);
EndCall(call);
ch->Finish(resp); // 最后一步:置 finished 并唤醒 provider 线程写出最终响应
}).detach();
res.status = 200;
res.set_chunked_content_provider(
"text/event-stream",
[ch](size_t, httplib::DataSink& sink) { return ch->Pump(sink); });
return;
}
auto t0 = std::chrono::steady_clock::now();
std::string resp;
{
McpCallScope scope(call); // 让工具实现里的 McpCallCancelled() 生效
resp = BuildToolsCall(root, m_parent);
}
const long long ms = (long long)std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - t0).count();
resp = finalize(std::move(resp));
EndCall(call);
auditResult(resp, ms);
res.set_content(resp, "application/json");
return;
}
// 未实现的方法
res.set_content(BuildError(root["id"], -32601, "Method not found"), "application/json");
}
// ===== P2b 挂起请求注册表实现 =====
bool CMcpServer::IsPending(uint64_t device_id) {
std::lock_guard<std::mutex> lk(m_PendingMutex);
auto it = m_Pending.find(device_id);
if (it == m_Pending.end()) return false;
// P8:主机管理/连接管理会话的响应包走 OnManagedSubPacket,不归 MFC 的
// TOKEN_PSLIST/TOKEN_WSLIST/SERVERLIST/DRIVE_LIST 分支消费(否则会抢走 UI 包)。
return it->second.kind == PendingKind::Generic || it->second.kind == PendingKind::FollowUp;
}
void CMcpServer::TakeMainResponse(uint64_t device_id, const BYTE* data, ULONG len) {
std::lock_guard<std::mutex> lk(m_PendingMutex);
auto it = m_Pending.find(device_id);
if (it == m_Pending.end()) { Mprintf("[MCP-P7] TakeMainResponse dev=%llu len=%d: no pending (late/dropped)\n", device_id, (int)len); return; } // 已超时清理 → 迟到数据,丢弃
if (it->second.kind != PendingKind::Generic && it->second.kind != PendingKind::FollowUp) return; // P8 会话:不接管
Mprintf("[MCP-P7] TakeMainResponse dev=%llu len=%d done\n", device_id, (int)len);
it->second.data.assign(data, data + len);
it->second.done = true;
m_PendingCv.notify_one();
}
bool CMcpServer::BeginPending(uint64_t device_id, const std::string& tool) {
if (IsFileTransferPending(device_id)) return false; // 该 host 有文件传输会话在飞(互斥,见 F2)
std::lock_guard<std::mutex> lk(m_PendingMutex);
if (m_Pending.find(device_id) != m_Pending.end()) return false; // 设备忙
PendingRequest r;
r.tool = tool;
m_Pending[device_id] = std::move(r);
return true;
}
bool CMcpServer::BeginPendingFileOp(uint64_t device_id, const std::string& tool,
const std::vector<BYTE>& followUp,
const std::string& verifyPath) {
if (IsFileTransferPending(device_id)) return false; // 该 host 有文件传输会话在飞(互斥,见 F2)
std::lock_guard<std::mutex> lk(m_PendingMutex);
if (m_Pending.find(device_id) != m_Pending.end()) return false; // 设备忙
PendingRequest r;
r.tool = tool;
r.kind = PendingKind::FollowUp; // IsPending 认这个 kind,TOKEN_DRIVE_LIST 才会交给 OnDriveList
r.followUp = followUp;
r.verifyPath = verifyPath;
m_Pending[device_id] = std::move(r);
return true;
}
CMcpServer::FileOpAck CMcpServer::TakeFileOpFinish(uint64_t device_id, context* subCtx,
const BYTE* data, ULONG len) {
std::vector<BYTE> listCmd;
{
std::lock_guard<std::mutex> lk(m_PendingMutex);
auto it = m_Pending.find(device_id);
if (it == m_Pending.end()) return FileOpAck::NotMine; // 已超时清理 → 迟到包
if (!IsFileWriteToolName(it->second.tool)) return FileOpAck::NotMine; // 别的写工具不会发这些 token
if (it->second.phase == 0 && !it->second.verifyPath.empty()) {
// phase 0 → 1:完成包不代表成功,先在同一子连接上补一次列目录复核。
// 不投递完成包、也不置 done:工具线程继续在同一超时窗口内等复核结果。
it->second.phase = 1;
it->second.data.clear();
it->second.done = false;
listCmd.push_back((BYTE)COMMAND_LIST_FILES);
listCmd.insert(listCmd.end(), it->second.verifyPath.begin(), it->second.verifyPath.end());
listCmd.push_back(0); // 客户端按 C 串取路径
} else {
// 没有复核目标(或伪造的第二次完成包):直接投递,让工具线程收尾。
it->second.data.assign(data, data + len);
it->second.done = true;
m_PendingCv.notify_one();
return FileOpAck::CloseSub;
}
}
if (!subCtx->Send2Client(listCmd.data(), (ULONG)listCmd.size())) {
// 复核下发失败:别把工具线程挂到超时,直接把完成包投递过去,
// 工具会看到「不是列表包」→ verified=null(结果未知),如实上报。
Mprintf("[MCP-P10B] TakeFileOpFinish dev=%llu: send verify listing failed\n",
(unsigned long long)device_id);
std::lock_guard<std::mutex> lk(m_PendingMutex);
auto it = m_Pending.find(device_id);
if (it == m_Pending.end()) return FileOpAck::CloseSub;
it->second.data.assign(data, data + len);
it->second.done = true;
m_PendingCv.notify_one();
return FileOpAck::CloseSub;
}
Mprintf("[MCP-P10B] TakeFileOpFinish dev=%llu: ack ok -> verify listing (%d bytes)\n",
(unsigned long long)device_id, (int)listCmd.size());
return FileOpAck::KeepSub; // 等 TOKEN_FILE_LIST;该分支投递数据后 CancelIO 收尾
}
bool CMcpServer::WaitPending(uint64_t device_id, std::vector<BYTE>& out, int timeoutMs) {
std::unique_lock<std::mutex> lk(m_PendingMutex);
auto it = m_Pending.find(device_id);
if (it == m_Pending.end()) return false;
// 500ms 一片地等:取消后最多一个切片就落到下面的超时分支,仍由本线程清理 map。
const bool signaled = WaitWithCancel(lk, m_PendingCv, DeadlineAfter(timeoutMs),
[&] { return it->second.done; });
if (!signaled || it->second.data.empty()) {
// 放弃:客户端可能在我们返回后才把应答首包发上来,登记吸收,别让它弹 MFC 窗口。
MarkLateFirstPacketForTool(device_id, it->second.tool);
m_Pending.erase(it); // 超时/空数据 → 清理
return false;
}
out = std::move(it->second.data);
m_Pending.erase(it);
return true;
}
void CMcpServer::ClearPending(uint64_t device_id) {
std::lock_guard<std::mutex> lk(m_PendingMutex);
m_Pending.erase(device_id);
}
// ===== 迟到首包吸收 =====
// 工具放弃后 5 分钟内到达的「应答首包」只吸收一次;过期即失效(不长期压制人工操作)。
static const int kFirstPacketMarkMs = 5 * 60 * 1000;
void CMcpServer::MarkLateFirstPacket(uint64_t device_id, std::initializer_list<BYTE> tokens) {
if (tokens.size() == 0) return;
const auto now = std::chrono::steady_clock::now();
std::lock_guard<std::mutex> lk(m_FirstPacketMutex);
for (auto it = m_FirstPacketMarks.begin(); it != m_FirstPacketMarks.end();) {
if (it->second.expiry <= now) it = m_FirstPacketMarks.erase(it);
else ++it;
}
FirstPacketMark mk;
mk.tokens.insert(tokens.begin(), tokens.end());
mk.expiry = now + std::chrono::milliseconds(kFirstPacketMarkMs);
m_FirstPacketMarks[device_id] = std::move(mk);
}
// 工具 → 应答首包 token。只有「子连接第一个包会弹 MFC 窗口」的工具需要登记。
void CMcpServer::MarkLateFirstPacketForTool(uint64_t device_id, const std::string& tool) {
if (tool == "list_files" || tool == "download_file" || tool == "upload_file" || tool == "search_file" ||
IsFileWriteToolName(tool))
MarkLateFirstPacket(device_id, { (BYTE)TOKEN_DRIVE_LIST });
else if (tool == "list_registry")
MarkLateFirstPacket(device_id, { (BYTE)TOKEN_REGEDIT });
else if (tool == "list_services" || tool == "control_service")
MarkLateFirstPacket(device_id, { (BYTE)TOKEN_SERVERLIST });
else if (tool == "list_processes" || tool == "kill_process")
MarkLateFirstPacket(device_id, { (BYTE)TOKEN_PSLIST });
else if (tool == "list_windows" || tool == "operate_window")
MarkLateFirstPacket(device_id, { (BYTE)TOKEN_WSLIST });
else if (tool == "get_client_log")
MarkLateFirstPacket(device_id, { (BYTE)TOKEN_REPORT_LOG });
else if (tool == "get_activity_history")
MarkLateFirstPacket(device_id, { (BYTE)TOKEN_REPORT_ACTIVITY });
}
bool CMcpServer::TakeToolFirstPacket(uint64_t device_id, BYTE token) {
std::lock_guard<std::mutex> lk(m_FirstPacketMutex);
auto it = m_FirstPacketMarks.find(device_id);
if (it == m_FirstPacketMarks.end()) return false;
if (it->second.expiry <= std::chrono::steady_clock::now()) { m_FirstPacketMarks.erase(it); return false; }
if (it->second.tokens.find(token) == it->second.tokens.end()) return false; // 不是该工具的应答首包
m_FirstPacketMarks.erase(it); // 一次性消费
Mprintf("[MCP] absorb late first token=%d dev=%llu (tool gave up earlier)\n",
(int)token, (unsigned long long)device_id);
return true;
}
// ===== P2c:list_files / get_screenshot 扩展 =====
bool CMcpServer::BeginPending(uint64_t device_id, const std::string& tool, const std::string& path) {
if (IsFileTransferPending(device_id)) return false; // 该 host 有文件传输会话在飞(互斥,见 F2)
std::lock_guard<std::mutex> lk(m_PendingMutex);
if (m_Pending.find(device_id) != m_Pending.end()) return false; // 设备忙
PendingRequest r;
r.tool = tool;
r.path = path;
m_Pending[device_id] = std::move(r);
return true;
}
uint16_t CMcpServer::NextPreviewReqId() {
uint16_t v = m_PreviewReqId.fetch_add(1, std::memory_order_relaxed);
if (v == 0) v = m_PreviewReqId.fetch_add(1, std::memory_order_relaxed); // 跳过 0
return v;
}
void CMcpServer::SetPendingReqId(uint64_t device_id, uint16_t reqId) {
std::lock_guard<std::mutex> lk(m_PendingMutex);
auto it = m_Pending.find(device_id);
if (it != m_Pending.end()) it->second.expectedReqId = reqId;
}
bool CMcpServer::TakePreviewResponse(uint64_t device_id, uint16_t reqId, const BYTE* data, ULONG len) {
std::lock_guard<std::mutex> lk(m_PendingMutex);
auto it = m_Pending.find(device_id);
if (it == m_Pending.end()) return false; // 已超时清理 → 迟到数据,回落 MFC
if (it->second.tool != "get_screenshot") return false;
if (it->second.expectedReqId == 0 || it->second.expectedReqId != reqId) return false; // 过期/他途响应
it->second.data.assign(data, data + len);
it->second.done = true;
m_PendingCv.notify_one();
return true;
}
bool CMcpServer::OnDriveList(uint64_t device_id, context* subCtx, const BYTE* buf, ULONG len) {
std::string path;
bool listDrives = true;
bool searchFile = false;
bool fileOp = false;
std::vector<BYTE> fileOpFollowUp;
{
std::lock_guard<std::mutex> lk(m_PendingMutex);
auto it = m_Pending.find(device_id);
if (it == m_Pending.end()) return true; // 已超时清理 → 调用方 CancelIO 收尾
path = it->second.path;
if (IsFileWriteToolName(it->second.tool)) {
// P10-B:文件写工具。子连接就绪即下发写命令(path 对这些工具无意义,
// payload 已整条存在 followUp 里),保持子连接等 TOKEN_*_FINISH。
fileOp = true;
it->second.subCtx = subCtx; // 超时 CancelIO / 阶段判断用
it->second.followUpSent = true;
fileOpFollowUp = it->second.followUp;
} else if (it->second.tool == "search_file") {
// B2:path 里装的是 [根目录 \0][模式 \0](含 NUL,不能用 C 字符串接口处理)。
searchFile = true;
it->second.subCtx = subCtx; // 超时停搜 / 收尾要用
} else {
listDrives = path.empty() || path == "." || path == "/" || path == "\\";
if (listDrives) {
it->second.data.assign(buf, buf + len);
it->second.done = true;
m_PendingCv.notify_one();
return true; // 只列盘 → 调用方用完即关
}
}
}
if (fileOp) {
// 锁外下发写命令。发送失败不额外处理:工具线程会在超时后按 -32001 收尾并 CancelIO。
if (!subCtx->Send2Client(fileOpFollowUp.data(), (ULONG)fileOpFollowUp.size()))
Mprintf("[MCP-P10B] OnDriveList: send file-op command failed (dev=%llu, %d bytes)\n",
(unsigned long long)device_id, (int)fileOpFollowUp.size());
return false; // 保持子连接,等完成包
}
if (searchFile) {
// 文件搜索:子链接已就绪,下发 COMMAND_SEARCH_FILE + FILESEARCH 结构体。
// 与 MFC 文件管理器 OnBtnSearch 的打包方式一致(命令字节后紧跟整个结构体)。
std::vector<BYTE> pkt;
pkt.reserve(1 + path.size());
pkt.push_back((BYTE)COMMAND_SEARCH_FILE);
pkt.insert(pkt.end(), path.begin(), path.end());
subCtx->Send2Client(pkt.data(), (ULONG)pkt.size());
return false; // 保持子链接,等 N 个结果包 + FINISH
}
// 列目录:锁外下发 COMMAND_LIST_FILES + path,子链接保持,等 TOKEN_FILE_LIST。
// path 已在 BuildListFiles 按客户端 ANSI 转好(OnDriveList 无需再转),结尾 '\0'
// 与 FileManagerDlg 的 PacketSize=len+2 一致。
std::vector<BYTE> pkt;
pkt.reserve(1 + path.size() + 1);
pkt.push_back((BYTE)COMMAND_LIST_FILES);
pkt.insert(pkt.end(), path.begin(), path.end());
pkt.push_back(0);
subCtx->Send2Client(pkt.data(), (ULONG)pkt.size());
return false; // 继续等 TOKEN_FILE_LIST,调用方不 CancelIO
}
// ===== B2:search_file =====
namespace {
// 收集上限:单次搜索最多记住 5000 条 / 4 MB 原始包,超过就让客户端停搜。
// 这是保护服务端内存(整盘搜索能命中几十万条),不是业务上限。
const size_t kSearchMaxRecords = 5000;
const size_t kSearchMaxBytes = 4 * 1024 * 1024;
}
bool CMcpServer::OnSearchFileRecords(uint64_t device_id, context* subCtx, const BYTE* buf, ULONG len) {
bool needStop = false;
{
std::lock_guard<std::mutex> lk(m_PendingMutex);
auto it = m_Pending.find(device_id);
if (it == m_Pending.end() || it->second.tool != "search_file") return false;
PendingRequest& p = it->second;
// 身份校验:只认登记过的那条子连接。旧搜索(已放弃)的尾包一律不受理,
// 由调用方原地丢弃——但调用方绝不能因此关连接(见 2015RemoteDlg.cpp 的注释)。
if (p.subCtx != subCtx) return false;
if (p.searchRecords.size() >= kSearchMaxRecords ||
p.searchBytes + len > kSearchMaxBytes) {
p.searchTruncated = true;
if (!p.searchStopSent) { p.searchStopSent = true; needStop = true; }
} else {
p.searchRecords.emplace_back(buf, buf + len);
p.searchBytes += len;
}
}
if (needStop && subCtx) {
BYTE stop = (BYTE)COMMAND_FILES_SEARCH_STOP;
subCtx->Send2Client(&stop, 1);
}
return true; // 命中挂起 → 本包由 MCP 消费(不论是否因超限被丢弃)
}
void CMcpServer::FinishSearchFile(uint64_t device_id, context* subCtx) {
std::lock_guard<std::mutex> lk(m_PendingMutex);
auto it = m_Pending.find(device_id);
if (it == m_Pending.end() || it->second.tool != "search_file") return;
if (it->second.subCtx != subCtx) return; // 别的子连接的 FINISH,与当前搜索无关
it->second.searchFinished = true;
m_PendingCv.notify_all();
}
bool CMcpServer::WaitSearchFile(uint64_t device_id, std::vector<std::vector<BYTE>>& records,
bool& finished, bool& truncated, context*& subCtx, int timeoutMs) {
std::unique_lock<std::mutex> lk(m_PendingMutex);
auto it = m_Pending.find(device_id);
if (it == m_Pending.end() || it->second.tool != "search_file") return false;
// 取消(search_file 120s 上限)后仍然把已收记录带出去:调用方会去停搜并返回部分结果。
WaitWithCancel(lk, m_PendingCv, DeadlineAfter(timeoutMs),
[&] { return it->second.searchFinished; });
records.swap(it->second.searchRecords);
it->second.searchRecords.clear();
it->second.searchBytes = 0;
finished = it->second.searchFinished;
truncated = it->second.searchTruncated;
subCtx = it->second.subCtx;
return true;
}
void CMcpServer::StopSearchFile(uint64_t device_id) {
context* subCtx = nullptr;
{
std::lock_guard<std::mutex> lk(m_PendingMutex);
auto it = m_Pending.find(device_id);
if (it == m_Pending.end() || it->second.tool != "search_file") return;
if (it->second.searchStopSent) return;
it->second.searchStopSent = true;
subCtx = it->second.subCtx;
}
if (subCtx) {
BYTE stop = (BYTE)COMMAND_FILES_SEARCH_STOP;
subCtx->Send2Client(&stop, 1);
}
}
// ===== P3:list_registry 扩展 =====
bool CMcpServer::OnRegeditReady(uint64_t device_id, context* subCtx) {
std::string rootAndPath;
{
std::lock_guard<std::mutex> lk(m_PendingMutex);
auto it = m_Pending.find(device_id);
if (it == m_Pending.end()) return false; // 无挂起 → 回落 MFC
if (it->second.tool != "list_registry") return false;
rootAndPath = it->second.path; // [rootToken:1][相对子键路径...]
}
if (rootAndPath.empty()) return false; // 不应发生:list_registry 必有 rootToken
BYTE rootToken = (BYTE)rootAndPath[0];
std::string relPath = rootAndPath.substr(1);
// 下发 COMMAND_REG_FIND:布局与 RegisterDlg::OnTvnSelchangedTree 一致
// [COMMAND_REG_FIND][rootToken][relPath...]['\0']。子链接保持,等 TOKEN_REG_PATH + KEY。
std::vector<BYTE> pkt;
pkt.reserve(2 + relPath.size() + 1);
pkt.push_back((BYTE)COMMAND_REG_FIND);
pkt.push_back(rootToken);
pkt.insert(pkt.end(), relPath.begin(), relPath.end());
pkt.push_back(0);
subCtx->Send2Client(pkt.data(), (ULONG)pkt.size());
return true; // 接管子链接,不打开 MFC 对话框
}
void CMcpServer::TakeRegPath(uint64_t device_id, const BYTE* data, ULONG len) {
std::lock_guard<std::mutex> lk(m_PendingMutex);
auto it = m_Pending.find(device_id);
if (it == m_Pending.end()) return; // 已超时清理 → 迟到数据丢弃
if (it->second.tool != "list_registry") return;
it->second.regPath.assign(data, data + len);
it->second.pathDone = true;
if (it->second.keyDone) {
it->second.done = true;
m_PendingCv.notify_one();
}
}
void CMcpServer::TakeRegKey(uint64_t device_id, const BYTE* data, ULONG len) {
std::lock_guard<std::mutex> lk(m_PendingMutex);
auto it = m_Pending.find(device_id);
if (it == m_Pending.end()) return;
if (it->second.tool != "list_registry") return;
it->second.regKey.assign(data, data + len);
it->second.keyDone = true;
if (it->second.pathDone) {
it->second.done = true;
m_PendingCv.notify_one();
}
}
// 工具默认等待超时([settings] McpToolTimeoutMs)。仅在启动初始化阶段调用,无并发写。
void CMcpServer::SetToolTimeoutMs(int ms) {
if (ms < 1000) ms = 1000; // 下限:短于一秒的等待几乎必然误判超时
if (ms > 600000) ms = 600000; // 上限:与 exec_command timeout_ms 同界
m_toolTimeoutMs = ms;
}
void CMcpServer::TakeRegError(uint64_t device_id, const BYTE* data, ULONG len) {
std::lock_guard<std::mutex> lk(m_PendingMutex);
auto it = m_Pending.find(device_id);
if (it == m_Pending.end()) return; // 已超时清理 → 迟到数据丢弃
if (it->second.tool != "list_registry") return;
// 失败时客户端只发这一包(不会有 PATH/KEY),故一次置满三个标志。
it->second.regPath.assign(data, data + len);
it->second.pathDone = true;
it->second.keyDone = true;
it->second.done = true;
m_PendingCv.notify_one();
}
bool CMcpServer::WaitPendingRegistry(uint64_t device_id, std::vector<BYTE>& subkeys,
std::vector<BYTE>& values, int timeoutMs) {
std::unique_lock<std::mutex> lk(m_PendingMutex);
auto it = m_Pending.find(device_id);
if (it == m_Pending.end()) return false;
bool signaled = WaitWithCancel(lk, m_PendingCv, DeadlineAfter(timeoutMs),
[&] { return it->second.done; });
if (!signaled) {
MarkLateFirstPacketForTool(device_id, it->second.tool); // 放弃后的 TOKEN_REGEDIT 不弹注册表窗口
m_Pending.erase(it); // 超时/取消 → 清理
return false;
}
subkeys = std::move(it->second.regPath);
values = std::move(it->second.regKey);
m_Pending.erase(it);
return true;
}
// ===== P7:设备管理控制(写工具接管)=====
bool CMcpServer::BeginPendingFollowUp(uint64_t device_id, const std::string& tool,
const std::vector<BYTE>& followUp) {
if (IsFileTransferPending(device_id)) return false; // 该 host 有文件传输会话在飞(互斥,见 F2)
std::lock_guard<std::mutex> lk(m_PendingMutex);
if (m_Pending.find(device_id) != m_Pending.end()) return false; // 设备忙
PendingRequest r;
r.tool = tool;
r.kind = PendingKind::FollowUp;
r.followUp = followUp;
m_Pending[device_id] = std::move(r);
return true;
}
bool CMcpServer::OnSystemReady(uint64_t device_id, context* subCtx) {
std::string tool;
std::vector<BYTE> followUp;
{
std::lock_guard<std::mutex> lk(m_PendingMutex);
auto it = m_Pending.find(device_id);
if (it == m_Pending.end()) { Mprintf("[MCP-P7] OnSystemReady dev=%llu: no pending\n", device_id); return false; } // 无挂起 → 回落 MFC
tool = it->second.tool;
if (tool != "kill_process" && tool != "operate_window") { Mprintf("[MCP-P7] OnSystemReady dev=%llu tool=%s: not write tool\n", device_id, tool.c_str()); return false; }
if (it->second.followUpSent) { Mprintf("[MCP-P7] OnSystemReady dev=%llu tool=%s: CONFIRM token -> TakeMainResponse\n", device_id, tool.c_str()); return false; } // 确认包 → TakeMainResponse
followUp = it->second.followUp;
it->second.subCtx = subCtx;
it->second.followUpSent = true;
}
// 锁外下发写命令;kill/test 需补发刷新命令索取新列表(close/control_service 客户端自动回)。
BOOL b1 = subCtx->Send2Client(followUp.data(), (ULONG)followUp.size());
BYTE refresh = 0;
if (tool == "kill_process") {
refresh = (BYTE)COMMAND_PSLIST;
} else if (!followUp.empty() && followUp[0] == CMD_WINDOW_TEST) {
refresh = (BYTE)COMMAND_WSLIST;
}
if (refresh) {
// followUp 与 refresh 是两次独立 Send2Client,各自 PostQueuedCompletionStatus(IOWrite),
// worker 会对同一 OutCompressedBuffer 并发发起 WSASend,造成竞态/丢包。用 WaitSendIdle
// 确定性等首个包真正发完再发刷新包(比 MFC 的 Sleep(100) 盲等更稳)。
subCtx->WaitSendIdle(2000);
BOOL b2 = subCtx->Send2Client(&refresh, 1);
Mprintf("[MCP-P7] OnSystemReady dev=%llu tool=%s READY: followUpSend=%d refreshSend=%d refresh=%d\n",
device_id, tool.c_str(), b1 ? 1 : 0, b2 ? 1 : 0, (int)refresh);
}
return true; // 已接管,不 CancelIO
}
bool CMcpServer::OnServiceReady(uint64_t device_id, context* subCtx) {
std::vector<BYTE> followUp;
{
std::lock_guard<std::mutex> lk(m_PendingMutex);
auto it = m_Pending.find(device_id);
if (it == m_Pending.end()) return false;
if (it->second.tool != "control_service") return false;
if (it->second.followUpSent) return false; // 确认包 → 调用方 TakeMainResponse
followUp = it->second.followUp;
it->second.subCtx = subCtx;
it->second.followUpSent = true;
}
subCtx->Send2Client(followUp.data(), (ULONG)followUp.size());
return true; // 客户端写后自动回,无需补发
}
bool CMcpServer::WaitPendingWrite(uint64_t device_id, std::vector<BYTE>& out, int timeoutMs,
int* phaseOut) {
context* subCtx = nullptr;
std::unique_lock<std::mutex> lk(m_PendingMutex);
auto it = m_Pending.find(device_id);
if (it == m_Pending.end()) {
if (phaseOut) *phaseOut = 0;
return false;
}
if (phaseOut) *phaseOut = it->second.phase;
bool signaled = WaitWithCancel(lk, m_PendingCv, DeadlineAfter(timeoutMs),
[&] { return it->second.done; });
// 超时/空数据时把「放弃那一刻所处的阶段」带出去:P10-B 的 phase 1 表示完成包已到、
// 只是复核列目录没回来(命令已送达),与 phase 0 的「连回包都没有」不是一回事。
if (phaseOut) *phaseOut = it->second.phase;
if (!signaled || it->second.data.empty()) {
subCtx = it->second.subCtx;
Mprintf("[MCP-P7] WaitPendingWrite dev=%llu TIMEOUT: signaled=%d dataEmpty=%d subCtx=%p\n",
device_id, signaled ? 1 : 0, it->second.data.empty() ? 1 : 0, (void*)subCtx);
MarkLateFirstPacketForTool(device_id, it->second.tool); // 就绪包迟到 → 吸收,不弹进程/服务窗口
m_Pending.erase(it); // 超时/空数据 → 清理
lk.unlock();
if (subCtx) subCtx->CancelIO(); // 锁外关子连接,防孤儿子连接
return false;
}
out = std::move(it->second.data);
Mprintf("[MCP-P7] WaitPendingWrite dev=%llu OK len=%d\n", device_id, (int)out.size());
m_Pending.erase(it);
return true;
}
void CMcpServer::OnManageSubClosed(context* subCtx) {
std::lock_guard<std::mutex> lk(m_PendingMutex);
// 只匹配「已接管、等确认包」的写工具子连接(read 工具从不存 subCtx,天然不命中)。
// 扫描而非按 device_id 查找,避免依赖断线后 GetClientID 是否仍有效。
for (auto& kv : m_Pending) {
if (kv.second.subCtx == subCtx) {
// P8 会话由 OnManagedContextClosed 处理(这里若清 subCtx 会让其无法按指针反查设备)。
if (kv.second.kind == PendingKind::Machine || kv.second.kind == PendingKind::ConnMgr) continue;
Mprintf("[MCP-P7] OnManageSubClosed subCtx=%p tool=%s: sub-conn closed before confirm\n",
(void*)subCtx, kv.second.tool.c_str());
kv.second.subCtx = nullptr; // 断线后子连接已死/将回收,超时路径不得再 CancelIO
kv.second.done = true; // 唤醒等待线程(WaitPendingWrite 见 data 空 → 返回失败)
m_PendingCv.notify_all();
break;
}
}
}
// rand_s:Windows CRT 加密安全随机源(基于系统 CSPRNG)。其声明需在 <stdlib.h> 前
// 定义 _CRT_RAND_S;为避免依赖 PCH 的包含顺序,这里手动声明其导出原型(errno_t == int)。
extern "C" int __cdecl rand_s(unsigned int* randomValue);
std::string GenerateRandomToken() {
static const char hex[] = "0123456789abcdef";
std::string out;
out.reserve(32);
for (int i = 0; i < 16; ++i) {
unsigned int v = 0;
if (rand_s(&v) != 0) {
// rand_s 失败(罕见):退化为时间 + 地址熵,保证仍返回非空 token。
v = (unsigned int)(GetTickCount() ^ (ULONG_PTR)&out);
}
out.push_back(hex[(v >> 4) & 0xF]);
out.push_back(hex[v & 0xF]);
}
return out;
}
// ===== P6:download_file 文件传输会话(状态机方法)=====
// 停滞看门狗:超过这么久没收到任何传输包即判失败(远程路径不存在时客户端不发包)。
// 60s 足够覆盖极慢链路,又远小于 download_file 默认的 600s 总超时。
static const int kFileXferStallMs = 60000;
bool CMcpServer::IsFileTransferPending(uint64_t device_id) {
std::lock_guard<std::mutex> lk(m_FileXferMutex);
return m_FileXferSessions.find(device_id) != m_FileXferSessions.end();
}
bool CMcpServer::IsC2CTransferPending(uint64_t src_id, uint64_t dst_id) {
std::lock_guard<std::mutex> lk(m_FileXferMutex);
auto it = m_FileXferSessions.find(src_id);
return it != m_FileXferSessions.end()
&& it->second.tool == "copy_files_c2c" && it->second.dstClientID == dst_id;
}
bool CMcpServer::BeginFileTransferPending(uint64_t device_id, const std::string& tool,
const std::string& localDir, const std::string& remotePath,
bool overwrite) {
// 与一次性挂起请求互斥(F2):先查对方注册表再查自己的,避免跨锁嵌套死锁。
{
std::lock_guard<std::mutex> lk(m_PendingMutex);
if (m_Pending.find(device_id) != m_Pending.end()) return false;
}
std::lock_guard<std::mutex> lk(m_FileXferMutex);
if (m_FileXferSessions.find(device_id) != m_FileXferSessions.end()) return false; // 单设备单传输
FileTransferSession s;
s.tool = tool;
s.localDir = localDir;
s.remotePath = remotePath;
s.overwrite = overwrite;
s.startAt = time(nullptr);
s.lastDataAt = std::chrono::steady_clock::now();
m_FileXferSessions[device_id] = std::move(s);
return true;
}
bool CMcpServer::BeginFileUpload(uint64_t device_id, uint64_t transfer_id) {
// 与一次性挂起请求互斥(F2):先查对方注册表再查自己的,避免跨锁嵌套死锁。
{
std::lock_guard<std::mutex> lk(m_PendingMutex);
if (m_Pending.find(device_id) != m_Pending.end()) return false;
}
std::lock_guard<std::mutex> lk(m_FileXferMutex);
if (m_FileXferSessions.find(device_id) != m_FileXferSessions.end()) return false; // 单设备单传输
FileTransferSession s;
s.tool = "upload_file";
s.dstClientID = device_id; // 目标端 = 会话宿主,回执按 dstClientID + transferID 匹配
s.transferID = transfer_id;
s.startAt = time(nullptr);
s.lastDataAt = std::chrono::steady_clock::now();
m_FileXferSessions[device_id] = std::move(s);
return true;
}
// ===== C2C 文件传输(copy_files_c2c)=====
// 源客户端收到 COMMAND_C2C_SEND_FILES 后自己开子连接上行,数据包由服务端的
// COMMAND_SEND_FILE_V2 转发分支(dstClientID != 0)原样中继到目标客户端主连接,
// 服务端不落盘、不解析文件内容;本会话只用来「等源端回传结果 + 单设备单传输互斥」。
bool CMcpServer::BeginC2CTransfer(uint64_t src_id, uint64_t dst_id, uint64_t transfer_id) {
if (src_id == 0 || src_id == dst_id) return false;
{
// 与一次性挂起请求互斥(F2):先查对方注册表再查自己的,避免跨锁嵌套死锁。
std::lock_guard<std::mutex> lk(m_PendingMutex);
if (m_Pending.find(src_id) != m_Pending.end()) return false;
if (m_Pending.find(dst_id) != m_Pending.end()) return false;
}
std::lock_guard<std::mutex> lk(m_FileXferMutex);
if (m_FileXferSessions.find(src_id) != m_FileXferSessions.end()) return false; // 单设备单传输
if (m_FileXferSessions.find(dst_id) != m_FileXferSessions.end()) return false; // 目标端另有在飞传输
FileTransferSession s;
s.tool = "copy_files_c2c";
s.dstClientID = dst_id;
s.transferID = transfer_id;
s.startAt = time(nullptr);
s.lastDataAt = std::chrono::steady_clock::now();
m_FileXferSessions[src_id] = std::move(s);
return true;
}
void CMcpServer::OnC2CResult(uint64_t src_id, const BYTE* buf, ULONG len) {
if (len < sizeof(C2CSendResultPacket)) return;
const C2CSendResultPacket* res = (const C2CSendResultPacket*)buf;
std::lock_guard<std::mutex> lk(m_FileXferMutex);
auto it = m_FileXferSessions.find(src_id);
if (it == m_FileXferSessions.end() || it->second.tool != "copy_files_c2c") return;
FileTransferSession& s = it->second;
if (s.c2cResult || res->transferID != s.transferID) return; // 首个结果为准,旧传输的迟到包忽略
s.c2cResult = true;
s.c2cStatus = res->status;
s.c2cWin32 = res->win32err;
s.c2cWorkerRc = res->workerRc;
s.c2cFileCount = res->fileCount;
s.c2cBytes = res->totalBytes;
s.done = true;
s.error = (res->status == (uint32_t)FEV2_OK && res->workerRc == 0)
? 0 : (int)(res->status ? res->status : 1001);
m_FileXferCv.notify_all();
}
void CMcpServer::OnC2CRecvResult(uint64_t dst_id, const BYTE* buf, ULONG len) {
if (len < sizeof(C2CSendResultPacket)) return;
const C2CSendResultPacket* res = (const C2CSendResultPacket*)buf;
if (res->cmd != TOKEN_C2C_RECV_RESULT || res->dstClientID != dst_id) return; // 身份自洽性
std::lock_guard<std::mutex> lk(m_FileXferMutex);
// copy_files_c2c:目标端在服务端没有会话条目(BeginC2CTransfer 只登记源端),只能反查;
// upload_file:会话键就是目标端本身。两者都用 dstClientID + transferID 定位。
for (auto& kv : m_FileXferSessions) {
FileTransferSession& s = kv.second;
if (s.tool != "copy_files_c2c" && s.tool != "upload_file") continue;
if (s.dstClientID != dst_id || s.transferID != res->transferID) continue;
if (s.recvAck) return; // 重复回执只认第一包
s.recvAck = true;
s.recvStatus = res->status;
s.recvErrno = res->win32err; // 176 里放的是 errno
s.recvFileCount = res->fileCount;
s.recvBytes = res->totalBytes;
m_FileXferCv.notify_all();
return;
}
}
bool CMcpServer::WaitC2CDone(uint64_t src_id, int timeoutMs, C2CResult& out) {
std::unique_lock<std::mutex> lk(m_FileXferMutex);
auto it = m_FileXferSessions.find(src_id);
if (it == m_FileXferSessions.end()) { out.error = 1002; return false; }
// 只有总超时,没有停滞看门狗:源端全程只在最后回一包结果,中途长时间无包是正常的
// (大文件传输),按「无数据即停滞」判会误杀。
const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutMs);
bool signaled = false;
while (true) {
auto slice = std::chrono::milliseconds(500);
auto now = std::chrono::steady_clock::now();
if (now + slice > deadline) slice = std::chrono::duration_cast<std::chrono::milliseconds>(deadline - now);
if (slice.count() <= 0) break; // 总超时
if (m_FileXferCv.wait_for(lk, slice, [&] { return it->second.done; })) {
signaled = true;
break;
}
if (McpCallCancelled()) break; // P11:取消按「未收到结果」收尾
}
FileTransferSession& s = it->second;
out.status = s.c2cStatus;
out.win32err = s.c2cWin32;
out.workerRc = s.c2cWorkerRc;
out.fileCount = s.c2cFileCount;
out.totalBytes = s.c2cBytes;
if (!signaled && !s.done) { out.error = 1002; return false; } // 超时:传输可能仍在继续
out.error = s.error;
return s.c2cResult && s.error == 0;
}
bool CMcpServer::WaitC2CReceiver(uint64_t src_id, int timeoutMs, C2CResult& out) {
std::unique_lock<std::mutex> lk(m_FileXferMutex);
auto it = m_FileXferSessions.find(src_id);
if (it == m_FileXferSessions.end()) return false; // 会话已收尾:按「无回执」处理
const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutMs);
while (!it->second.recvAck) {
auto slice = std::chrono::milliseconds(250);
auto now = std::chrono::steady_clock::now();
if (now + slice > deadline) slice = std::chrono::duration_cast<std::chrono::milliseconds>(deadline - now);
if (slice.count() <= 0) break; // 超时:老客户端/Windows 目标根本不回执
m_FileXferCv.wait_for(lk, slice);
if (McpCallCancelled()) break;
}
FileTransferSession& s = it->second;
out.recvAck = s.recvAck;
out.recvStatus = s.recvStatus;
out.recvErrno = s.recvErrno;
out.recvFileCount = s.recvFileCount;
out.recvBytes = s.recvBytes;
return s.recvAck;
}
bool CMcpServer::OnDownloadDriveList(uint64_t device_id, context* fmSubCtx) {
std::string localDir, remotePath;
{
std::lock_guard<std::mutex> lk(m_FileXferMutex);
auto it = m_FileXferSessions.find(device_id);
if (it == m_FileXferSessions.end() || it->second.tool != "download_file")
return false; // 会话已清理 → 调用方 CancelIO 收尾
FileTransferSession& s = it->second;
if (s.fmSubCtx != nullptr) return true; // 已下发过,防重复
s.fmSubCtx = fmSubCtx;
m_FileXferContextToDevice[fmSubCtx] = device_id; // OfflineProc 反查用
localDir = s.localDir;
remotePath = s.remotePath;
}
// 锁外组包下发(Send2Client 异步投递,子链接保持到 ClearFileTransfer 收尾,见 §13 F3)。
// 布局与 FileManagerDlg::OnTransferV2ToLocal 一致:[cmd][targetDir\0][remotePath\0][\0]
std::vector<BYTE> pkt;
pkt.reserve(1 + localDir.size() + 1 + remotePath.size() + 2);
pkt.push_back((BYTE)CMD_DOWN_FILES_V2);
pkt.insert(pkt.end(), localDir.begin(), localDir.end());
pkt.push_back(0);
pkt.insert(pkt.end(), remotePath.begin(), remotePath.end());
pkt.push_back(0);
pkt.push_back(0);
fmSubCtx->Send2Client(pkt.data(), (ULONG)pkt.size());
Mprintf("[MCP] download_file: 下发 CMD_DOWN_FILES_V2 remote=%s\n", remotePath.c_str());
return true;
}
void CMcpServer::OnFileChunkV2(uint64_t device_id, context* streamSubCtx, const BYTE* buf, ULONG len) {
if (len < (ULONG)sizeof(FileChunkPacketV2)) return;
const FileChunkPacketV2* pkt = (const FileChunkPacketV2*)buf;
if (pkt->nameLength > (uint64_t)(len - sizeof(FileChunkPacketV2))) return; // 畸形包:名字越界
// 与 FileManagerDlg.cpp 落盘同款参数(镜像其 GetPwdHash()/GetHMAC(100))。
std::string hash = GetPwdHash(), hmac = GetHMAC(100);
std::lock_guard<std::mutex> lk(m_FileXferMutex);
auto it = m_FileXferSessions.find(device_id);
if (it == m_FileXferSessions.end()) return;
FileTransferSession& s = it->second;
if (s.tool != "download_file") return;
if (s.done) return; // 已出错/完成,丢弃迟到包
s.lastDataAt = std::chrono::steady_clock::now(); // 停滞看门狗:有包就续命
s.bytesReceived += pkt->dataLength; // P11:进度通知的兜底量(文件数未知时用)
if (s.streamSubCtx == nullptr) {
s.streamSubCtx = streamSubCtx;
m_FileXferContextToDevice[streamSubCtx] = device_id; // OfflineProc 反查用
}
if (s.transferID == 0) {
s.transferID = pkt->transferID;
s.totalFiles = pkt->totalFiles;
}
uint32_t fileIndex = pkt->fileIndex;
std::string fileName((char*)(pkt + 1), pkt->nameLength); // ANSI = localDir + relPath
// 目录项:只建目录(RecvFileChunkV2 会 mkdir),不参与 files 输出(见 §13 F4)。
// 与文件项一样先做路径穿越校验(F5):目录项的 filename 同样可能越界(如远程目录名含 ..)。
if (pkt->flags & FFV2_DIRECTORY) {
if (!PathWithinDirA(s.localDir, fileName)) {
s.error = 1001;
s.done = true;
m_FileXferCv.notify_one();
return;
}
s.directoryCount++;
RecvFileChunkV2((char*)buf, len, nullptr, nullptr, hash, hmac, 0);
// 目录项不发 COMPLETE 包,而条目顺序由客户端决定(目录可能排在最后,如空子目录),
// 完成判定必须在每一类条目定案后都做:文件数 + 目录数覆盖 totalFiles 即完成(F4)。
if (s.totalFiles > 0 && s.filesDone + s.directoryCount >= s.totalFiles) {
s.done = true;
m_FileXferCv.notify_one();
}
return;
}
if (pkt->offset == 0) {
// 路径穿越校验(F5):规范化后必须在 localDir 内。
if (!PathWithinDirA(s.localDir, fileName)) {
s.error = 1001;
s.done = true;
m_FileXferCv.notify_one();
return;
}
// overwrite=false 且同名已存在 → 跳过该文件(丢弃其后续分块,不落盘)。
if (!s.overwrite && GetFileAttributesA(fileName.c_str()) != INVALID_FILE_ATTRIBUTES) {
s.skipIndexes.insert(fileIndex);
FileTransferEntry e;
e.path = fileName;
e.size = pkt->fileSize;
s.skipped.push_back(std::move(e));
return;
}
// 记录文件条目(size 已知;sha256 待 COMPLETE 包回填)。
FileTransferEntry e;
e.path = fileName;
e.size = pkt->fileSize;
s.fileEntries[fileIndex] = std::move(e);
} else {
if (s.skipIndexes.count(fileIndex)) return; // 已跳过的文件,丢弃后续分块
}
int n = RecvFileChunkV2((char*)buf, len, nullptr, nullptr, hash, hmac, 0);
if (n) {
s.error = n;
s.done = true;
m_FileXferCv.notify_one();
}
}
void CMcpServer::OnDownloadError(uint64_t device_id, context* fmSubCtx, const BYTE* buf, ULONG len) {
// [TOKEN_DOWNLOAD_ERROR][win32err:4 LE]:客户端在 FileManager 子连接上直接回报
// 「远端路径全部不存在/不可访问」,此时传输子连接还没建立,不会再有 chunk 到达。
DWORD win32err = 0;
if (len >= 1 + sizeof(DWORD)) memcpy(&win32err, buf + 1, sizeof(DWORD));
std::lock_guard<std::mutex> lk(m_FileXferMutex);
auto it = m_FileXferSessions.find(device_id);
if (it == m_FileXferSessions.end()) return;
FileTransferSession& s = it->second;
if (s.tool != "download_file") return;
if (s.fmSubCtx != fmSubCtx) return; // 非本会话的子连接 → 忽略
if (s.done) return; // 已出错/完成,丢弃迟到包
s.error = (win32err == ERROR_FILE_NOT_FOUND || win32err == ERROR_PATH_NOT_FOUND) ? 1005
: (win32err == ERROR_ACCESS_DENIED) ? 1006
: 1007;
s.errorDetail = win32err; // 供 BuildDownloadFile 在文案里带出 win32 码
s.done = true;
m_FileXferCv.notify_one(); // 不 CancelIO:由 ClearFileTransfer 统一收尾
}
void CMcpServer::OnFileCompleteV2(uint64_t device_id, const BYTE* buf, ULONG len) {
if (len < (ULONG)sizeof(FileCompletePacketV2)) return;
const FileCompletePacketV2* pkt = (const FileCompletePacketV2*)buf;
std::lock_guard<std::mutex> lk(m_FileXferMutex);
auto it = m_FileXferSessions.find(device_id);
if (it == m_FileXferSessions.end()) return;
FileTransferSession& s = it->second;
if (s.tool != "download_file") return;
if (s.done) return;
s.lastDataAt = std::chrono::steady_clock::now(); // 停滞看门狗:有包就续命
uint32_t fileIndex = pkt->fileIndex;
if (s.skipIndexes.count(fileIndex)) {
s.filesDone++; // 跳过的文件:不校验,直接计数
} else {
bool verifyOk = HandleFileCompleteV2((const char*)buf, len, 0);
auto fe = s.fileEntries.find(fileIndex);
if (fe != s.fileEntries.end()) fe->second.sha256 = Sha256Hex(pkt->sha256, 32);
if (!verifyOk) {
s.error = FEV2_HASH_MISMATCH;
s.done = true;
m_FileXferCv.notify_one();
return;
}
s.filesDone++;
}
// 完成判定:目录不发 COMPLETE 包,故 filesDone 达 totalFiles - directoryCount 即完成(F4)。
uint32_t expectedFiles = (s.totalFiles > s.directoryCount) ? (s.totalFiles - s.directoryCount) : 0;
if (s.filesDone >= expectedFiles) {
s.done = true;
m_FileXferCv.notify_one();
}
}
bool CMcpServer::WaitFileTransferDone(uint64_t device_id, int timeoutMs,
std::vector<FileTransferEntry>& files, int& skipped, int& error,
DWORD* errorDetail) {
if (errorDetail) *errorDetail = 0;
std::unique_lock<std::mutex> lk(m_FileXferMutex);
auto it = m_FileXferSessions.find(device_id);
if (it == m_FileXferSessions.end()) { error = 1002; return false; }
// 分段等待 + 停滞看门狗:远程路径不存在时客户端一个包都不发,只靠总超时(默认 600s)
// 会把整台主机的单飞互斥占满 10 分钟(评审 P2)。改为「N 秒没有任何数据就判停滞」,
// 大文件正常传输时每个 chunk 都会续命,不受影响。
const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutMs);
bool signaled = false;
while (true) {
auto slice = std::chrono::milliseconds(500);
auto now = std::chrono::steady_clock::now();
if (now + slice > deadline) slice = std::chrono::duration_cast<std::chrono::milliseconds>(deadline - now);
if (slice.count() <= 0) break; // 总超时
if (m_FileXferCv.wait_for(lk, slice, [&] { return it->second.done; })) {
signaled = true;
break;
}
// 进度:已落盘文件数 / 期望文件数(总量未知时退回已收字节数)。
// EmitProgress 内部按 1s 节流,这里每片(500ms)报一次不会把流刷爆。
{
const uint32_t expectedNow =
(it->second.totalFiles > it->second.directoryCount)
? (it->second.totalFiles - it->second.directoryCount) : 0;
if (expectedNow > 0)
McpCallProgress((double)it->second.filesDone, (double)expectedNow);
else
McpCallProgress((double)it->second.bytesReceived);
}
if (McpCallCancelled()) break; // 取消 → 下面按超时(1002)收尾
if (std::chrono::steady_clock::now() - it->second.lastDataAt >=
std::chrono::milliseconds(kFileXferStallMs)) {
it->second.error = 1004; // 停滞
it->second.done = true;
break;
}
}
FileTransferSession& s = it->second;
if (!signaled && !s.done) s.error = 1002; // 总超时
error = s.error;
if (errorDetail) *errorDetail = s.errorDetail;
// 复制已见文件(成功=完整文件;失败=供调用方删半成品)。跳过的既有文件不在此列。
for (auto& kv : s.fileEntries) files.push_back(kv.second);
skipped = (int)s.skipped.size();
const bool ok = s.done && s.error == 0;
// 放弃的文件工具:迟到的 TOKEN_DRIVE_LIST(文件管理器子链接首包)不能弹文件管理器窗口。
if (!ok) MarkLateFirstPacketForTool(device_id, s.tool);
return ok;
}
void CMcpServer::ClearFileTransfer(uint64_t device_id) {
FileTransferSession s;
bool found = false;
{
std::lock_guard<std::mutex> lk(m_FileXferMutex);
auto it = m_FileXferSessions.find(device_id);
if (it != m_FileXferSessions.end()) {
s = std::move(it->second);
m_FileXferSessions.erase(it);
found = true;
}
// 反查表按 context* 键,必须随会话一起擦,否则连接池复用同一指针后会被误转成断线事件。
if (s.fmSubCtx) m_FileXferContextToDevice.erase(s.fmSubCtx);
if (s.streamSubCtx) m_FileXferContextToDevice.erase(s.streamSubCtx);
}
if (!found) return;
// 锁外关闭两条子链接(CancelIO 触发客户端断开,停掉仍在飞的流式数据)。
if (s.fmSubCtx) s.fmSubCtx->CancelIO();
if (s.streamSubCtx) s.streamSubCtx->CancelIO();
}
void CMcpServer::OnFileTransferContextClosed(context* subCtx) {
std::lock_guard<std::mutex> lk(m_FileXferMutex);
auto mapIt = m_FileXferContextToDevice.find(subCtx);
if (mapIt == m_FileXferContextToDevice.end()) return; // 不是文件传输子链接
uint64_t device_id = mapIt->second;
m_FileXferContextToDevice.erase(mapIt);
auto it = m_FileXferSessions.find(device_id);
if (it == m_FileXferSessions.end()) return;
FileTransferSession& s = it->second;
// 无论如何先清裸指针:此后工具线程的 ClearFileTransfer 绝不能再对这条已回收的连接 CancelIO。
bool wasStream = (s.streamSubCtx == subCtx);
if (s.fmSubCtx == subCtx) s.fmSubCtx = nullptr;
if (s.streamSubCtx == subCtx) s.streamSubCtx = nullptr;
// 流式子链接承载数据,它断了传输就不可能完成 → 立即判失败并唤醒工具线程(不用等 timeout)。
// 文件管理器子链接只用来下发命令,断开不代表传输失败,清指针即可。
if (wasStream && !s.done) {
s.error = 1003; // 断线
s.done = true;
m_FileXferCv.notify_all();
}
}