Feature(mcp): add http_probe for private-network HTTP checks
Run an HTTP/HTTPS request inside a shell on a managed host and return a structured result: status code, headers, body (UTF-8 or base64), size and elapsed time, so interface health on the host or its subnet can be checked without a full remote-control session. The safety boundary is hard-coded on the server, not in the shell script: only http/https and IP literals (or localhost); only loopback and private ranges (127/8, ::1, 10/8, 172.16/12, 192.168/16) are accepted; redirects are not followed; the body is capped at 64KB; TLS certificates are verified. Domain names are refused on purpose - resolving them on the server would probe the wrong network. Windows runs a single-line PowerShell 2.0-compatible script based on HttpWebRequest. Accept/User-Agent/Referer are mapped to their dedicated properties because .NET rejects them through Headers.Add. Linux uses curl with temp files. Payloads cross the terminal channel as 56-character base64 chunks with a declared byte length. ConPTY re-emits the boundary character of lines wider than 80 columns, so single-line base64 arrives corrupted; the length check converts any remaining loss into an explicit error rather than silent garbage. The tool reuses an existing persistent terminal session. Sessions it creates itself are closed after the command and kept only when the probe timed out while still running. Platform gating: Windows and Linux only. Co-Authored-By: deepseek-flash
This commit is contained in:
1 parent
697044d84b
commit
613aa7291a
3 files changed
+992
-2
No files matched your search
+117
-1
@@ -15,7 +15,7 @@
|
||||
],
|
||||
"version": 2,
|
||||
"protocolVersion": "2025-06-18",
|
||||
"toolCount": 64,
|
||||
"toolCount": 65,
|
||||
"tools": [
|
||||
{
|
||||
"name": "list_online_hosts",
|
||||
@@ -3027,6 +3027,122 @@
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "http_probe",
|
||||
"description": "在指定在线 Windows 或 Linux 主机上请求一个 HTTP/HTTPS 地址,返回结构化结果(状态码、响应头、响应体、耗时),用于探测主机上或同网段的业务接口健康。url 必须是 http:// 或 https:// + IP 字面量(或 localhost)+ 可选 :端口 + 路径;只允许私网/回环地址(127.0.0.0/8、::1、10/8、172.16/12、192.168/16)与 localhost,域名和公网地址一律拒绝(域名要通过被管主机解析才有意义,服务端解析自己的 DNS 是错的)。默认 GET;method 支持 GET/POST/PUT/DELETE/HEAD/PATCH/OPTIONS;headers 为名→值的字符串对象;body 为请求体(≤2048 字节,按 UTF-8 发送)。不跟随重定向(3xx 原样返回,Location 在 headers 里);https 校验证书,自签名证书会失败。响应体最多返回 max_bytes(默认与上限均为 64KB),超出置 truncated=true;响应体是合法 UTF-8 时放在 body,否则 body 为空并给出 body_base64。实现上复用终端通道(需 McpTerminal=1、McpReadonly=0):会复用该主机已有的持久终端会话;没有则内部打开一个、用完即关(超时仍在跑时保留,便于轮询)。该主机上已有命令在跑或输出未取完时返回 -32003。",
|
||||
"gate": "terminal",
|
||||
"write": true,
|
||||
"platforms": [
|
||||
"win",
|
||||
"lnx"
|
||||
],
|
||||
"impl": "mfc",
|
||||
"inputSchema": {
|
||||
"properties": {
|
||||
"body": {
|
||||
"description": "请求体(可选,≤2048 字节),按 UTF-8 发送;POST/PUT/PATCH 时常用",
|
||||
"type": "string"
|
||||
},
|
||||
"headers": {
|
||||
"additionalProperties": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": "请求头(对象,名→值都是字符串),如 {\"Authorization\":\"Bearer x\"};序列化后上限 512 字节,不接受 Content-Length;Windows 上少数受限头(如 Connection、Expect、Range)会被系统拒收,Accept/User-Agent/Referer 已单独支持",
|
||||
"type": "object"
|
||||
},
|
||||
"id": {
|
||||
"description": "主机 id,取 list_online_hosts / search_hosts 返回的 id 字段",
|
||||
"type": "string"
|
||||
},
|
||||
"max_bytes": {
|
||||
"description": "响应体最多返回的字节数(默认 65536,范围 1-65536),超出置 truncated=true",
|
||||
"type": "integer"
|
||||
},
|
||||
"method": {
|
||||
"description": "HTTP 方法,默认 GET",
|
||||
"enum": [
|
||||
"GET",
|
||||
"POST",
|
||||
"PUT",
|
||||
"DELETE",
|
||||
"HEAD",
|
||||
"PATCH",
|
||||
"OPTIONS"
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
"timeout_ms": {
|
||||
"description": "请求超时毫秒数(默认 10000,范围 1000-60000);工具等待 = 该值 + 20 秒(含 shell 启动)",
|
||||
"type": "integer"
|
||||
},
|
||||
"url": {
|
||||
"description": "要请求的地址:http:// 或 https:// + IP 字面量(或 localhost)+ 可选 :端口 + 路径,如 http://127.0.0.1:8003/health",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"url"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"outputSchema": {
|
||||
"properties": {
|
||||
"body": {
|
||||
"description": "响应体(响应体是合法 UTF-8 时才填;否则为空,看 body_base64)",
|
||||
"type": "string"
|
||||
},
|
||||
"body_base64": {
|
||||
"description": "响应体的 base64(仅 body_encoding=base64 时提供,非 UTF-8 的二进制响应)",
|
||||
"type": "string"
|
||||
},
|
||||
"body_bytes": {
|
||||
"description": "本次返回的响应体字节数(被截断时即 max_bytes 内实际读到的)",
|
||||
"type": "integer"
|
||||
},
|
||||
"body_encoding": {
|
||||
"description": "body 的编码:utf-8 或 base64",
|
||||
"type": "string"
|
||||
},
|
||||
"elapsed_ms": {
|
||||
"description": "请求耗时毫秒(Windows 在 PowerShell 内计时;Linux 为服务端整轮计时)",
|
||||
"type": "integer"
|
||||
},
|
||||
"headers": {
|
||||
"description": "响应头(名→值;同名多值用逗号拼接)",
|
||||
"type": "object"
|
||||
},
|
||||
"ok": {
|
||||
"description": "true = 2xx/3xx;3xx 未跟随重定向",
|
||||
"type": "boolean"
|
||||
},
|
||||
"status": {
|
||||
"description": "HTTP 状态码",
|
||||
"type": "integer"
|
||||
},
|
||||
"truncated": {
|
||||
"description": "true = 响应体超过 max_bytes,只返回了前缀",
|
||||
"type": "boolean"
|
||||
},
|
||||
"url": {
|
||||
"description": "回显请求的 url",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"status",
|
||||
"ok",
|
||||
"headers",
|
||||
"body",
|
||||
"body_encoding",
|
||||
"body_bytes",
|
||||
"truncated",
|
||||
"elapsed_ms",
|
||||
"url"
|
||||
],
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "upload_file",
|
||||
"description": "把主控本机文件或目录上传到指定在线主机的目录(V2 协议,主连接发送)。支持 Windows 与 Linux/macOS 主机;local_path 为主控本机绝对路径(文件或目录,目录递归上传);remote_dir 为远程保存目录(不存在自动创建),Windows 用 C:\\uploads 这类盘符路径,Linux/macOS 用 /home/user/uploads 这类绝对 POSIX 路径;overwrite=false 时跳过 remote_dir 下已存在的同名顶层项。返回 files[{path,size,sha256}] 与 total_bytes/skipped/receiver_ack;sha256 恒为空(发送端不计算)。receiver_ack=true 表示目标端已确认写入(Linux 客户端回执),false 表示目标端没有回执(Windows 目标、老客户端或 macOS),此时需要确证请用 list_files 复核。",
|
||||
|
||||
@@ -329,6 +329,9 @@ const char* kServerInstructions =
|
||||
u8"命令执行:exec_command 一次性取输出(受白名单约束)。terminal_exec 无需先 terminal_open:带 command 时"
|
||||
u8"自动复用或创建该主机的持久会话(cwd/环境变量跨命令保持,闲置 300 秒回收),结果里带回 session_id,"
|
||||
u8"后续轮询用它;只有需要显式管理会话时才用 terminal_open / terminal_close。\n"
|
||||
u8"HTTP 探测:探主机本机或同网段的接口用 http_probe(只收私网/回环 IP 与 localhost,不给域名,"
|
||||
u8"不跟随重定向,响应体上限 64KB),不要为此自己写 Invoke-WebRequest / curl;Windows 与 Linux 可用,"
|
||||
u8"macOS 与 Android 不支持。\n"
|
||||
u8"\n"
|
||||
u8"5) 客户端平台差异\n"
|
||||
u8"工具能否执行取决于目标主机的平台,这与服务端开关无关,两者是叠加关系。调用前用 "
|
||||
@@ -345,7 +348,7 @@ const char* kServerInstructions =
|
||||
u8"remote_mouse / remote_keyboard / remote_clipboard)、get_screenshot、"
|
||||
u8"活动历史(get_activity_history)、"
|
||||
u8"exec_command、terminal_open / terminal_exec / terminal_close"
|
||||
u8"(客户端有 PTY 实现,但服务端本轮未开放)、kill_process;"
|
||||
u8"(客户端有 PTY 实现,但服务端本轮未开放)、kill_process、http_probe;"
|
||||
u8"文件传输、进程列表、日志可用。\n"
|
||||
u8"apk(APK):支持主机列表(list_online_hosts / list_all_hosts)/ 详情 / 搜索 / "
|
||||
u8"审计日志 / 服务状态 / 会话管理、运行日志(get_client_log)、活动历史"
|
||||
@@ -2063,6 +2066,10 @@ std::string BuildDownloadFile(const Json::Value& id, const Json::Value& args, CM
|
||||
Json::Value BuildReadFileInputSchema();
|
||||
Json::Value BuildReadFileOutputSchema();
|
||||
std::string BuildReadFile(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent);
|
||||
// P1-2:在被管主机上请求私有网段 HTTP 地址(复用持久终端的 shell 通道)
|
||||
Json::Value BuildHttpProbeInputSchema();
|
||||
Json::Value BuildHttpProbeOutputSchema();
|
||||
std::string BuildHttpProbe(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent);
|
||||
Json::Value BuildUploadFileInputSchema();
|
||||
Json::Value BuildUploadFileOutputSchema();
|
||||
std::string BuildUploadFile(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent);
|
||||
@@ -2617,6 +2624,17 @@ std::string BuildToolsListResult(const Json::Value& id) {
|
||||
tools.append(tool);
|
||||
}
|
||||
|
||||
// 16c) http_probe(P1-2:在被管主机上请求私有网段 HTTP 地址;复用持久终端的 shell 通道)。
|
||||
// 与终端族同门控:McpTerminal=1 且 McpReadonly=0(内部会执行一条固定的 shell 命令)。
|
||||
if (CMcpServer::Instance().IsTerminalEnabled() && !CMcpServer::Instance().IsReadonly()) {
|
||||
Json::Value tool(Json::objectValue);
|
||||
tool["name"] = "http_probe";
|
||||
tool["description"] = u8"在指定在线 Windows 或 Linux 主机上请求一个 HTTP/HTTPS 地址,返回结构化结果(状态码、响应头、响应体、耗时),用于探测主机上或同网段的业务接口健康。url 必须是 http:// 或 https:// + IP 字面量(或 localhost)+ 可选 :端口 + 路径;只允许私网/回环地址(127.0.0.0/8、::1、10/8、172.16/12、192.168/16)与 localhost,域名和公网地址一律拒绝(域名要通过被管主机解析才有意义,服务端解析自己的 DNS 是错的)。默认 GET;method 支持 GET/POST/PUT/DELETE/HEAD/PATCH/OPTIONS;headers 为名→值的字符串对象;body 为请求体(≤2048 字节,按 UTF-8 发送)。不跟随重定向(3xx 原样返回,Location 在 headers 里);https 校验证书,自签名证书会失败。响应体最多返回 max_bytes(默认与上限均为 64KB),超出置 truncated=true;响应体是合法 UTF-8 时放在 body,否则 body 为空并给出 body_base64。实现上复用终端通道(需 McpTerminal=1、McpReadonly=0):会复用该主机已有的持久终端会话;没有则内部打开一个、用完即关(超时仍在跑时保留,便于轮询)。该主机上已有命令在跑或输出未取完时返回 -32003。";
|
||||
tool["inputSchema"] = BuildHttpProbeInputSchema();
|
||||
tool["outputSchema"] = BuildHttpProbeOutputSchema();
|
||||
tools.append(tool);
|
||||
}
|
||||
|
||||
// 17) upload_file(P2:MCP 文件上传,安全门:McpFileTransfer=1 且 McpReadonly=0)
|
||||
// 写远程盘,故额外要求关闭只读(与 terminal_* / remote_* 一致)。
|
||||
if (CMcpServer::Instance().IsFileTransferEnabled() && !CMcpServer::Instance().IsReadonly()) {
|
||||
@@ -7890,6 +7908,853 @@ std::string BuildReadFile(const Json::Value& id, const Json::Value& args, CMy201
|
||||
return BuildResult(id, result);
|
||||
}
|
||||
|
||||
// ===== P1-2:http_probe(在被管主机上请求私有网段 HTTP 地址) =====
|
||||
//
|
||||
// 客户端没有 HTTP 命令,故复用持久终端的 shell 通道:Windows 用 PowerShell + HttpWebRequest,
|
||||
// Linux 用 curl。两者都只打印 ASCII 标记行 + base64 负载,服务端解析成结构化结果。
|
||||
// 用 HttpWebRequest 而不是 Invoke-WebRequest:只有它能拿到原始响应字节(-UseBasicParsing 的
|
||||
// Content 会被字符集解码),也能在读满 max_bytes 后主动断开,不把整个大响应拉回来。
|
||||
//
|
||||
// 安全边界全部硬编码(不可配置,见 docs/Mcp_Tool_Optimization_Plan.md P1-2):
|
||||
// - 只允许 http/https;只接受 IP 字面量(外加 localhost)。域名校验在服务端没有意义
|
||||
// (被管主机上的 DNS 结果才算数),私网/回环外的地址一律拒绝,避免把主机当代理用。
|
||||
// - 不跟随重定向:3xx 原样返回,Location 留在 headers 里。
|
||||
// - 响应体最多返回 max_bytes(默认与上限都是 64KB),超出置 truncated=true。
|
||||
static const int kHttpProbeDefaultTimeoutMs = 10000;
|
||||
static const int kHttpProbeMinTimeoutMs = 1000;
|
||||
static const int kHttpProbeMaxTimeoutMs = 60000;
|
||||
static const int kHttpProbeDefaultMaxBytes = 65536;
|
||||
static const int kHttpProbeMaxUrlBytes = 1024;
|
||||
static const int kHttpProbeMaxHeaderBlob = 512; // headers 序列化后("Name: value\n")的上限
|
||||
static const int kHttpProbeMaxBodyBytes = 2048; // 请求体上限(命令要挤进 cmd 的 8191 字符)
|
||||
static const int kHttpProbeCmdLineBudget = 7800; // cmd.exe 单行输入上限约 8191,留余量
|
||||
static const int kHttpProbeWaitMarginMs = 20000; // 工具等待 = timeout_ms + 这段(shell 启动开销)
|
||||
static const int kHttpProbeMaxOutputBytes = 1024 * 1024;
|
||||
static const int kHttpProbeChunkChars = 56; // 负载按行分块:标记 + 56 < 80 列,避开 PTY 折行
|
||||
|
||||
static const char* const kHttpProbeStatusMarker = "__YAMA_HTTP_STATUS__";
|
||||
static const char* const kHttpProbeErrMarker = "__YAMA_HTTP_ERR__";
|
||||
static const char* const kHttpProbeErrStartMarker = "__YAMA_HTTP_ERRS__";
|
||||
static const char* const kHttpProbeErrChunkMarker = "__YAMA_HTTP_E__";
|
||||
static const char* const kHttpProbeErrEndMarker = "__YAMA_HTTP_ERRE__";
|
||||
static const char* const kHttpProbeTruncMarker = "__YAMA_HTTP_TRUNC__";
|
||||
static const char* const kHttpProbeElapsedMarker = "__YAMA_HTTP_ELAPSED__";
|
||||
// 负载必须分块:ConPTY 是 80 列屏幕渲染流,超宽行在折行处会把边界字符重复一次,
|
||||
// 单行 base64 会被污染成乱码。分块后每行(标记 + 56 字符)都短于 80 列,不会被折行。
|
||||
// 长度行给出解码后的字节数,服务端据此校验是否有字符丢失。
|
||||
static const char* const kHttpProbeHdrLenMarker = "__YAMA_HTTP_HLEN__";
|
||||
static const char* const kHttpProbeHdrStartMarker = "__YAMA_HTTP_HS__";
|
||||
static const char* const kHttpProbeHdrChunkMarker = "__YAMA_HTTP_H__";
|
||||
static const char* const kHttpProbeHdrEndMarker = "__YAMA_HTTP_HE__";
|
||||
static const char* const kHttpProbeBodyLenMarker = "__YAMA_HTTP_BLEN__";
|
||||
static const char* const kHttpProbeBodyStartMarker= "__YAMA_HTTP_BS__";
|
||||
static const char* const kHttpProbeBodyChunkMarker= "__YAMA_HTTP_B__";
|
||||
static const char* const kHttpProbeBodyEndMarker = "__YAMA_HTTP_BE__";
|
||||
static const char* const kHttpProbeRcMarker = "__YAMA_HTTP_RC__";
|
||||
static const char* const kHttpProbeSizeMarker = "__YAMA_HTTP_SIZE__";
|
||||
|
||||
static int HttpProbeB64Value(unsigned char c) {
|
||||
if (c >= 'A' && c <= 'Z') return c - 'A';
|
||||
if (c >= 'a' && c <= 'z') return c - 'a' + 26;
|
||||
if (c >= '0' && c <= '9') return c - '0' + 52;
|
||||
if (c == '+') return 62;
|
||||
if (c == '/') return 63;
|
||||
return -1;
|
||||
}
|
||||
|
||||
// 宽容的 base64 解码:跳过空白与其它非字母表字符(ConPTY 会按屏宽给长行插换行)。
|
||||
static std::string HttpProbeB64Decode(const std::string& in) {
|
||||
std::string out;
|
||||
out.reserve(in.size() * 3 / 4 + 3);
|
||||
int val = 0, valb = -8;
|
||||
for (unsigned char c : in) {
|
||||
if (c == '=') break;
|
||||
int d = HttpProbeB64Value(c);
|
||||
if (d < 0) continue;
|
||||
val = (val << 6) + d;
|
||||
valb += 6;
|
||||
if (valb >= 0) {
|
||||
out.push_back((char)((val >> valb) & 0xFF));
|
||||
valb -= 8;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// 跳过空白(含折行)后读一个十进制整数;没有数字返回 0。
|
||||
static int HttpProbeReadInt(const std::string& s, size_t& i) {
|
||||
while (i < s.size() && (s[i] == '\r' || s[i] == '\n' || s[i] == ' ' || s[i] == '\t')) ++i;
|
||||
bool neg = false;
|
||||
if (i < s.size() && s[i] == '-') { neg = true; ++i; }
|
||||
int v = 0;
|
||||
bool any = false;
|
||||
while (i < s.size() && s[i] >= '0' && s[i] <= '9') {
|
||||
if (v < 100000000) v = v * 10 + (s[i] - '0');
|
||||
++i;
|
||||
any = true;
|
||||
}
|
||||
return any ? (neg ? -v : v) : 0;
|
||||
}
|
||||
|
||||
static bool HttpProbeParseIpv4(const std::string& s, unsigned out[4]) {
|
||||
int part = 0, digits = 0;
|
||||
unsigned val = 0;
|
||||
for (char ch : s) {
|
||||
if (ch >= '0' && ch <= '9') {
|
||||
val = val * 10 + (unsigned)(ch - '0');
|
||||
if (++digits > 3) return false;
|
||||
} else if (ch == '.' && part < 3 && digits > 0) {
|
||||
out[part++] = val;
|
||||
val = 0;
|
||||
digits = 0;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (part != 3 || digits == 0) return false;
|
||||
out[3] = val;
|
||||
for (int i = 0; i < 4; ++i) if (out[i] > 255) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
// URL 白名单校验。只收 scheme + IP 字面量(或 localhost),私网/回环之外一律拒绝。
|
||||
static bool HttpProbeCheckUrl(const std::string& url, std::string& err) {
|
||||
if (url.empty()) { err = "Missing required parameter: url"; return false; }
|
||||
if ((int)url.size() > kHttpProbeMaxUrlBytes) {
|
||||
err = "url is too long (max " + std::to_string(kHttpProbeMaxUrlBytes) + " bytes)";
|
||||
return false;
|
||||
}
|
||||
if (ContainsControlChar(url) || url.find(' ') != std::string::npos) {
|
||||
err = "Invalid URL: contains whitespace or control characters";
|
||||
return false;
|
||||
}
|
||||
|
||||
size_t p = url.find("://");
|
||||
if (p == std::string::npos) {
|
||||
err = "Invalid URL: expected http://<ip>[:port][/path]";
|
||||
return false;
|
||||
}
|
||||
std::string scheme = url.substr(0, p);
|
||||
if (_stricmp(scheme.c_str(), "http") != 0 && _stricmp(scheme.c_str(), "https") != 0) {
|
||||
err = "Invalid URL: only http and https are allowed";
|
||||
return false;
|
||||
}
|
||||
|
||||
size_t a = p + 3;
|
||||
size_t e = url.find_first_of("/?#", a);
|
||||
std::string authority = url.substr(a, e == std::string::npos ? std::string::npos : e - a);
|
||||
if (authority.empty()) { err = "Invalid URL: missing host"; return false; }
|
||||
if (authority.find('@') != std::string::npos) {
|
||||
err = "Invalid URL: userinfo (user:pass@) is not allowed";
|
||||
return false;
|
||||
}
|
||||
|
||||
std::string host, portStr;
|
||||
if (authority[0] == '[') {
|
||||
size_t rb = authority.find(']');
|
||||
if (rb == std::string::npos) { err = "Invalid URL: malformed IPv6 literal"; return false; }
|
||||
host = authority.substr(1, rb - 1);
|
||||
if (rb + 1 < authority.size()) {
|
||||
if (authority[rb + 1] != ':') { err = "Invalid URL: malformed authority"; return false; }
|
||||
portStr = authority.substr(rb + 2);
|
||||
}
|
||||
} else {
|
||||
size_t c = authority.rfind(':');
|
||||
if (c != std::string::npos) {
|
||||
host = authority.substr(0, c);
|
||||
portStr = authority.substr(c + 1);
|
||||
} else {
|
||||
host = authority;
|
||||
}
|
||||
}
|
||||
if (host.empty()) { err = "Invalid URL: missing host"; return false; }
|
||||
if (!portStr.empty()) {
|
||||
bool digits = portStr.size() <= 5;
|
||||
for (char ch : portStr) if (ch < '0' || ch > '9') digits = false;
|
||||
if (!digits) { err = "Invalid URL: port must be numeric (1-65535)"; return false; }
|
||||
int port = atoi(portStr.c_str());
|
||||
if (port < 1 || port > 65535) { err = "Invalid URL: port must be 1-65535"; return false; }
|
||||
}
|
||||
|
||||
if (_stricmp(host.c_str(), "localhost") == 0) return true;
|
||||
if (host == "::1" || host == "0:0:0:0:0:0:0:1") return true;
|
||||
unsigned o[4] = { 0, 0, 0, 0 };
|
||||
if (HttpProbeParseIpv4(host, o) &&
|
||||
(o[0] == 127 || o[0] == 10 || (o[0] == 172 && o[1] >= 16 && o[1] <= 31) ||
|
||||
(o[0] == 192 && o[1] == 168)))
|
||||
return true;
|
||||
|
||||
err = "Refused URL: only private/loopback IP literals are allowed "
|
||||
"(127.0.0.0/8, ::1, 10/8, 172.16/12, 192.168/16) or localhost — got host '" + host + "'";
|
||||
return false;
|
||||
}
|
||||
|
||||
// headers 对象 → "Name: value\n" 序列化(同时做注入校验)。
|
||||
static bool HttpProbeBuildHeaderBlob(const Json::Value& headers, std::string& blob, std::string& err) {
|
||||
blob.clear();
|
||||
if (headers.isNull()) return true;
|
||||
if (!headers.isObject()) { err = "headers must be an object mapping header names to string values"; return false; }
|
||||
for (const std::string& k : headers.getMemberNames()) {
|
||||
if (!headers[k].isString()) { err = "headers." + k + " must be a string"; return false; }
|
||||
if (k.empty() || k.size() > 64) { err = "Invalid header name: " + k; return false; }
|
||||
for (char ch : k) {
|
||||
const bool alphaNum = (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') ||
|
||||
(ch >= '0' && ch <= '9');
|
||||
if (!alphaNum && ch != '-' && ch != '_') {
|
||||
err = "Invalid header name: " + k;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (_stricmp(k.c_str(), "Content-Length") == 0) {
|
||||
err = "Invalid header: Content-Length is set by the tool, do not pass it";
|
||||
return false;
|
||||
}
|
||||
std::string v = headers[k].asString();
|
||||
if (v.size() > 256) { err = "Header value too long: " + k; return false; }
|
||||
for (char ch : v) {
|
||||
if ((unsigned char)ch < 0x20 && ch != '\t') {
|
||||
err = "Invalid header value for " + k + ": contains control characters";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
blob += k + ": " + v + "\n";
|
||||
if ((int)blob.size() > kHttpProbeMaxHeaderBlob) {
|
||||
err = "headers are too large (max " + std::to_string(kHttpProbeMaxHeaderBlob) + " bytes after serialization)";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// POSIX 单引号转义:' → '\'',其余原样。
|
||||
static std::string HttpProbeShellQuote(const std::string& s) {
|
||||
std::string out = "'";
|
||||
for (char c : s) {
|
||||
if (c == '\'') out += "'\\''";
|
||||
else out += c;
|
||||
}
|
||||
out += "'";
|
||||
return out;
|
||||
}
|
||||
|
||||
// Windows 命令:powershell -Command "<内联脚本>"。脚本里只出现单引号,值一律 base64,
|
||||
// 因此 cmd 的双引号包裹不需要再转义;整行长度受 kHttpProbeCmdLineBudget 约束。
|
||||
static std::string BuildHttpProbeWindowsCommand(const std::string& url, const std::string& method,
|
||||
const std::string& headerBlob, const std::string& body,
|
||||
int timeoutMs, int maxBytes) {
|
||||
using httplib::detail::base64_encode;
|
||||
const std::string st = kHttpProbeStatusMarker;
|
||||
const std::string hlen = kHttpProbeHdrLenMarker;
|
||||
const std::string hs = kHttpProbeHdrStartMarker;
|
||||
const std::string hc = kHttpProbeHdrChunkMarker;
|
||||
const std::string he = kHttpProbeHdrEndMarker;
|
||||
const std::string tr = kHttpProbeTruncMarker;
|
||||
const std::string el = kHttpProbeElapsedMarker;
|
||||
const std::string blen = kHttpProbeBodyLenMarker;
|
||||
const std::string bs = kHttpProbeBodyStartMarker;
|
||||
const std::string bc = kHttpProbeBodyChunkMarker;
|
||||
const std::string be = kHttpProbeBodyEndMarker;
|
||||
const std::string er = kHttpProbeErrMarker;
|
||||
const std::string ers = kHttpProbeErrStartMarker;
|
||||
const std::string ec = kHttpProbeErrChunkMarker;
|
||||
const std::string ere = kHttpProbeErrEndMarker;
|
||||
const std::string chunk = std::to_string(kHttpProbeChunkChars);
|
||||
|
||||
std::string s;
|
||||
s += "$ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue';";
|
||||
s += "try{[Net.ServicePointManager]::SecurityProtocol=[Net.SecurityProtocolType]::Tls12}catch{};";
|
||||
s += "$u=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('" + base64_encode(url) + "'));";
|
||||
s += "$hx=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('" + base64_encode(headerBlob) + "'));";
|
||||
s += "$y=[Convert]::FromBase64String('" + base64_encode(body) + "');";
|
||||
s += "$sw=[Diagnostics.Stopwatch]::StartNew();";
|
||||
s += "try{";
|
||||
s += "$r=[Net.HttpWebRequest]::Create($u);";
|
||||
s += "$r.Method='" + method + "';$r.Timeout=" + std::to_string(timeoutMs) + ";";
|
||||
s += "$r.ReadWriteTimeout=" + std::to_string(timeoutMs) + ";$r.AllowAutoRedirect=$false;";
|
||||
s += "foreach($l in $hx.Split([char]10)){if($l.Length -gt 0){$i=$l.IndexOf(':');if($i -gt 0){";
|
||||
s += "$k=$l.Substring(0,$i);$v=$l.Substring($i+1).Trim();";
|
||||
// 受限头(.NET 不接受 Headers.Add)里常用的三个走专用属性;其余受限头由框架报错。
|
||||
s += "if($k -ieq 'Content-Type'){$r.ContentType=$v}else{if($k -ieq 'Host'){$r.Host=$v}else{";
|
||||
s += "if($k -ieq 'Accept'){$r.Accept=$v}else{if($k -ieq 'User-Agent'){$r.UserAgent=$v}else{";
|
||||
s += "if($k -ieq 'Referer'){$r.Referer=$v}else{$r.Headers.Add($k,$v)}}}}}}}};";
|
||||
s += "if($y.Length -gt 0){$r.ContentLength=$y.Length;if($null -eq $r.ContentType){$r.ContentType='application/octet-stream'};";
|
||||
s += "$q=$r.GetRequestStream();$q.Write($y,0,$y.Length);$q.Close()};";
|
||||
s += "try{$p=$r.GetResponse()}catch [Net.WebException] {$p=$_.Exception.Response;if($null -eq $p){throw}};";
|
||||
s += "$gs=$p.GetResponseStream();$ms=New-Object IO.MemoryStream;$bf=New-Object byte[] 8192;$tr=0;";
|
||||
s += "while($true){$n=$gs.Read($bf,0,$bf.Length);if($n -le 0){break};";
|
||||
s += "$left=" + std::to_string(maxBytes) + "-$ms.Length;";
|
||||
s += "if($n -gt $left){$ms.Write($bf,0,[int]$left);$tr=1;break};$ms.Write($bf,0,$n)};";
|
||||
s += "$gs.Close();";
|
||||
s += "$hl='';foreach($k in $p.Headers.AllKeys){$hl=$hl+$k+': '+$p.Headers[$k]+[char]10};";
|
||||
s += "$hb=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($hl));";
|
||||
s += "$bb=[Convert]::ToBase64String($ms.ToArray());";
|
||||
s += "[Console]::Out.WriteLine('" + st + "'+[int]$p.StatusCode);";
|
||||
s += "[Console]::Out.WriteLine('" + hlen + "'+[Text.Encoding]::UTF8.GetByteCount($hl));";
|
||||
s += "[Console]::Out.WriteLine('" + hs + "');";
|
||||
s += "for($i=0;$i -lt $hb.Length;$i+=" + chunk + "){[Console]::Out.WriteLine('" + hc +
|
||||
"'+$hb.Substring($i,[Math]::Min(" + chunk + ",$hb.Length-$i)))};";
|
||||
s += "[Console]::Out.WriteLine('" + he + "');";
|
||||
s += "[Console]::Out.WriteLine('" + tr + "'+$tr);";
|
||||
s += "[Console]::Out.WriteLine('" + el + "'+[int]$sw.ElapsedMilliseconds);";
|
||||
s += "[Console]::Out.WriteLine('" + blen + "'+$ms.Length);";
|
||||
s += "[Console]::Out.WriteLine('" + bs + "');";
|
||||
s += "for($i=0;$i -lt $bb.Length;$i+=" + chunk + "){[Console]::Out.WriteLine('" + bc +
|
||||
"'+$bb.Substring($i,[Math]::Min(" + chunk + ",$bb.Length-$i)))};";
|
||||
s += "[Console]::Out.WriteLine('" + be + "');";
|
||||
s += "try{$p.Close()}catch{}";
|
||||
s += "}catch{$em=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($_.Exception.Message));";
|
||||
s += "[Console]::Out.WriteLine('" + er + "'+[Text.Encoding]::UTF8.GetByteCount($_.Exception.Message));";
|
||||
s += "[Console]::Out.WriteLine('" + ers + "');";
|
||||
s += "for($i=0;$i -lt $em.Length;$i+=" + chunk + "){[Console]::Out.WriteLine('" + ec +
|
||||
"'+$em.Substring($i,[Math]::Min(" + chunk + ",$em.Length-$i)))};";
|
||||
s += "[Console]::Out.WriteLine('" + ere + "')}";
|
||||
|
||||
return "powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command \"" + s + "\"";
|
||||
}
|
||||
|
||||
// POSIX 命令:curl 写临时文件,再按行分块打印标记 + base64。所有值走单引号转义。
|
||||
static std::string BuildHttpProbePosixCommand(const std::string& nonce, const std::string& url,
|
||||
const std::string& method, const std::string& headerBlob,
|
||||
const std::string& body, int timeoutMs, int maxBytes) {
|
||||
using httplib::detail::base64_encode;
|
||||
const std::string base = "/tmp/.yama_hp_" + nonce;
|
||||
const std::string req = base + ".req";
|
||||
const std::string resp = base + ".resp";
|
||||
const std::string hdr = base + ".hdr";
|
||||
const std::string bdy = base + ".body";
|
||||
const int secs = (timeoutMs + 999) / 1000;
|
||||
const std::string chunk = std::to_string(kHttpProbeChunkChars);
|
||||
|
||||
std::string cmd;
|
||||
if (!body.empty())
|
||||
cmd += "printf %s '" + base64_encode(body) + "' | base64 -d > " + req + " ; ";
|
||||
// --max-filesize 只是防止被巨大响应拖死(16MB 安全阀);返回给调用方的仍是最多 max_bytes。
|
||||
cmd += "curl -sS -m " + std::to_string(secs) +
|
||||
" --max-filesize 16777216" +
|
||||
" -X " + HttpProbeShellQuote(method) +
|
||||
" -D " + hdr + " -o " + resp;
|
||||
{
|
||||
size_t i = 0;
|
||||
while (i < headerBlob.size()) {
|
||||
size_t j = headerBlob.find('\n', i);
|
||||
if (j == std::string::npos) j = headerBlob.size();
|
||||
std::string line = headerBlob.substr(i, j - i);
|
||||
if (!line.empty()) cmd += " -H " + HttpProbeShellQuote(line);
|
||||
i = j + 1;
|
||||
}
|
||||
}
|
||||
if (!body.empty()) cmd += " --data-binary @" + req;
|
||||
cmd += " -w '" + std::string(kHttpProbeStatusMarker) + "%{http_code}\\n' " + HttpProbeShellQuote(url);
|
||||
cmd += " ; __hp_rc=$?";
|
||||
cmd += " ; head -c " + std::to_string(maxBytes) + " " + resp + " > " + bdy + " 2>/dev/null";
|
||||
cmd += " ; echo '" + std::string(kHttpProbeHdrLenMarker) + "'$(wc -c < " + hdr + " 2>/dev/null)";
|
||||
cmd += " ; echo '" + std::string(kHttpProbeHdrStartMarker) + "'";
|
||||
cmd += " ; base64 -w " + chunk + " < " + hdr + " 2>/dev/null";
|
||||
cmd += " ; echo '" + std::string(kHttpProbeHdrEndMarker) + "'";
|
||||
cmd += " ; echo '" + std::string(kHttpProbeBodyLenMarker) + "'$(wc -c < " + bdy + " 2>/dev/null)";
|
||||
cmd += " ; echo '" + std::string(kHttpProbeBodyStartMarker) + "'";
|
||||
cmd += " ; base64 -w " + chunk + " < " + bdy + " 2>/dev/null";
|
||||
cmd += " ; echo '" + std::string(kHttpProbeBodyEndMarker) + "'";
|
||||
cmd += " ; echo '" + std::string(kHttpProbeRcMarker) + "'$__hp_rc";
|
||||
cmd += " ; echo '" + std::string(kHttpProbeSizeMarker) + "'$(wc -c < " + resp + " 2>/dev/null)";
|
||||
cmd += " ; rm -f " + req + " " + resp + " " + hdr + " " + bdy;
|
||||
return cmd;
|
||||
}
|
||||
|
||||
struct HttpProbeParsed {
|
||||
bool hasStatus = false;
|
||||
int status = 0;
|
||||
int rc = 0;
|
||||
long long size = -1;
|
||||
bool truncated = false;
|
||||
int elapsedMs = 0;
|
||||
std::string headerBlob;
|
||||
std::string body;
|
||||
std::string error;
|
||||
};
|
||||
|
||||
static std::string HttpProbeSnippet(const std::string& out) {
|
||||
std::string t = Trim(out);
|
||||
if (t.size() > 400) t = "..." + t.substr(t.size() - 400);
|
||||
return t.empty() ? std::string("(empty output)") : t;
|
||||
}
|
||||
|
||||
// 收集 LEN/START/CHUNK/END 四个标记之间的分块 base64 并解码。
|
||||
// Windows 的每行带 chunk 前缀;POSIX 用 `base64 -w 56` 折行,行内只有 base64 字符。
|
||||
// 长度行给出解码后的字节数,用于发现折行/清洗造成的字符丢失(PTY 曾把边界字符重复)。
|
||||
static bool HttpProbeCollectPayload(const std::string& out, size_t from,
|
||||
const char* lenMarker, const char* startMarker,
|
||||
const char* chunkMarker, const char* endMarker,
|
||||
std::string& decoded) {
|
||||
decoded.clear();
|
||||
const size_t lp = out.find(lenMarker, from);
|
||||
if (lp == std::string::npos) return false;
|
||||
size_t lj = lp + strlen(lenMarker);
|
||||
const int declared = HttpProbeReadInt(out, lj);
|
||||
const size_t sp = out.find(startMarker, lp);
|
||||
if (sp == std::string::npos) return false;
|
||||
const size_t spEnd = sp + strlen(startMarker);
|
||||
const size_t ep = out.find(endMarker, spEnd);
|
||||
if (ep == std::string::npos) return false;
|
||||
|
||||
const size_t cm = strlen(chunkMarker);
|
||||
std::string b64;
|
||||
size_t i = spEnd;
|
||||
while (i < ep) {
|
||||
size_t e = out.find('\n', i);
|
||||
if (e == std::string::npos || e > ep) e = ep;
|
||||
std::string line = out.substr(i, e - i);
|
||||
i = (e < ep) ? e + 1 : ep;
|
||||
if (!line.empty() && line.back() == '\r') line.pop_back();
|
||||
size_t b = line.find_first_not_of(' ');
|
||||
line = (b == std::string::npos) ? std::string() : line.substr(b);
|
||||
if (line.empty()) continue;
|
||||
if (line.compare(0, cm, chunkMarker) == 0) b64 += line.substr(cm);
|
||||
else b64 += line; // POSIX 的裸 base64 行
|
||||
}
|
||||
decoded = HttpProbeB64Decode(b64);
|
||||
return declared >= 0 && (long long)decoded.size() == (long long)declared;
|
||||
}
|
||||
|
||||
// Windows:tail = 最后一个 STATUS 标记之后(回显里也可能有标记,最后一个是真实输出)。
|
||||
// 若有更晚的 ERR 标记则按错误处理。
|
||||
static bool ParseHttpProbeWindowsOutput(const std::string& out, HttpProbeParsed& p) {
|
||||
const size_t st = out.rfind(kHttpProbeStatusMarker);
|
||||
const size_t er = out.rfind(kHttpProbeErrMarker);
|
||||
if (st == std::string::npos && er == std::string::npos) return false;
|
||||
|
||||
if (er != std::string::npos && (st == std::string::npos || er > st)) {
|
||||
if (!HttpProbeCollectPayload(out, er, kHttpProbeErrMarker, kHttpProbeErrStartMarker,
|
||||
kHttpProbeErrChunkMarker, kHttpProbeErrEndMarker, p.error))
|
||||
p.error = "request failed on host (error detail was corrupted or truncated)";
|
||||
else if (p.error.empty())
|
||||
p.error = "request failed on host (no error detail)";
|
||||
return true;
|
||||
}
|
||||
|
||||
size_t i = st + strlen(kHttpProbeStatusMarker);
|
||||
p.status = HttpProbeReadInt(out, i);
|
||||
p.hasStatus = true;
|
||||
|
||||
size_t tp = out.find(kHttpProbeTruncMarker, i);
|
||||
if (tp != std::string::npos) {
|
||||
size_t j = tp + strlen(kHttpProbeTruncMarker);
|
||||
p.truncated = HttpProbeReadInt(out, j) != 0;
|
||||
}
|
||||
size_t ep = out.find(kHttpProbeElapsedMarker, i);
|
||||
if (ep != std::string::npos) {
|
||||
size_t j = ep + strlen(kHttpProbeElapsedMarker);
|
||||
p.elapsedMs = HttpProbeReadInt(out, j);
|
||||
}
|
||||
if (!HttpProbeCollectPayload(out, i, kHttpProbeHdrLenMarker, kHttpProbeHdrStartMarker,
|
||||
kHttpProbeHdrChunkMarker, kHttpProbeHdrEndMarker, p.headerBlob)) {
|
||||
p.error = "host output was corrupted or truncated (response headers)";
|
||||
return true;
|
||||
}
|
||||
if (!HttpProbeCollectPayload(out, i, kHttpProbeBodyLenMarker, kHttpProbeBodyStartMarker,
|
||||
kHttpProbeBodyChunkMarker, kHttpProbeBodyEndMarker, p.body)) {
|
||||
p.error = "host output was corrupted or truncated (response body)";
|
||||
return true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// POSIX:curl -w 打 STATUS,随后 HLEN/HS/HE、BLEN/BS/BE、RC、SIZE 各标记行。
|
||||
static bool ParseHttpProbePosixOutput(const std::string& out, int maxBytes, HttpProbeParsed& p) {
|
||||
const size_t st = out.rfind(kHttpProbeStatusMarker);
|
||||
if (st == std::string::npos) return false;
|
||||
size_t i = st + strlen(kHttpProbeStatusMarker);
|
||||
p.status = HttpProbeReadInt(out, i);
|
||||
p.hasStatus = true;
|
||||
|
||||
size_t rp = out.find(kHttpProbeRcMarker, i);
|
||||
if (rp != std::string::npos) {
|
||||
size_t j = rp + strlen(kHttpProbeRcMarker);
|
||||
p.rc = HttpProbeReadInt(out, j);
|
||||
}
|
||||
size_t zp = out.find(kHttpProbeSizeMarker, i);
|
||||
if (zp != std::string::npos) {
|
||||
size_t j = zp + strlen(kHttpProbeSizeMarker);
|
||||
int v = HttpProbeReadInt(out, j);
|
||||
if (v > 0) p.size = v;
|
||||
}
|
||||
p.truncated = (p.rc == 63) || (p.size > (long long)maxBytes);
|
||||
if (p.status == 0) {
|
||||
std::string detail;
|
||||
std::istringstream iss(out);
|
||||
std::string line;
|
||||
while (std::getline(iss, line)) {
|
||||
if (line.find("curl:") != std::string::npos) { detail = Trim(line); break; }
|
||||
}
|
||||
if (detail.empty()) detail = HttpProbeSnippet(out);
|
||||
p.error = "curl failed (exit " + std::to_string(p.rc) + "): " + detail;
|
||||
return true;
|
||||
}
|
||||
if (!HttpProbeCollectPayload(out, i, kHttpProbeHdrLenMarker, kHttpProbeHdrStartMarker,
|
||||
kHttpProbeHdrChunkMarker, kHttpProbeHdrEndMarker, p.headerBlob)) {
|
||||
p.error = "host output was corrupted or truncated (response headers)";
|
||||
return true;
|
||||
}
|
||||
if (!HttpProbeCollectPayload(out, i, kHttpProbeBodyLenMarker, kHttpProbeBodyStartMarker,
|
||||
kHttpProbeBodyChunkMarker, kHttpProbeBodyEndMarker, p.body)) {
|
||||
p.error = "host output was corrupted or truncated (response body)";
|
||||
return true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static void ParseHttpProbeHeaders(const std::string& blob, Json::Value& hdrs) {
|
||||
hdrs = Json::Value(Json::objectValue);
|
||||
std::istringstream iss(blob);
|
||||
std::string line, lastKey;
|
||||
while (std::getline(iss, line)) {
|
||||
if (!line.empty() && line.back() == '\r') line.pop_back();
|
||||
if (line.empty()) continue;
|
||||
if (line[0] == ' ' || line[0] == '\t') { // 折行续接
|
||||
if (!lastKey.empty())
|
||||
hdrs[lastKey] = hdrs[lastKey].asString() + " " + Trim(line);
|
||||
continue;
|
||||
}
|
||||
if (line.compare(0, 5, "HTTP/") == 0) continue; // curl -D 的状态行
|
||||
size_t c = line.find(':');
|
||||
if (c == std::string::npos) continue;
|
||||
std::string k = Trim(line.substr(0, c));
|
||||
std::string v = Trim(line.substr(c + 1));
|
||||
if (k.empty()) continue;
|
||||
if (hdrs.isMember(k)) hdrs[k] = hdrs[k].asString() + ", " + v;
|
||||
else hdrs[k] = v;
|
||||
lastKey = k;
|
||||
}
|
||||
}
|
||||
|
||||
Json::Value BuildHttpProbeInputSchema() {
|
||||
Json::Value props(Json::objectValue);
|
||||
Json::Value idProp(Json::objectValue);
|
||||
idProp["type"] = "string";
|
||||
idProp["description"] = u8"主机 id,取 list_online_hosts / search_hosts 返回的 id 字段";
|
||||
props["id"] = idProp;
|
||||
Json::Value urlProp(Json::objectValue);
|
||||
urlProp["type"] = "string";
|
||||
urlProp["description"] = u8"要请求的地址:http:// 或 https:// + IP 字面量(或 localhost)+ 可选 :端口 + 路径,如 http://127.0.0.1:8003/health";
|
||||
props["url"] = urlProp;
|
||||
Json::Value mProp(Json::objectValue);
|
||||
mProp["type"] = "string";
|
||||
mProp["enum"] = Json::Value(Json::arrayValue);
|
||||
for (const char* m : { "GET", "POST", "PUT", "DELETE", "HEAD", "PATCH", "OPTIONS" })
|
||||
mProp["enum"].append(m);
|
||||
mProp["description"] = u8"HTTP 方法,默认 GET";
|
||||
props["method"] = mProp;
|
||||
Json::Value hProp(Json::objectValue);
|
||||
hProp["type"] = "object";
|
||||
Json::Value hAdd(Json::objectValue);
|
||||
hAdd["type"] = "string";
|
||||
hProp["additionalProperties"] = hAdd;
|
||||
hProp["description"] = u8"请求头(对象,名→值都是字符串),如 {\"Authorization\":\"Bearer x\"};序列化后上限 512 字节,不接受 Content-Length;Windows 上少数受限头(如 Connection、Expect、Range)会被系统拒收,Accept/User-Agent/Referer 已单独支持";
|
||||
props["headers"] = hProp;
|
||||
Json::Value bProp(Json::objectValue);
|
||||
bProp["type"] = "string";
|
||||
bProp["description"] = u8"请求体(可选,≤2048 字节),按 UTF-8 发送;POST/PUT/PATCH 时常用";
|
||||
props["body"] = bProp;
|
||||
Json::Value tProp(Json::objectValue);
|
||||
tProp["type"] = "integer";
|
||||
tProp["description"] = u8"请求超时毫秒数(默认 10000,范围 1000-60000);工具等待 = 该值 + 20 秒(含 shell 启动)";
|
||||
props["timeout_ms"] = tProp;
|
||||
Json::Value mbProp(Json::objectValue);
|
||||
mbProp["type"] = "integer";
|
||||
mbProp["description"] = u8"响应体最多返回的字节数(默认 65536,范围 1-65536),超出置 truncated=true";
|
||||
props["max_bytes"] = mbProp;
|
||||
Json::Value schema(Json::objectValue);
|
||||
schema["type"] = "object";
|
||||
schema["properties"] = props;
|
||||
Json::Value required(Json::arrayValue);
|
||||
required.append("id");
|
||||
required.append("url");
|
||||
schema["required"] = required;
|
||||
return schema;
|
||||
}
|
||||
|
||||
Json::Value BuildHttpProbeOutputSchema() {
|
||||
Json::Value props(Json::objectValue);
|
||||
Json::Value statusProp(Json::objectValue);
|
||||
statusProp["type"] = "integer";
|
||||
statusProp["description"] = u8"HTTP 状态码";
|
||||
props["status"] = statusProp;
|
||||
Json::Value okProp(Json::objectValue);
|
||||
okProp["type"] = "boolean";
|
||||
okProp["description"] = u8"true = 2xx/3xx;3xx 未跟随重定向";
|
||||
props["ok"] = okProp;
|
||||
Json::Value headersProp(Json::objectValue);
|
||||
headersProp["type"] = "object";
|
||||
headersProp["description"] = u8"响应头(名→值;同名多值用逗号拼接)";
|
||||
props["headers"] = headersProp;
|
||||
Json::Value bodyProp(Json::objectValue);
|
||||
bodyProp["type"] = "string";
|
||||
bodyProp["description"] = u8"响应体(响应体是合法 UTF-8 时才填;否则为空,看 body_base64)";
|
||||
props["body"] = bodyProp;
|
||||
Json::Value encProp(Json::objectValue);
|
||||
encProp["type"] = "string";
|
||||
encProp["description"] = u8"body 的编码:utf-8 或 base64";
|
||||
props["body_encoding"] = encProp;
|
||||
Json::Value b64Prop(Json::objectValue);
|
||||
b64Prop["type"] = "string";
|
||||
b64Prop["description"] = u8"响应体的 base64(仅 body_encoding=base64 时提供,非 UTF-8 的二进制响应)";
|
||||
props["body_base64"] = b64Prop;
|
||||
Json::Value bytesProp(Json::objectValue);
|
||||
bytesProp["type"] = "integer";
|
||||
bytesProp["description"] = u8"本次返回的响应体字节数(被截断时即 max_bytes 内实际读到的)";
|
||||
props["body_bytes"] = bytesProp;
|
||||
Json::Value truncProp(Json::objectValue);
|
||||
truncProp["type"] = "boolean";
|
||||
truncProp["description"] = u8"true = 响应体超过 max_bytes,只返回了前缀";
|
||||
props["truncated"] = truncProp;
|
||||
Json::Value elProp(Json::objectValue);
|
||||
elProp["type"] = "integer";
|
||||
elProp["description"] = u8"请求耗时毫秒(Windows 在 PowerShell 内计时;Linux 为服务端整轮计时)";
|
||||
props["elapsed_ms"] = elProp;
|
||||
Json::Value urlProp(Json::objectValue);
|
||||
urlProp["type"] = "string";
|
||||
urlProp["description"] = u8"回显请求的 url";
|
||||
props["url"] = urlProp;
|
||||
Json::Value schema(Json::objectValue);
|
||||
schema["type"] = "object";
|
||||
schema["properties"] = props;
|
||||
Json::Value required(Json::arrayValue);
|
||||
for (const char* k : { "status", "ok", "headers", "body", "body_encoding", "body_bytes",
|
||||
"truncated", "elapsed_ms", "url" })
|
||||
required.append(k);
|
||||
schema["required"] = required;
|
||||
return schema;
|
||||
}
|
||||
|
||||
// tools/call:http_probe(在被管主机上请求私有网段 HTTP 地址;复用持久终端会话)
|
||||
std::string BuildHttpProbe(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
|
||||
CMcpServer& mcp = CMcpServer::Instance();
|
||||
if (!mcp.IsTerminalEnabled() || mcp.IsReadonly())
|
||||
return BuildError(id, -32006,
|
||||
"http_probe is disabled: requires McpTerminal=1 and McpReadonly=0");
|
||||
|
||||
uint64_t devId = 0;
|
||||
std::string err;
|
||||
if (!ParseHostIdArg(args, devId, err))
|
||||
return BuildError(id, -32602, err);
|
||||
|
||||
context* ctx = FindMainContext(parent, devId);
|
||||
if (!ctx)
|
||||
return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId));
|
||||
|
||||
CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
|
||||
if (clientType == "MAC" || clientType == "APK")
|
||||
return BuildError(id, -32005, "http_probe is only supported on Windows and Linux hosts");
|
||||
const bool posix = (clientType == "LNX");
|
||||
|
||||
std::string url = Trim(GetStringArg(args, "url"));
|
||||
std::string method = Trim(GetStringArg(args, "method"));
|
||||
if (method.empty()) method = "GET";
|
||||
for (char& c : method) if (c >= 'a' && c <= 'z') c = (char)(c - 'a' + 'A');
|
||||
static const char* const kAllowedMethods[] = { "GET", "POST", "PUT", "DELETE", "HEAD", "PATCH", "OPTIONS" };
|
||||
bool methodOk = false;
|
||||
for (const char* m : kAllowedMethods) if (method == m) methodOk = true;
|
||||
if (!methodOk)
|
||||
return BuildError(id, -32602, "Invalid method: " + method +
|
||||
" (allowed: GET, POST, PUT, DELETE, HEAD, PATCH, OPTIONS)");
|
||||
|
||||
if (!HttpProbeCheckUrl(url, err))
|
||||
return BuildError(id, -32602, err);
|
||||
|
||||
std::string headerBlob;
|
||||
if (!HttpProbeBuildHeaderBlob(args["headers"], headerBlob, err))
|
||||
return BuildError(id, -32602, err);
|
||||
|
||||
std::string body;
|
||||
if (args.isMember("body") && !args["body"].isNull()) {
|
||||
if (!args["body"].isString())
|
||||
return BuildError(id, -32602, "body must be a string");
|
||||
body = args["body"].asString();
|
||||
}
|
||||
if ((int)body.size() > kHttpProbeMaxBodyBytes)
|
||||
return BuildError(id, -32602, "body is too large (max " + std::to_string(kHttpProbeMaxBodyBytes) + " bytes)");
|
||||
|
||||
int timeoutMs = kHttpProbeDefaultTimeoutMs;
|
||||
int v = 0;
|
||||
if (GetIntArg(args, "timeout_ms", v) && v > 0) {
|
||||
if (v < kHttpProbeMinTimeoutMs || v > kHttpProbeMaxTimeoutMs)
|
||||
return BuildError(id, -32602, "timeout_ms must be between " +
|
||||
std::to_string(kHttpProbeMinTimeoutMs) + " and " +
|
||||
std::to_string(kHttpProbeMaxTimeoutMs));
|
||||
timeoutMs = v;
|
||||
}
|
||||
|
||||
int maxBytes = kHttpProbeDefaultMaxBytes;
|
||||
if (GetIntArg(args, "max_bytes", v) && v > 0) {
|
||||
if (v > kHttpProbeDefaultMaxBytes)
|
||||
return BuildError(id, -32602, "max_bytes must be between 1 and " + std::to_string(kHttpProbeDefaultMaxBytes));
|
||||
maxBytes = v;
|
||||
}
|
||||
|
||||
mcp.SweepIdleTerminals(kTermIdleTimeoutSec);
|
||||
|
||||
std::string sessionId;
|
||||
bool reused = true;
|
||||
int openOrReuse = mcp.OpenOrReuseTermSession(devId, sessionId, reused);
|
||||
if (openOrReuse != 0)
|
||||
return BuildError(id, -32003, "Device busy: a terminal session for this host is still starting");
|
||||
if (!reused) {
|
||||
BYTE openCmd = COMMAND_SHELL;
|
||||
if (!ctx->Send2Client(&openCmd, 1)) {
|
||||
mcp.ClearTermPending(devId);
|
||||
return BuildError(id, -32004, "Failed to send command to host");
|
||||
}
|
||||
context* openSubCtx = nullptr;
|
||||
bool openPty = false;
|
||||
// 冷启动可能比 ToolTimeoutMs 慢(客户端要先拉起 shell/PTY),用探测超时 + 余量兜住。
|
||||
const int probeWaitMs = timeoutMs + kHttpProbeWaitMarginMs;
|
||||
const int toolWaitMs = mcp.ToolTimeoutMs();
|
||||
const int openWaitMs = probeWaitMs > toolWaitMs ? probeWaitMs : toolWaitMs;
|
||||
if (!mcp.WaitTerminalReady(devId, openSubCtx, openPty, openWaitMs))
|
||||
return BuildError(id, -32001, "Timeout waiting for shell to start");
|
||||
}
|
||||
|
||||
auto sessionErr = [&](int code) -> std::string {
|
||||
std::string destroyed = mcp.DescribeTermDestroyed(devId, sessionId);
|
||||
if (!destroyed.empty())
|
||||
return BuildError(id, -32002, destroyed);
|
||||
if (code == 4)
|
||||
return BuildError(id, -32003, "Device busy: another command is running in this host's terminal session");
|
||||
if (code == 6)
|
||||
return BuildError(id, -32003,
|
||||
"Device busy: the previous terminal command's output is not fully drained; "
|
||||
"call terminal_exec with only session_id to collect it first");
|
||||
if (code == 7)
|
||||
return BuildError(id, -32002, "Terminal session is idle: no command is running");
|
||||
return BuildError(id, -32002, "Terminal session is not ready: " + sessionId);
|
||||
};
|
||||
|
||||
std::string nonce = GenerateRandomToken().substr(0, 8);
|
||||
std::string command = posix
|
||||
? BuildHttpProbePosixCommand(nonce, url, method, headerBlob, body, timeoutMs, maxBytes)
|
||||
: BuildHttpProbeWindowsCommand(url, method, headerBlob, body, timeoutMs, maxBytes);
|
||||
if ((int)command.size() > kHttpProbeCmdLineBudget)
|
||||
return BuildError(id, -32602,
|
||||
"Request too large for the host shell: command would be " +
|
||||
std::to_string(command.size()) + " chars, limit is " +
|
||||
std::to_string(kHttpProbeCmdLineBudget) +
|
||||
" (shorten url/headers/body)");
|
||||
|
||||
context* subCtx = nullptr;
|
||||
bool isPty = false;
|
||||
// POSIX 端没有可靠的进程内计时(curl 拿不到),用服务端整轮耗时兜底。
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
int begin = mcp.BeginTermCommand(devId, sessionId, "http_probe " + method + " " + url, nonce, subCtx, isPty);
|
||||
if (begin != 0)
|
||||
return sessionErr(begin);
|
||||
|
||||
if (posix && isPty)
|
||||
mcp.WaitTerminalBootstrap(devId, 2000);
|
||||
|
||||
std::string cmdLine, sentLine;
|
||||
SendTerminalCommandLine(subCtx, isPty, posix, command, nonce, cmdLine, sentLine);
|
||||
|
||||
// 审计:请求的目标(不可关闭;不带 body/headers,避免泄露凭据)。
|
||||
if (parent) {
|
||||
std::string text = "host " + std::to_string(devId) + " http-probe: " + method + " " + url;
|
||||
parent->PostMessageA(WM_SHOWERRORMSG,
|
||||
(WPARAM)new CString(ToAnsi(text, 936).c_str()),
|
||||
(LPARAM)new CString(_TR("MCP命令执行")));
|
||||
}
|
||||
|
||||
const int waitMs = timeoutMs + kHttpProbeWaitMarginMs;
|
||||
std::vector<BYTE> all;
|
||||
bool done = false, closed = false, chunkTruncated = false;
|
||||
size_t dropped = 0;
|
||||
int exitCode = -1;
|
||||
int wr = mcp.WaitTermCommand(devId, sessionId, all, done, exitCode, closed,
|
||||
chunkTruncated, dropped, isPty, nonce,
|
||||
kHttpProbeMaxOutputBytes, waitMs, false);
|
||||
if (wr == 2)
|
||||
return BuildError(id, -32001, "Request cancelled; the terminal session was destroyed");
|
||||
if (wr != 0 && wr != 1)
|
||||
return sessionErr(wr);
|
||||
|
||||
// 交付上限 1MB,正常一次取完;万一还没结束就继续轮询(与 terminal_exec 的超时语义一致)。
|
||||
int polls = 0;
|
||||
while (!done && polls < 200) {
|
||||
std::vector<BYTE> more;
|
||||
wr = mcp.WaitTermCommand(devId, sessionId, more, done, exitCode, closed,
|
||||
chunkTruncated, dropped, isPty, nonce,
|
||||
kHttpProbeMaxOutputBytes, waitMs, true);
|
||||
if (wr == 2)
|
||||
return BuildError(id, -32001, "Request cancelled; the terminal session was destroyed");
|
||||
if (wr != 0 && wr != 1)
|
||||
return sessionErr(wr);
|
||||
all.insert(all.end(), more.begin(), more.end());
|
||||
++polls;
|
||||
}
|
||||
if (!done)
|
||||
return BuildError(id, -32001,
|
||||
"Timeout waiting for http_probe result; the request is still running in terminal session " +
|
||||
sessionId + " (call terminal_exec with only session_id to collect the tail)");
|
||||
|
||||
// 本工具隐式创建的会话用完即关:留着会让后续 exec_command 被 -32003「终端会话已存在」
|
||||
// 挡到空闲回收为止。命令未结束时(上面的超时分支)保持会话,便于调用方轮询。
|
||||
if (!reused)
|
||||
mcp.CloseTermSession(devId, sessionId);
|
||||
|
||||
std::string out = CleanTerminalOutput(all, (posix || isPty) ? CP_UTF8 : 936, isPty,
|
||||
cmdLine, sentLine, nonce);
|
||||
|
||||
HttpProbeParsed p;
|
||||
bool parsed = posix ? ParseHttpProbePosixOutput(out, maxBytes, p) : ParseHttpProbeWindowsOutput(out, p);
|
||||
if (!parsed || (!p.hasStatus && p.error.empty()))
|
||||
return BuildError(id, -32001, "http_probe failed: unexpected output from host: " + HttpProbeSnippet(out));
|
||||
if (!p.error.empty())
|
||||
return BuildError(id, -32001, "http_probe failed: " + p.error);
|
||||
if (posix) {
|
||||
p.elapsedMs = (int)std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
std::chrono::steady_clock::now() - t0).count();
|
||||
}
|
||||
if (p.elapsedMs <= 0) p.elapsedMs = 0;
|
||||
|
||||
const std::string& rawBody = p.body;
|
||||
Json::Value hdrs(Json::objectValue);
|
||||
ParseHttpProbeHeaders(p.headerBlob, hdrs);
|
||||
const bool bodyUtf8 = IsValidUtf8(rawBody);
|
||||
|
||||
Json::Value sc(Json::objectValue);
|
||||
sc["status"] = p.status;
|
||||
sc["ok"] = (p.status >= 200 && p.status < 400);
|
||||
sc["headers"] = hdrs;
|
||||
sc["body"] = bodyUtf8 ? rawBody : std::string();
|
||||
sc["body_encoding"] = bodyUtf8 ? "utf-8" : "base64";
|
||||
if (!bodyUtf8) sc["body_base64"] = httplib::detail::base64_encode(rawBody);
|
||||
sc["body_bytes"] = (Json::UInt64)rawBody.size();
|
||||
sc["truncated"] = p.truncated;
|
||||
sc["elapsed_ms"] = p.elapsedMs;
|
||||
sc["url"] = url;
|
||||
|
||||
Json::Value result(Json::objectValue);
|
||||
result["structuredContent"] = sc;
|
||||
|
||||
std::string head = "[http_probe] " + method + " " + url + " -> " + std::to_string(p.status)
|
||||
+ " | " + std::to_string(rawBody.size()) + " bytes"
|
||||
+ (p.truncated ? " (truncated)" : "")
|
||||
+ " | " + std::to_string(p.elapsedMs) + " ms";
|
||||
std::string text = head;
|
||||
if (!rawBody.empty())
|
||||
text += "\n" + (bodyUtf8 ? rawBody : std::string("(base64) ") + sc["body_base64"].asString());
|
||||
|
||||
Json::Value content(Json::arrayValue);
|
||||
Json::Value item(Json::objectValue);
|
||||
item["type"] = "text";
|
||||
item["text"] = text;
|
||||
content.append(item);
|
||||
result["content"] = content;
|
||||
result["isError"] = false;
|
||||
// 正文已在 content 里,避免再把整份 JSON 追加一遍(响应体可能 64KB)。
|
||||
SetStructuredTextPayload(result, Json::Value(Json::objectValue));
|
||||
|
||||
return BuildResult(id, result);
|
||||
}
|
||||
|
||||
// ===== P2:upload_file 辅助 =====
|
||||
|
||||
// ASCII 小写(GBK 双字节首字节 0x81..0xFE 不含 A-Z,安全);Windows 路径名不区分大小写。
|
||||
@@ -10944,6 +11809,9 @@ const ToolPlatform kToolPlatforms[] = {
|
||||
{ "terminal_close", kPlatWin|kPlatLnx|kPlatApk },
|
||||
// macOS 客户端有 COMMAND_KILLPROCESS 分支,服务端同样拦着(McpServer.cpp:6870)
|
||||
{ "kill_process", kPlatWin|kPlatLnx },
|
||||
// http_probe 要走终端通道(Windows 用 PowerShell、Linux 用 curl);macOS 终端未开放,
|
||||
// Android 的 toybox 不保证有 curl/base64,故只标 win/lnx(工具内部对 MAC/APK 返回 -32005)。
|
||||
{ "http_probe", kPlatWin|kPlatLnx },
|
||||
// ---- win ---- 服务 / 注册表 / 键日志 / 文件写 / host_* / chat_* / power_action
|
||||
// list_windows 单列:BuildListWindows 把 COMMAND_WSLIST 发在**主连接**上
|
||||
// (McpServer.cpp:2931 的 Send2Client),而 Linux/macOS 主循环只处理 COMMAND_SYSTEM
|
||||
@@ -11312,6 +12180,7 @@ std::string DispatchSingleHostTool(const Json::Value& id, const std::string& too
|
||||
if (toolName == "remote_block_input") return BuildRemoteBlockInput(id, args, parent);
|
||||
if (toolName == "download_file") return BuildDownloadFile(id, args, parent);
|
||||
if (toolName == "read_file") return BuildReadFile(id, args, parent);
|
||||
if (toolName == "http_probe") return BuildHttpProbe(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);
|
||||
|
||||
@@ -52,6 +52,8 @@ GATE = {
|
||||
"terminal_open": ("terminal", True, False),
|
||||
"terminal_exec": ("terminal", True, False),
|
||||
"terminal_close": ("terminal", True, False),
|
||||
# http_probe 在主机上跑 shell(Windows PowerShell / Linux curl),与终端族同门控
|
||||
"http_probe": ("terminal", True, False),
|
||||
|
||||
# ---- remote_control ----
|
||||
"remote_open": ("remote_control", True, False),
|
||||
@@ -170,6 +172,9 @@ PLATFORMS = {
|
||||
"terminal_close": _WLA,
|
||||
"exec_command": _WLA,
|
||||
|
||||
# http_probe 走终端通道:macOS 终端未开放;Android 的 toybox 不保证有 curl/base64
|
||||
"http_probe": _WL,
|
||||
|
||||
# macOS 客户端有 COMMAND_KILLPROCESS 分支,但服务端同样拦着(McpServer.cpp:6870)
|
||||
"kill_process": _WL,
|
||||
|
||||
|
||||
Reference in new issue
Block a user