Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bfb17d0d25 | ||
|
|
6236ed1eb4 | ||
|
|
c271911fcb | ||
|
|
27d40f5678 | ||
|
|
a7dd86ff0f |
No files matched your search
+183
-8
@@ -1512,14 +1512,7 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
|
||||
case COMMAND_SEND_FILE_V2: {
|
||||
// 主连接接收 V2 上传:确保文件传输模块已初始化(RecvFileChunkV2 依赖 g_status==1)。
|
||||
// static 标志保证进程内只初始化一次,不随主连接重连反复 Init/Uninit。
|
||||
static bool s_v2RecvInited = false;
|
||||
if (!s_v2RecvInited) {
|
||||
int chunkKb, durMs;
|
||||
GetTransferSpeed(*m_cfg, chunkKb, durMs);
|
||||
InitFileUpload({}, m_LoginMsg, m_LoginSignature, chunkKb, durMs, Logf);
|
||||
s_v2RecvInited = true;
|
||||
}
|
||||
EnsureV2TransferInited();
|
||||
// C2C/V2 文件接收(RecvFileChunkV2 内部会打印进度)
|
||||
// 展开文件名中的环境变量(如 %USERPROFILE%),与 V1 的 COMMAND_FILE_SIZE 保持一致。
|
||||
// 快捷图标定位远程目录时,主控端下发的 targetDir 仍含未展开的 %USERPROFILE%
|
||||
@@ -1563,6 +1556,12 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
break;
|
||||
}
|
||||
|
||||
case COMMAND_C2C_SEND_FILES: {
|
||||
// C2C 按路径清单发送:服务端指定「源端路径 + 目标端目录」,见 OnC2CSendFiles。
|
||||
OnC2CSendFiles(szBuffer, ulLength);
|
||||
break;
|
||||
}
|
||||
|
||||
case COMMAND_CLIPBOARD_V2: {
|
||||
// C2C 剪贴板请求:被请求发送剪贴板文件到另一个客户端
|
||||
ClipboardRequestV2* req = (ClipboardRequestV2*)szBuffer;
|
||||
@@ -1838,6 +1837,182 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
}
|
||||
}
|
||||
|
||||
// V2 文件传输模块是进程级的(InitFileUpload/UninitFileUpload 成对),发送与接收共用一次初始化:
|
||||
// static 标志保证进程内只初始化一次,不随主连接重连反复 Init/Uninit,也不会被发送/接收两个
|
||||
// 入口各自初始化一次(第二次 Init 会重置状态并泄漏前一次的上下文)。
|
||||
void CKernelManager::EnsureV2TransferInited()
|
||||
{
|
||||
static bool s_v2Inited = false;
|
||||
if (s_v2Inited) return;
|
||||
int chunkKb, durMs;
|
||||
GetTransferSpeed(*m_cfg, chunkKb, durMs);
|
||||
int rc = InitFileUpload({}, m_LoginMsg, m_LoginSignature, chunkKb, durMs, Logf);
|
||||
if (rc != 0) Mprintf("[V2] InitFileUpload 返回 %d,V2 文件传输可能不可用\n", rc);
|
||||
s_v2Inited = true;
|
||||
}
|
||||
|
||||
// 收集目录下的文件与子目录(语义同 CFileManager::CollectFilesRecursiveV2:
|
||||
// 目录本身先作为一条 V2 目录项,随后是子项)。无成员依赖,主连接侧直接复用。
|
||||
static void CollectFilesForC2C(const std::string& dirPath, std::vector<std::string>& files)
|
||||
{
|
||||
std::string dirEntry = dirPath;
|
||||
while (!dirEntry.empty() && (dirEntry.back() == '\\' || dirEntry.back() == '/'))
|
||||
dirEntry.pop_back();
|
||||
if (!dirEntry.empty()) files.push_back(dirEntry);
|
||||
|
||||
WIN32_FIND_DATAA wfd;
|
||||
HANDLE hFind = FindFirstFileA((dirPath + "*.*").c_str(), &wfd);
|
||||
if (hFind == INVALID_HANDLE_VALUE) return;
|
||||
do {
|
||||
if (wfd.cFileName[0] == '.') continue;
|
||||
std::string fullPath = dirPath + wfd.cFileName;
|
||||
if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
|
||||
CollectFilesForC2C(fullPath + "\\", files);
|
||||
else
|
||||
files.push_back(fullPath);
|
||||
} while (FindNextFileA(hFind, &wfd));
|
||||
FindClose(hFind);
|
||||
}
|
||||
|
||||
// 展开 %VAR%(与 CFileManager 的静态 ExpandPath 同语义,展开失败返回原路径)
|
||||
static std::string ExpandPathForC2C(const char* path)
|
||||
{
|
||||
char szExpanded[MAX_PATH * 2] = { 0 };
|
||||
DWORD len = ExpandEnvironmentStringsA(path, szExpanded, (DWORD)sizeof(szExpanded));
|
||||
if (len > 0 && len < (DWORD)sizeof(szExpanded)) return szExpanded;
|
||||
return path;
|
||||
}
|
||||
|
||||
// C2C 按路径清单发送(服务端 → 源客户端)。
|
||||
// 包格式:[C2CSendFilesPacket][targetDir\0][path1\0]...[pathN\0][\0](ANSI/936)。
|
||||
// 与 COMMAND_CLIPBOARD_V2 的差别只在文件来源:这里的路径由服务端指定,不取剪贴板/资源管理器选中项。
|
||||
// 数据由本端新开子连接上行,服务端按包内 dstClientID 原样中继到目标客户端的主连接。
|
||||
void CKernelManager::OnC2CSendFiles(PBYTE szBuffer, ULONG ulLength)
|
||||
{
|
||||
if (ulLength < sizeof(C2CSendFilesPacket)) return;
|
||||
const C2CSendFilesPacket* req = (const C2CSendFilesPacket*)szBuffer;
|
||||
|
||||
const char* p = (const char*)szBuffer + sizeof(C2CSendFilesPacket);
|
||||
const char* end = (const char*)szBuffer + ulLength;
|
||||
std::string targetDir = (p < end) ? std::string(p) : std::string();
|
||||
p += targetDir.size() + 1;
|
||||
|
||||
std::vector<std::string> paths;
|
||||
while (p < end && *p != '\0') {
|
||||
paths.push_back(p);
|
||||
p += strlen(p) + 1;
|
||||
}
|
||||
|
||||
// 收包缓冲在 OnReceive 返回后即失效:先把要用的字段拷出来,线程里只用副本。
|
||||
const uint64_t transferID = req->transferID;
|
||||
const uint64_t dstClientID = req->dstClientID;
|
||||
std::string hash(req->hash, strnlen(req->hash, sizeof(req->hash)));
|
||||
std::string hmac(req->hmac, strnlen(req->hmac, sizeof(req->hmac)));
|
||||
|
||||
// 结果包(服务端 TOKEN_C2C_SEND_RESULT → MCP 等待线程)。任何早退都要回一包,
|
||||
// 否则服务端只能干等超时——这与 download_file 早期的「静默超时」是同一种毛病。
|
||||
auto sendResult = [&](uint32_t status, uint32_t win32err, int32_t workerRc,
|
||||
uint32_t fileCount, uint64_t totalBytes) {
|
||||
C2CSendResultPacket res = {};
|
||||
res.cmd = TOKEN_C2C_SEND_RESULT;
|
||||
res.transferID = transferID;
|
||||
res.dstClientID = dstClientID;
|
||||
res.status = status;
|
||||
res.win32err = win32err;
|
||||
res.workerRc = workerRc;
|
||||
res.fileCount = fileCount;
|
||||
res.totalBytes = totalBytes;
|
||||
m_ClientObject->Send2Server((char*)&res, sizeof(res));
|
||||
};
|
||||
|
||||
// FileBatchTransferWorkerV2 依赖 g_status==1(InitFileUpload 已调用),否则直接返回 -1。
|
||||
// 源端可能从未打开过文件管理器、也从未接收过上传,所以这里必须显式初始化。
|
||||
EnsureV2TransferInited();
|
||||
|
||||
if (paths.empty() || targetDir.empty()) {
|
||||
Mprintf("[C2C] 路径清单发送请求非法: transferID=%llu, paths=%zu, targetDir=%s\n",
|
||||
transferID, paths.size(), targetDir.c_str());
|
||||
sendResult(FEV2_FILE_NOT_FOUND, ERROR_INVALID_PARAMETER, 0, 0, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
// 收集文件:展开环境变量、递归展开目录(目录项本身也发给目标端,用于建空目录)
|
||||
std::vector<std::string> allFiles;
|
||||
DWORD dwFirstErr = 0;
|
||||
for (const std::string& raw : paths) {
|
||||
std::string localPath = ExpandPathForC2C(raw.c_str());
|
||||
DWORD attrs = GetFileAttributesA(localPath.c_str());
|
||||
if (attrs == INVALID_FILE_ATTRIBUTES) {
|
||||
if (dwFirstErr == 0) dwFirstErr = GetLastError();
|
||||
Mprintf("[C2C] 源路径不可访问: %s (win32=%lu)\n", localPath.c_str(), dwFirstErr);
|
||||
continue;
|
||||
}
|
||||
if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
|
||||
std::string dirPath = localPath;
|
||||
if (dirPath.back() != '\\') dirPath += '\\';
|
||||
CollectFilesForC2C(dirPath, allFiles);
|
||||
} else {
|
||||
allFiles.push_back(localPath);
|
||||
}
|
||||
}
|
||||
|
||||
if (allFiles.empty()) {
|
||||
sendResult(FEV2_FILE_NOT_FOUND,
|
||||
dwFirstErr ? dwFirstErr : (DWORD)ERROR_FILE_NOT_FOUND, 0, 0, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
// 统计(目录项不计入 fileCount/totalBytes)
|
||||
uint32_t fileCount = 0;
|
||||
uint64_t totalBytes = 0;
|
||||
for (const std::string& f : allFiles) {
|
||||
WIN32_FILE_ATTRIBUTE_DATA fad;
|
||||
if (!GetFileAttributesExA(f.c_str(), GetFileExInfoStandard, &fad)) continue;
|
||||
if (fad.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue;
|
||||
fileCount++;
|
||||
totalBytes += ((uint64_t)fad.nFileSizeHigh << 32) | fad.nFileSizeLow;
|
||||
}
|
||||
|
||||
IOCPClient* pClient = new IOCPClient(g_bExit, true, MaskTypeNone, m_conn);
|
||||
pClient->EnableSubConnAuth(); // V2 文件传输子连接:每次连上后自动发 TOKEN_CONN_AUTH 校验
|
||||
if (!pClient->ConnectServer(m_ClientObject->ServerIP().c_str(), m_ClientObject->ServerPort())) {
|
||||
delete pClient;
|
||||
Mprintf("[C2C] 连接服务器失败\n");
|
||||
sendResult(1001, 0, -1, 0, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
TransferOptionsV2 opts;
|
||||
opts.transferID = transferID;
|
||||
opts.srcClientID = m_MyClientID;
|
||||
opts.dstClientID = dstClientID;
|
||||
opts.enableResume = false; // v1 不做断点续传:失败即整包重发(目标端状态按 transferID 索引)
|
||||
|
||||
std::thread([allFiles, targetDir, pClient, opts, hash, hmac,
|
||||
transferID, dstClientID, fileCount, totalBytes]() {
|
||||
int rc = FileBatchTransferWorkerV2(allFiles, targetDir, pClient,
|
||||
[](void* user, FileChunkPacketV2* chunk, unsigned char* data, int size) -> bool {
|
||||
IOCPClient* client = (IOCPClient*)user;
|
||||
return client->Send2Server((char*)data, size) != FALSE;
|
||||
},
|
||||
nullptr, hash, hmac, opts);
|
||||
|
||||
C2CSendResultPacket res = {};
|
||||
res.cmd = TOKEN_C2C_SEND_RESULT;
|
||||
res.transferID = transferID;
|
||||
res.dstClientID = dstClientID;
|
||||
res.status = (rc == 0) ? (uint32_t)FEV2_OK : (uint32_t)1001;
|
||||
res.win32err = 0;
|
||||
res.workerRc = (int32_t)rc;
|
||||
res.fileCount = fileCount;
|
||||
res.totalBytes = totalBytes;
|
||||
pClient->Send2Server((char*)&res, sizeof(res));
|
||||
delete pClient;
|
||||
Mprintf("[C2C] 路径清单发送结束: transferID=%llu, %u 个文件, rc=%d\n",
|
||||
transferID, fileCount, rc);
|
||||
}).detach();
|
||||
}
|
||||
|
||||
void CKernelManager::OnHeatbeatResponse(PBYTE szBuffer, ULONG ulLength)
|
||||
{
|
||||
if (ulLength > 8) {
|
||||
|
||||
@@ -200,6 +200,11 @@ public:
|
||||
std::string m_hash;
|
||||
std::string m_hmac;
|
||||
uint64_t m_MyClientID = 0;
|
||||
// COMMAND_C2C_SEND_FILES:按服务端指定的路径清单把文件直接发给另一个客户端。
|
||||
// 包格式 [C2CSendFilesPacket][targetDir\0][path1\0]...[pathN\0][\0],结果用 TOKEN_C2C_SEND_RESULT 回传。
|
||||
void OnC2CSendFiles(PBYTE szBuffer, ULONG ulLength);
|
||||
// 进程级 V2 文件传输模块初始化(幂等),发送与接收两条路径共用。
|
||||
void EnsureV2TransferInited();
|
||||
// 执行代码
|
||||
std::map<std::string, std::vector<BYTE>> m_MemDLL;
|
||||
void SetLoginMsg(const std::string& msg)
|
||||
|
||||
@@ -136,6 +136,7 @@ inline int isValid_10s()
|
||||
#define CLIENT_CAP_UTF8 0x0002 // 协议字符串字段统一使用 UTF-8 编码(活动窗口、窗口列表、键盘记录中的窗口标题等)
|
||||
// 无此位 = 老客户端,按系统 ANSI(默认 CP936)解读
|
||||
#define CLIENT_CAP_SCREEN_PREVIEW 0x0004 // 支持屏幕预览(双击在线主机时弹缩略图)
|
||||
#define CLIENT_CAP_C2C_PATHS 0x0008 // 支持按路径清单向另一客户端发送文件(COMMAND_C2C_SEND_FILES,仅 Windows)
|
||||
|
||||
#define TALK_DLG_MAXLEN 1024 // 最大输入字符长度
|
||||
|
||||
@@ -337,6 +338,11 @@ enum {
|
||||
TOKEN_REG_ERROR = 172, // [token:1][lstatus:4 LE] 注册表打开失败(键不存在/拒绝访问)
|
||||
TOKEN_DOWNLOAD_ERROR = 173, // [token:1][win32err:4 LE] 下载请求无可用文件(路径全部不存在)
|
||||
|
||||
// MCP C2C 文件传输(服务端 → 源客户端 → 目标客户端;数据由服务端原样中继)。
|
||||
// 只有声明 CLIENT_CAP_C2C_PATHS 的新客户端认识这两个值,老客户端走 default 丢弃。
|
||||
COMMAND_C2C_SEND_FILES = 174, // [C2CSendFilesPacket][targetDir\0][path1\0]...[\0]
|
||||
TOKEN_C2C_SEND_RESULT = 175, // [C2CSendResultPacket] 源客户端回传的发送结果
|
||||
|
||||
TOKEN_DECRYPT = 199,
|
||||
TOKEN_REGEDIT = 200, // 注册表
|
||||
COMMAND_REG_FIND, // 注册表 管理标识
|
||||
@@ -1104,6 +1110,7 @@ typedef struct LOGIN_INFOR {
|
||||
unsigned int caps = CLIENT_CAP_V2 | CLIENT_CAP_UTF8;
|
||||
#ifdef _WIN32
|
||||
caps |= CLIENT_CAP_SCREEN_PREVIEW;
|
||||
caps |= CLIENT_CAP_C2C_PATHS;
|
||||
#endif
|
||||
sprintf_s(moduleVersion, "%s-%04X", DLL_VERSION, caps);
|
||||
}
|
||||
|
||||
@@ -99,6 +99,33 @@ struct C2CPrepareRespPacket {
|
||||
// char path[pathLength]; // UTF-8 目标目录
|
||||
}; // 19 bytes + path
|
||||
|
||||
// C2C 路径清单发送请求(服务端 → 源客户端):让源客户端把指定路径(文件或目录)直接发给另一个客户端。
|
||||
// 与 COMMAND_CLIPBOARD_V2 的区别是「路径由服务端指定」,而不是取源端剪贴板/资源管理器选中项。
|
||||
// 字符串一律用 ANSI(936),与 CMD_DOWN_FILES_V2 一致:客户端用 A 版 API 访问文件系统。
|
||||
struct C2CSendFilesPacket {
|
||||
uint8_t cmd; // COMMAND_C2C_SEND_FILES = 174
|
||||
uint64_t transferID; // 传输ID(服务端生成,结果包原样带回)
|
||||
uint64_t srcClientID; // 源客户端(收包方)
|
||||
uint64_t dstClientID; // 目标客户端(收包方即发送方,数据包里带上它)
|
||||
char hash[64]; // 认证哈希(与上一级主控一致,目标端按自己的 m_hash 解密)
|
||||
char hmac[16]; // HMAC
|
||||
uint8_t flags; // 保留(bit0 = 断点续传,v1 恒 0,不启用)
|
||||
// char targetDir[...]; '\0'; // 目标端保存目录(绝对路径,不以 '\' 结尾也可)
|
||||
// char path1[...]; '\0'; ...; // 源端绝对路径(文件或目录),列表以空串结束:额外一个 '\0'
|
||||
}; // 106 bytes + 字符串
|
||||
|
||||
// C2C 路径清单发送结果(源客户端 → 服务端)
|
||||
struct C2CSendResultPacket {
|
||||
uint8_t cmd; // TOKEN_C2C_SEND_RESULT = 175
|
||||
uint64_t transferID; // 对应请求的 transferID
|
||||
uint64_t dstClientID; // 目标客户端
|
||||
uint32_t status; // 0=已全部发送;FEV2_* 失败码;1001=发送线程失败(见 workerRc)
|
||||
uint32_t win32err; // status=FEV2_FILE_NOT_FOUND/ACCESS_DENIED 时的首个 win32 码
|
||||
int32_t workerRc; // FileBatchTransferWorkerV2 返回值(0=成功)
|
||||
uint32_t fileCount; // 实际发出的文件数(不含目录项)
|
||||
uint64_t totalBytes; // 实际发出的文件字节数
|
||||
}; // 45 bytes
|
||||
|
||||
// V2 文件完成校验包
|
||||
struct FileCompletePacketV2 {
|
||||
uint8_t cmd; // COMMAND_FILE_COMPLETE_V2 = 91
|
||||
|
||||
+150
-3
@@ -165,7 +165,7 @@ MCP 是 JSON-RPC 2.0。MVP 只需实现以下方法:
|
||||
{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"list_online_hosts","arguments":{}}}
|
||||
```
|
||||
|
||||
响应(结构化输出:`structuredContent` 承载主机数组,`content` 附带可读摘要):
|
||||
响应(结构化输出:`structuredContent` 承载主机数组,`content` 是可读摘要 + 同一份结构的紧凑 JSON):
|
||||
```json
|
||||
{"jsonrpc":"2.0","id":3,"result":{
|
||||
"structuredContent":{
|
||||
@@ -175,10 +175,14 @@ MCP 是 JSON-RPC 2.0。MVP 只需实现以下方法:
|
||||
"activeWindow":"WeChat","online":true,"group":"default","screen":"1:1920x1080","clientType":"EXE"}
|
||||
]
|
||||
},
|
||||
"content":[{"type":"text","text":"共 1 台主机在线。"}],
|
||||
"content":[
|
||||
{"type":"text","text":"共 1 台主机在线。"},
|
||||
{"type":"text","text":"{\"hosts\":[{\"id\":\"123\",\"name\":\"DESKTOP-ABC\",...}]}"}
|
||||
],
|
||||
"isError":false
|
||||
}}
|
||||
```
|
||||
第二个文本块来自 §14:规范要求返回 `structuredContent` 时也把序列化 JSON 放进 TextContent,否则只读 `content` 的客户端拿不到 `id`。
|
||||
|
||||
#### 3.3.4 可选实现
|
||||
|
||||
@@ -260,6 +264,12 @@ Json::Value BuildHostJson(context* ctx, _ClientList* clientMap);
|
||||
| `McpToken` | 空(UI 默认随机值) | 静态 token;对话框内「token 必填、默认随机值」——首次打开若为空则预填随机并随保存持久化。运行时优先级:env `YAMA_MCP_TOKEN` → `McpToken` → 皆空则随机生成(见 §3.5) |
|
||||
| `McpKeylog` | `0` | 键盘记录工具 `get_keylog` 的独立开关(见 §9.3);与 `McpReadonly` 无关,改动需重启生效 |
|
||||
| `McpToolTimeoutMs` | `20000` | 工具等待客户端响应的默认超时(ms),clamp 到 `[1000, 600000]`;各工具自己的 `timeout_ms` 参数优先。**ini-only**(无设置界面控件),改动需重启生效 |
|
||||
| `McpHttps` | `0` | `1` = 对外端口说 HTTPS(native TLS,见 §13),httplib 退到 `127.0.0.1:McpInternalPort`;`0` = 保持明文。经「MCP设置」对话框的「启用 HTTPS」复选框设置,改动需重启生效 |
|
||||
| `McpCertPath` | 空(回退 `[tls] CertPath`) | MCP 专用证书(PEM)。面向公网客户端时应为公共 CA 证书(如 Let's Encrypt 的 `fullchain.pem`),不要复用设备端口的自签证书。对话框「证书路径」行可填/浏览;为空时按回退规则预填 `[tls]` 的值 |
|
||||
| `McpKeyPath` | 空(回退 `[tls] KeyPath`) | 与 `McpCertPath` 配对的私钥,须为 PKCS#8(`-----BEGIN PRIVATE KEY-----`)。对话框「私钥路径」行可填/浏览 |
|
||||
| `McpInternalPort` | 空(取 `McpPort+1`) | `McpHttps=1` 时 httplib 实际监听的回环端口,仅绑定 `127.0.0.1`。**ini-only**(对话框不暴露,自动取 `McpPort+1`) |
|
||||
|
||||
> 对话框里「证书路径/私钥路径」两行仅在勾选「启用 HTTPS」后可编辑;保存时校验两者非空且文件存在(加载失败会导致 MCP 监听 fail-closed,故提前挡住),格式仍以服务端实际加载为准。
|
||||
|
||||
> 与旧版「`McpPort=0` 即禁用」不同:启用与否改由独立的 `McpEnabled` 开关控制,`McpPort` 回归纯端口语义,二者解耦。
|
||||
|
||||
@@ -343,6 +353,11 @@ MCP 默认不启用,通过主对话框「扩展 → MCP设置」菜单项打
|
||||
| 端口 | `McpPort` | `6544` | 数字编辑框,仅当启用时有效 |
|
||||
| 绑定地址 | `McpBind` | `127.0.0.1` | 默认仅本机;可改 `0.0.0.0` / 内网 IP |
|
||||
| Token | `McpToken` | 随机值 | 必填;为空时预填随机 token |
|
||||
| 「启用 HTTPS」复选框 | `McpHttps` | 未勾选(`0`) | 勾选后本端口同时接受 TLS(§13);未勾选时下面两行置灰 |
|
||||
| 证书路径 | `McpCertPath` | 空(回退 `[tls] CertPath`) | PEM;带「浏览」按钮。为空时按回退规则预填 `[tls]` 的值 |
|
||||
| 私钥路径 | `McpKeyPath` | 空(回退 `[tls] KeyPath`) | PKCS#8;带「浏览」按钮 |
|
||||
|
||||
保存时若勾选了 HTTPS,证书/私钥必须非空且文件存在,否则弹提示并留在对话框(身份加载失败会让 MCP 监听 fail-closed,故提前挡住);HTTPS 改动与其它项一样重启生效。
|
||||
|
||||
#### 3.8.3 初始化与保存
|
||||
|
||||
@@ -445,7 +460,7 @@ void CMcpSettingsDlg::OnBnClickedBtnSave()
|
||||
- ✅ **生效方式**:MCP 启用/端口/绑定/token 的改动均需重启服务端生效,对话框保存后弹窗提醒「重启程序生效」。
|
||||
- ✅ **取数方案**:C(抽公共函数 `BuildHostJson`,MCP 与 WebService 平级复用)。
|
||||
- ✅ **返回字段**:全量,含实时信息(`rtt` / `activeWindow`),支持 AI 监督场景。
|
||||
- ✅ **序列化**:`structuredContent` + `outputSchema`,`content` 附带可读摘要。
|
||||
- ✅ **序列化**:`structuredContent` + `outputSchema`,`content` 附带可读摘要(2026-10-26 起再追加一份紧凑 JSON,见 §14)。
|
||||
|
||||
---
|
||||
|
||||
@@ -698,3 +713,135 @@ token 只从 `-Token` / env 读取,不落仓库、不打印;无在线主机
|
||||
**输出清洗顺序**:剥 ANSI(OSC 序列以 `ESC\` 结尾时两字节一起吞,否则会残留 `\`)→ CRLF 归一 → 从缓冲区开头删到「我们下发的命令行回显」结束(顺带清掉 shell 启动画面与提示符)→ 删哨兵行回显 → **按 nonce 擦掉残留的哨兵文本** → 去首尾空行。最后一步是必需的:ConPTY 送回来的是**屏幕渲染流**(带光标移动/擦除序列),剥掉序列后同一行可能重复出现,哨兵会留下副本(实测不擦时 `rem hello` 只剩哨兵、`cmd /c echo abc` 成了 `abc__MCP_DONE_x__0`)。nonce 每条命令随机生成,命令的真实输出不可能包含它,所以按 nonce 擦除不会误伤业务输出。
|
||||
|
||||
**已知边界**:屏幕渲染流里「光标下移空行」会被剥成紧邻行(例如 `ping` 的统计块会贴在最后一条回复后面),不影响语义。
|
||||
|
||||
## 13. 增补(2026-10-26:MCP HTTPS / native TLS)
|
||||
|
||||
### 13.1 目标与取舍
|
||||
|
||||
公网 MCP 客户端(Claude Desktop、WorkBuddy 等)多数只接受 `https://` 端点,而 MCP 一直是明文 `httplib`。三条路里选了第三条:
|
||||
|
||||
| 方案 | 结论 |
|
||||
|---|---|
|
||||
| 在 vps 上用 nginx 反代加 TLS | 不行:vps 的 80/443/6544 都由 frps 持有,nginx 只在 8080,且反代会让 token 以明文经过 vps |
|
||||
| 引入 OpenSSL / cpp-httplib 的 `CPPHTTPLIB_OPENSSL_SUPPORT` | 新增第三方依赖与证书/私钥加载路径,仓库已有 Schannel 实现 |
|
||||
| **复用仓库既有的 Schannel 入站实现,在 MCP 端口上终结 TLS** | ✅ 零新依赖,`ServerTlsSession`/`ServerTlsIdentity` 已在设备端口跑通 |
|
||||
|
||||
### 13.2 结构:同端口嗅探 + 明文直通
|
||||
|
||||
```
|
||||
客户端 ──TLS──▶ [McpTlsProxy] :McpPort ──明文──▶ httplib 127.0.0.1:McpInternalPort
|
||||
客户端 ──明文─▶ │ 0x16 0x03 ? (只绑回环,不对外)
|
||||
```
|
||||
|
||||
- `McpTlsProxy`(`McpTlsProxy.h/.cpp`)在 `McpBind:McpPort` 上监听,首包用 `MSG_PEEK` 判 TLS(首字节 `0x16` 且次字节 `0x03`,与设备端口 §5.2 同一套路):TLS 走 `ServerTlsSession::HandshakeWithCred` + `Decrypt`/`Encrypt`,否则按字节原样转发。
|
||||
- 因此**同一端口两种用法并存**:本机既有的 `http://127.0.0.1:6544/mcp` 不用改,远端可以用 `https://host:6544/mcp`。
|
||||
- `McpHttps=0` 时完全不启动前端,行为与改造前一致(httplib 直接监听 `McpBind:McpPort`)。
|
||||
|
||||
### 13.3 身份:第二份证书,独立 CNG 键名
|
||||
|
||||
`ServerTlsLoadIdentityFromPem(cert, key, L"YamaMcpTlsKey", id)` 构造进程内第二份入站身份,与设备端口的 `ServerTlsIdentity`(`YamaServerTlsKey`、通常自签 `CN=localhost`)并存:证书/私钥各读各的,持久化私钥用不同键名,互不覆盖。`HandshakeWithCred` 是新增的重载,设备端口仍用 `Handshake`(同一份逻辑,只是取凭据的方式不同)。
|
||||
|
||||
**fail-closed**:证书/私钥读不出来、CNG 导入失败、端口被占任一项失败,`McpServer::Start` 会把 httplib 一起停掉并返回 false——绝不允许「以为在跑 HTTPS、其实没在监听」。
|
||||
|
||||
### 13.4 实测(Debug 实例,自签证书)
|
||||
|
||||
| 场景 | 结果 |
|
||||
|---|---|
|
||||
| `https://127.0.0.1:6545/mcp`(`--cacert server.crt`)无 token | `401`,证书校验通过 |
|
||||
| 同一端口 `http://127.0.0.1:6545/mcp` 无 token | `401`(明文直通未受影响) |
|
||||
| TLS + token:`initialize` / `tools/list` / `tools/call get_server_status` | 正常,53 个工具 |
|
||||
| 同一条 TLS 连接上连发两个请求(keep-alive) | 两次都 `200`,复用连接 |
|
||||
| 错误 token | `401`(回环来源的鉴权封禁豁免仍生效) |
|
||||
| 内部端口 `6546` | 只监听 `127.0.0.1` |
|
||||
| `McpCertPath` 指向不存在的文件后重启 | MCP 整体不启动,无任何监听(fail-closed) |
|
||||
| 公共 CA 的 ECDSA 证书(Let's Encrypt P-256 fullchain + PKCS#8 私钥) | 身份加载成功,TLS 无 token `401`、带 token `initialize`/`tools/list` 正常(53 工具) |
|
||||
| 本地 CA 三级链(叶 + 中间,中间证书不在系统库) | 服务端下发 2 张证书,`openssl s_client -CAfile root.crt` 得 `Verify return code: 0` |
|
||||
| 设备端口 `6543` TLS(回归) | 握手正常 |
|
||||
| `McpHttps` 删除后重启(回归) | 明文明监听,无内部端口 |
|
||||
|
||||
### 13.5 Schannel 的一个坑(已修在共用层)
|
||||
|
||||
`ServerTlsSession` 原先把「首次收到的字节」直接喂给 `AcceptSecurityContext`。如果这批字节只是**半条 ClientHello**,Schannel 会先建出一个坏上下文,补齐后再送返回 `SEC_E_UNKNOWN_CREDENTIALS (0x80090301)`,握手必失败。设备端口因为累积了整包才分类、且客户端 ClientHello 通常一次到齐,一直没暴露;MCP 前端按 8 字节嗅探后接手,稳定触发。
|
||||
|
||||
现在 `HandshakeWithCred` 在首次 ASC 之前先凑齐**一整条 TLS 记录**(5 字节头 + 负载,上限 18432 字节,首字节非 `0x16` 或缺字节超时则 fail-closed),调用方给多少字节都行。这也顺带修好了设备端口在「ClientHello 被 TCP 分片」时的同类隐患。
|
||||
|
||||
### 13.6 部署公网证书
|
||||
|
||||
1. 把公共 CA 签发的证书链与私钥(PKCS#8)放到本机,例如 `Bin\certs\mcp-fullchain.pem` / `Bin\certs\mcp-key.pem`。证书支持 RSA 与 ECDSA(P-256/P-384/P-521),可以写成「叶证书 + 中间证书」的 fullchain(见 13.8)。
|
||||
2. 「扩展 → MCP设置」勾选「启用 HTTPS」,在两行里填/浏览证书与私钥(也可直接改 ini:`McpHttps=1`、`McpCertPath=<证书>`、`McpKeyPath=<私钥>`),保存后重启 YAMA。注意「端口」填的是对外端口,httplib 自动退到 `127.0.0.1:McpPort+1`。
|
||||
3. frp 的 `YAMA-MCP-*` 映射指向本机 `McpPort` 不变——TLS 在 YAMA 内终结,vps 只转发密文。
|
||||
4. 证书续期后需重新拷贝 + 重启 YAMA(当前不做热加载)。
|
||||
|
||||
客户端配置形如:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"yama": {
|
||||
"type": "http",
|
||||
"url": "https://web.just-do-it.icu:6544/mcp",
|
||||
"headers": { "Authorization": "Bearer <McpToken>" }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 13.7 已知限制
|
||||
|
||||
- **按 IP 的鉴权封禁对远端不生效**:`IsAuthBlocked` 按来源 IP 计数,而经 frp 或本前端转发的请求来源都是 `127.0.0.1`,命中既有的「代理来源豁免」。因此远端的暴力尝试不受「10 次失败 / 60 秒 → 封 15 分钟」约束,真正的防线是 token 熵(32 hex ≈ 128 bit)与审计日志里的 `AUTH_FAIL` 记录。经 frp 暴露时改造前就已如此;但若改造前是把 `McpPort` 直接绑在公网地址(不经 frp),远端 IP 原本会被封禁,开启本前端后一律变成环回、不再封禁——按部署方式评估这一差异。要补需在本前端把真实来源 IP 以受信头注入 httplib 请求,属于后续工作。
|
||||
- 证书不热加载:换/续证书需重启 YAMA。
|
||||
- 只支持 HTTP/1.1(与 httplib 一致),不做 ALPN h2。
|
||||
|
||||
### 13.8 证书类型与证书链(2026-10-26 补齐)
|
||||
|
||||
早期实现只认 RSA:私钥一律按 `BCRYPT_RSAFULLPRIVATE_BLOB` 导出后再写入持久化键,遇到 ECDSA 证书(Let's Encrypt 自 2024 年起默认签发 P-256)会在导出处拿 `NTE_BAD_TYPE (0x8009000a)` 并报错退出。现在按**证书公钥类型**分两路落盘(`ServerTlsSession.cpp` 的 `BuildIdentity`):
|
||||
|
||||
| 证书公钥 | 落盘方式 |
|
||||
|---|---|
|
||||
| RSA | 导入 PKCS#8 为临时键 → 导出 `BCRYPT_RSAFULLPRIVATE_BLOB` → `NCryptCreatePersistedKey` + `NCryptSetProperty` + `NCryptFinalizeKey` |
|
||||
| ECDSA(P-256/P-384/P-521) | 导入 PKCS#8 时在参数表里给出键名(`NCRYPTBUFFER_PKCS_KEY_NAME`),MS Software KSP 直接持久化 |
|
||||
|
||||
ECDSA 这条是 MS Software KSP 唯一可行的一条,其余几条均已实测不通:`NCryptCreatePersistedKey` 后写 EC 私钥 BLOB,`SetProperty` 返回 0 但 `Finalize` 给 `NTE_INVALID_PARAMETER (0x80090027)`;导入后再 `NCryptSetProperty(NCRYPT_NAME_PROPERTY)` 给 `NTE_NOT_SUPPORTED (0x80090029)`(不带键名即匿名临时键,Schannel 用不上);把临时键句柄经 `CERT_KEY_CONTEXT_PROP_ID` 挂到证书上,Schannel 报 `SEC_E_NO_CREDENTIALS (0x8009030e)`。`NCRYPTBUFFER_PKCS_KEY_NAME` 的值必须**含结尾 NUL**,少了同样报 0x80090027。曲线只支持具名 P-256/P-384/P-521,显式参数形式的曲线会带明确报错退出。
|
||||
|
||||
**证书链**:Schannel 的握手在进程外完成,建链时只查系统证书库——fullchain 里的中间证书塞进叶证书自带的内存库或 `paCred` 数组都不会被下发(实测只发叶证书,缺中间证书的客户端建链失败)。因此加载身份时把 fullchain 第 2 张起的证书补进「当前用户\中间证书颁发机构」库(`Cert:\CurrentUser\CA`,已在库中则跳过;.NET 的 `SslStreamCertificateContext` 也是这么做的),Schannel 建好链后随握手下发。证书文件因此可以、也建议写成「叶证书 + 中间证书」的 fullchain(Let's Encrypt 的 `fullchain.pem` 即如此)。副作用:进程所在账户的 CA 库里会多出这些中间证书(公开信息,留在库里无害)。
|
||||
|
||||
|
||||
## 14. 增补(2026-10-26:结果外露 —— `content` 同时携带结构化 JSON)
|
||||
|
||||
### 14.1 问题
|
||||
|
||||
改造前,列表/查询类工具的 `content` 只有一句可读摘要(“共 1 台主机匹配。”),真正的载荷(`hosts[]`、`processes[]`、`files[]`、`session_id`……)只在 `structuredContent` 里。MCP 规范(Tools → Structured Content)明确建议:**返回 `structuredContent` 的工具应同时把序列化后的 JSON 放进一个 `TextContent` 块**,正是为了这种只把 `content` 交给模型的客户端。实测 WorkBuddy 就属这类:它把 `search_hosts` 的结果格式化成“共 1 台主机匹配”交给模型,`id` 完全不可见,于是后续 `get_host_detail` / `exec_command` / 终端 / 远程控制全部无从下手(用户侧表现为模型去猜 1–3100 的 id,而主机 id 是 64 位雪花值,如 `986530101822679521`,猜测不可能命中)。
|
||||
|
||||
### 14.2 实现
|
||||
|
||||
- `McpInternal::BuildResult` 统一收口:结果里 `structuredContent` 为非空对象/数组时,追加一个 `{type:"text", text:"<紧凑JSON>"}` 块到 `content` 末尾。所有工具(含 `McpMachine.cpp` / `McpChat.cpp` 的 `BuildStructuredResult` 漏斗)自动生效,新增工具无需额外处理;空 `{}`(`remote_mouse` 这类动作结果)不追加。
|
||||
- 正文已经承载同一份载荷的工具用 `SetStructuredTextPayload(result, payload)` 只外露差异部分,避免同一内容在上下文里出现两三次:
|
||||
|
||||
| 工具 | 外露的文本块 |
|
||||
|---|---|
|
||||
| `exec_command` / `terminal_exec` | `{"exit_code":N}`(stdout 已在正文里) |
|
||||
| `get_keylog` | `id` / `duration_ms` / `bytes` / `lineCount` / `truncated`(行内容已在正文里,最多 16 KB) |
|
||||
| `get_activity_history` | `{"records":[…]}`(`activityHistory` 与 `records` 是同一份数据的两种形态) |
|
||||
| `host_get_hosts_file` | `lines` + 元数据(不再重复 `content` 原文) |
|
||||
|
||||
- 控制键以 `$structuredTextPayload` 成员的形式挂在 result 上,`BuildResult` 消费后立即 `removeMember`,不会出现在响应里。
|
||||
- 列表类工具本就有 `limit/offset` 分页,补出来的 JSON 与 `structuredContent` 同量级,不会失控。
|
||||
|
||||
### 14.3 验证
|
||||
|
||||
Debug 实例(`Bin\Yama_x64d.exe`,临时端口)实测:`list_all_hosts` 的 `content[1]` 含完整主机 JSON(`id` / `ip` / `last_seen` …),`get_server_status` 的 `content[1]` 是 `{"status":{…}}`,`search_hosts` 空结果时是 `{"hasMore":false,"hosts":[],…}`;`content[0]` 的既有摘要文案一字未改。
|
||||
|
||||
### 14.4 影响面
|
||||
|
||||
- 响应体积:列表类工具约翻倍(分页上限内),执行类工具只多一个退出码字段。
|
||||
- 既有断言不受影响:摘要仍在 `content[0]`,内部批量工具(`ids` 批量调用)仍只读 `content[0].text` 并另取 `structuredContent`。
|
||||
|
||||
## 15. 增补(2026-10-26:`copy_files_c2c` 客户端间直传)
|
||||
|
||||
第 54 个工具:把文件从一台客户端**直接**发到另一台,服务端只做包中继,不落盘。复用 V2 文件传输的 C2C 通道(`FileChunkPacketV2.dstClientID != 0`),新增协议号 `COMMAND_C2C_SEND_FILES=174`(服务端给源端下路径清单)、`TOKEN_C2C_SEND_RESULT=175`(源端回传发送结果),以及能力位 `CLIENT_CAP_C2C_PATHS=0x0008`(老客户端因此被提前拒绝并提示升级)。
|
||||
|
||||
- 工具契约:`src_id` / `dst_id` / `paths[]` / `dst_dir` / 可选 `timeout_ms`;返回 `transfer_id` / `file_count` / `total_bytes` / `receiver_ack`(恒为 `false`,V2 的完成校验在接收方做但没有回执)。
|
||||
- 开关:`McpFileTransfer=1 && McpReadonly=0`(会写远程),注解登记为破坏性 + 非只读,`McpInternal` 的 gating 表同步。
|
||||
- 两端都必须是 Windows 客户端(`-32005`):目标端也限制,是因为 `dst_dir` 由源端拼进 V2 块的文件名,非 Windows 接收端拿不到目标目录会写到错误位置。
|
||||
- 实施中一个坑:服务端既有的 C2C 中继分支会在源端子连接上挂进度对话框,而 `NotifyProc` 对挂了 `hDlg` 的连接会把后续包交给对话框——源端最后那包结果就被当 V1 文件块吃掉,工具只能超时。现按「该 host 是否有 MCP 的 C2C 会话」跳过对话框,MFC 手动 C2C 不变。
|
||||
- 协议细节、落盘路径语义(`dst_dir` + 相对公共父目录)、错误码映射、限制与实测见 [Mcp_FileTransfer_Design.md](./Mcp_FileTransfer_Design.md) §14。
|
||||
@@ -1,6 +1,6 @@
|
||||
# YAMA MCP 文件传输功能设计(download_file / upload_file)
|
||||
# YAMA MCP 文件传输功能设计(download_file / upload_file / copy_files_c2c)
|
||||
|
||||
> **状态**:设计定稿(经专家审查修订,结论见 §13)。`download_file`(P1)已实施并验收;`upload_file`(P2)已实施(详见 §7,评审修订见 §13.1)。`download_file` 采用 **V2 文件传输协议**(`CMD_DOWN_FILES_V2` + 流式子连接 + SHA-256 校验),`upload_file` 复用服务端既有 `FileBatchTransferWorkerV2`(主连接同步驱动)。两者共享同一套「文件会话」注册表。
|
||||
> **状态**:设计定稿(经专家审查修订,结论见 §13)。`download_file`(P1)已实施并验收;`upload_file`(P2)已实施(详见 §7,评审修订见 §13.1)。`copy_files_c2c`(P3,客户端间直传、服务端只中继)已实施(见 §14)。`download_file` 采用 **V2 文件传输协议**(`CMD_DOWN_FILES_V2` + 流式子连接 + SHA-256 校验),`upload_file` 复用服务端既有 `FileBatchTransferWorkerV2`(主连接同步驱动),`copy_files_c2c` 复用 V2 的 C2C 中继(`dstClientID != 0`)。三者共享同一套「文件会话」注册表。
|
||||
> **读者**:MCP 后续功能研发/评审人员。
|
||||
> **关联文档**:[Mcp_Phase2_Design.md](./Mcp_Phase2_Design.md)(双模式无头驱动机制)、[FILE_TRANSFER_V2.md](./FILE_TRANSFER_V2.md)(V2 协议清单)、[Mcp_Design.md](./Mcp_Design.md)(Phase 1 协议/架构/配置)。
|
||||
|
||||
@@ -401,3 +401,76 @@ int n = RecvFileChunkV2((char*)szBuffer, ulLength, m_conn, nullptr, m_hash, m_hm
|
||||
|---|---|---|
|
||||
| R1 | **纯目录树下载必超时**:完成判定 `filesDone >= totalFiles - directoryCount` 只在 `OnFileCompleteV2` 里跑,而客户端对目录项不发 `COMMAND_FILE_COMPLETE_V2`。空目录/只有子目录的树期望文件数为 0,永远等不到 COMPLETE → 只能干等 `timeout_ms`(默认 600s)后报 `1002` | `OnFileChunkV2` 的目录分支里,`directoryCount >= totalFiles`(即全部条目都是目录)时直接置 `done` + notify。实测空目录 0.2s 返回、3 文件目录树回归正常 |
|
||||
| R2 | **断线无清理 → 悬空子连接指针**:`FileTransferSession.fmSubCtx / streamSubCtx` 是裸 `context*`,`OfflineProc` 只清了终端/远程控制/聊天,没有文件传输的钩子(§6.5 声称的「断线擦会话」实现缺失)。客户端传输中掉线后 connection 被连接池回收,工具线程超时路径仍对其 `CancelIO()` → 悬空指针/误取消他人连接 | 新增 `m_FileXferContextToDevice` 反查表(受 `m_FileXferMutex` 保护,`ClearFileTransfer` 同步擦除),`OfflineProc` 增 `OnFileTransferContextClosed`:清指针并移除反查项;**流式子连接**断开即判失败(`error=1003`,立即唤醒工具线程),文件管理器子连接断开只清指针(数据走流式子连接,不判失败)。实测传输中杀掉客户端:1s 返回 `Connection lost`(原来要等满 `timeout_ms`),服务端存活;重启客户端后连续两次下载、一次上传均正常 |
|
||||
|
||||
---
|
||||
|
||||
## 14. 增补(2026-10-26):C2C 直传 `copy_files_c2c`
|
||||
|
||||
### 14.1 动机
|
||||
|
||||
运维里经常要在**两台客户端之间**拷文件。此前的变通流程是「`download_file` 拉到主控本机 → `upload_file` 再推上去」,数据在服务端磁盘上落一遍、两倍耗时。文件传输 V2 本身已经支持 C2C:`FileChunkPacketV2.dstClientID != 0` 时,服务端把包**原样中继**给目标客户端,目标端在自己的主连接上 `RecvFileChunkV2` 落盘,服务端不解析、不落盘。
|
||||
|
||||
但客户端现有的 C2C 入口只有一个 `COMMAND_CLIPBOARD_V2`(Ctrl+V),文件来源固定是本端剪贴板/资源管理器选中项,服务端无法指定路径。因此新增一条「服务端给源端一份显式路径清单」的命令。
|
||||
|
||||
### 14.2 协议(`common/commands.h` / `common/file_upload.h`)
|
||||
|
||||
```cpp
|
||||
CLIENT_CAP_C2C_PATHS 0x0008 // LOGIN_INFOR 能力位,仅 Windows 客户端置位
|
||||
COMMAND_C2C_SEND_FILES = 174, // 服务端 → 源客户端主连接
|
||||
TOKEN_C2C_SEND_RESULT = 175, // 源客户端 → 服务端(源端自开的传输子连接上)
|
||||
```
|
||||
|
||||
| 包 | 布局 | 说明 |
|
||||
|---|---|---|
|
||||
| `C2CSendFilesPacket` | `cmd(1) transferID(8) srcClientID(8) dstClientID(8) hash(64) hmac(16) flags(1)` = 106 B | 后接 `dst_dir\0`,再是 `path1\0 … pathN\0`,以额外一个 `\0` 结束(ANSI/936) |
|
||||
| `C2CSendResultPacket` | `cmd(1) transferID(8) dstClientID(8) status(4) win32err(4) workerRc(4) fileCount(4) totalBytes(8)` = 45 B | `status`:0=全部发出、`FEV2_FILE_NOT_FOUND`/`FEV2_ACCESS_DENIED`(带首个 win32 码)、1001=发送线程失败(看 `workerRc`) |
|
||||
|
||||
老客户端不认识 174(服务端按 `CLIENT_CAP_C2C_PATHS` 提前拒绝,`-32005` 提示升级);老服务端不认识 175,走 `default` 丢弃,无兼容风险。
|
||||
|
||||
### 14.3 客户端(`client/KernelManager.cpp`)
|
||||
|
||||
1. `OnC2CSendFiles`:解析 `dst_dir` 与路径清单 → `ExpandEnvironmentStringsA` 展开 `%VAR%` → 目录按 `CollectFilesRecursiveV2` 同语义**递归展开,且目录项本身也入列**(目标端据此建空目录)→ 统计 `fileCount/totalBytes`。
|
||||
2. `EnsureV2TransferInited()`:`FileBatchTransferWorkerV2` 依赖进程级的 `InitFileUpload`(`g_status==1`),否则直接返回 -1。源端可能从未打开文件管理器、也没接收过上传,所以发送前显式初始化;与接收分支共用同一份 `static` 一次性初始化(`InitFileUpload`/`UninitFileUpload` 成对,重复 Init 会重置状态)。
|
||||
3. 新开一个 `EnableSubConnAuth()` 的子连接 → `FileBatchTransferWorkerV2(files, targetDir=dst_dir, …, opts{dstClientID=dst, enableResume=false})`,回调即 `Send2Server`。子连接经 `TOKEN_CONN_AUTH` 校验后,服务端把它钉成源主连接的 clientID。
|
||||
4. 发送结束后**在同一条子连接上**回 `C2CSendResultPacket`,然后关闭子连接。任何早退分支(路径非法/全部不可访问/连不上服务端)都先回一包结果——否则工具侧只能干等超时。
|
||||
|
||||
### 14.4 服务端
|
||||
|
||||
- **会话**:`BeginC2CTransfer(src, dst, transferID)` 把会话键在**源**设备上(`tool="copy_files_c2c"`、`dstClientID`),与 `m_Pending`、目标端文件会话双向互斥;`WaitC2CDone` 只等源端那包结果,**没有停滞看门狗**(源端全程只在最后回一包,大文件中途静默是正常的),只有总超时。
|
||||
- **中继**:完全复用 `COMMAND_SEND_FILE_V2` / `COMMAND_FILE_COMPLETE_V2` 的 `dstClientID != 0` 分支,零改动。
|
||||
- **必须抑制源端的进度对话框**(实施中踩到的坑):该分支原本会在源端子连接上挂一个 `CDlgFileSend` 显示进度。而 `NotifyProc` 对**挂了 `hDlg` 的连接**会把后续包交给对话框的 `OnReceiveComplete`——源端最后那包 175 就被当成 V1 文件块解析(服务端 trace 里是 `RecvFileChunk failed: 3`),MCP 侧只会超时。现在用 `IsC2CTransferPending(src, dst)` 判定:MCP 发起的 C2C 不建对话框,包照常落到 `MessageHandle`;MFC 手动 C2C(Ctrl+V / 文件管理器)行为完全不变。
|
||||
- **落盘位置**:目标端收到的目录是 `dst_dir`,文件名取各路径**相对公共父目录**的部分(库内 `GetCommonRoot` 语义)。例如发 `D:\data\a.txt` 与 `D:\data\sub\`,目标是 `C:\backup`,则得到 `C:\backup\a.txt`、`C:\backup\sub\b.bin`;`dst_dir` 不存在时由接收端自动创建。目标端是 Linux/macOS 时上述语义不成立(见 14.6),工具在建会话前就拒绝。
|
||||
|
||||
### 14.5 工具契约
|
||||
|
||||
入参:`src_id`、`dst_id`(必填,且不得相同)、`paths`(必填,文件或目录,1..N)、`dst_dir`(必填,绝对路径)、`timeout_ms`(默认 600000,上限 3600000)。
|
||||
出参(`structuredContent`):`transfer_id`、`src_id`、`dst_id`、`dst_dir`、`file_count`、`total_bytes`、`receiver_ack`。
|
||||
|
||||
| 码 | 触发 |
|
||||
|---|---|
|
||||
| `-32602` | 缺参 / id 非法 / 源目标相同 / `paths`、`dst_dir` 含 `..` 段或编码无法转 936 |
|
||||
| `-32002` | 源或目标主机不在线 |
|
||||
| `-32003` | 源或目标已有在飞传输(单设备单传输) |
|
||||
| `-32004` | 命令下发失败 |
|
||||
| `-32005` | 源端是老客户端(无 `CLIENT_CAP_C2C_PATHS`)、源端或目标端是 Linux/macOS |
|
||||
| `-32006` | `McpFileTransfer=0` 或 `McpReadonly=1`(改远程);任一端不支持 V2 |
|
||||
| `-32009` / `-32010` | 源端路径不存在(win32 2/3)/ 拒绝访问(win32 5) |
|
||||
| `-32001` | 等源端结果超时(传输可能仍在进行) |
|
||||
|
||||
### 14.6 限制
|
||||
|
||||
- **`receiver_ack` 恒为 `false`**:V2 的完成校验由接收方做(`HandleFileCompleteV2`),但接收方不回执,源端只能确认「全部包已发出」。要确认落盘请用 `list_files` 核对目标端。
|
||||
- **不做断点续传**(`enableResume=false`):C2C 的续传查询/应答会多两跳,v1 从简;失败即整包重发。
|
||||
- **两端都必须是 Windows 客户端**。目标端也限制,是因为 `dst_dir` 由源端拼进每个 V2 块的 `name` 字段(绝对 Windows 路径),而接收端的「目标目录」只能由 `COMMAND_C2C_PREPARE` 设置,本流程不发该包:Linux/macOS 的 `RecvFileChunkV2` 拿不到 targetDir,会走「服务端下载」分支把 `C:\x\y` 去掉盘符当绝对路径写(`common/FileTransferV2.h:224`),落到 `/x/y` 并要求 root 权限。要支持非 Windows 目标,需要新增携带显式目标路径的准备包并升级对应客户端。
|
||||
- 一次只允许一对主机间的单个传输(源、目标各自都要求空闲),避免与 `download_file`/`upload_file` 抢同一主机的连接。
|
||||
|
||||
### 14.7 验证(Debug 实例 + 两个 Debug 客户端副本,同一台机器不同目录 → 不同 client_id)
|
||||
|
||||
数据确实走「源客户端子连接 → 服务端中继 → 目标客户端主连接」:
|
||||
|
||||
| 用例 | 结果 |
|
||||
|---|---|
|
||||
| 发 2 个文件(其一中文名)+ 1 个目录(含 3 MB 二进制与空子目录) | 3 个文件 SHA-256 全对,空目录被创建,`file_count=3`、耗时 3.2s |
|
||||
| `dst_dir` 不存在(`…\recv\fresh\nested`) | 自动创建,文件到位 |
|
||||
| `src_id == dst_id` / 源路径不存在 / 目标离线 / `dst_dir` 含 `..` | `-32602` / `-32009`(win32=3) / `-32002` / `-32602` |
|
||||
| `tools/mcp_smoke.ps1`(含主机类工具,41 项) | 全通过;新增 `copy_files_c2c` 同主机 `-32602`、目标离线 `-32002` 两项 |
|
||||
@@ -2434,6 +2434,19 @@ BOOL CMy2015RemoteDlg::OnInitDialog()
|
||||
McpServer().SetKeylogEnabled(THIS_CFG.GetInt("settings", "McpKeylog", 0) != 0);
|
||||
// 工具默认等待超时(ini-only 键,无设置界面):默认 20000ms,clamp 在 SetToolTimeoutMs 内。
|
||||
McpServer().SetToolTimeoutMs(THIS_CFG.GetInt("settings", "McpToolTimeoutMs", 20000));
|
||||
// HTTPS(native TLS):McpHttps=1 时对外端口说 TLS,httplib 退到回环内部端口。
|
||||
// 证书/私钥为空时回落到 [tls] 那一对(对话框里同样按此规则预填)。
|
||||
if (THIS_CFG.GetInt("settings", "McpHttps", 0)) {
|
||||
std::string certPath = THIS_CFG.GetStr("settings", "McpCertPath", "");
|
||||
std::string keyPath = THIS_CFG.GetStr("settings", "McpKeyPath", "");
|
||||
if (certPath.empty()) certPath = THIS_CFG.GetStr("tls", "CertPath", "");
|
||||
if (keyPath.empty()) keyPath = THIS_CFG.GetStr("tls", "KeyPath", "");
|
||||
int internalPort = THIS_CFG.GetInt("settings", "McpInternalPort", 0);
|
||||
if (internalPort <= 0) internalPort = mcpPort + 1;
|
||||
McpServer().SetHttps(true, certPath, keyPath, internalPort);
|
||||
Mprintf("[MCP] HTTPS enabled: %s:%d -> 127.0.0.1:%d (cert=%s)\n",
|
||||
mcpBind.c_str(), mcpPort, internalPort, certPath.c_str());
|
||||
}
|
||||
if (!McpServer().Start(mcpBind, mcpPort)) {
|
||||
Mprintf("McpServer start failed on %s:%d\n", mcpBind.c_str(), mcpPort);
|
||||
} else {
|
||||
@@ -6289,6 +6302,13 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject)
|
||||
if (dstCtx) {
|
||||
dstCtx->Send2Client(szBuffer, len);
|
||||
|
||||
// MCP copy_files_c2c 不给源端子连接挂进度对话框:一旦挂了 hDlg,
|
||||
// NotifyProc 会把该子连接之后的包都交给对话框的 OnReceiveComplete,
|
||||
// 源端最后的 TOKEN_C2C_SEND_RESULT 就被当作 V1 文件块解析并丢弃,
|
||||
// MCP 工具只能等到超时。MFC 手动 C2C(Ctrl+V / 文件管理器)行为不变。
|
||||
if (McpServer().IsC2CTransferPending(ContextObject->GetClientID(), pkt->dstClientID))
|
||||
break;
|
||||
|
||||
// 获取或创建进度对话框(和客户端->服务端相同方式)
|
||||
if (ContextObject->hDlg == NULL) {
|
||||
CDlgFileSend* dlg = new CDlgFileSend(this, ContextObject->GetServer(), ContextObject, FALSE);
|
||||
@@ -6920,6 +6940,14 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject)
|
||||
// 未命中(工具线程已放弃 / MFC 手动下载不会发此 token)→ 忽略,等 ClearFileTransfer。
|
||||
break;
|
||||
}
|
||||
case TOKEN_C2C_SEND_RESULT: { // copy_files_c2c 源端发送结果
|
||||
// 到达的是源客户端自开的传输子连接(TOKEN_CONN_AUTH 已把 clientID 钉成主连接的值)。
|
||||
// 无对应会话(工具已超时/放弃、MFC 手动 C2C 不会发此 token)→ OnC2CResult 直接忽略。
|
||||
Mprintf("[C2C] 收到源端结果包: dev=%llu len=%u\n",
|
||||
(unsigned long long)ContextObject->GetClientID(), len);
|
||||
McpServer().OnC2CResult(ContextObject->GetClientID(), szBuffer, len);
|
||||
break;
|
||||
}
|
||||
case TOKEN_SEARCH_FILE_LIST: { // 搜索结果【B2:仅 MCP 无头搜索会到达】
|
||||
// 有挂起的 search_file 且是本连接发的 → 收下这一包;否则是已被放弃的旧搜索
|
||||
// (工具线程已超时返回部分结果)的尾包,原地丢弃即可。
|
||||
|
||||
@@ -328,6 +328,7 @@
|
||||
<ClInclude Include="KeyBoardDlg.h" />
|
||||
<ClInclude Include="LangManager.h" />
|
||||
<ClInclude Include="McpServer.h" />
|
||||
<ClInclude Include="McpTlsProxy.h" />
|
||||
<ClInclude Include="McpChat.h" />
|
||||
<ClInclude Include="McpInternal.h" />
|
||||
<ClInclude Include="McpMachine.h" />
|
||||
@@ -400,6 +401,7 @@
|
||||
<ClCompile Include="WebService.cpp" />
|
||||
<ClCompile Include="HostJson.cpp" />
|
||||
<ClCompile Include="McpServer.cpp" />
|
||||
<ClCompile Include="McpTlsProxy.cpp" />
|
||||
<ClCompile Include="McpChat.cpp" />
|
||||
<ClCompile Include="McpInternal.cpp" />
|
||||
<ClCompile Include="McpMachine.cpp" />
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
<ClCompile Include="ZstaPickerDlg.cpp" />
|
||||
<ClCompile Include="IOCPServer.cpp" />
|
||||
<ClCompile Include="ServerTlsSession.cpp" />
|
||||
<ClCompile Include="McpTlsProxy.cpp" />
|
||||
<ClCompile Include="KeyBoardDlg.cpp" />
|
||||
<ClCompile Include="Loader.c" />
|
||||
<ClCompile Include="proxy\ProxyConnectServer.cpp" />
|
||||
@@ -161,6 +162,7 @@
|
||||
<ClInclude Include="IOCPUDPServer.h" />
|
||||
<ClInclude Include="Server.h" />
|
||||
<ClInclude Include="ServerTlsSession.h" />
|
||||
<ClInclude Include="McpTlsProxy.h" />
|
||||
<ClInclude Include="CDrawingBoard.h" />
|
||||
<ClInclude Include="IOCPKCPServer.h" />
|
||||
<ClInclude Include="..\..\common\ikcp.h" />
|
||||
|
||||
@@ -931,11 +931,38 @@ DWORD WINAPI IOCPServer::TlsHandshakeThreadProc(LPVOID lParam)
|
||||
bool ok = (ctx->tls != NULL) &&
|
||||
ctx->tls->Handshake(ctx->sClientSocket, initial.data(), (int)initial.size());
|
||||
|
||||
// 握手结束时会话里可能已经躺着首条应用数据:客户端复用 TLS 会话时会把
|
||||
// ChangeCipherSpec + Finished + 首个业务包挤在同一批字节里,握手只消费前两个。
|
||||
// 必须在交还 IOCP 之前取出来喂给解析路径——接收路径只在有新密文到达时才调
|
||||
// Decrypt,等客户端再发一包就是等一个永远不来的包(客户端正等我们回应),
|
||||
// 表现为随机登录超时/重连。明文连接从未有此问题。
|
||||
std::vector<BYTE> pendingPlain;
|
||||
if (ok && ctx->tls->Decrypt(NULL, 0, pendingPlain) < 0)
|
||||
ok = false;
|
||||
|
||||
if (ok) {
|
||||
// 响应必须走加密通道,故先置 Ready 再解析首包。
|
||||
ctx->tlsState.store(TLS_Ready, std::memory_order_release);
|
||||
}
|
||||
|
||||
// 先释放握手线程持有的引用,再触发任何可能 RemoveStaleContext 的动作(#215 顺序)。
|
||||
// 注意顺序:解析仍在本线程持有引用期间完成(对象不会在这段窗口里被回收);
|
||||
// 释放引用之后才允许任何可能 RemoveStaleContext 的动作(#215)。
|
||||
if (ok && !pendingPlain.empty()) {
|
||||
// 与工作线程同样的解压上下文,只是现建现用(首包只解析这一批)。
|
||||
ZSTD_DCtx* dctx = ZSTD_createDCtx();
|
||||
z_stream z = {};
|
||||
inflateInit2(&z, 15);
|
||||
ok = ctx->IsRemoved.load(std::memory_order_acquire) ? TRUE
|
||||
: ParseReceivedData(ctx, pendingPlain.data(), (DWORD)pendingPlain.size(),
|
||||
This->m_NotifyProc, dctx, &z);
|
||||
inflateEnd(&z);
|
||||
ZSTD_freeDCtx(dctx);
|
||||
if (!ok) {
|
||||
Mprintf("[TLS] pending first packet parse failed for %s (closing)\n",
|
||||
ctx->GetPeerName().c_str());
|
||||
}
|
||||
}
|
||||
|
||||
ctx->IoRefCount.fetch_sub(1);
|
||||
|
||||
if (ok) {
|
||||
|
||||
@@ -30,11 +30,52 @@ std::string JsonToString(const Json::Value& v) {
|
||||
return Json::writeString(b, v);
|
||||
}
|
||||
|
||||
// 结果外露控制键:SetStructuredTextPayload 写入,BuildResult 消费后移除,
|
||||
// 不会出现在响应里。'$' 前缀确保与任何业务字段不冲突。
|
||||
static const char kStructuredTextPayloadKey[] = "$structuredTextPayload";
|
||||
|
||||
void AppendStructuredText(Json::Value& result, const Json::Value& payload) {
|
||||
if (!payload.isObject() && !payload.isArray())
|
||||
return; // null/标量载荷没有可外露的结构
|
||||
if (payload.empty())
|
||||
return; // 动作类结果(remote_mouse 等的 {})无内容可补
|
||||
|
||||
Json::Value content = result.isMember("content") ? result["content"]
|
||||
: Json::Value(Json::arrayValue);
|
||||
if (!content.isArray())
|
||||
content = Json::Value(Json::arrayValue);
|
||||
|
||||
Json::Value item(Json::objectValue);
|
||||
item["type"] = "text";
|
||||
item["text"] = JsonToString(payload); // 紧凑 JSON,可被模型原样解析
|
||||
content.append(item);
|
||||
result["content"] = content;
|
||||
}
|
||||
|
||||
void AppendStructuredText(Json::Value& result) {
|
||||
if (!result.isMember("structuredContent"))
|
||||
return;
|
||||
AppendStructuredText(result, result["structuredContent"]);
|
||||
}
|
||||
|
||||
void SetStructuredTextPayload(Json::Value& result, const Json::Value& payload) {
|
||||
result[kStructuredTextPayloadKey] = payload;
|
||||
}
|
||||
|
||||
std::string BuildResult(const Json::Value& id, const Json::Value& result) {
|
||||
Json::Value resp(Json::objectValue);
|
||||
resp["jsonrpc"] = "2.0";
|
||||
resp["id"] = id;
|
||||
resp["result"] = result;
|
||||
// resp["result"] 本来就是深拷贝,直接在上面补文本块,不多拷一次。
|
||||
Json::Value& out = resp["result"];
|
||||
if (out.isMember(kStructuredTextPayloadKey)) {
|
||||
Json::Value payload = out[kStructuredTextPayloadKey];
|
||||
out.removeMember(kStructuredTextPayloadKey);
|
||||
AppendStructuredText(out, payload);
|
||||
} else {
|
||||
AppendStructuredText(out);
|
||||
}
|
||||
return JsonToString(resp);
|
||||
}
|
||||
|
||||
@@ -370,6 +411,7 @@ const ToolHints kToolHints[] = {
|
||||
{ "remote_clipboard", false, false, false, true }, // 覆盖对端剪贴板
|
||||
// --- 文件传输 ---
|
||||
{ "upload_file", false, true, false, true }, // 覆盖/新增远端文件
|
||||
{ "copy_files_c2c", false, true, false, true }, // 覆盖/新增目标主机文件
|
||||
// --- 设备管理(McpManage)---
|
||||
{ "kill_process", false, true, false, true },
|
||||
{ "operate_window", false, true, false, true },
|
||||
|
||||
@@ -27,6 +27,28 @@ std::string JsonToString(const Json::Value& v);
|
||||
std::string BuildResult(const Json::Value& id, const Json::Value& result);
|
||||
std::string BuildError(const Json::Value& id, int code, const std::string& msg);
|
||||
|
||||
// ===== 结果外露(content 文本块)=====
|
||||
//
|
||||
// MCP 规范(Tools > Structured Content)要求:返回 structuredContent 的工具,
|
||||
// 应同时把序列化后的 JSON 放进一个 TextContent 块。有些客户端(如 WorkBuddy)
|
||||
// 只把 content 交给模型、完全忽略 structuredContent——不补这一块,模型就拿不到
|
||||
// id / session_id / pid 这类串联下一跳的关键字段,只能看到「共 N 台主机匹配」。
|
||||
//
|
||||
// 因此 BuildResult 默认给每个带非空 structuredContent 的结果追加一个文本块
|
||||
// (紧凑 JSON)。工具的正文已经承载同一份载荷时,用 SetStructuredTextPayload
|
||||
// 指定只外露哪部分,避免同一份内容在上下文里出现两三次:
|
||||
//
|
||||
// exec_command / terminal_exec → {"exit_code":N} (stdout 已在正文里)
|
||||
// get_keylog → 行数/字节数等元数据(行已在正文里)
|
||||
// get_activity_history → {"records":[…]}
|
||||
// host_get_hosts_file → 去掉 content 的 sc (原文已在 lines 里)
|
||||
void AppendStructuredText(Json::Value& result, const Json::Value& payload); // 内部用
|
||||
void AppendStructuredText(Json::Value& result); // 内部用
|
||||
|
||||
// 本次结果只外露 payload(BuildResult 消费后移除,不出现在响应里)。
|
||||
// payload 为空对象/空数组时本次不追加文本块。
|
||||
void SetStructuredTextPayload(Json::Value& result, const Json::Value& payload);
|
||||
|
||||
// 仅 ASCII 小写化;不区分大小写的子串匹配
|
||||
std::string ToLowerAscii(const std::string& s);
|
||||
bool ContainsCI(const std::string& haystack, const std::string& needle);
|
||||
|
||||
@@ -276,9 +276,13 @@ Json::Value ActionOutputSchema() {
|
||||
}
|
||||
|
||||
std::string BuildStructuredResult(const Json::Value& id, const Json::Value& sc,
|
||||
const std::string& text) {
|
||||
const std::string& text,
|
||||
const Json::Value* textPayload = nullptr) {
|
||||
Json::Value result(Json::objectValue);
|
||||
result["structuredContent"] = sc;
|
||||
// 默认由 BuildResult 把 structuredContent 原样外露到 content;工具可指定更小的
|
||||
// 载荷(例如 hosts 文件只外露 lines,不再重复 content 原文)。
|
||||
if (textPayload) SetStructuredTextPayload(result, *textPayload);
|
||||
|
||||
Json::Value content(Json::arrayValue);
|
||||
Json::Value item(Json::objectValue);
|
||||
@@ -2000,7 +2004,10 @@ static std::string BuildHostGetHostsFile(const Json::Value& id, const Json::Valu
|
||||
|
||||
std::string summary = std::string(u8"hosts 文件 ") + std::to_string(contentLen) + u8" 字节" +
|
||||
(truncated ? u8"(已截断)" : "");
|
||||
return BuildStructuredResult(id, sc, summary);
|
||||
// 正文外露 lines + 元数据即可;sc 里的 content 是同一份原文,别再重复一遍。
|
||||
Json::Value textPayload = sc;
|
||||
textPayload.removeMember("content");
|
||||
return BuildStructuredResult(id, sc, summary, &textPayload);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
|
||||
@@ -1373,6 +1373,9 @@ std::string BuildDownloadFile(const Json::Value& id, const Json::Value& args, CM
|
||||
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 分派」前)=====
|
||||
@@ -1769,6 +1772,18 @@ std::string BuildToolsListResult(const Json::Value& id) {
|
||||
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"在两个在线 Windows 主机之间直接拷贝文件(V2 C2C:源主机自己发、目标主机自己收,服务端只中继,不在主控落盘)。paths 为源主机绝对路径(文件或目录,目录递归、保留相对目录结构);dst_dir 为目标主机保存目录(不存在自动创建)。返回 transfer_id/file_count/total_bytes;receiver_ack 恒为 false —— V2 没有目标端回执,目标端校验失败只记在目标机日志里,需要确证请用 list_files 复核。";
|
||||
tool["inputSchema"] = BuildCopyFilesC2CInputSchema();
|
||||
tool["outputSchema"] = BuildCopyFilesC2COutputSchema();
|
||||
tools.append(tool);
|
||||
}
|
||||
|
||||
// 18) kill_process / operate_window / control_service / power_action(P7:设备管理控制,
|
||||
// 仅 Windows,安全门:McpManage=1 且 McpReadonly=0)
|
||||
if (CMcpServer::Instance().IsManageEnabled() && !CMcpServer::Instance().IsReadonly()) {
|
||||
@@ -2280,6 +2295,12 @@ std::string BuildGetActivityHistory(const Json::Value& id, const Json::Value& ar
|
||||
structuredContent["activityHistory"] = text;
|
||||
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";
|
||||
@@ -2905,6 +2926,11 @@ std::string BuildExecCommand(const Json::Value& id, const Json::Value& args, CMy
|
||||
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";
|
||||
@@ -3451,6 +3477,11 @@ std::string BuildTerminalExec(const Json::Value& id, const Json::Value& args, CM
|
||||
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";
|
||||
@@ -5061,6 +5092,250 @@ std::string BuildUploadFile(const Json::Value& id, const Json::Value& args, CMy2
|
||||
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"目标主机保存目录(绝对路径,不存在自动创建),如 D:\\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 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 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:dst_dir 由源端拼进每个块的 name 字段(绝对 Windows 路径),
|
||||
// 非 Windows 接收端拿不到 COMMAND_C2C_PREPARE 设置的目标目录,会把 C:\x\y 去盘符后
|
||||
// 当绝对路径写(common/FileTransferV2.h:224)——落到 /x/y 并要求 root 权限。
|
||||
CString dstType = dstCtx->GetAdditionalData(RES_CLIENT_TYPE);
|
||||
if (dstType == "LNX" || dstType == "MAC")
|
||||
return BuildError(id, -32005, "copy_files_c2c requires a Windows destination host: "
|
||||
"non-Windows clients cannot honour dst_dir yet");
|
||||
|
||||
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 前缀)。
|
||||
std::string 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);
|
||||
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();
|
||||
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);
|
||||
}
|
||||
|
||||
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 : pathAnsi) {
|
||||
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);
|
||||
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);
|
||||
}
|
||||
|
||||
// 审计(不可关闭;只记主机 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;
|
||||
// V2 没有「目标端已校验」的回执回到服务端:目标端校验失败只记在目标主机日志里。
|
||||
sc["receiver_ack"] = 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(r.fileCount) + u8" 个文件("
|
||||
+ std::to_string(r.totalBytes) + u8" 字节),目标主机保存目录 " + dstDirUtf8
|
||||
+ 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
|
||||
@@ -5630,6 +5905,15 @@ std::string BuildGetKeylog(const Json::Value& id, const Json::Value& args, CMy20
|
||||
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";
|
||||
@@ -6352,6 +6636,7 @@ std::string DispatchSingleHostTool(const Json::Value& id, const std::string& too
|
||||
if (toolName == "remote_clipboard") return BuildRemoteClipboard(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);
|
||||
@@ -6860,17 +7145,40 @@ bool CMcpServer::Start(const std::string& bind, int port) {
|
||||
m_bind = bind;
|
||||
m_port = port;
|
||||
|
||||
m_thread = std::thread([this, bind, port]() {
|
||||
m_server.listen(bind, 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());
|
||||
return m_running.load();
|
||||
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;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void CMcpServer::Stop() {
|
||||
// 先停前端:不再接入新连接,再停后端。Stop 内部会 join 前端线程。
|
||||
m_tlsProxy.Stop();
|
||||
m_server.stop();
|
||||
if (m_thread.joinable()) {
|
||||
m_thread.join();
|
||||
@@ -7680,6 +7988,13 @@ bool CMcpServer::IsFileTransferPending(uint64_t device_id) {
|
||||
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) {
|
||||
@@ -7717,6 +8032,82 @@ bool CMcpServer::BeginFileUpload(uint64_t device_id) {
|
||||
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();
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
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::OnDownloadDriveList(uint64_t device_id, context* fmSubCtx) {
|
||||
std::string localDir, remotePath;
|
||||
{
|
||||
|
||||
@@ -27,6 +27,8 @@
|
||||
#define min(a,b) (((a) < (b)) ? (a) : (b))
|
||||
#endif
|
||||
|
||||
#include "McpTlsProxy.h"
|
||||
|
||||
#pragma comment(lib, "ws2_32.lib")
|
||||
|
||||
class CMy2015RemoteDlg;
|
||||
@@ -58,6 +60,18 @@ public:
|
||||
void SetParentDlg(CMy2015RemoteDlg* pDlg) { m_parent = pDlg; }
|
||||
void SetToken(const std::string& token) { m_token = token; }
|
||||
|
||||
// HTTPS(native TLS):开启后 httplib 退到 127.0.0.1:internalPort,对外由 McpTlsProxy
|
||||
// 在 bind:port 上同端口嗅探(TLS 解密 / 明文直通)。internalPort <= 0 时取 port+1。
|
||||
void SetHttps(bool enabled, const std::string& certPath, const std::string& keyPath,
|
||||
int internalPort) {
|
||||
m_httpsEnabled = enabled;
|
||||
m_certPath = certPath;
|
||||
m_keyPath = keyPath;
|
||||
m_internalPort = internalPort;
|
||||
}
|
||||
bool IsHttps() const { return m_httpsEnabled; }
|
||||
int GetInternalPort() const { return m_internalPort; }
|
||||
|
||||
bool Start(const std::string& bind, int port);
|
||||
void Stop();
|
||||
bool IsRunning() const { return m_running.load(); }
|
||||
@@ -259,6 +273,11 @@ public:
|
||||
// 该 host 是否有进行中的文件传输会话(MessageHandle 分派守卫)。
|
||||
bool IsFileTransferPending(uint64_t device_id);
|
||||
|
||||
// 该 host 上是否有「MCP 发起的 C2C 传输」正发往 dst_id。用于 COMMAND_SEND_FILE_V2
|
||||
// 转发分支:MCP 的 C2C 不给源端子连接挂进度对话框(挂上后子连接的后续包会被路由到
|
||||
// 对话框而不是 MessageHandle,源端最后的 TOKEN_C2C_SEND_RESULT 就会丢)。
|
||||
bool IsC2CTransferPending(uint64_t src_id, uint64_t dst_id);
|
||||
|
||||
// 登记文件传输会话(false = 该 host 已有文件会话或一次性挂起请求)。
|
||||
bool BeginFileTransferPending(uint64_t device_id, const std::string& tool,
|
||||
const std::string& localDir, const std::string& remotePath,
|
||||
@@ -269,6 +288,28 @@ public:
|
||||
// (无 fmSubCtx/streamSubCtx,ClearFileTransfer 对空指针安全)。
|
||||
bool BeginFileUpload(uint64_t device_id);
|
||||
|
||||
// ===== C2C 文件传输(copy_files_c2c:源客户端 → 目标客户端,服务端只做中继)=====
|
||||
// 会话键控在「源」设备上:工具线程只等源客户端回传的 TOKEN_C2C_SEND_RESULT,
|
||||
// 目标端的收发由服务端现有的 COMMAND_SEND_FILE_V2 转发分支完成(不经过 MCP)。
|
||||
struct C2CResult {
|
||||
int error = 0; // 0=ok;1002=超时(工具侧);其余为客户端上报的 status
|
||||
uint32_t status = 0; // C2CSendResultPacket.status(0=全部发出;FEV2_* / 1001)
|
||||
DWORD win32err = 0; // 源端首个不可访问路径的 win32 码
|
||||
int32_t workerRc = 0; // FileBatchTransferWorkerV2 返回值
|
||||
uint32_t fileCount = 0;
|
||||
uint64_t totalBytes = 0;
|
||||
};
|
||||
|
||||
// 登记 C2C 会话(false = 源设备已有文件会话/挂起请求,或源==目标)。
|
||||
bool BeginC2CTransfer(uint64_t src_id, uint64_t dst_id, uint64_t transfer_id);
|
||||
|
||||
// TOKEN_C2C_SEND_RESULT:源客户端回传发送结果,填会话并唤醒工具线程。
|
||||
// 无对应会话(迟到的结果、MFC 侧手写包)直接忽略。
|
||||
void OnC2CResult(uint64_t src_id, const BYTE* buf, ULONG len);
|
||||
|
||||
// 工具线程:等源客户端回传结果;true=全部发出(error=0)。调用方随后 ClearFileTransfer(src)。
|
||||
bool WaitC2CDone(uint64_t src_id, int timeoutMs, C2CResult& out);
|
||||
|
||||
// TOKEN_DRIVE_LIST:识别 download_file,存文件管理器子链接并下发 CMD_DOWN_FILES_V2。
|
||||
// 返回 true=已接管(保持子链接,收尾由 ClearFileTransfer);false=会话已清理(调用方 CancelIO)。
|
||||
bool OnDownloadDriveList(uint64_t device_id, context* fmSubCtx);
|
||||
@@ -501,11 +542,16 @@ private:
|
||||
PendingKind kind, context* mainCtx);
|
||||
|
||||
httplib::Server m_server;
|
||||
McpTlsProxy m_tlsProxy; // HTTPS 前端(仅在 m_httpsEnabled 时启动)
|
||||
std::thread m_thread;
|
||||
std::atomic<bool> m_running{false};
|
||||
std::string m_token;
|
||||
std::string m_bind; // Start 传入的监听地址
|
||||
int m_port = 0; // Start 传入的监听端口
|
||||
bool m_httpsEnabled = false; // SetHttps 设置(默认明文)
|
||||
std::string m_certPath; // MCP TLS 证书(PEM)
|
||||
std::string m_keyPath; // MCP TLS 私钥(PEM, PKCS#8)
|
||||
int m_internalPort = 0; // httplib 实际监听的回环端口
|
||||
CMy2015RemoteDlg* m_parent = nullptr;
|
||||
|
||||
// 挂起请求注册表(受 m_PendingMutex 保护,键 = device_id)。
|
||||
@@ -632,7 +678,14 @@ private:
|
||||
|
||||
// ===== P6:文件传输会话(受 m_FileXferMutex 保护;单设备单传输)=====
|
||||
struct FileTransferSession {
|
||||
std::string tool; // "download_file" / "upload_file"
|
||||
std::string tool; // "download_file" / "upload_file" / "copy_files_c2c"
|
||||
uint64_t dstClientID = 0; // copy_files_c2c:目标客户端(其余工具恒 0)
|
||||
bool c2cResult = false; // copy_files_c2c:已收到源端结果包
|
||||
uint32_t c2cStatus = 0; // 结果包 status(0=全部发出)
|
||||
DWORD c2cWin32 = 0; // 结果包 win32err
|
||||
int32_t c2cWorkerRc = 0; // 结果包 workerRc
|
||||
uint32_t c2cFileCount = 0; // 结果包 fileCount
|
||||
uint64_t c2cBytes = 0; // 结果包 totalBytes
|
||||
std::string localDir; // download:本机保存目录(ANSI,结尾 '\')
|
||||
std::string remotePath; // 客户端远程路径(ANSI,发 CMD_DOWN_FILES_V2 用)
|
||||
bool overwrite = false; // 是否覆盖已存在文件
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
#include "McpServer.h" // GenerateRandomToken
|
||||
#include "2015Remote.h" // THIS_CFG (GetThisCfg)
|
||||
#include <atlconv.h>
|
||||
#include <afxdlgs.h>
|
||||
|
||||
#ifdef _DEBUG
|
||||
#define new DEBUG_NEW
|
||||
@@ -95,6 +96,9 @@ std::string WhitelistForDisplay(const std::string& stored)
|
||||
} // namespace
|
||||
|
||||
BEGIN_MESSAGE_MAP(CMcpSettingsDlg, CDialog)
|
||||
ON_BN_CLICKED(IDC_MCP_HTTPS, &CMcpSettingsDlg::OnHttpsToggle)
|
||||
ON_BN_CLICKED(IDC_MCP_CERT_BROWSE, &CMcpSettingsDlg::OnBrowseCert)
|
||||
ON_BN_CLICKED(IDC_MCP_KEY_BROWSE, &CMcpSettingsDlg::OnBrowseKey)
|
||||
END_MESSAGE_MAP()
|
||||
|
||||
CMcpSettingsDlg::CMcpSettingsDlg(CWnd* parent)
|
||||
@@ -106,7 +110,7 @@ INT_PTR CMcpSettingsDlg::DoModal()
|
||||
{
|
||||
USES_CONVERSION;
|
||||
CString title = _TR("MCP设置");
|
||||
BuildDialogTemplate(m_Template, T2CW(title), 320, 540);
|
||||
BuildDialogTemplate(m_Template, T2CW(title), 320, 640);
|
||||
InitModalIndirect((LPCDLGTEMPLATE)m_Template.data());
|
||||
return CDialog::DoModal();
|
||||
}
|
||||
@@ -133,6 +137,19 @@ BOOL CMcpSettingsDlg::OnInitDialog()
|
||||
m_lblToken.Create(_TR("Token"), WS_CHILD | WS_VISIBLE, r0, this, (UINT)-1);
|
||||
m_editToken.Create(WS_CHILD | WS_VISIBLE | WS_BORDER | WS_TABSTOP | ES_AUTOHSCROLL,
|
||||
r0, this, IDC_MCP_TOKEN);
|
||||
m_btnHttps.Create(_TR("启用 HTTPS(本端口同时接受 TLS 连接)"),
|
||||
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
|
||||
r0, this, IDC_MCP_HTTPS);
|
||||
m_lblCert.Create(_TR("证书路径"), WS_CHILD | WS_VISIBLE, r0, this, (UINT)-1);
|
||||
m_editCert.Create(WS_CHILD | WS_VISIBLE | WS_BORDER | WS_TABSTOP | ES_AUTOHSCROLL,
|
||||
r0, this, IDC_MCP_CERT);
|
||||
m_btnCertBrowse.Create(_TR("浏览"), WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON,
|
||||
r0, this, IDC_MCP_CERT_BROWSE);
|
||||
m_lblKey.Create(_TR("私钥路径"), WS_CHILD | WS_VISIBLE, r0, this, (UINT)-1);
|
||||
m_editKey.Create(WS_CHILD | WS_VISIBLE | WS_BORDER | WS_TABSTOP | ES_AUTOHSCROLL,
|
||||
r0, this, IDC_MCP_KEY);
|
||||
m_btnKeyBrowse.Create(_TR("浏览"), WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON,
|
||||
r0, this, IDC_MCP_KEY_BROWSE);
|
||||
m_btnReadonly.Create(_TR("只读模式(禁命令执行)"),
|
||||
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
|
||||
r0, this, IDC_MCP_READONLY);
|
||||
@@ -179,6 +196,13 @@ BOOL CMcpSettingsDlg::OnInitDialog()
|
||||
m_editBind.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||||
m_lblToken.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||||
m_editToken.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||||
m_btnHttps.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||||
m_lblCert.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||||
m_editCert.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||||
m_btnCertBrowse.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||||
m_lblKey.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||||
m_editKey.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||||
m_btnKeyBrowse.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||||
m_btnReadonly.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||||
m_btnTerminal.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||||
m_btnRemoteControl.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||||
@@ -210,6 +234,13 @@ BOOL CMcpSettingsDlg::OnInitDialog()
|
||||
int chat = THIS_CFG.GetInt("settings", "McpChat", 0);
|
||||
int keylog = THIS_CFG.GetInt("settings", "McpKeylog", 0);
|
||||
std::string whitelist = THIS_CFG.GetStr("settings", "McpCmdWhitelist", "");
|
||||
int https = THIS_CFG.GetInt("settings", "McpHttps", 0);
|
||||
std::string certPath = THIS_CFG.GetStr("settings", "McpCertPath", "");
|
||||
std::string keyPath = THIS_CFG.GetStr("settings", "McpKeyPath", "");
|
||||
// 未单独配置 MCP 证书时,按启动逻辑的同一回落规则预填设备端口的 [tls] 路径,
|
||||
// 用户改或直接用都可以(保存后即成为 MCP 自己的显式配置)。
|
||||
if (certPath.empty()) certPath = THIS_CFG.GetStr("tls", "CertPath", "");
|
||||
if (keyPath.empty()) keyPath = THIS_CFG.GetStr("tls", "KeyPath", "");
|
||||
|
||||
m_btnEnable.SetCheck(enabled ? BST_CHECKED : BST_UNCHECKED);
|
||||
m_editPort.SetWindowText(CString(std::to_string(port).c_str()));
|
||||
@@ -227,17 +258,66 @@ BOOL CMcpSettingsDlg::OnInitDialog()
|
||||
// 白名单存储为逗号分隔,展示为每行一条。
|
||||
m_editWhitelist.SetWindowText(CString(WhitelistForDisplay(whitelist).c_str()));
|
||||
|
||||
m_btnHttps.SetCheck(https ? BST_CHECKED : BST_UNCHECKED);
|
||||
m_editCert.SetWindowText(CString(certPath.c_str()));
|
||||
m_editKey.SetWindowText(CString(keyPath.c_str()));
|
||||
|
||||
LayoutControls(cli.Width(), cli.Height());
|
||||
UpdateHttpsState();
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
void CMcpSettingsDlg::UpdateHttpsState()
|
||||
{
|
||||
const BOOL on = (m_btnHttps.GetCheck() == BST_CHECKED);
|
||||
m_lblCert.EnableWindow(on);
|
||||
m_editCert.EnableWindow(on);
|
||||
m_btnCertBrowse.EnableWindow(on);
|
||||
m_lblKey.EnableWindow(on);
|
||||
m_editKey.EnableWindow(on);
|
||||
m_btnKeyBrowse.EnableWindow(on);
|
||||
}
|
||||
|
||||
void CMcpSettingsDlg::OnHttpsToggle()
|
||||
{
|
||||
UpdateHttpsState();
|
||||
}
|
||||
|
||||
void CMcpSettingsDlg::OnBrowseCert()
|
||||
{
|
||||
CString cur;
|
||||
m_editCert.GetWindowText(cur);
|
||||
CFileDialog dlg(TRUE, _T("pem"), cur.IsEmpty() ? nullptr : (LPCTSTR)cur,
|
||||
OFN_FILEMUSTEXIST | OFN_HIDEREADONLY,
|
||||
_T("Certificate Files (*.pem;*.crt;*.cer)|*.pem;*.crt;*.cer|All Files (*.*)|*.*||"),
|
||||
this);
|
||||
dlg.m_ofn.lpstrTitle = _T("Select Certificate");
|
||||
if (dlg.DoModal() == IDOK)
|
||||
m_editCert.SetWindowText(dlg.GetPathName());
|
||||
}
|
||||
|
||||
void CMcpSettingsDlg::OnBrowseKey()
|
||||
{
|
||||
CString cur;
|
||||
m_editKey.GetWindowText(cur);
|
||||
CFileDialog dlg(TRUE, _T("key"), cur.IsEmpty() ? nullptr : (LPCTSTR)cur,
|
||||
OFN_FILEMUSTEXIST | OFN_HIDEREADONLY,
|
||||
_T("Key Files (*.key;*.pem)|*.key;*.pem|All Files (*.*)|*.*||"),
|
||||
this);
|
||||
dlg.m_ofn.lpstrTitle = _T("Select Private Key");
|
||||
if (dlg.DoModal() == IDOK)
|
||||
m_editKey.SetWindowText(dlg.GetPathName());
|
||||
}
|
||||
|
||||
void CMcpSettingsDlg::OnOK()
|
||||
{
|
||||
CString sPort, sBind, sToken, sWhitelist;
|
||||
CString sPort, sBind, sToken, sWhitelist, sCert, sKey;
|
||||
m_editPort.GetWindowText(sPort);
|
||||
m_editBind.GetWindowText(sBind);
|
||||
m_editToken.GetWindowText(sToken);
|
||||
m_editWhitelist.GetWindowText(sWhitelist);
|
||||
m_editCert.GetWindowText(sCert);
|
||||
m_editKey.GetWindowText(sKey);
|
||||
bool enabled = (m_btnEnable.GetCheck() == BST_CHECKED);
|
||||
bool readonly = (m_btnReadonly.GetCheck() == BST_CHECKED);
|
||||
bool terminal = (m_btnTerminal.GetCheck() == BST_CHECKED);
|
||||
@@ -248,6 +328,7 @@ void CMcpSettingsDlg::OnOK()
|
||||
bool machineDangerous = (m_btnMachineDangerous.GetCheck() == BST_CHECKED);
|
||||
bool chat = (m_btnChat.GetCheck() == BST_CHECKED);
|
||||
bool keylog = (m_btnKeylog.GetCheck() == BST_CHECKED);
|
||||
bool https = (m_btnHttps.GetCheck() == BST_CHECKED);
|
||||
|
||||
// 危险子集依附于主机管理总开关:没开主机管理就没有工具可放开,直接清除并提示。
|
||||
if (machineDangerous && !machine) {
|
||||
@@ -273,6 +354,27 @@ void CMcpSettingsDlg::OnOK()
|
||||
return;
|
||||
}
|
||||
|
||||
// HTTPS:证书与私钥必须都在且存在(启动时加载失败会直接拒绝监听,故此处先挡住)
|
||||
std::string certPath = CT2A(sCert);
|
||||
std::string keyPath = CT2A(sKey);
|
||||
if (https) {
|
||||
if (certPath.empty()) {
|
||||
MessageBoxL(_TR("请填写证书路径"), _TR("提示"), MB_ICONWARNING);
|
||||
return;
|
||||
}
|
||||
if (keyPath.empty()) {
|
||||
MessageBoxL(_TR("请填写私钥路径"), _TR("提示"), MB_ICONWARNING);
|
||||
return;
|
||||
}
|
||||
DWORD ca = GetFileAttributesA(certPath.c_str());
|
||||
DWORD ka = GetFileAttributesA(keyPath.c_str());
|
||||
if (ca == INVALID_FILE_ATTRIBUTES || (ca & FILE_ATTRIBUTE_DIRECTORY) ||
|
||||
ka == INVALID_FILE_ATTRIBUTES || (ka & FILE_ATTRIBUTE_DIRECTORY)) {
|
||||
MessageBoxL(_TR("证书或私钥文件不存在,请检查路径。"), _TR("提示"), MB_ICONWARNING);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 落盘
|
||||
THIS_CFG.SetInt("settings", "McpEnabled", enabled ? 1 : 0);
|
||||
THIS_CFG.SetInt("settings", "McpPort", port);
|
||||
@@ -290,6 +392,9 @@ void CMcpSettingsDlg::OnOK()
|
||||
std::string whitelist = CT2A(sWhitelist);
|
||||
whitelist = NormalizeWhitelist(whitelist);
|
||||
THIS_CFG.SetStr("settings", "McpCmdWhitelist", whitelist);
|
||||
THIS_CFG.SetInt("settings", "McpHttps", https ? 1 : 0);
|
||||
THIS_CFG.SetStr("settings", "McpCertPath", certPath);
|
||||
THIS_CFG.SetStr("settings", "McpKeyPath", keyPath);
|
||||
|
||||
// 拆成多段可翻译的单行键,中间用 \r\n 连接(多行键无法在 INI 中表示)
|
||||
MessageBox(_TR("MCP 设置已保存。") + _T("\r\n") +
|
||||
@@ -297,7 +402,9 @@ void CMcpSettingsDlg::OnOK()
|
||||
_TR("持久终端、远程控制与管理操作仅在只读模式关闭时生效。") + _T("\r\n") +
|
||||
_TR("主机管理的写操作需只读模式关闭;冻结/解冻进程、停止/重启服务还需启用危险主机操作。") + _T("\r\n") +
|
||||
_TR("远程交谈开关的改动需重启程序生效。") + _T("\r\n") +
|
||||
_TR("键盘记录开关的改动需重启程序生效。"),
|
||||
_TR("键盘记录开关的改动需重启程序生效。") + _T("\r\n") +
|
||||
_TR("HTTPS 开关与证书路径的改动需重启程序生效。") + _T("\r\n") +
|
||||
_TR("证书须为 PEM 格式,私钥须为 PKCS#8 格式。"),
|
||||
_TR("提示"), MB_ICONINFORMATION);
|
||||
|
||||
CDialog::OnOK();
|
||||
@@ -328,6 +435,22 @@ void CMcpSettingsDlg::LayoutControls(int cx, int cy)
|
||||
m_editToken.MoveWindow(margin + labelW, y - 2, cx - margin * 2 - labelW, rowH);
|
||||
y += rowH + gap;
|
||||
|
||||
// HTTPS:勾选后证书/私钥两行才可编辑(未勾选时置灰,值仍保留)。
|
||||
const int browseW = 64;
|
||||
int editW = cx - margin * 2 - labelW - browseW - gap;
|
||||
m_btnHttps.MoveWindow(margin, y, cx - margin * 2, 22);
|
||||
y += 30;
|
||||
|
||||
m_lblCert.MoveWindow(margin, y, labelW, rowH);
|
||||
m_editCert.MoveWindow(margin + labelW, y - 2, editW, rowH);
|
||||
m_btnCertBrowse.MoveWindow(cx - margin - browseW, y - 2, browseW, rowH);
|
||||
y += rowH + gap;
|
||||
|
||||
m_lblKey.MoveWindow(margin, y, labelW, rowH);
|
||||
m_editKey.MoveWindow(margin + labelW, y - 2, editW, rowH);
|
||||
m_btnKeyBrowse.MoveWindow(cx - margin - browseW, y - 2, browseW, rowH);
|
||||
y += rowH + gap;
|
||||
|
||||
m_btnReadonly.MoveWindow(margin, y, cx - margin * 2, 22);
|
||||
y += 30;
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
#include <afxcmn.h>
|
||||
#include <vector>
|
||||
|
||||
// 「MCP设置」配置对话框:启用 MCP / 端口 / 绑定地址 / Token。
|
||||
// 「MCP设置」配置对话框:启用 MCP / 端口 / 绑定地址 / Token / HTTPS 与证书。
|
||||
// 因 2015Remote.rc 为 UTF-16 编码、不宜手工编辑,参照 ZstaPickerDlg 用
|
||||
// InitModalIndirect + 内存 DLGTEMPLATE 程序化创建(见 docs/Mcp_Design.md §3.8)。
|
||||
class CMcpSettingsDlg : public CDialog
|
||||
@@ -18,6 +18,10 @@ protected:
|
||||
virtual BOOL OnInitDialog();
|
||||
virtual void OnOK();
|
||||
|
||||
afx_msg void OnHttpsToggle();
|
||||
afx_msg void OnBrowseCert();
|
||||
afx_msg void OnBrowseKey();
|
||||
|
||||
DECLARE_MESSAGE_MAP()
|
||||
|
||||
private:
|
||||
@@ -36,6 +40,11 @@ private:
|
||||
IDC_MCP_MACHINE_DANGEROUS = 1012, // 「启用危险主机操作」复选框(冻结/停止/重启)
|
||||
IDC_MCP_CHAT = 1013, // 「启用远程交谈」复选框(chat_* 工具族,不要求只读关)
|
||||
IDC_MCP_KEYLOG = 1014, // 「启用键盘记录」复选框(get_keylog,不要求只读关)
|
||||
IDC_MCP_HTTPS = 1015, // 「启用 HTTPS」复选框(MCP 端口同时接受 TLS)
|
||||
IDC_MCP_CERT = 1016, // 证书路径编辑框(PEM)
|
||||
IDC_MCP_KEY = 1017, // 私钥路径编辑框(PKCS#8)
|
||||
IDC_MCP_CERT_BROWSE = 1018, // 证书路径「浏览」按钮
|
||||
IDC_MCP_KEY_BROWSE = 1019, // 私钥路径「浏览」按钮
|
||||
};
|
||||
|
||||
CButton m_btnEnable;
|
||||
@@ -52,9 +61,14 @@ private:
|
||||
CButton m_btnKeylog;
|
||||
CStatic m_lblWhitelist;
|
||||
CEdit m_editWhitelist;
|
||||
CButton m_btnHttps;
|
||||
CStatic m_lblCert, m_lblKey;
|
||||
CEdit m_editCert, m_editKey;
|
||||
CButton m_btnCertBrowse, m_btnKeyBrowse;
|
||||
CButton m_btnOK, m_btnCancel;
|
||||
|
||||
std::vector<BYTE> m_Template; // 内存 DLGTEMPLATE 字节
|
||||
|
||||
void LayoutControls(int cx, int cy);
|
||||
void UpdateHttpsState(); // 勾选 HTTPS 才允许编辑证书/私钥
|
||||
};
|
||||
@@ -0,0 +1,440 @@
|
||||
// McpTlsProxy.cpp — MCP 端口的 TLS 前端实现(Schannel 入站,同端口嗅探)
|
||||
#include "StdAfx.h"
|
||||
#include "McpTlsProxy.h"
|
||||
|
||||
#include <ws2tcpip.h>
|
||||
|
||||
namespace
|
||||
{
|
||||
// MCP 身份在 CNG KSP 里的键名,与设备端口的 YamaServerTlsKey 区分,避免互相覆盖。
|
||||
const wchar_t* kMcpKeyName = L"YamaMcpTlsKey";
|
||||
|
||||
const size_t kMaxConns = 64; // 并发连接上限(MCP 客户端数量很少,防资源耗尽)
|
||||
const DWORD kSniffTimeoutMs = 10000; // 首字节嗅探超时:连上不说话的直接断开
|
||||
}
|
||||
|
||||
bool McpTlsProxy::WaitReady(SOCKET sock, bool forRead, int timeoutMs)
|
||||
{
|
||||
fd_set fds;
|
||||
FD_ZERO(&fds);
|
||||
FD_SET(sock, &fds);
|
||||
timeval tv;
|
||||
tv.tv_sec = timeoutMs / 1000;
|
||||
tv.tv_usec = (timeoutMs % 1000) * 1000;
|
||||
return select(0, forRead ? &fds : NULL, forRead ? NULL : &fds, NULL, &tv) > 0;
|
||||
}
|
||||
|
||||
bool McpTlsProxy::SendAll(SOCKET sock, const void* data, int len)
|
||||
{
|
||||
const char* p = (const char*)data;
|
||||
int sent = 0;
|
||||
while (sent < len)
|
||||
{
|
||||
int n = send(sock, p + sent, len - sent, 0);
|
||||
if (n == SOCKET_ERROR)
|
||||
{
|
||||
if (WSAGetLastError() == WSAEWOULDBLOCK)
|
||||
{
|
||||
if (!WaitReady(sock, false, 30000))
|
||||
return false;
|
||||
continue;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (n <= 0)
|
||||
return false;
|
||||
sent += n;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
SOCKET McpTlsProxy::ConnectLoopback(int port)
|
||||
{
|
||||
SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
|
||||
if (s == INVALID_SOCKET)
|
||||
return INVALID_SOCKET;
|
||||
|
||||
sockaddr_in addr = {};
|
||||
addr.sin_family = AF_INET;
|
||||
addr.sin_port = htons((u_short)port);
|
||||
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
||||
|
||||
if (connect(s, (sockaddr*)&addr, sizeof(addr)) != 0)
|
||||
{
|
||||
closesocket(s);
|
||||
return INVALID_SOCKET;
|
||||
}
|
||||
u_long nb = 1;
|
||||
ioctlsocket(s, FIONBIO, &nb); // 连接建立后转非阻塞,交给 select 驱动
|
||||
return s;
|
||||
}
|
||||
|
||||
bool McpTlsProxy::Start(const std::string& bind, int listenPort, int backendPort,
|
||||
const std::string& certPath, const std::string& keyPath)
|
||||
{
|
||||
if (m_running.load())
|
||||
return true;
|
||||
if (listenPort <= 0 || backendPort <= 0)
|
||||
return false;
|
||||
|
||||
// 身份必须先加载成功:证书坏了就 fail-closed,绝不以明文对外监听。
|
||||
if (!ServerTlsLoadIdentityFromPem(certPath, keyPath, kMcpKeyName, m_identity))
|
||||
{
|
||||
Mprintf("[McpTls] FATAL: cannot load MCP TLS identity (cert=%s key=%s); "
|
||||
"refusing to start MCP listener\n", certPath.c_str(), keyPath.c_str());
|
||||
return false;
|
||||
}
|
||||
m_identityLoaded = true;
|
||||
m_backendPort = backendPort;
|
||||
|
||||
addrinfo hints = {};
|
||||
hints.ai_family = AF_INET;
|
||||
hints.ai_socktype = SOCK_STREAM;
|
||||
addrinfo* res = nullptr;
|
||||
char portStr[16] = {};
|
||||
sprintf_s(portStr, "%d", listenPort);
|
||||
const char* node = (bind.empty() || bind == "0.0.0.0") ? "0.0.0.0" : bind.c_str();
|
||||
|
||||
if (getaddrinfo(node, portStr, &hints, &res) != 0 || res == nullptr)
|
||||
{
|
||||
Mprintf("[McpTls] FATAL: cannot resolve bind address %s\n", node);
|
||||
ServerTlsFreeIdentity(m_identity);
|
||||
m_identityLoaded = false;
|
||||
return false;
|
||||
}
|
||||
|
||||
SOCKET ls = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
|
||||
if (ls == INVALID_SOCKET)
|
||||
{
|
||||
freeaddrinfo(res);
|
||||
ServerTlsFreeIdentity(m_identity);
|
||||
m_identityLoaded = false;
|
||||
return false;
|
||||
}
|
||||
BOOL reuse = TRUE;
|
||||
setsockopt(ls, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(reuse));
|
||||
u_long nb = 1;
|
||||
ioctlsocket(ls, FIONBIO, &nb); // 非阻塞监听,accept 用 select 驱动
|
||||
|
||||
if (::bind(ls, res->ai_addr, (int)res->ai_addrlen) != 0 ||
|
||||
listen(ls, SOMAXCONN) != 0)
|
||||
{
|
||||
Mprintf("[McpTls] FATAL: bind/listen %s:%d failed (%d)\n", node, listenPort, WSAGetLastError());
|
||||
freeaddrinfo(res);
|
||||
closesocket(ls);
|
||||
ServerTlsFreeIdentity(m_identity);
|
||||
m_identityLoaded = false;
|
||||
return false;
|
||||
}
|
||||
freeaddrinfo(res);
|
||||
|
||||
m_listen = ls;
|
||||
m_running.store(true);
|
||||
m_acceptThread = std::thread(&McpTlsProxy::AcceptLoop, this);
|
||||
Mprintf("[McpTls] listening on %s:%d (TLS + plaintext passthrough) -> 127.0.0.1:%d\n",
|
||||
node, listenPort, backendPort);
|
||||
return true;
|
||||
}
|
||||
|
||||
void McpTlsProxy::Stop()
|
||||
{
|
||||
if (!m_running.exchange(false) && m_listen == INVALID_SOCKET && !m_acceptThread.joinable())
|
||||
{
|
||||
// 从未启动或已停止
|
||||
if (m_identityLoaded)
|
||||
{
|
||||
ServerTlsFreeIdentity(m_identity);
|
||||
m_identityLoaded = false;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
SOCKET ls = m_listen;
|
||||
m_listen = INVALID_SOCKET;
|
||||
if (ls != INVALID_SOCKET)
|
||||
{
|
||||
shutdown(ls, SD_BOTH); // 唤醒阻塞 accept
|
||||
closesocket(ls);
|
||||
}
|
||||
if (m_acceptThread.joinable())
|
||||
m_acceptThread.join();
|
||||
|
||||
std::vector<std::shared_ptr<Conn>> all;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(m_connMtx);
|
||||
all.swap(m_conns);
|
||||
}
|
||||
for (auto& c : all)
|
||||
{
|
||||
if (c->done.load())
|
||||
continue; // 已自行收尾,句柄可能已关闭,勿再触碰
|
||||
SOCKET cl = c->client.load();
|
||||
if (cl != INVALID_SOCKET)
|
||||
shutdown(cl, SD_BOTH);
|
||||
SOCKET b = c->backend.load();
|
||||
if (b != INVALID_SOCKET)
|
||||
shutdown(b, SD_BOTH);
|
||||
}
|
||||
for (auto& c : all)
|
||||
{
|
||||
if (c->th.joinable())
|
||||
c->th.join();
|
||||
}
|
||||
|
||||
if (m_identityLoaded)
|
||||
{
|
||||
ServerTlsFreeIdentity(m_identity);
|
||||
m_identityLoaded = false;
|
||||
}
|
||||
Mprintf("[McpTls] stopped\n");
|
||||
}
|
||||
|
||||
void McpTlsProxy::SweepFinished()
|
||||
{
|
||||
std::vector<std::shared_ptr<Conn>> finished;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(m_connMtx);
|
||||
for (auto it = m_conns.begin(); it != m_conns.end();)
|
||||
{
|
||||
if ((*it)->done.load())
|
||||
{
|
||||
finished.push_back(*it);
|
||||
it = m_conns.erase(it);
|
||||
}
|
||||
else
|
||||
{
|
||||
++it;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (auto& c : finished)
|
||||
{
|
||||
if (c->th.joinable())
|
||||
c->th.join();
|
||||
}
|
||||
}
|
||||
|
||||
void McpTlsProxy::AcceptLoop()
|
||||
{
|
||||
while (m_running.load())
|
||||
{
|
||||
if (!WaitReady(m_listen, true, 500))
|
||||
continue; // 超时轮询 m_running,便于 Stop 及时退出
|
||||
|
||||
SOCKET cs = accept(m_listen, NULL, NULL);
|
||||
if (cs == INVALID_SOCKET)
|
||||
{
|
||||
if (!m_running.load())
|
||||
break;
|
||||
int e = WSAGetLastError();
|
||||
if (e == WSAEWOULDBLOCK)
|
||||
continue;
|
||||
Mprintf("[McpTls] accept failed (%d); listener stops\n", e);
|
||||
break;
|
||||
}
|
||||
|
||||
SweepFinished();
|
||||
|
||||
std::lock_guard<std::mutex> lk(m_connMtx);
|
||||
if (m_conns.size() >= kMaxConns)
|
||||
{
|
||||
closesocket(cs);
|
||||
continue;
|
||||
}
|
||||
u_long nb = 1;
|
||||
ioctlsocket(cs, FIONBIO, &nb); // 嗅探/泵送全部走 select
|
||||
|
||||
auto c = std::make_shared<Conn>();
|
||||
c->client.store(cs);
|
||||
m_conns.push_back(c);
|
||||
c->th = std::thread([this, c]() { ServeConn(c); });
|
||||
}
|
||||
}
|
||||
|
||||
void McpTlsProxy::CloseConn(Conn& c)
|
||||
{
|
||||
SOCKET cl = c.client.exchange(INVALID_SOCKET);
|
||||
if (cl != INVALID_SOCKET)
|
||||
{
|
||||
shutdown(cl, SD_BOTH);
|
||||
closesocket(cl);
|
||||
}
|
||||
SOCKET b = c.backend.exchange(INVALID_SOCKET);
|
||||
if (b != INVALID_SOCKET)
|
||||
{
|
||||
shutdown(b, SD_BOTH);
|
||||
closesocket(b);
|
||||
}
|
||||
c.done.store(true);
|
||||
}
|
||||
|
||||
void McpTlsProxy::ServeConn(std::shared_ptr<Conn> sp)
|
||||
{
|
||||
Conn& c = *sp;
|
||||
SOCKET client = c.client.load();
|
||||
|
||||
// ---- 1) 首字节嗅探(同设备端口 §5.2):0x16 0x03 = TLS ClientHello ----
|
||||
BYTE peek[8] = {};
|
||||
int pn = 0;
|
||||
DWORD start = GetTickCount();
|
||||
for (;;)
|
||||
{
|
||||
int r = recv(client, (char*)peek, sizeof(peek), MSG_PEEK);
|
||||
if (r > 0)
|
||||
{
|
||||
pn = r;
|
||||
break;
|
||||
}
|
||||
if (r == 0)
|
||||
{
|
||||
CloseConn(c); // 对端直接关闭
|
||||
return;
|
||||
}
|
||||
if (WSAGetLastError() != WSAEWOULDBLOCK)
|
||||
{
|
||||
CloseConn(c);
|
||||
return;
|
||||
}
|
||||
if (GetTickCount() - start > kSniffTimeoutMs || !m_running.load())
|
||||
{
|
||||
CloseConn(c); // 连上不说话的,直接断开
|
||||
return;
|
||||
}
|
||||
WaitReady(client, true, 200);
|
||||
}
|
||||
const bool isTls = (peek[0] == 0x16) && (pn < 2 || peek[1] == 0x03);
|
||||
|
||||
// ---- 2) 后端:httplib 只监听 127.0.0.1 的内部端口 ----
|
||||
SOCKET backend = ConnectLoopback(m_backendPort);
|
||||
if (backend == INVALID_SOCKET)
|
||||
{
|
||||
Mprintf("[McpTls] backend 127.0.0.1:%d not reachable\n", m_backendPort);
|
||||
CloseConn(c);
|
||||
return;
|
||||
}
|
||||
c.backend.store(backend);
|
||||
|
||||
// ---- 3) 分流 ----
|
||||
if (isTls)
|
||||
{
|
||||
// 嗅探用的是 MSG_PEEK(不消费),ClientHello 原样留在内核缓冲里;交多少字节
|
||||
// HandshakeWithCred 都能自己补齐,这里直接让它从 socket 读完整首条记录。
|
||||
ServerTlsSession sess;
|
||||
if (!sess.HandshakeWithCred(client, NULL, 0, m_identity.cred))
|
||||
{
|
||||
Mprintf("[McpTls] TLS handshake failed; closing connection\n");
|
||||
CloseConn(c);
|
||||
return;
|
||||
}
|
||||
PumpTls(c, sess);
|
||||
}
|
||||
else
|
||||
{
|
||||
PumpRaw(c); // 本机 http://127.0.0.1:port 的既有用法原样透传
|
||||
}
|
||||
CloseConn(c);
|
||||
}
|
||||
|
||||
void McpTlsProxy::PumpRaw(Conn& c)
|
||||
{
|
||||
char buf[16384];
|
||||
const SOCKET client = c.client.load();
|
||||
const SOCKET backend = c.backend.load();
|
||||
|
||||
for (;;)
|
||||
{
|
||||
fd_set rd;
|
||||
FD_ZERO(&rd);
|
||||
FD_SET(client, &rd);
|
||||
FD_SET(backend, &rd);
|
||||
int n = select(0, &rd, NULL, NULL, NULL);
|
||||
if (n <= 0)
|
||||
break;
|
||||
|
||||
if (FD_ISSET(client, &rd))
|
||||
{
|
||||
int r = recv(client, buf, sizeof(buf), 0);
|
||||
if (r == 0) break;
|
||||
if (r < 0)
|
||||
{
|
||||
if (WSAGetLastError() == WSAEWOULDBLOCK) continue;
|
||||
break;
|
||||
}
|
||||
if (!SendAll(backend, buf, r)) break;
|
||||
}
|
||||
if (FD_ISSET(backend, &rd))
|
||||
{
|
||||
int r = recv(backend, buf, sizeof(buf), 0);
|
||||
if (r == 0) break;
|
||||
if (r < 0)
|
||||
{
|
||||
if (WSAGetLastError() == WSAEWOULDBLOCK) continue;
|
||||
break;
|
||||
}
|
||||
if (!SendAll(client, buf, r)) break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void McpTlsProxy::PumpTls(Conn& c, ServerTlsSession& sess)
|
||||
{
|
||||
char buf[16384];
|
||||
const SOCKET client = c.client.load();
|
||||
const SOCKET backend = c.backend.load();
|
||||
std::vector<BYTE> plain;
|
||||
std::vector<BYTE> wire;
|
||||
|
||||
// 握手阶段已经收到的明文要先送给后端:客户端复用 TLS 会话时会把 ChangeCipherSpec +
|
||||
// Finished + 首条请求挤在同一批字节里,握手只会消费前两个,请求留在会话缓冲里。
|
||||
// 不在这里取走,后端就一个字节也收不到,5s 后按 keep-alive 超时关连接,客户端看到的是
|
||||
// “fetch failed (other side closed)”(实测 undici/Node 24 稳定复现)。
|
||||
{
|
||||
std::vector<BYTE> head;
|
||||
if (sess.Decrypt(NULL, 0, head) < 0)
|
||||
return;
|
||||
if (!head.empty() && !SendAll(backend, head.data(), (int)head.size()))
|
||||
return;
|
||||
}
|
||||
|
||||
for (;;)
|
||||
{
|
||||
fd_set rd;
|
||||
FD_ZERO(&rd);
|
||||
FD_SET(client, &rd);
|
||||
FD_SET(backend, &rd);
|
||||
int n = select(0, &rd, NULL, NULL, NULL);
|
||||
if (n <= 0)
|
||||
break;
|
||||
|
||||
if (FD_ISSET(client, &rd))
|
||||
{
|
||||
int r = recv(client, buf, sizeof(buf), 0);
|
||||
if (r == 0) break;
|
||||
if (r < 0)
|
||||
{
|
||||
if (WSAGetLastError() == WSAEWOULDBLOCK) continue;
|
||||
break;
|
||||
}
|
||||
plain.clear();
|
||||
if (sess.Decrypt((const BYTE*)buf, r, plain) < 0)
|
||||
break; // 对端 close_notify / 解密失败
|
||||
if (!plain.empty() && !SendAll(backend, plain.data(), (int)plain.size()))
|
||||
break;
|
||||
}
|
||||
if (FD_ISSET(backend, &rd))
|
||||
{
|
||||
int r = recv(backend, buf, sizeof(buf), 0);
|
||||
if (r == 0) break;
|
||||
if (r < 0)
|
||||
{
|
||||
if (WSAGetLastError() == WSAEWOULDBLOCK) continue;
|
||||
break;
|
||||
}
|
||||
wire.clear();
|
||||
if (sess.Encrypt((const BYTE*)buf, r, wire) < 0)
|
||||
break;
|
||||
if (!wire.empty() && !SendAll(client, wire.data(), (int)wire.size()))
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
// McpTlsProxy.h — MCP 端口的 TLS 前端(同端口嗅探:TLS 解密 / 明文直通)
|
||||
//
|
||||
// 背景:CMcpServer 用的 httplib::Server 是明文 HTTP。要让 MCP 客户端经公网用 https
|
||||
// 访问,又不引入 OpenSSL 依赖,这里在 MCP 前面加一层基于 Schannel 的 TLS 前端:
|
||||
//
|
||||
// 客户端 → :McpPort(本类)→ 127.0.0.1:<内部端口>(httplib)
|
||||
//
|
||||
// 首字节嗅探与设备端口(IOCPServer.cpp §5.2)同一套路:首字节 0x16 且次字节 0x03
|
||||
// 视为 TLS ClientHello,走 ServerTlsSession 入站握手;否则按明文原样转发。因此本机
|
||||
// 现有的 http://127.0.0.1:6544 用法不需要改动,远端可同时用 https。
|
||||
//
|
||||
// 身份:独立于设备端口的 [tls] 证书(MCP 面向公网客户端,需公共 CA 证书),
|
||||
// 由 ServerTlsLoadIdentityFromPem 加载,CNG 键名 YamaMcpTlsKey,与设备端口互不覆盖。
|
||||
#pragma once
|
||||
|
||||
#include <WinSock2.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#include "ServerTlsSession.h"
|
||||
|
||||
class ServerTlsSession;
|
||||
|
||||
class McpTlsProxy
|
||||
{
|
||||
public:
|
||||
McpTlsProxy() {}
|
||||
~McpTlsProxy() { Stop(); }
|
||||
|
||||
McpTlsProxy(const McpTlsProxy&) = delete;
|
||||
McpTlsProxy& operator=(const McpTlsProxy&) = delete;
|
||||
|
||||
// 监听 bind:listenPort,把解密后的字节转发到 127.0.0.1:backendPort。
|
||||
// certPath/keyPath 为 PEM(证书 + PKCS#8 私钥)。任一环节失败返回 false(fail-closed)。
|
||||
bool Start(const std::string& bind, int listenPort, int backendPort,
|
||||
const std::string& certPath, const std::string& keyPath);
|
||||
void Stop();
|
||||
|
||||
bool IsRunning() const { return m_running.load(); }
|
||||
|
||||
private:
|
||||
// 单条前端连接:客户端套接字 + 连到 httplib 的后端套接字。
|
||||
// Stop() 需要能打断正在 select/recv 的线程,故后端套接字放在原子量里随时可取。
|
||||
struct Conn
|
||||
{
|
||||
std::atomic<SOCKET> client{ INVALID_SOCKET };
|
||||
std::atomic<SOCKET> backend{ INVALID_SOCKET };
|
||||
std::atomic<bool> done{ false };
|
||||
std::thread th;
|
||||
};
|
||||
|
||||
void AcceptLoop();
|
||||
void ServeConn(std::shared_ptr<Conn> c);
|
||||
void PumpRaw(Conn& c);
|
||||
void PumpTls(Conn& c, ServerTlsSession& sess);
|
||||
void SweepFinished();
|
||||
void CloseConn(Conn& c);
|
||||
|
||||
static SOCKET ConnectLoopback(int port);
|
||||
static bool WaitReady(SOCKET sock, bool forRead, int timeoutMs);
|
||||
static bool SendAll(SOCKET sock, const void* data, int len);
|
||||
|
||||
SOCKET m_listen = INVALID_SOCKET;
|
||||
std::thread m_acceptThread;
|
||||
std::atomic<bool> m_running{ false };
|
||||
int m_backendPort = 0;
|
||||
ServerTlsExtraIdentity m_identity;
|
||||
bool m_identityLoaded = false;
|
||||
|
||||
std::mutex m_connMtx;
|
||||
std::vector<std::shared_ptr<Conn>> m_conns;
|
||||
};
|
||||
@@ -1415,6 +1415,31 @@ VOID CScreenSpyDlg::DrawFirstScreen(void)
|
||||
PostMessage(WM_PAINT);//触发WM_PAINT消息
|
||||
}
|
||||
|
||||
// 把远程光标的位置/类型同步给 Web 客户端。抓屏画面本身不含光标(GDI/DXGI 都不合成),
|
||||
// 非控制态的浏览器靠这条消息在画面上自己画一个光标。
|
||||
// 类型变化 → 立即发(force=true);
|
||||
// 位置变化 → 50ms 节流;
|
||||
// 完全静止 → 每秒重发一次,让刚打开页面的观察者也能立刻看到光标位置
|
||||
// (否则要等远程鼠标下一次移动)。
|
||||
void CScreenSpyDlg::BroadcastCursorToWeb(bool force)
|
||||
{
|
||||
if (!m_bIsWebSession || !WebService().IsRunning()) return;
|
||||
ULONGLONG now = GetTickCount64();
|
||||
ULONGLONG since = now - m_nLastCursorBroadcast;
|
||||
bool reshaped = force || m_bCursorIndex != m_bBroadcastCursorIndex;
|
||||
bool moved = m_ClientCursorPos.x != m_ptBroadcastCursor.x ||
|
||||
m_ClientCursorPos.y != m_ptBroadcastCursor.y;
|
||||
if (!reshaped) {
|
||||
if (since < 50) return; // 位置变化节流
|
||||
if (!moved && since < 1000) return; // 静止时每秒兜底一次
|
||||
}
|
||||
m_nLastCursorBroadcast = now;
|
||||
m_bBroadcastCursorIndex = m_bCursorIndex;
|
||||
m_ptBroadcastCursor = m_ClientCursorPos;
|
||||
WebService().BroadcastCursor(m_ClientID, m_bCursorIndex,
|
||||
(int)m_ClientCursorPos.x, (int)m_ClientCursorPos.y);
|
||||
}
|
||||
|
||||
VOID CScreenSpyDlg::DrawNextScreenDiff(bool keyFrame)
|
||||
{
|
||||
//该函数不是直接画到屏幕上,而是更新一下变化部分的屏幕数据然后调用
|
||||
@@ -1452,10 +1477,6 @@ VOID CScreenSpyDlg::DrawNextScreenDiff(bool keyFrame)
|
||||
m_bCursorIndex = m_ContextObject->InDeCompressedBuffer.GetBuffer(2+sizeof(POINT))[0];
|
||||
if (bOldCursorIndex != m_bCursorIndex) {
|
||||
bChange = TRUE;
|
||||
// 通知 Web 客户端光标变化 (只有 Web 会话的对话框才广播)
|
||||
if (m_bIsWebSession && WebService().IsRunning()) {
|
||||
WebService().BroadcastCursor(m_ClientID, m_bCursorIndex);
|
||||
}
|
||||
if (m_bIsCtrl && !m_bIsTraceCursor) {//替换指定窗口所属类的WNDCLASSEX结构
|
||||
HCURSOR cursor;
|
||||
if (m_bCursorIndex == 254) { // -2: 使用自定义光标
|
||||
@@ -1473,6 +1494,8 @@ VOID CScreenSpyDlg::DrawNextScreenDiff(bool keyFrame)
|
||||
#endif
|
||||
}
|
||||
}
|
||||
// 通知 Web 客户端光标位置/类型(内部按类型变化/位置节流/每秒兜底决定是否真发)
|
||||
BroadcastCursorToWeb(false);
|
||||
|
||||
// 屏幕是否变化
|
||||
if (NextScreenLength > 0) {
|
||||
@@ -1638,11 +1661,9 @@ VOID CScreenSpyDlg::DrawScrollFrame()
|
||||
m_bCursorIndex = m_ContextObject->InDeCompressedBuffer.GetBuffer(2 + sizeof(POINT))[0];
|
||||
if (bOldCursorIndex != m_bCursorIndex) {
|
||||
bChange = TRUE;
|
||||
// 通知 Web 客户端光标变化 (只有 Web 会话的对话框才广播)
|
||||
if (m_bIsWebSession && WebService().IsRunning()) {
|
||||
WebService().BroadcastCursor(m_ClientID, m_bCursorIndex);
|
||||
}
|
||||
}
|
||||
// 通知 Web 客户端光标位置/类型(内部按类型变化/位置节流/每秒兜底决定是否真发)
|
||||
BroadcastCursorToWeb(false);
|
||||
|
||||
// 读取滚动参数
|
||||
LPBYTE buffer = m_ContextObject->InDeCompressedBuffer.GetBuffer(ulHeadLength);
|
||||
|
||||
@@ -218,6 +218,10 @@ public:
|
||||
bool IsWebSession() const { return m_bIsWebSession.load(); }
|
||||
void SetWebSession(bool isWeb) { m_bIsWebSession.store(isWeb); }
|
||||
|
||||
// 把远程光标的位置/类型同步给 Web 客户端(非控制态由浏览器自己画光标)。
|
||||
// force=true 用于类型变化,跳过节流立即发送。
|
||||
void BroadcastCursorToWeb(bool force);
|
||||
|
||||
VOID SendNext(void);
|
||||
VOID OnReceiveComplete();
|
||||
HDC m_hFullDC;
|
||||
@@ -264,6 +268,9 @@ public:
|
||||
std::atomic<bool> m_bIsWebSession{false}; // True if this dialog was created by Web request (atomic for thread safety)
|
||||
std::string m_strSaveNotice; // 截图保存路径提示
|
||||
ULONGLONG m_nSaveNoticeTime = 0; // 截图提示开始时间
|
||||
ULONGLONG m_nLastCursorBroadcast = 0; // 上次向 Web 广播光标的时间(50ms 节流)
|
||||
BYTE m_bBroadcastCursorIndex = 0; // 上次广播的光标类型
|
||||
POINT m_ptBroadcastCursor = {0, 0}; // 上次广播的光标位置
|
||||
BOOL m_bUsingFRP = FALSE;
|
||||
|
||||
// 文件接收进度对话框(用于 Linux Ctrl+C -> 服务端 Ctrl+V)
|
||||
|
||||
@@ -75,6 +75,31 @@ KeyFmt DetectKeyFormat(const std::string& keyPem)
|
||||
return KF_PKCS1;
|
||||
return KF_UNKNOWN;
|
||||
}
|
||||
|
||||
// 证书文件里可能有多个 PEM 块(fullchain:叶证书 + 中间证书)。逐块切出来解码,
|
||||
// 顺序即文件顺序。单证书文件也走这里(返回 1 块)。
|
||||
std::vector<std::vector<BYTE>> PemToDerList(const std::string& pem)
|
||||
{
|
||||
static const std::string kBegin = "-----BEGIN CERTIFICATE-----";
|
||||
static const std::string kEnd = "-----END CERTIFICATE-----";
|
||||
std::vector<std::vector<BYTE>> out;
|
||||
size_t pos = 0;
|
||||
while (true)
|
||||
{
|
||||
size_t b = pem.find(kBegin, pos);
|
||||
if (b == std::string::npos)
|
||||
break;
|
||||
size_t e = pem.find(kEnd, b);
|
||||
if (e == std::string::npos)
|
||||
break;
|
||||
e += kEnd.size();
|
||||
std::vector<BYTE> der;
|
||||
if (PemToDer(pem.substr(b, e - b), der) && !der.empty())
|
||||
out.push_back(std::move(der));
|
||||
pos = e;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
// =====================================================================================
|
||||
@@ -143,7 +168,35 @@ bool ServerTlsIdentity::Load(config& cfg)
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ServerTlsIdentity::LoadIdentity(const std::string& certPath, const std::string& keyPath)
|
||||
namespace
|
||||
{
|
||||
// 用证书上下文换入站凭据:显式指定服务端证书,不请求客户端证书(单向 TLS)。
|
||||
// 单独成函数,因为 EC 键的几种绑定方式都要靠「凭据能否建立」来验证。
|
||||
SECURITY_STATUS AcquireInboundCredFor(PCCERT_CONTEXT cert, CredHandle& cred)
|
||||
{
|
||||
SCHANNEL_CRED sc = {};
|
||||
sc.dwVersion = SCHANNEL_CRED_VERSION;
|
||||
sc.cCreds = 1;
|
||||
sc.paCred = &cert;
|
||||
sc.grbitEnabledProtocols = SP_PROT_TLS1_2_SERVER;
|
||||
// NO_DEFAULT_CREDS 避免回退到系统默认凭据,确保只用我们提供的证书/私钥。
|
||||
//(单向 TLS 不请求客户端证书,故无需 SCH_CRED_MANUAL_CRED_VALIDATION。)
|
||||
sc.dwFlags = SCH_CRED_NO_DEFAULT_CREDS;
|
||||
|
||||
cred = {};
|
||||
TimeStamp tsExpiry = {};
|
||||
return AcquireCredentialsHandleA(
|
||||
NULL, (SEC_CHAR*)"Microsoft Unified Security Protocol Provider", SECPKG_CRED_INBOUND,
|
||||
NULL, &sc, NULL, NULL, &cred, &tsExpiry);
|
||||
}
|
||||
|
||||
// 按给定 PEM(证书链 + PKCS#8 私钥)与 CNG 持久化键名构造一份入站身份。
|
||||
// 设备端口(ServerTlsIdentity,键名 YamaServerTlsKey)与 MCP 前端(独立键名)共用这段
|
||||
// 逻辑;键名不同则两份身份可并存,互不覆盖。
|
||||
// 成功时 outCred / outCert / outKey 均有效,生命周期由调用方释放。
|
||||
bool BuildIdentity(const std::string& certPath, const std::string& keyPath,
|
||||
const wchar_t* keyName,
|
||||
CredHandle& outCred, PCCERT_CONTEXT& outCert, NCRYPT_KEY_HANDLE& outKey)
|
||||
{
|
||||
std::string certPem, keyPem;
|
||||
if (!ReadFileText(certPath, certPem))
|
||||
@@ -157,28 +210,100 @@ bool ServerTlsIdentity::LoadIdentity(const std::string& certPath, const std::str
|
||||
return false;
|
||||
}
|
||||
|
||||
// 1) 证书:PEM → DER → PCCERT_CONTEXT。
|
||||
std::vector<BYTE> certDer;
|
||||
if (!PemToDer(certPem, certDer))
|
||||
// 1) 证书:PEM → DER → PCCERT_CONTEXT(第一块为叶证书)。
|
||||
std::vector<std::vector<BYTE>> certDers = PemToDerList(certPem);
|
||||
if (certDers.empty())
|
||||
{
|
||||
Mprintf("[TLS] FATAL: cert file %s is not a valid PEM\n", certPath.c_str());
|
||||
return false;
|
||||
}
|
||||
PCCERT_CONTEXT cert = CertCreateCertificateContext(X509_ASN_ENCODING,
|
||||
certDer.data(), (DWORD)certDer.size());
|
||||
certDers[0].data(), (DWORD)certDers[0].size());
|
||||
if (cert == NULL)
|
||||
{
|
||||
Mprintf("[TLS] FATAL: CertCreateCertificateContext failed (%u)\n", GetLastError());
|
||||
return false;
|
||||
}
|
||||
// fullchain 里剩下的中间证书要补进「当前用户\中间证书颁发机构」库里:Schannel 的
|
||||
// 握手在进程外完成,建链时只查系统证书库——塞进叶证书自带的内存库或 paCred 数组都
|
||||
// 不会被下发(实测只发叶证书,缺中间证书的客户端建链失败)。补进库里之后 Schannel
|
||||
// 会随握手把整条链下发,这与 .NET SslStreamCertificateContext 的做法一致。
|
||||
// 已经是公开信息,留在库里无害;已在库中则跳过。
|
||||
for (size_t i = 1; i < certDers.size(); ++i)
|
||||
{
|
||||
PCCERT_CONTEXT chainCert = CertCreateCertificateContext(
|
||||
X509_ASN_ENCODING, certDers[i].data(), (DWORD)certDers[i].size());
|
||||
if (chainCert == NULL)
|
||||
{
|
||||
Mprintf("[TLS] WARN: chain cert #%u in %s is unreadable (%u); "
|
||||
"handshake will only send the certificates already in the store\n",
|
||||
(unsigned)i, certPath.c_str(), GetLastError());
|
||||
continue;
|
||||
}
|
||||
static HCERTSTORE s_caStore = NULL; // 进程级;关掉反而让 Schannel 后续取不到
|
||||
if (s_caStore == NULL)
|
||||
s_caStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_W, 0, 0,
|
||||
CERT_SYSTEM_STORE_CURRENT_USER, L"CA");
|
||||
bool inStore = s_caStore != NULL &&
|
||||
CertFindCertificateInStore(s_caStore, X509_ASN_ENCODING, 0,
|
||||
CERT_FIND_EXISTING, chainCert, NULL) != NULL;
|
||||
if (!inStore &&
|
||||
(s_caStore == NULL ||
|
||||
!CertAddEncodedCertificateToStore(s_caStore, X509_ASN_ENCODING,
|
||||
certDers[i].data(), (DWORD)certDers[i].size(),
|
||||
CERT_STORE_ADD_USE_EXISTING, NULL)))
|
||||
{
|
||||
Mprintf("[TLS] WARN: cannot add chain cert #%u from %s to the user CA store (%u); "
|
||||
"handshake may not send the full chain\n",
|
||||
(unsigned)i, certPath.c_str(), GetLastError());
|
||||
}
|
||||
CertFreeCertificateContext(chainCert);
|
||||
}
|
||||
|
||||
// 2) 私钥:PEM → DER → 持久化到 CNG KSP(仅支持 PKCS#8;PKCS#1 给出可操作的转换提示)。
|
||||
//
|
||||
// 关键:Schannel 入站凭据(AcquireCredentialsHandle)需要「能按名重开」的持久化私钥。
|
||||
// NCryptImportKey 产出的是匿名临时键,绑定 CERT_NCRYPT_KEY_HANDLE_PROP_ID 后 Schannel 仍
|
||||
// 拿不到(AcquireCredentialsHandle 返回 SEC_E_NO_CREDENTIALS 0x8009030e)。因此先把
|
||||
// PKCS#8 导入为临时键、导出为裸 RSA 私钥 BLOB(NCryptSetProperty 只认裸 BLOB,不认
|
||||
// PKCS#8),再写入持久化键并 finalize,最后用 CERT_KEY_PROV_INFO_PROP_ID 按名引用。
|
||||
// 匿名临时键不行:绑定 CERT_NCRYPT_KEY_HANDLE_PROP_ID 或 CERT_KEY_CONTEXT_PROP_ID
|
||||
// 后 Schannel 仍拿不到(AcquireCredentialsHandle 返回 SEC_E_NO_CREDENTIALS 0x8009030e)。
|
||||
// 最后由 CERT_KEY_PROV_INFO_PROP_ID 按名引用持久化键。
|
||||
//
|
||||
// 私钥类型沿用证书公钥类型(早期版本写死 RSA,对 Let's Encrypt 现默认的 ECDSA 证书
|
||||
// 导裸 BLOB 会拿 NTE_BAD_TYPE 0x8009000a,必须按 EC BLOB 导出)。判断用证书而不是
|
||||
// NCryptGetProperty(BCRYPT_ALGORITHM_NAME):导入的临时键不支持该属性(实测
|
||||
// NTE_NOT_SUPPORTED 0x80090029);且私钥本就该与证书匹配。
|
||||
const char* certKeyOid = cert->pCertInfo->SubjectPublicKeyInfo.Algorithm.pszObjId;
|
||||
const bool certKeyIsRsa = certKeyOid && strcmp(certKeyOid, szOID_RSA_RSA) == 0;
|
||||
const bool certKeyIsEc = certKeyOid && strcmp(certKeyOid, szOID_ECC_PUBLIC_KEY) == 0;
|
||||
if (!certKeyIsRsa && !certKeyIsEc)
|
||||
{
|
||||
Mprintf("[TLS] FATAL: cert %s uses unsupported public key type (%s); "
|
||||
"RSA and ECDSA (P-256/P-384/P-521) are supported\n",
|
||||
certPath.c_str(), certKeyOid ? certKeyOid : "unknown");
|
||||
CertFreeCertificateContext(cert);
|
||||
return false;
|
||||
}
|
||||
|
||||
// ECDSA 只支持具名曲线:曲线在证书公钥参数里是 DER 编码的曲线 OID,先核对一遍,
|
||||
// 好给出比 KSP 报错更清楚的提示(显式参数形式的曲线 KSP 也不吃)。
|
||||
if (certKeyIsEc)
|
||||
{
|
||||
static const BYTE kP256[] = { 0x06,0x08,0x2A,0x86,0x48,0xCE,0x3D,0x03,0x01,0x07 };
|
||||
static const BYTE kP384[] = { 0x06,0x05,0x2B,0x81,0x04,0x00,0x22 };
|
||||
static const BYTE kP521[] = { 0x06,0x05,0x2B,0x81,0x04,0x00,0x23 };
|
||||
const CRYPT_OBJID_BLOB& parm = cert->pCertInfo->SubjectPublicKeyInfo.Algorithm.Parameters;
|
||||
auto isCurve = [&](const BYTE* der, DWORD len) {
|
||||
return parm.cbData == len && parm.pbData && memcmp(parm.pbData, der, len) == 0;
|
||||
};
|
||||
if (!isCurve(kP256, sizeof(kP256)) && !isCurve(kP384, sizeof(kP384)) &&
|
||||
!isCurve(kP521, sizeof(kP521)))
|
||||
{
|
||||
Mprintf("[TLS] FATAL: cert %s uses an ECDSA curve other than P-256/P-384/P-521 "
|
||||
"(or explicit curve parameters); convert it to an RSA or named-curve key\n",
|
||||
certPath.c_str());
|
||||
CertFreeCertificateContext(cert);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
std::vector<BYTE> keyDer;
|
||||
NCRYPT_KEY_HANDLE persistedKey = 0;
|
||||
if (DetectKeyFormat(keyPem) == KF_PKCS8)
|
||||
@@ -201,37 +326,67 @@ bool ServerTlsIdentity::LoadIdentity(const std::string& certPath, const std::str
|
||||
return false;
|
||||
}
|
||||
|
||||
// 2a) PKCS#8 → 临时键。
|
||||
NCRYPT_KEY_HANDLE tmp = 0;
|
||||
st = NCryptImportKey(hProv, NULL, NCRYPT_PKCS8_PRIVATE_KEY_BLOB, NULL,
|
||||
&tmp, keyDer.data(), (DWORD)keyDer.size(), 0);
|
||||
if (st == ERROR_SUCCESS)
|
||||
// EC 与 RSA 的落盘路径不同:
|
||||
// - EC:MS Software KSP 唯一支持的「导入私钥并落盘」方式,是在导入参数表里给出
|
||||
// 键名(NCRYPTBUFFER_PKCS_KEY_NAME)——不带键名一律按匿名临时键处理。同为导入
|
||||
// 后的持久化,CreatePersistedKey 后写私钥 BLOB 虽然 SetProperty 返回 0,Finalize
|
||||
// 却给 NTE_INVALID_PARAMETER(0x80090027);导入后再
|
||||
// NCryptSetProperty(NCRYPT_NAME_PROPERTY) 给 NTE_NOT_SUPPORTED(0x80090029)。
|
||||
// - RSA:导入为临时键 → 导出裸私钥 BLOB(NCryptSetProperty 只认裸 BLOB,不认
|
||||
// PKCS#8)→ 写入持久化键 → finalize。
|
||||
if (certKeyIsEc)
|
||||
{
|
||||
// 2b) 允许明文导出,导出为裸 RSA 私钥 BLOB。
|
||||
DWORD policy = NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG | NCRYPT_ALLOW_EXPORT_FLAG;
|
||||
NCryptSetProperty(tmp, NCRYPT_EXPORT_POLICY_PROPERTY, (PBYTE)&policy, sizeof(policy), 0);
|
||||
std::wstring nameW(keyName);
|
||||
NCryptBuffer nameBuf = {};
|
||||
nameBuf.cbBuffer = (ULONG)((nameW.size() + 1) * sizeof(WCHAR));
|
||||
nameBuf.BufferType = NCRYPTBUFFER_PKCS_KEY_NAME;
|
||||
nameBuf.pvBuffer = (PVOID)nameW.c_str();
|
||||
NCryptBufferDesc desc = {};
|
||||
desc.ulVersion = NCRYPTBUFFER_VERSION;
|
||||
desc.cBuffers = 1;
|
||||
desc.pBuffers = &nameBuf;
|
||||
|
||||
std::vector<BYTE> raw;
|
||||
DWORD rawLen = 0;
|
||||
st = NCryptExportKey(tmp, NULL, BCRYPT_RSAFULLPRIVATE_BLOB, NULL, NULL, 0, &rawLen, 0);
|
||||
st = NCryptImportKey(hProv, NULL, NCRYPT_PKCS8_PRIVATE_KEY_BLOB, &desc,
|
||||
&persistedKey, keyDer.data(), (DWORD)keyDer.size(),
|
||||
NCRYPT_OVERWRITE_KEY_FLAG);
|
||||
}
|
||||
else
|
||||
{
|
||||
NCRYPT_KEY_HANDLE tmp = 0;
|
||||
st = NCryptImportKey(hProv, NULL, NCRYPT_PKCS8_PRIVATE_KEY_BLOB, NULL,
|
||||
&tmp, keyDer.data(), (DWORD)keyDer.size(), 0);
|
||||
if (st == ERROR_SUCCESS)
|
||||
{
|
||||
raw.resize(rawLen);
|
||||
DWORD policy = NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG | NCRYPT_ALLOW_EXPORT_FLAG;
|
||||
NCryptSetProperty(tmp, NCRYPT_EXPORT_POLICY_PROPERTY,
|
||||
(PBYTE)&policy, sizeof(policy), 0);
|
||||
|
||||
std::vector<BYTE> raw;
|
||||
DWORD rawLen = 0;
|
||||
st = NCryptExportKey(tmp, NULL, BCRYPT_RSAFULLPRIVATE_BLOB, NULL,
|
||||
raw.data(), rawLen, &rawLen, 0);
|
||||
NULL, 0, &rawLen, 0);
|
||||
if (st == ERROR_SUCCESS)
|
||||
{
|
||||
raw.resize(rawLen);
|
||||
st = NCryptExportKey(tmp, NULL, BCRYPT_RSAFULLPRIVATE_BLOB, NULL,
|
||||
raw.data(), rawLen, &rawLen, 0);
|
||||
}
|
||||
if (st == ERROR_SUCCESS)
|
||||
{
|
||||
st = NCryptCreatePersistedKey(hProv, &persistedKey, BCRYPT_RSA_ALGORITHM,
|
||||
keyName, AT_KEYEXCHANGE,
|
||||
NCRYPT_OVERWRITE_KEY_FLAG);
|
||||
}
|
||||
if (st == ERROR_SUCCESS)
|
||||
{
|
||||
st = NCryptSetProperty(persistedKey, BCRYPT_RSAFULLPRIVATE_BLOB,
|
||||
raw.data(), (DWORD)raw.size(), 0);
|
||||
}
|
||||
if (st == ERROR_SUCCESS)
|
||||
st = NCryptFinalizeKey(persistedKey, 0);
|
||||
|
||||
NCryptFreeObject(tmp);
|
||||
}
|
||||
|
||||
// 2c) 写入持久化键并 finalize(落到 KSP,可被 Schannel 按名重开)。
|
||||
if (st == ERROR_SUCCESS)
|
||||
st = NCryptCreatePersistedKey(hProv, &persistedKey, BCRYPT_RSA_ALGORITHM,
|
||||
g_keyName, AT_KEYEXCHANGE, NCRYPT_OVERWRITE_KEY_FLAG);
|
||||
if (st == ERROR_SUCCESS)
|
||||
st = NCryptSetProperty(persistedKey, BCRYPT_RSAFULLPRIVATE_BLOB,
|
||||
raw.data(), (DWORD)raw.size(), 0);
|
||||
if (st == ERROR_SUCCESS)
|
||||
st = NCryptFinalizeKey(persistedKey, 0);
|
||||
|
||||
NCryptFreeObject(tmp);
|
||||
}
|
||||
NCryptFreeObject(hProv);
|
||||
|
||||
@@ -257,54 +412,55 @@ bool ServerTlsIdentity::LoadIdentity(const std::string& certPath, const std::str
|
||||
|
||||
// 3) 绑定私钥到证书上下文:按名引用持久化键。Schannel 经 CryptAcquireCertificatePrivateKey
|
||||
// 在 MS_KEY_STORAGE_PROVIDER 里用 pwszContainerName 重开该键。
|
||||
// 4) 换入站凭据(单向 TLS,不请求客户端证书)。
|
||||
CRYPT_KEY_PROV_INFO provInfo = {};
|
||||
provInfo.pwszContainerName = (LPWSTR)g_keyName;
|
||||
provInfo.pwszContainerName = (LPWSTR)keyName;
|
||||
provInfo.pwszProvName = (LPWSTR)MS_KEY_STORAGE_PROVIDER;
|
||||
provInfo.dwProvType = 0; // 0 = CNG(无 CAPI provider type)
|
||||
provInfo.dwKeySpec = AT_KEYEXCHANGE;
|
||||
provInfo.dwKeySpec = certKeyIsEc ? 0 : AT_KEYEXCHANGE; // ECDSA 键无 legacy key spec
|
||||
|
||||
CredHandle cred = {};
|
||||
SECURITY_STATUS st = SEC_E_NO_CREDENTIALS;
|
||||
if (!CertSetCertificateContextProperty(cert, CERT_KEY_PROV_INFO_PROP_ID, 0, &provInfo))
|
||||
{
|
||||
st = (SECURITY_STATUS)HRESULT_FROM_WIN32(GetLastError());
|
||||
Mprintf("[TLS] FATAL: CertSetCertificateContextProperty(CERT_KEY_PROV_INFO_PROP_ID) "
|
||||
"failed (%u)\n", GetLastError());
|
||||
NCryptDeleteKey(persistedKey, 0); // 删除并释放句柄
|
||||
CertFreeCertificateContext(cert);
|
||||
return false;
|
||||
"failed 0x%08x\n", (unsigned)st);
|
||||
}
|
||||
else
|
||||
{
|
||||
st = AcquireInboundCredFor(cert, cred);
|
||||
}
|
||||
// 绑定后持久化键句柄交进程级 g_persistedKey,随 FreeIdentity 删除(覆盖旧键,避免残留)。
|
||||
g_persistedKey = persistedKey;
|
||||
|
||||
// 4) 入站凭据:显式指定服务端证书,不请求客户端证书(单向 TLS)。
|
||||
SCHANNEL_CRED sc = {};
|
||||
sc.dwVersion = SCHANNEL_CRED_VERSION;
|
||||
sc.cCreds = 1;
|
||||
sc.paCred = &cert;
|
||||
sc.grbitEnabledProtocols = SP_PROT_TLS1_2_SERVER;
|
||||
// NO_DEFAULT_CREDS 避免回退到系统默认凭据,确保只用我们提供的证书/私钥。
|
||||
//(单向 TLS 不请求客户端证书,故无需 SCH_CRED_MANUAL_CRED_VALIDATION。)
|
||||
sc.dwFlags = SCH_CRED_NO_DEFAULT_CREDS;
|
||||
|
||||
TimeStamp tsExpiry = {};
|
||||
SECURITY_STATUS st = AcquireCredentialsHandleA(
|
||||
NULL, (SEC_CHAR*)"Microsoft Unified Security Protocol Provider", SECPKG_CRED_INBOUND,
|
||||
NULL, &sc, NULL, NULL, &g_cred, &tsExpiry);
|
||||
|
||||
if (st != SEC_E_OK)
|
||||
{
|
||||
Mprintf("[TLS] FATAL: AcquireCredentialsHandle(SECPKG_CRED_INBOUND) failed 0x%08x\n",
|
||||
(unsigned)st);
|
||||
CertFreeCertificateContext(cert); // 无凭据引用,安全释放
|
||||
g_cred = {};
|
||||
if (g_persistedKey) // 回滚:删除已持久化的私钥,避免残留
|
||||
{
|
||||
NCryptDeleteKey(g_persistedKey, 0); // 删除并释放句柄
|
||||
g_persistedKey = 0;
|
||||
}
|
||||
NCryptDeleteKey(persistedKey, 0); // 回滚:删除已持久化的私钥,避免残留
|
||||
return false;
|
||||
}
|
||||
|
||||
outCert = cert;
|
||||
outKey = persistedKey;
|
||||
outCred = cred;
|
||||
return true;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
bool ServerTlsIdentity::LoadIdentity(const std::string& certPath, const std::string& keyPath)
|
||||
{
|
||||
CredHandle cred = {};
|
||||
PCCERT_CONTEXT cert = NULL;
|
||||
NCRYPT_KEY_HANDLE key = 0;
|
||||
if (!BuildIdentity(certPath, keyPath, g_keyName, cred, cert, key))
|
||||
return false;
|
||||
|
||||
// 成功:把证书上下文生命周期交给进程级 g_cert,随 FreeIdentity 释放,
|
||||
// 保证在 FreeCredentialsHandle 之前私钥一直可用。
|
||||
g_cred = cred;
|
||||
g_cert = cert;
|
||||
g_persistedKey = key;
|
||||
g_credValid = true;
|
||||
return true;
|
||||
}
|
||||
@@ -385,25 +541,89 @@ bool ServerTlsSession::SendAll(SOCKET sock, const void* data, int len)
|
||||
}
|
||||
|
||||
bool ServerTlsSession::Handshake(SOCKET sock, const BYTE* initial, int initialLen)
|
||||
{
|
||||
return HandshakeWithCred(sock, initial, initialLen, ServerTlsIdentity::Cred());
|
||||
}
|
||||
|
||||
bool ServerTlsSession::HandshakeWithCred(SOCKET sock, const BYTE* initial, int initialLen,
|
||||
CredHandle cred)
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(m_mtx);
|
||||
if (m_ctxValid)
|
||||
CloseHandles(); // 防御:会话应只握手一次
|
||||
|
||||
CredHandle cred = ServerTlsIdentity::Cred();
|
||||
|
||||
// 单向 TLS:服务端不请求客户端证书,故无需 ASC_REQ_MANUAL_CRED_VALIDATION
|
||||
//(该标志只在 mTLS 校验客户端证书时有意义;SDK 的 ASC 命名空间里亦无此常量)。
|
||||
DWORD req = ASC_REQ_SEQUENCE_DETECT | ASC_REQ_REPLAY_DETECT | ASC_REQ_CONFIDENTIALITY |
|
||||
ASC_REQ_ALLOCATE_MEMORY | ASC_REQ_STREAM;
|
||||
|
||||
std::vector<BYTE> hs(initial, initial + initialLen);
|
||||
std::vector<BYTE> hs;
|
||||
if (initial != NULL && initialLen > 0)
|
||||
hs.assign(initial, initial + initialLen);
|
||||
CtxtHandle ctx = {};
|
||||
bool ctxValid = false;
|
||||
TimeStamp tsExpiry = {};
|
||||
ULONG attrs = 0;
|
||||
SECURITY_STATUS sc = SEC_I_CONTINUE_NEEDED;
|
||||
|
||||
// 握手期间同步收字节:非阻塞套接字上等可读再收,避免误判为致命错误。
|
||||
auto RecvMore = [&](std::vector<BYTE>& buf) -> bool
|
||||
{
|
||||
char raw[8192];
|
||||
int r;
|
||||
for (;;)
|
||||
{
|
||||
r = recv(sock, raw, sizeof(raw), 0);
|
||||
if (r == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
|
||||
{
|
||||
if (!WaitSocketReady(sock, true, 15000))
|
||||
{
|
||||
r = SOCKET_ERROR;
|
||||
break; // 等可读超时
|
||||
}
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (r <= 0)
|
||||
{
|
||||
Mprintf("[TLS] handshake recv failed/EOF (r=%d err=%d)\n", r, WSAGetLastError());
|
||||
return false;
|
||||
}
|
||||
buf.insert(buf.end(), (BYTE*)raw, (BYTE*)raw + r);
|
||||
return true;
|
||||
};
|
||||
|
||||
// 首次 AcceptSecurityContext 之前必须凑齐一整条 TLS 记录(5 字节头 + 负载)。
|
||||
// 实测(2026-10-26):用「半条 ClientHello」做首次调用,Schannel 会建出一个坏上下文,
|
||||
// 之后补齐数据再送返回 SEC_E_UNKNOWN_CREDENTIALS(0x80090301),握手必失败。设备端口
|
||||
// 一直整包到达所以没暴露;MCP TLS 前端按 8 字节嗅探后接手,稳定触发。故在此统一兜底:
|
||||
// 调用方给多少都行,缺的字节由本函数从 socket 补齐。
|
||||
for (;;)
|
||||
{
|
||||
if (hs.size() < 5)
|
||||
{
|
||||
if (!RecvMore(hs))
|
||||
return false;
|
||||
continue;
|
||||
}
|
||||
if (hs[0] != 0x16)
|
||||
{
|
||||
Mprintf("[TLS] handshake: first byte 0x%02x is not a handshake record; fail-closed\n", hs[0]);
|
||||
return false;
|
||||
}
|
||||
const size_t recLen = 5 + (((size_t)hs[3] << 8) | (size_t)hs[4]);
|
||||
if (recLen > 18432) // TLS 记录上限 16384 + 允许的额外开销
|
||||
{
|
||||
Mprintf("[TLS] handshake: absurd record length %u; fail-closed\n", (unsigned)recLen);
|
||||
return false;
|
||||
}
|
||||
if (hs.size() >= recLen)
|
||||
break;
|
||||
if (!RecvMore(hs))
|
||||
return false;
|
||||
}
|
||||
|
||||
for (;;)
|
||||
{
|
||||
SecBuffer inBufs[2] = {
|
||||
@@ -454,29 +674,11 @@ bool ServerTlsSession::Handshake(SOCKET sock, const BYTE* initial, int initialLe
|
||||
break; // 真正的失败
|
||||
}
|
||||
|
||||
char raw[8192];
|
||||
int r;
|
||||
for (;;)
|
||||
if (!RecvMore(hs))
|
||||
{
|
||||
r = recv(sock, raw, sizeof(raw), 0);
|
||||
if (r == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
|
||||
{
|
||||
if (!WaitSocketReady(sock, true, 15000))
|
||||
{
|
||||
r = SOCKET_ERROR;
|
||||
break; // 等可读超时
|
||||
}
|
||||
continue; // 非阻塞套接字暂无数据:等可读后重试
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (r <= 0)
|
||||
{
|
||||
Mprintf("[TLS] handshake recv failed/EOF (r=%d err=%d)\n", r, WSAGetLastError());
|
||||
sc = SEC_E_INTERNAL_ERROR;
|
||||
break;
|
||||
}
|
||||
hs.insert(hs.end(), (BYTE*)raw, (BYTE*)raw + r);
|
||||
}
|
||||
|
||||
if (sc != SEC_E_OK)
|
||||
@@ -512,11 +714,14 @@ int ServerTlsSession::Decrypt(const BYTE* cipher, int len, std::vector<BYTE>& pl
|
||||
std::lock_guard<std::mutex> lk(m_mtx);
|
||||
if (!m_ready)
|
||||
return -1;
|
||||
if (len <= 0)
|
||||
// len == 0 表示「只取残留」:握手结束时会话里可能已经躺着紧随 Finished 的首条
|
||||
// 应用数据(见 HandshakeWithCred 末尾),调用方必须在进入收发循环前取一次,
|
||||
// 否则这份数据要等下一条密文到达才会被解出来。
|
||||
if (len > 0)
|
||||
m_raw.insert(m_raw.end(), cipher, cipher + len);
|
||||
if (m_raw.empty())
|
||||
return 0;
|
||||
|
||||
m_raw.insert(m_raw.end(), cipher, cipher + len);
|
||||
|
||||
for (;;)
|
||||
{
|
||||
SecBuffer bufs[4] = {
|
||||
@@ -602,3 +807,42 @@ void CONTEXT_OBJECT::FreeTls()
|
||||
delete tls;
|
||||
tls = NULL;
|
||||
}
|
||||
|
||||
// =====================================================================================
|
||||
// 额外入站身份(MCP 等第二套证书)
|
||||
// =====================================================================================
|
||||
|
||||
bool ServerTlsLoadIdentityFromPem(const std::string& certPath, const std::string& keyPath,
|
||||
const wchar_t* keyName, ServerTlsExtraIdentity& out)
|
||||
{
|
||||
CredHandle cred = {};
|
||||
PCCERT_CONTEXT cert = NULL;
|
||||
NCRYPT_KEY_HANDLE key = 0;
|
||||
if (!BuildIdentity(certPath, keyPath, keyName, cred, cert, key))
|
||||
return false;
|
||||
|
||||
out.cred = cred;
|
||||
out.cert = cert;
|
||||
out.key = (ULONG_PTR)key;
|
||||
return true;
|
||||
}
|
||||
|
||||
void ServerTlsFreeIdentity(ServerTlsExtraIdentity& id)
|
||||
{
|
||||
// 顺序同 ServerTlsIdentity::FreeIdentity:凭据 → 证书 → 持久化私钥。
|
||||
if (id.cred.dwLower || id.cred.dwUpper)
|
||||
{
|
||||
FreeCredentialsHandle(&id.cred);
|
||||
id.cred = {};
|
||||
}
|
||||
if (id.cert)
|
||||
{
|
||||
CertFreeCertificateContext(id.cert);
|
||||
id.cert = NULL;
|
||||
}
|
||||
if (id.key)
|
||||
{
|
||||
NCryptDeleteKey((NCRYPT_KEY_HANDLE)id.key, 0);
|
||||
id.key = 0;
|
||||
}
|
||||
}
|
||||
@@ -54,6 +54,27 @@ private:
|
||||
static bool LoadIdentity(const std::string& certPath, const std::string& keyPath);
|
||||
};
|
||||
|
||||
// ---- 额外入站身份(MCP 等第二套证书)----
|
||||
//
|
||||
// 进程级身份 ServerTlsIdentity 只服务设备端口,证书由 [tls] 指定(通常是自签
|
||||
// CN=localhost)。MCP 要暴露给公网客户端,必须用公共 CA 签发的证书,故需要第二份
|
||||
// 身份。两者可并存:证书/私钥各自加载,持久化私钥用不同的键名(keyName)分开存放,
|
||||
// 不会互相覆盖。调用方负责在停止时调用 ServerTlsFreeIdentity。
|
||||
struct ServerTlsExtraIdentity
|
||||
{
|
||||
CredHandle cred = {}; // AcquireCredentialsHandle 产出的入站凭据
|
||||
PCCERT_CONTEXT cert = NULL; // 凭据按名引用的证书上下文
|
||||
ULONG_PTR key = 0; // NCrypt 持久化私钥句柄(NCRYPT_KEY_HANDLE)
|
||||
};
|
||||
|
||||
// 从 PEM(证书链 + PKCS#8 私钥)构造一份独立入站身份。keyName 为 CNG 持久化键名,
|
||||
// 须与其它身份不同(例如 L"YamaServerTlsKey" / L"YamaMcpTlsKey")。
|
||||
bool ServerTlsLoadIdentityFromPem(const std::string& certPath, const std::string& keyPath,
|
||||
const wchar_t* keyName, ServerTlsExtraIdentity& out);
|
||||
|
||||
// 释放 ServerTlsLoadIdentityFromPem 构造的身份(先凭据、再证书、最后删除持久化私钥)。
|
||||
void ServerTlsFreeIdentity(ServerTlsExtraIdentity& id);
|
||||
|
||||
// ---- 单连接服务端 TLS 会话(握手 + 加解密)----
|
||||
class ServerTlsSession
|
||||
{
|
||||
@@ -69,7 +90,13 @@ public:
|
||||
// 成功返回 true,失败 false(调用方关闭连接,fail-closed)。
|
||||
bool Handshake(SOCKET sock, const BYTE* initial, int initialLen);
|
||||
|
||||
// 同上,但使用调用方提供的入站凭据(MCP TLS 前端用独立的第二份身份,
|
||||
// 见 ServerTlsLoadIdentityFromPem)。
|
||||
bool HandshakeWithCred(SOCKET sock, const BYTE* initial, int initialLen, CredHandle cred);
|
||||
|
||||
// 解密:把本次 WSARecv 收到的密文 cipher[0..len] 喂入,把能解出的明文追加到 plain。
|
||||
// len == 0 表示只解出会话里已缓存的密文(握手结束后必须先取一次,否则紧随 Finished
|
||||
// 到达的首条应用数据会一直躺着,直到客户端再发一包)。
|
||||
// 返回 0 = 成功(可能无明文);-1 = 错误 / 对端 close_notify(调用方关闭连接)。
|
||||
int Decrypt(const BYTE* cipher, int len, std::vector<BYTE>& plain);
|
||||
|
||||
|
||||
@@ -2344,7 +2344,7 @@ void CWebService::NotifyAudioState(uint64_t device_id, bool enabled) {
|
||||
}
|
||||
}
|
||||
|
||||
void CWebService::BroadcastCursor(uint64_t device_id, uint8_t cursor_index) {
|
||||
void CWebService::BroadcastCursor(uint64_t device_id, uint8_t cursor_index, int x, int y) {
|
||||
if (m_bStopping) return;
|
||||
|
||||
// Build JSON message
|
||||
@@ -2352,6 +2352,9 @@ void CWebService::BroadcastCursor(uint64_t device_id, uint8_t cursor_index) {
|
||||
res["cmd"] = "cursor";
|
||||
res["id"] = std::to_string(device_id);
|
||||
res["index"] = cursor_index;
|
||||
// 位置是发送位图(即浏览器 canvas)坐标系;老页面忽略这两个字段。
|
||||
res["x"] = x;
|
||||
res["y"] = y;
|
||||
|
||||
Json::StreamWriterBuilder builder;
|
||||
builder["indentation"] = "";
|
||||
|
||||
@@ -167,8 +167,11 @@ public:
|
||||
// clients watching this device and caches it for newcomers.
|
||||
void NotifyAudioState(uint64_t device_id, bool enabled);
|
||||
|
||||
// Cursor change notification (called from ScreenSpyDlg)
|
||||
void BroadcastCursor(uint64_t device_id, uint8_t cursor_index);
|
||||
// Cursor notification (called from ScreenSpyDlg): the shape index plus the
|
||||
// position in the transmitted frame's coordinate space. The browser draws
|
||||
// the remote cursor itself while it is not in control mode — the captured
|
||||
// frames never contain one.
|
||||
void BroadcastCursor(uint64_t device_id, uint8_t cursor_index, int x, int y);
|
||||
|
||||
// 远程剪贴板文本回传通知(called from ScreenSpyDlg,payload 为 UTF-8)
|
||||
void NotifyClipboardText(uint64_t device_id, const std::string& text);
|
||||
|
||||
@@ -81,6 +81,14 @@ public:
|
||||
return (strtoul(caps.GetString(), nullptr, 16) & CLIENT_CAP_UTF8) != 0;
|
||||
}
|
||||
|
||||
// 检查客户端是否支持按服务端给出的路径清单向另一客户端发送文件(COMMAND_C2C_SEND_FILES)。
|
||||
// 只有 Windows 客户端实现该命令,老客户端无此能力位 → 服务端据此在 MCP 侧提前拒绝。
|
||||
bool SupportsC2CPaths() const {
|
||||
CString caps = GetClientData(ONLINELIST_CAPABILITIES);
|
||||
if (caps.IsEmpty()) return false;
|
||||
return (strtoul(caps.GetString(), nullptr, 16) & CLIENT_CAP_C2C_PATHS) != 0;
|
||||
}
|
||||
|
||||
// 检查客户端是否支持屏幕预览(双击主机时拉缩略图)。
|
||||
bool SupportsScreenPreview() const {
|
||||
CString caps = GetClientData(ONLINELIST_CAPABILITIES);
|
||||
|
||||
@@ -2019,6 +2019,10 @@ MCPԶ
|
||||
远程交谈开关的改动需重启程序生效。=Changes to the remote chat switch take effect after restart.
|
||||
启用键盘记录(AI 采集击键)=Enable keylogger (AI keystroke capture)
|
||||
键盘记录开关的改动需重启程序生效。=Changes to the keylogger switch take effect after restart.
|
||||
启用 HTTPS(本端口同时接受 TLS 连接)=Enable HTTPS (this port also accepts TLS connections)
|
||||
HTTPS 开关与证书路径的改动需重启程序生效。=Changes to the HTTPS switch and certificate paths take effect after restart.
|
||||
证书或私钥文件不存在,请检查路径。=Certificate or private key file not found; check the path.
|
||||
证书须为 PEM 格式,私钥须为 PKCS#8 格式。=Certificate must be PEM; private key must be PKCS#8.
|
||||
主机管理的写操作需只读模式关闭;冻结/解冻进程、停止/重启服务还需启用危险主机操作。=Host management write operations require read-only mode to be off; freezing/thawing processes and stopping/restarting services also require dangerous host operations.
|
||||
第 %d 个钱包地址不合法!=Wallet address #%d is invalid!
|
||||
%d 新连接\r\n=%d New connection\r\n
|
||||
|
||||
@@ -2010,6 +2010,10 @@ MCPԶ
|
||||
远程交谈开关的改动需重启程序生效。=遠端交談開關的變更需重新啟動程式後生效。
|
||||
启用键盘记录(AI 采集击键)=啟用鍵盤記錄(AI 擷取按鍵)
|
||||
键盘记录开关的改动需重启程序生效。=鍵盤記錄開關的改動需重新啟動程式方可生效。
|
||||
启用 HTTPS(本端口同时接受 TLS 连接)=啟用 HTTPS(本連接埠同時接受 TLS 連線)
|
||||
HTTPS 开关与证书路径的改动需重启程序生效。=HTTPS 開關與憑證路徑的改動需重啟程式生效。
|
||||
证书或私钥文件不存在,请检查路径。=憑證或私鑰檔案不存在,請檢查路徑。
|
||||
证书须为 PEM 格式,私钥须为 PKCS#8 格式。=憑證須為 PEM 格式,私鑰須為 PKCS#8 格式。
|
||||
主机管理的写操作需只读模式关闭;冻结/解冻进程、停止/重启服务还需启用危险主机操作。=主機管理的寫入操作需關閉唯讀模式;凍結/解凍處理程序、停止/重新啟動服務還需啟用危險主機操作。
|
||||
第 %d 个钱包地址不合法!=第 %d 個錢包位址不合法!
|
||||
%d 新连接\r\n=%d 新連線\r\n
|
||||
|
||||
+16
-5
@@ -418,13 +418,24 @@ func (h *MyHandler) handleScreenFrame(ctx *connection.Context, data []byte, alwa
|
||||
}
|
||||
// data[0] is the token; the 11-byte header sits at data[1..12].
|
||||
const skip = 1 + protocol.ScreenFrameHeaderLen
|
||||
if len(data) <= skip {
|
||||
if len(data) < skip {
|
||||
return // truncated header
|
||||
}
|
||||
// Cursor position + index live in the per-frame header: [1]=algorithm,
|
||||
// [2..9]=POINT (x,y int32 LE), [10]=cursor index. Publish before the heavy
|
||||
// frame work so the browser sees cursor updates even if we drop the frame.
|
||||
// The position is in the captured frame's coordinate space, which is also
|
||||
// the browser canvas space — the overlay can draw it as-is.
|
||||
//
|
||||
// The client also sends header-only packets (no bitmap change) at the frame
|
||||
// rate, so this keeps a static desktop's cursor fresh for non-controlling
|
||||
// viewers; those packets carry no video and are dropped right after.
|
||||
cursorX := int(int32(binary.LittleEndian.Uint32(data[2:6])))
|
||||
cursorY := int(int32(binary.LittleEndian.Uint32(data[6:10])))
|
||||
h.hub.PublishCursor(deviceID, data[10], cursorX, cursorY)
|
||||
if len(data) == skip {
|
||||
return
|
||||
}
|
||||
// Cursor index lives at the last byte of the small per-frame header
|
||||
// (offset 1 + 1 + 8 = 10). Publish before the heavy frame work so the
|
||||
// browser sees cursor updates even if we end up dropping frames later.
|
||||
h.hub.PublishCursor(deviceID, data[10])
|
||||
|
||||
video := data[skip:]
|
||||
// 按首字节嗅探 H.264 / AV1,分发到对应的 keyframe 探测器。浏览器侧用同样方式
|
||||
|
||||
@@ -21,15 +21,15 @@ type recordedFrame struct {
|
||||
func (r *frameRecorder) OnScreenFrame(deviceID string, packet []byte, isKeyframe bool) {
|
||||
r.frames = append(r.frames, recordedFrame{deviceID, packet, isKeyframe})
|
||||
}
|
||||
func (r *frameRecorder) OnDeviceOnline(hub.DeviceInfo) {}
|
||||
func (r *frameRecorder) OnDeviceOffline(string) {}
|
||||
func (r *frameRecorder) OnDeviceUpdate(string, int, string) {}
|
||||
func (r *frameRecorder) OnResolutionChange(string, int, int) {}
|
||||
func (r *frameRecorder) OnCursorChange(string, byte) {}
|
||||
func (r *frameRecorder) OnClipboardText(string, string) {}
|
||||
func (r *frameRecorder) OnTerminalReady(string, bool) {}
|
||||
func (r *frameRecorder) OnTerminalData(string, []byte) {}
|
||||
func (r *frameRecorder) OnTerminalClosed(string, string) {}
|
||||
func (r *frameRecorder) OnDeviceOnline(hub.DeviceInfo) {}
|
||||
func (r *frameRecorder) OnDeviceOffline(string) {}
|
||||
func (r *frameRecorder) OnDeviceUpdate(string, int, string) {}
|
||||
func (r *frameRecorder) OnResolutionChange(string, int, int) {}
|
||||
func (r *frameRecorder) OnCursorChange(string, byte, int, int) {}
|
||||
func (r *frameRecorder) OnClipboardText(string, string) {}
|
||||
func (r *frameRecorder) OnTerminalReady(string, bool) {}
|
||||
func (r *frameRecorder) OnTerminalData(string, []byte) {}
|
||||
func (r *frameRecorder) OnTerminalClosed(string, string) {}
|
||||
|
||||
// TestOnReceiveRelaysKeyframeToken guards the forced-IDR recovery path: when
|
||||
// the browser asks for a keyframe, the client replies with TOKEN_KEYFRAME.
|
||||
|
||||
@@ -193,14 +193,14 @@ func (s *Store) offlineAt(id string, at time.Time) {
|
||||
}
|
||||
|
||||
// The remaining EventHandler methods are not relevant to device history.
|
||||
func (s *Store) OnDeviceUpdate(string, int, string) {}
|
||||
func (s *Store) OnScreenFrame(string, []byte, bool) {}
|
||||
func (s *Store) OnResolutionChange(string, int, int) {}
|
||||
func (s *Store) OnCursorChange(string, byte) {}
|
||||
func (s *Store) OnClipboardText(string, string) {}
|
||||
func (s *Store) OnTerminalReady(string, bool) {}
|
||||
func (s *Store) OnTerminalData(string, []byte) {}
|
||||
func (s *Store) OnTerminalClosed(string, string) {}
|
||||
func (s *Store) OnDeviceUpdate(string, int, string) {}
|
||||
func (s *Store) OnScreenFrame(string, []byte, bool) {}
|
||||
func (s *Store) OnResolutionChange(string, int, int) {}
|
||||
func (s *Store) OnCursorChange(string, byte, int, int) {}
|
||||
func (s *Store) OnClipboardText(string, string) {}
|
||||
func (s *Store) OnTerminalReady(string, bool) {}
|
||||
func (s *Store) OnTerminalData(string, []byte) {}
|
||||
func (s *Store) OnTerminalClosed(string, string) {}
|
||||
|
||||
// Offline returns the records whose IDs are not in online, newest last_seen
|
||||
// first, converted to the hub's device payload shape with Online=false.
|
||||
|
||||
+37
-14
@@ -73,11 +73,15 @@ type Device struct {
|
||||
screenHeight int
|
||||
lastKeyframe []byte // fully-packed WS binary packet of the most recent IDR
|
||||
|
||||
// Cursor index dedup: cursors arrive on every frame (~30 Hz) but only
|
||||
// rarely change. Suppress duplicates so the WS doesn't carry redundant
|
||||
// JSON messages.
|
||||
// Cursor dedup/throttle: cursors arrive on every frame (~30 Hz) and the
|
||||
// position changes most frames. An index change is published immediately
|
||||
// (the shape matters visually); a position-only change is rate-limited so
|
||||
// the WS doesn't carry 30 JSON messages per second per viewer.
|
||||
cursorSeen bool
|
||||
lastCursorIndex byte
|
||||
lastCursorX int
|
||||
lastCursorY int
|
||||
cursorPubAt time.Time
|
||||
|
||||
// Terminal session state — at most one web terminal per device (MVP
|
||||
// constraint shared with the C++ server). All three fields are
|
||||
@@ -186,10 +190,11 @@ type EventHandler interface {
|
||||
// OnResolutionChange fires when a screen session starts (TOKEN_BITMAPINFO)
|
||||
// or whenever the device reports a new screen geometry mid-stream.
|
||||
OnResolutionChange(deviceID string, width, height int)
|
||||
// OnCursorChange fires when the device's foreground cursor index changes.
|
||||
// Duplicates (same index as the previous frame) are filtered out by the
|
||||
// hub before reaching subscribers.
|
||||
OnCursorChange(deviceID string, index byte)
|
||||
// OnCursorChange fires when the device's foreground cursor changes shape or
|
||||
// moves. x/y are in the captured frame's coordinate space (== browser canvas
|
||||
// space). The hub filters duplicates and rate-limits position-only changes
|
||||
// before reaching subscribers.
|
||||
OnCursorChange(deviceID string, index byte, x, y int)
|
||||
// OnClipboardText delivers the device's clipboard text (already UTF-8),
|
||||
// captured in response to a browser "clipboard_get" request.
|
||||
OnClipboardText(deviceID string, text string)
|
||||
@@ -536,25 +541,43 @@ func deviceToInfo(d *Device) DeviceInfo {
|
||||
}
|
||||
}
|
||||
|
||||
// cursorMinInterval rate-limits position-only cursor updates. Shape changes
|
||||
// bypass it; pure movement is published at most this often.
|
||||
const cursorMinInterval = 50 * time.Millisecond
|
||||
|
||||
// cursorRefreshInterval re-sends an unchanged cursor at least this often so a
|
||||
// viewer that joins while the pointer is idle still learns where it is (it
|
||||
// would otherwise wait for the next mouse movement).
|
||||
const cursorRefreshInterval = time.Second
|
||||
|
||||
// PublishCursor notifies subscribers when the device reports a new cursor
|
||||
// index. Repeated identical indices are suppressed so the WS isn't spammed
|
||||
// with per-frame cursor JSON. No-op for unknown devices.
|
||||
func (h *Hub) PublishCursor(deviceID string, index byte) {
|
||||
// position/shape. x/y are in the captured frame's coordinate space. Identical
|
||||
// reports are suppressed and position-only changes are throttled, so the WS
|
||||
// isn't spammed with per-frame cursor JSON; an idle cursor is refreshed once a
|
||||
// second for late joiners. No-op for unknown devices.
|
||||
func (h *Hub) PublishCursor(deviceID string, index byte, x, y int) {
|
||||
h.mu.Lock()
|
||||
d, ok := h.devices[deviceID]
|
||||
if !ok {
|
||||
h.mu.Unlock()
|
||||
return
|
||||
}
|
||||
if d.cursorSeen && d.lastCursorIndex == index {
|
||||
h.mu.Unlock()
|
||||
return
|
||||
moved := d.lastCursorX != x || d.lastCursorY != y
|
||||
reshaped := !d.cursorSeen || d.lastCursorIndex != index
|
||||
if !reshaped {
|
||||
since := time.Since(d.cursorPubAt)
|
||||
if since < cursorMinInterval || (!moved && since < cursorRefreshInterval) {
|
||||
h.mu.Unlock()
|
||||
return
|
||||
}
|
||||
}
|
||||
d.cursorSeen = true
|
||||
d.lastCursorIndex = index
|
||||
d.lastCursorX, d.lastCursorY = x, y
|
||||
d.cursorPubAt = time.Now()
|
||||
h.mu.Unlock()
|
||||
for _, s := range h.snapshotSubscribers() {
|
||||
s.OnCursorChange(deviceID, index)
|
||||
s.OnCursorChange(deviceID, index, x, y)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -58,6 +58,7 @@ type captureHandler struct {
|
||||
online []string
|
||||
offline []string
|
||||
updates []string // formatted "id:rtt"
|
||||
cursors [][3]int // recorded {index, x, y}
|
||||
}
|
||||
|
||||
func (c *captureHandler) OnDeviceOnline(d DeviceInfo) {
|
||||
@@ -82,7 +83,11 @@ func (c *captureHandler) OnScreenFrame(_ string, _ []byte, _ bool) {}
|
||||
|
||||
func (c *captureHandler) OnResolutionChange(_ string, _, _ int) {}
|
||||
|
||||
func (c *captureHandler) OnCursorChange(_ string, _ byte) {}
|
||||
func (c *captureHandler) OnCursorChange(_ string, index byte, x, y int) {
|
||||
c.mu.Lock()
|
||||
c.cursors = append(c.cursors, [3]int{int(index), x, y})
|
||||
c.mu.Unlock()
|
||||
}
|
||||
|
||||
func (c *captureHandler) OnClipboardText(_ string, _ string) {}
|
||||
|
||||
@@ -225,3 +230,72 @@ func TestHubConcurrent(t *testing.T) {
|
||||
t.Fatalf("after all unregisters: want 0, got %d", got)
|
||||
}
|
||||
}
|
||||
|
||||
// The web console draws the remote cursor itself while the user is not in
|
||||
// control mode, so the hub must deliver the position reliably but without
|
||||
// relaying every ~30 Hz frame to every viewer.
|
||||
func TestPublishCursorDedupAndThrottle(t *testing.T) {
|
||||
h := New()
|
||||
c := &captureHandler{}
|
||||
h.Subscribe(c)
|
||||
h.Register(&Device{ID: "d", Name: "d"}, stubCtx())
|
||||
|
||||
// First report always goes out, even for the zero value.
|
||||
h.PublishCursor("d", 1, 10, 20)
|
||||
if len(c.cursors) != 1 || c.cursors[0] != [3]int{1, 10, 20} {
|
||||
t.Fatalf("first publish: %+v", c.cursors)
|
||||
}
|
||||
|
||||
// Identical report: suppressed.
|
||||
h.PublishCursor("d", 1, 10, 20)
|
||||
if len(c.cursors) != 1 {
|
||||
t.Fatalf("identical report should be dropped: %+v", c.cursors)
|
||||
}
|
||||
|
||||
// Position-only change inside the throttle window: suppressed.
|
||||
h.PublishCursor("d", 1, 11, 21)
|
||||
if len(c.cursors) != 1 {
|
||||
t.Fatalf("position-only change should be throttled: %+v", c.cursors)
|
||||
}
|
||||
|
||||
// Shape change bypasses the throttle.
|
||||
h.PublishCursor("d", 5, 12, 22)
|
||||
if len(c.cursors) != 2 || c.cursors[1] != [3]int{5, 12, 22} {
|
||||
t.Fatalf("shape change should be immediate: %+v", c.cursors)
|
||||
}
|
||||
|
||||
// After the window a position-only change is delivered again.
|
||||
time.Sleep(cursorMinInterval + 10*time.Millisecond)
|
||||
h.PublishCursor("d", 5, 13, 23)
|
||||
if len(c.cursors) != 3 || c.cursors[2] != [3]int{5, 13, 23} {
|
||||
t.Fatalf("post-window move: %+v", c.cursors)
|
||||
}
|
||||
|
||||
// Unknown device: no event, no panic.
|
||||
h.PublishCursor("ghost", 1, 0, 0)
|
||||
if len(c.cursors) != 3 {
|
||||
t.Fatalf("unknown device should not publish: %+v", c.cursors)
|
||||
}
|
||||
}
|
||||
|
||||
// A viewer joining while the pointer is idle must still learn its position:
|
||||
// the hub re-sends an unchanged cursor once the refresh interval passes.
|
||||
func TestPublishCursorRefreshesIdleState(t *testing.T) {
|
||||
h := New()
|
||||
c := &captureHandler{}
|
||||
h.Subscribe(c)
|
||||
h.Register(&Device{ID: "d", Name: "d"}, stubCtx())
|
||||
|
||||
h.PublishCursor("d", 3, 100, 200)
|
||||
time.Sleep(cursorRefreshInterval / 2)
|
||||
h.PublishCursor("d", 3, 100, 200) // inside the refresh window: dropped
|
||||
if len(c.cursors) != 1 {
|
||||
t.Fatalf("duplicate inside refresh window should be dropped: %+v", c.cursors)
|
||||
}
|
||||
|
||||
time.Sleep(cursorRefreshInterval/2 + 50*time.Millisecond)
|
||||
h.PublishCursor("d", 3, 100, 200) // stale: re-published for late joiners
|
||||
if len(c.cursors) != 2 || c.cursors[1] != [3]int{3, 100, 200} {
|
||||
t.Fatalf("idle refresh missing: %+v", c.cursors)
|
||||
}
|
||||
}
|
||||
+13
-5
@@ -63,6 +63,11 @@ type wsClient struct {
|
||||
user string // mirrors session username after login/resume
|
||||
termWatching string // device ID for an open web terminal session, "" otherwise
|
||||
|
||||
// wheelResidue carries the sub-notch remainder between wheel events so one
|
||||
// physical notch becomes exactly one WM_MOUSEWHEEL (see handleMouse). Only
|
||||
// the read loop that owns this client touches it.
|
||||
wheelResidue float64
|
||||
|
||||
// watchIDs is the set of devices this browser is streaming (the screen
|
||||
// wall watches several at once). Empty while on the device list.
|
||||
// Guarded by wsHub.mu.
|
||||
@@ -346,15 +351,18 @@ func (h *wsHub) OnDeviceOffline(id string) {
|
||||
}
|
||||
}
|
||||
|
||||
// OnCursorChange relays the remote cursor index to every viewer of this
|
||||
// device. The browser maps the index to a CSS cursor (desktop) or overlay
|
||||
// SVG variant (touch). Hub already de-duplicates so we always have a real
|
||||
// transition here.
|
||||
func (h *wsHub) OnCursorChange(deviceID string, index byte) {
|
||||
// OnCursorChange relays the remote cursor's shape and position to every viewer
|
||||
// of this device. The browser draws the cursor itself while it is not in
|
||||
// control mode (captured frames never contain one) and maps the index to a CSS
|
||||
// cursor on desktop while in control mode. x/y are in frame/canvas space.
|
||||
// Hub already de-duplicates and throttles, so we always have a real transition.
|
||||
func (h *wsHub) OnCursorChange(deviceID string, index byte, x, y int) {
|
||||
msg := mustJSON(map[string]any{
|
||||
"cmd": "cursor",
|
||||
"id": deviceID,
|
||||
"index": index,
|
||||
"x": x,
|
||||
"y": y,
|
||||
})
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// The non-controlling browser draws the remote cursor itself, so the relayed
|
||||
// "cursor" message must carry the position, not just the shape index. Without
|
||||
// x/y an older page still works (it ignores unknown fields), but the new
|
||||
// overlay has nothing to place.
|
||||
func TestOnCursorChangeCarriesPosition(t *testing.T) {
|
||||
c := &wsClient{
|
||||
send: make(chan wsMsg, 4),
|
||||
closed: make(chan struct{}),
|
||||
token: "tok",
|
||||
watchIDs: map[string]struct{}{"42": {}},
|
||||
}
|
||||
h := &wsHub{clients: map[*wsClient]struct{}{c: {}}}
|
||||
|
||||
h.OnCursorChange("42", 5, 1280, 720)
|
||||
|
||||
var msg struct {
|
||||
Cmd string `json:"cmd"`
|
||||
ID string `json:"id"`
|
||||
Index int `json:"index"`
|
||||
X *int `json:"x"`
|
||||
Y *int `json:"y"`
|
||||
}
|
||||
m := <-c.send
|
||||
if m.binary {
|
||||
t.Fatal("cursor message must be a text frame")
|
||||
}
|
||||
if err := json.Unmarshal(m.data, &msg); err != nil {
|
||||
t.Fatalf("unmarshal %s: %v", m.data, err)
|
||||
}
|
||||
if msg.Cmd != "cursor" || msg.ID != "42" || msg.Index != 5 {
|
||||
t.Fatalf("message = %+v", msg)
|
||||
}
|
||||
if msg.X == nil || msg.Y == nil || *msg.X != 1280 || *msg.Y != 720 {
|
||||
t.Fatalf("position missing: x=%v y=%v (raw %s)", msg.X, msg.Y, m.data)
|
||||
}
|
||||
|
||||
// A viewer not watching the device must not receive anything.
|
||||
other := &wsClient{
|
||||
send: make(chan wsMsg, 1),
|
||||
closed: make(chan struct{}),
|
||||
token: "tok",
|
||||
watchIDs: map[string]struct{}{"7": {}},
|
||||
}
|
||||
h.clients[other] = struct{}{}
|
||||
h.OnCursorChange("42", 5, 1, 1)
|
||||
select {
|
||||
case <-other.send:
|
||||
t.Fatal("non-watching client received a cursor message")
|
||||
default:
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package web
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"math"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -803,11 +804,12 @@ func (h *wsHub) handleMouse(c *wsClient, raw []byte) {
|
||||
return
|
||||
}
|
||||
var in struct {
|
||||
Type string `json:"type"`
|
||||
X int32 `json:"x"`
|
||||
Y int32 `json:"y"`
|
||||
Button int `json:"button"`
|
||||
Delta int `json:"delta"`
|
||||
Type string `json:"type"`
|
||||
X int32 `json:"x"`
|
||||
Y int32 `json:"y"`
|
||||
Button int `json:"button"`
|
||||
Delta float64 `json:"delta"`
|
||||
DeltaMode int `json:"deltaMode"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &in); err != nil {
|
||||
return
|
||||
@@ -845,17 +847,13 @@ func (h *wsHub) handleMouse(c *wsClient, raw []byte) {
|
||||
message = protocol.WMMouseMove
|
||||
case "wheel":
|
||||
message = protocol.WMMouseWheel
|
||||
// Windows expects ±120 per notch in HIWORD(wParam). Browsers report
|
||||
// `deltaY` in pixels with sign flipped relative to Win32 conventions
|
||||
// (positive deltaY = scroll down). Normalize to one notch per call,
|
||||
// signed so up scrolls "up" on the remote.
|
||||
var wheel int16
|
||||
switch {
|
||||
case in.Delta > 0:
|
||||
wheel = -120
|
||||
case in.Delta < 0:
|
||||
wheel = 120
|
||||
// Windows expects ±120 per notch in HIWORD(wParam); wheelNotches turns the
|
||||
// browser's distance into whole notches (see its doc comment).
|
||||
notches := wheelNotches(&c.wheelResidue, in.Delta, in.DeltaMode)
|
||||
if notches == 0 {
|
||||
return // less than a notch so far: keep it for the next event
|
||||
}
|
||||
wheel := int16(-notches * 120) // positive deltaY = scroll down
|
||||
wParam = uint64(uint16(wheel)) << 16
|
||||
case "dblclick":
|
||||
// Windows synthesizes double-click from rapid down/up sequences, so
|
||||
@@ -872,6 +870,47 @@ func (h *wsHub) handleMouse(c *wsClient, raw []byte) {
|
||||
_ = h.devices.SendToScreen(deviceID, pkt)
|
||||
}
|
||||
|
||||
// maxWheelNotches caps how many wheel notches one browser event may inject.
|
||||
// A touchpad fling or a scrollbar drag can report a huge delta; without the cap
|
||||
// the remote jumps pages at a time.
|
||||
const maxWheelNotches = 20
|
||||
|
||||
// wheelNotches converts one browser wheel event into whole Windows wheel
|
||||
// notches, carrying the sub-notch remainder in *residue.
|
||||
//
|
||||
// The browser reports a *distance*, not a notch count: deltaMode 0 = pixels
|
||||
// (Chrome's notch is about 100px), 1 = lines (about 3 per notch), 2 = pages.
|
||||
// Chrome's smooth scrolling splits one physical notch into several events with
|
||||
// fractional deltas (33.33 + 33.33 + 33.34) and touchpads go well below one
|
||||
// pixel per event, so events have to be accumulated: reading the delta as an
|
||||
// int dropped every fractional event (the wheel did nothing at all), and
|
||||
// treating every event as one notch scrolled three to four times too far.
|
||||
//
|
||||
// Rounding, not truncation: the split events do not sum to exactly 1.0 in
|
||||
// float (33.33*3 = 99.99), so an integer cast would sit at 0.999 forever. With
|
||||
// rounding the first notch fires halfway through a physical one, which is how
|
||||
// native scrolling feels, and *residue always stays within ±0.5 — it is a
|
||||
// positional carry, not a bank of credit — so a change of direction needs no
|
||||
// special case.
|
||||
func wheelNotches(residue *float64, delta float64, deltaMode int) int {
|
||||
unit := 100.0
|
||||
switch deltaMode {
|
||||
case 1:
|
||||
unit = 3
|
||||
case 2:
|
||||
unit = 1
|
||||
}
|
||||
*residue += delta / unit
|
||||
notches := int(math.Round(*residue))
|
||||
*residue -= float64(notches)
|
||||
if notches > maxWheelNotches {
|
||||
notches = maxWheelNotches
|
||||
} else if notches < -maxWheelNotches {
|
||||
notches = -maxWheelNotches
|
||||
}
|
||||
return notches
|
||||
}
|
||||
|
||||
// handleKey forwards one keyboard event to the device. lParam is built to
|
||||
// match the Windows convention so applications relying on TranslateMessage
|
||||
// (e.g. text input fields) behave correctly. Mirrors
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
package web
|
||||
|
||||
import "testing"
|
||||
|
||||
// Chrome's smooth scrolling splits one physical notch (100px) into a few
|
||||
// fractional wheel events. Each event must not become a notch on its own, and
|
||||
// the whole physical notch must inject exactly one.
|
||||
func TestWheelNotchesSmoothScrollSequence(t *testing.T) {
|
||||
var residue float64
|
||||
seq := []float64{33.33, 33.33, 33.34}
|
||||
total := 0
|
||||
for _, d := range seq {
|
||||
total += abs(wheelNotches(&residue, d, 0))
|
||||
}
|
||||
if total != 1 {
|
||||
t.Fatalf("one 100px notch in %d events gave %d notches, want 1", len(seq), total)
|
||||
}
|
||||
if residue > 0.5 || residue < -0.5 {
|
||||
t.Fatalf("residue must stay within half a notch, got %v", residue)
|
||||
}
|
||||
}
|
||||
|
||||
// Touchpads report sub-pixel deltas: they used to truncate to 0 and the wheel
|
||||
// did nothing at all. They must accumulate into one notch.
|
||||
func TestWheelNotchesSubPixelDeltas(t *testing.T) {
|
||||
var residue float64
|
||||
got := 0
|
||||
for i := 0; i < 167; i++ { // 167 events x 0.6px = 100.2px
|
||||
got += wheelNotches(&residue, 0.6, 0)
|
||||
}
|
||||
if got != 1 {
|
||||
t.Fatalf("167 x 0.6px gave %d notches, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
// The same split in three equal parts must also land on exactly one notch:
|
||||
// 33.33*3 is 99.99 in float, and truncating would never reach a whole notch.
|
||||
func TestWheelNotchesEqualThirds(t *testing.T) {
|
||||
var residue float64
|
||||
got := 0
|
||||
for i := 0; i < 3; i++ {
|
||||
got += wheelNotches(&residue, 33.33, 0)
|
||||
}
|
||||
if got != 1 {
|
||||
t.Fatalf("3 x 33.33px gave %d notches, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWheelNotchesDirection(t *testing.T) {
|
||||
var residue float64
|
||||
if n := wheelNotches(&residue, 100, 0); n != 1 {
|
||||
t.Fatalf("down: got %d notches, want 1", n)
|
||||
}
|
||||
if n := wheelNotches(&residue, -100, 0); n != -1 {
|
||||
t.Fatalf("up: got %d notches, want -1", n)
|
||||
}
|
||||
// A half-scrolled notch does not block a reversal: the carry is a position,
|
||||
// so 40px down then a full notch up is one notch up.
|
||||
residue = 0.4
|
||||
if n := wheelNotches(&residue, -100, 0); n != -1 {
|
||||
t.Fatalf("flip: got %d notches, want -1", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWheelNotchesDeltaModes(t *testing.T) {
|
||||
var pixel, line, page float64
|
||||
if n := wheelNotches(&pixel, 100, 0); n != 1 {
|
||||
t.Fatalf("pixel mode: got %d, want 1", n)
|
||||
}
|
||||
if n := wheelNotches(&line, 3, 1); n != 1 {
|
||||
t.Fatalf("line mode: got %d, want 1", n)
|
||||
}
|
||||
if n := wheelNotches(&page, 1, 2); n != 1 {
|
||||
t.Fatalf("page mode: got %d, want 1", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWheelNotchesClamp(t *testing.T) {
|
||||
var residue float64
|
||||
if n := wheelNotches(&residue, 100000, 0); n != maxWheelNotches {
|
||||
t.Fatalf("huge delta gave %d notches, want %d", n, maxWheelNotches)
|
||||
}
|
||||
if n := wheelNotches(&residue, -100000, 0); n != -maxWheelNotches {
|
||||
t.Fatalf("huge negative delta gave %d notches, want %d", n, -maxWheelNotches)
|
||||
}
|
||||
}
|
||||
|
||||
func abs(n int) int {
|
||||
if n < 0 {
|
||||
return -n
|
||||
}
|
||||
return n
|
||||
}
|
||||
+70
-14
@@ -2648,8 +2648,12 @@
|
||||
isAndroidRemote = msg.client_type === 'APK';
|
||||
updateAndroidNavbar();
|
||||
// Refresh cursor overlay and immersive layout
|
||||
document.getElementById('cursor-overlay').classList.toggle(
|
||||
'active', controlEnabled && isTouchDevice && !isAndroidRemote);
|
||||
if (controlEnabled) {
|
||||
document.getElementById('cursor-overlay').classList.toggle(
|
||||
'active', isTouchDevice && !isAndroidRemote);
|
||||
} else {
|
||||
renderRemoteCursor();
|
||||
}
|
||||
if (isTouchDevice) updateUIForOrientation();
|
||||
}
|
||||
initDecoder(msg.width, msg.height);
|
||||
@@ -2662,8 +2666,18 @@
|
||||
// Update remote cursor visual: native CSS cursor on desktop,
|
||||
// overlay variant on touch. 254=custom (unsupported), 255=unsupported.
|
||||
currentCursorIndex = msg.index;
|
||||
remoteCursor.index = msg.index;
|
||||
// 服务端每帧带上光标位置(帧坐标 == canvas 坐标)。老版本服务端
|
||||
// 只发 index,此时 known 保持 false,退回原来的表现。
|
||||
if (typeof msg.x === 'number' && typeof msg.y === 'number') {
|
||||
remoteCursor.x = msg.x;
|
||||
remoteCursor.y = msg.y;
|
||||
remoteCursor.known = true;
|
||||
}
|
||||
if (controlEnabled) {
|
||||
applyRemoteCursor(msg.index);
|
||||
} else {
|
||||
renderRemoteCursor();
|
||||
}
|
||||
break;
|
||||
}
|
||||
@@ -2778,6 +2792,8 @@
|
||||
|
||||
// Update input shortcuts position after canvas resize
|
||||
requestAnimationFrame(updateInputShortcutsPosition);
|
||||
// 分辨率变了:非控制态的远程光标按新画布重新定位
|
||||
requestAnimationFrame(renderRemoteCursor);
|
||||
|
||||
// Windows/Linux/macOS clients send bottom-up H.264 (BMP convention) → flip.
|
||||
// Android MediaCodec sends top-down H.264 → no flip needed.
|
||||
@@ -5193,6 +5209,11 @@
|
||||
];
|
||||
let currentCursorIndex = 1; // Default: arrow
|
||||
|
||||
// 远程真实光标位置(服务端随每帧回报)。抓屏画面本身不含光标,所以非控制态
|
||||
// 由浏览器自己画一个。known=false 表示服务端还没上报过位置(老版本服务端),
|
||||
// 这时退回浏览器自己的指针,保持原有观感。
|
||||
let remoteCursor = { x: 0, y: 0, index: 1, known: false };
|
||||
|
||||
// IDC_* index -> CSS class on .cursor-overlay (touch-mode visual cursor).
|
||||
// Indices not listed (0,2,4,6,8,14, custom) fall back to default arrow.
|
||||
const cursorOverlayClassMap = {
|
||||
@@ -5226,6 +5247,28 @@
|
||||
}
|
||||
}
|
||||
|
||||
// 非控制态的光标渲染:把远程光标画在它真正所在的位置上,同时藏起浏览器
|
||||
// 自己的箭头,否则屏幕上会同时出现两个指针。控制态不走这里——桌面端本地
|
||||
// 指针本身就是远程光标,触摸端由 updateCursorOverlay 画触控光标。
|
||||
function renderRemoteCursor() {
|
||||
if (controlEnabled) return;
|
||||
const canvas = document.getElementById('screen-canvas');
|
||||
const overlay = document.getElementById('cursor-overlay');
|
||||
if (!canvas || !overlay) return;
|
||||
// 屏幕墙(以及没打开远程桌面时)不画:多路光标会落在同一个固定层上。
|
||||
const screenPage = document.getElementById('screen-page');
|
||||
const onScreen = !!screenPage && screenPage.classList.contains('active');
|
||||
// Android 直连模式没有指针概念(手指即指针),不画。
|
||||
const show = onScreen && remoteCursor.known && !isAndroidRemote;
|
||||
canvas.style.cursor = show ? 'none' : 'default';
|
||||
overlay.className = 'cursor-overlay' + (show ? ' active' : '');
|
||||
const cls = cursorOverlayClassMap[remoteCursor.index];
|
||||
if (show) {
|
||||
if (cls) overlay.classList.add(cls);
|
||||
positionCursorOverlay(remoteCursor.x, remoteCursor.y);
|
||||
}
|
||||
}
|
||||
|
||||
// Floating toolbar state
|
||||
let toolbarVisible = false;
|
||||
let toolbarHideTimer = null;
|
||||
@@ -5481,17 +5524,18 @@
|
||||
// Cursor handling
|
||||
const canvas = document.getElementById('screen-canvas');
|
||||
const cursorOverlay = document.getElementById('cursor-overlay');
|
||||
// Touch: hide native cursor and show our overlay (touchpad mode).
|
||||
// Desktop: native CSS cursor is set by applyRemoteCursor below.
|
||||
if (controlEnabled && isTouchDevice) {
|
||||
canvas.style.cursor = 'none';
|
||||
} else if (!controlEnabled) {
|
||||
canvas.style.cursor = 'default';
|
||||
}
|
||||
// Android direct mode: no cursor overlay (finger IS the pointer)
|
||||
cursorOverlay.classList.toggle('active', controlEnabled && isTouchDevice && !isAndroidRemote);
|
||||
if (controlEnabled) {
|
||||
// Touch: hide native cursor and show our overlay (touchpad mode).
|
||||
// Desktop: native CSS cursor is set by applyRemoteCursor below.
|
||||
if (isTouchDevice) {
|
||||
canvas.style.cursor = 'none';
|
||||
}
|
||||
// Android direct mode: no cursor overlay (finger IS the pointer)
|
||||
cursorOverlay.classList.toggle('active', isTouchDevice && !isAndroidRemote);
|
||||
applyRemoteCursor(currentCursorIndex);
|
||||
} else {
|
||||
// 非控制态:藏起本地指针,只留远程真实光标
|
||||
renderRemoteCursor();
|
||||
}
|
||||
// Sync the keyboard lock: in fullscreen + control mode, ESC and F11
|
||||
// must be passed through to the remote OS instead of triggering the
|
||||
@@ -5505,9 +5549,16 @@
|
||||
// Only used on touch devices (touchpad mode)
|
||||
function updateCursorOverlay(canvasX, canvasY) {
|
||||
if (!controlEnabled || !isTouchDevice) return;
|
||||
positionCursorOverlay(canvasX, canvasY);
|
||||
}
|
||||
|
||||
// Place the overlay at a canvas coordinate, applying the zoom/pan
|
||||
// transform. Shared by the touch control cursor and the non-control
|
||||
// remote cursor.
|
||||
function positionCursorOverlay(canvasX, canvasY) {
|
||||
const canvas = document.getElementById('screen-canvas');
|
||||
const cursorOverlay = document.getElementById('cursor-overlay');
|
||||
|
||||
if (!canvas || !cursorOverlay) return;
|
||||
// Get canvas base position (without transform, use container + offset)
|
||||
// offsetLeft/offsetTop are layout positions, unaffected by CSS transform
|
||||
const container = document.querySelector('.canvas-container');
|
||||
@@ -5679,6 +5730,8 @@
|
||||
canvas.style.transformOrigin = zoomState.originX + '% ' + zoomState.originY + '%';
|
||||
canvas.style.transform = 'scale(' + zoomState.scale + ') translate(' + zoomState.translateX + 'px, ' + zoomState.translateY + 'px)';
|
||||
}
|
||||
// 非控制态:缩放/平移后远程光标要跟着画面走
|
||||
if (!controlEnabled) renderRemoteCursor();
|
||||
}
|
||||
|
||||
function getPinchDistance(touches) {
|
||||
@@ -5854,13 +5907,15 @@
|
||||
};
|
||||
}
|
||||
|
||||
function sendMouse(type, x, y, button, delta) {
|
||||
function sendMouse(type, x, y, button, delta, deltaMode) {
|
||||
if (!controlEnabled) return; // Control mode required
|
||||
// Update cursor overlay position
|
||||
updateCursorOverlay(x, y);
|
||||
if (ws && ws.readyState === WebSocket.OPEN && token) {
|
||||
const msg = { cmd: 'mouse', token, id: currentDeviceId(), type, x, y, button: button || 0 };
|
||||
if (delta !== undefined) msg.delta = delta;
|
||||
// deltaMode: 0=像素 1=行 2=页。服务端按它把 delta 换算成滚轮刻度。
|
||||
if (deltaMode !== undefined) msg.deltaMode = deltaMode;
|
||||
ws.send(JSON.stringify(msg));
|
||||
}
|
||||
}
|
||||
@@ -6495,7 +6550,7 @@
|
||||
canvas.addEventListener('wheel', function(e) {
|
||||
e.preventDefault();
|
||||
const pos = getMousePos(e);
|
||||
sendMouse('wheel', pos.x, pos.y, 0, e.deltaY);
|
||||
sendMouse('wheel', pos.x, pos.y, 0, e.deltaY, e.deltaMode);
|
||||
}, { passive: false });
|
||||
|
||||
canvas.addEventListener('contextmenu', e => e.preventDefault());
|
||||
@@ -6632,6 +6687,7 @@
|
||||
// Strip any cursor-* variant on the overlay, leaving the bare default arrow.
|
||||
document.getElementById('cursor-overlay').className = 'cursor-overlay';
|
||||
currentCursorIndex = 1; // Reset to default arrow
|
||||
remoteCursor = { x: 0, y: 0, index: 1, known: false }; // 切设备后位置作废
|
||||
|
||||
// Reset zoom state
|
||||
zoomState.scale = 1;
|
||||
|
||||
@@ -86,6 +86,18 @@ function HasPaging($obj) {
|
||||
return $true
|
||||
}
|
||||
|
||||
# 结果外露(docs/Mcp_Design.md §14):content 末尾必须有一个可解析的 JSON 文本块,
|
||||
# 内容与 structuredContent 对应。只读 content 的客户端(WorkBuddy)靠它拿到 id。
|
||||
function HasJsonText($rpc) {
|
||||
if ($null -eq $rpc -or $null -eq $rpc.result) { return $false }
|
||||
$c = @($rpc.result.content)
|
||||
if ($c.Count -lt 2) { return $false }
|
||||
$last = $c[$c.Count - 1]
|
||||
if ($last.type -ne 'text' -or [string]::IsNullOrEmpty($last.text)) { return $false }
|
||||
try { $null = $last.text | ConvertFrom-Json } catch { return $false }
|
||||
return $true
|
||||
}
|
||||
|
||||
Write-Host "MCP smoke test -> $Base"
|
||||
if (-not $Token) {
|
||||
Write-Host "缺少 token:请设置环境变量 YAMA_MCP_TOKEN 或传 -Token。" -ForegroundColor Red
|
||||
@@ -153,9 +165,15 @@ Check 'list_online_hosts 过滤后 totalAll 仍是全部在线数' ([int]$noMatc
|
||||
|
||||
$all = Rpc '' $null 'list_all_hosts' @{ limit = 5 }
|
||||
Check 'list_all_hosts 带分页字段' (HasPaging $all.result.structuredContent)
|
||||
Check 'list_all_hosts 的 content 附带结构化 JSON' (HasJsonText $all)
|
||||
$allJson = $null
|
||||
if (HasJsonText $all) { $allJson = $all.result.content[-1].text | ConvertFrom-Json }
|
||||
Check 'content 的 JSON 里能取到主机 id(串联下一跳)' ($null -eq $allJson -or
|
||||
@($allJson.hosts).Count -eq 0 -or [string]$allJson.hosts[0].id -ne '')
|
||||
|
||||
$found = Rpc '' $null 'search_hosts' @{ query = ''; limit = 5 }
|
||||
Check 'search_hosts 正常返回' ($found.error -eq $null -and (HasPaging $found.result.structuredContent))
|
||||
Check 'search_hosts 的 content 附带结构化 JSON' (HasJsonText $found)
|
||||
|
||||
$audit = Rpc '' $null 'get_audit_log' @{ limit = 5 }
|
||||
Check 'get_audit_log 正常返回' ($audit.error -eq $null)
|
||||
@@ -172,6 +190,7 @@ if ($Base -match ':(\d+)(/|$)') { $basePort = [int]$Matches[1] }
|
||||
Check 'get_server_status 版本/端口/开关齐全' `
|
||||
([string]$st.version -ne '' -and [int]$st.port -eq $basePort -and $null -ne $st.switches -and $null -ne $st.sessions)
|
||||
Check 'get_server_status 不含 token' (($st | ConvertTo-Json -Depth 6) -notmatch '(?i)token')
|
||||
Check 'get_server_status 的 content 附带结构化 JSON' (HasJsonText $status)
|
||||
|
||||
if (-not $HostId) {
|
||||
$first = @($sc.hosts)[0]
|
||||
@@ -273,6 +292,26 @@ if (-not $SkipHost -and $drive) {
|
||||
} else {
|
||||
Write-Host " download_file 未开启(McpFileTransfer),跳过下载负例。" -ForegroundColor Yellow
|
||||
}
|
||||
|
||||
# copy_files_c2c:只测「不需要两台在线主机」的拒绝分支,避免冒烟改变远端文件。
|
||||
# 同主机 → -32602(参数被拒);目标不在线 → -32002(主机找不到)。
|
||||
if (@($tools | Where-Object { $_.name -eq 'copy_files_c2c' }).Count -gt 0) {
|
||||
$c2cSame = Rpc '' $null 'copy_files_c2c' @{
|
||||
src_id = $HostId; dst_id = $HostId
|
||||
paths = @($ghostDir + '\a.txt'); dst_dir = (Join-Path $env:TEMP 'mcp_smoke_c2c')
|
||||
}
|
||||
Check 'copy_files_c2c 同主机返回 -32602' `
|
||||
($c2cSame.error -and [int]$c2cSame.error.code -eq -32602) ([string]$c2cSame.error.message)
|
||||
|
||||
$c2cOff = Rpc '' $null 'copy_files_c2c' @{
|
||||
src_id = $HostId; dst_id = '1'
|
||||
paths = @($ghostDir + '\a.txt'); dst_dir = (Join-Path $env:TEMP 'mcp_smoke_c2c')
|
||||
}
|
||||
Check 'copy_files_c2c 目标离线返回 -32002' `
|
||||
($c2cOff.error -and [int]$c2cOff.error.code -eq -32002) ([string]$c2cOff.error.message)
|
||||
} else {
|
||||
Write-Host " copy_files_c2c 未开启(McpFileTransfer/McpReadonly),跳过 C2C 负例。" -ForegroundColor Yellow
|
||||
}
|
||||
}
|
||||
|
||||
# ===== 5. 策略拒绝(-32006) =====
|
||||
|
||||
Reference in new issue
Block a user