Compare commits
29
Commits
425d737ca0
...
v1.4.3
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
db4543ad54 | ||
|
|
06b93f7bdb | ||
|
|
c2b59f5d4a | ||
|
|
4456467c50 | ||
|
|
a25e89b220 | ||
|
|
b743de6747 | ||
|
|
3d87ec6720 | ||
|
|
80c7d1ed53 | ||
|
|
9fadb58c76 | ||
|
|
a818ace83c | ||
|
|
31883edc09 | ||
|
|
61b9031269 | ||
|
|
d49ebe521d | ||
|
|
292c3191dc | ||
|
|
5e012019ba | ||
|
|
42dd70fe20 | ||
|
|
3d18b2119a | ||
|
|
70556391dd | ||
|
|
d4f10db1f2 | ||
|
|
9ce1a58bc3 | ||
|
|
d7accf1d30 | ||
|
|
5227d4d78e | ||
|
|
808747f9d2 | ||
|
|
599c891c00 | ||
|
|
12b1bd4786 | ||
|
|
1076e7614a | ||
|
|
774c0d2545 | ||
|
|
3f1957a9c9 | ||
|
|
5f124fcb3a |
No files matched your search
@@ -95,6 +95,7 @@ server/go/web/assets/index.html
|
||||
server/go/users.json
|
||||
server/go/devices.json
|
||||
server/go/build/
|
||||
server/go/cmd/*.syso
|
||||
server/go/.claude/settings.json
|
||||
android/app/.cxx/
|
||||
|
||||
|
||||
@@ -32,6 +32,8 @@
|
||||
> 本软件**仅供教育目的及授权使用场景**:组织内远程 IT 管理、经授权的渗透测试与安全研究、个人设备管理与技术学习。
|
||||
>
|
||||
> **未经授权访问计算机系统属违法行为。** 使用者须对遵守所有适用法律承担全部责任。开发者对任何滥用行为概不负责。
|
||||
>
|
||||
> **二次开发红线:** 如使用大模型协助对本项目进行二次开发,不得破解本项目,也不得替换本项目的私有库以达到绕过授权的目的。一经发现,授权服务器将对其**永久拉黑**。
|
||||
|
||||
---
|
||||
|
||||
@@ -378,6 +380,38 @@ nohup ./server_linux_amd64 --port 6543 --http-port 9001 > yama.log 2>&1 &
|
||||
|
||||
## 更新日志
|
||||
|
||||
### v1.4.3 (2026.11.14)
|
||||
|
||||
**MCP 工具面收敛 & Go 极简 MCP & Android / macOS 能力补齐 & TLS 开箱即用**
|
||||
|
||||
**新功能:**
|
||||
- **MCP 工具收敛 60 → 54**:`host_list_*` 十个只读工具合并为 `host_inspect(aspects[])`、三个主机列表合并为 `list_hosts`、窗口与服务控制各只留一个名字;加上本次新增的 5 个工具,清单最终为 54 项(全部开关打开时 `tools/list` 列出 49 项),响应体从 193 KB 降到 169 KB(-12.6%)。旧名保留为可调用别名;`McpMachine` 开启时降级的 `list_processes` / `list_windows` / `list_services` 不再列出
|
||||
- **MCP 新工具**:`http_probe`(仅私网 IP 的 HTTP 检查,不跟随重定向、正文 64 KB、校验证书)、`read_file`(按行读远端文本,BOM / UTF-8 / GBK 自动识别,负 offset 从尾部读,回整文件 SHA-256)、`get_foreground_window` 与窗口信息 RPC(179/180,`expect_hwnd` / `require_foreground`)、`uninstall_host`、`remote_lock_screen`
|
||||
- **MCP 原生捕获**:`get_screenshot` 支持区域 / 窗口 / 单显示器 1:1 捕获(`CLIENT_CAP_SCREEN_REGION`,返回源矩形与缩放),`remote_open` 可只推目标窗口或区域,`remote_mouse` 支持窗口相对坐标
|
||||
- **Go 极简 MCP**:无状态 `POST /mcp` + Bearer 鉴权,9 个工具(只读 7 个),每设备锁与全局并发闸门、每次调用写审计;终端 256 KiB 环形缓冲,`list_files` / `read_file` 走文件管理子连接,`get_screenshot` 走主连接预览 RPC
|
||||
- **Android 客户端补齐**:屏幕预览(API 30+ 无障碍抓屏)、活动历史、运行日志上报、TLS 热切换(OpenSSL 3.5.0 静态链接)、主控推送 APK 升级、远程交谈 / 终端 / 剪贴板 / 锁屏 / 隐私遮罩 / 卸载、语音监听,并让远控调优命令真正生效(此前硬编码 Good 使自适应质量永远无法启动)
|
||||
- **macOS 客户端阶段 0 / 1**:TLS 传输、运行日志上报、授权后自动重启、终端与进程管理能力位、屏幕预览、活动历史、关键帧请求
|
||||
- **TLS 开箱即用**:未配置证书时首次需要即自签(RSA-2048,十年),可在对话框导出 PEM,也可内嵌进生成的客户端与下发的 DLL,首连即 TLS
|
||||
- **Linux 客户端**:分享到另一主控(fork 子实例)、转移到另一主控(到期自动恢复)、活动历史(有桌面走 X11,无桌面汇总登录与 shell 历史)、记住全屏与远端光标
|
||||
- **Windows 远控**:多显示器改抓整个虚拟桌面、采集监视器索引跨重启稳定、自适应质量新增吞吐判据与防振荡、调优开关改为按客户端保存、注入按键在断连 / 切后台时释放
|
||||
- **主控与 Web**:高级菜单「运行测试程序」(载荷在主控进程内加载,带防误伤标记)、文件管理器传输历史落盘、特性限制与真实菜单对齐(57/19/46 项)、Web 控制台设备列表分组过滤、状态栏 TLS / MCP 状态
|
||||
|
||||
**改进:**
|
||||
- MCP 契约与实现对齐:条件必填改 `allOf` / `if` / `then`,`outputSchema` 与实际返回一致,说明文本逐条对过代码
|
||||
- 只交文本块的 MCP 客户端也能看到主机 ID 与列表行;`list_files` 改为列全目录再分页,路径统一 GBK
|
||||
- 终端会话语义:可隐式开会话、超时保留并轮询、`terminal_close` 显式回收、忙时提示占用者、取消可按 id / session_id 定位
|
||||
- 危险操作确认框列出目标主机且默认「否」;「高速 / 极速」更名为「高画质 / 流畅」;Ctrl+F 改为即输即筛
|
||||
- 中文进程名显示、配置读取创建空注册表子键、试用口令覆盖等一批细节修正
|
||||
|
||||
**Bug 修复:**
|
||||
- 两个能让远程对端打死服务端的路径:httplib `Content-Length: -1` 无鉴权死循环 DoS、畸形 JPEG 触发 libjpeg `exit()`
|
||||
- 远控音频偶发永久静音(环形缓冲跨线程无锁、格式包丢失、Modern Standby 恢复、端点变更)
|
||||
- 质量切换跳到另一台显示器、从 RGB565 / DIFF 切回 H.264 冻结最长 10 秒;慢帧下自适应质量永远弃权
|
||||
- Web 远端画面在分辨率 / 质量变化后黑屏;Web 终端心跳重连后按键全部丢失
|
||||
- 远程桌面窗口缩放后不重绘;浮动工具栏质量菜单一打开就收回;注入按键卡住修饰键
|
||||
- macOS 子连接线程泄漏(六周后达 2048 线程);HELL 头编码固定导致约三分之一 Release 客户端登不上 Go fallback
|
||||
- 特性限制在 32 位主控上丢失 bit 32 以上的 40 项;运行时长跨时区恒显示 0;登录保留区越界
|
||||
|
||||
### v1.4.2 (2026.10.31)
|
||||
|
||||
**MCP 运维套件 & WebSocket 传输 & 抓屏健壮性**
|
||||
|
||||
@@ -32,6 +32,8 @@
|
||||
> This software is intended **solely for educational purposes and authorized use cases**: remote IT administration within your own organization, authorized penetration testing and security research, personal device management, and technical learning.
|
||||
>
|
||||
> **Unauthorized access to computer systems is illegal.** Users are fully responsible for compliance with all applicable laws. The developers assume no liability for misuse.
|
||||
>
|
||||
> **Secondary development:** if you use a large language model to assist with secondary development of this project, you must not crack the software or replace this project's private libraries to bypass authorization. Violations are detected and the authorization server **permanently blacklists** the offender.
|
||||
|
||||
---
|
||||
|
||||
@@ -378,6 +380,38 @@ Valid : 2026-02-01 to 2028-02-01
|
||||
|
||||
## Changelog
|
||||
|
||||
### v1.4.3 (2026.11.14)
|
||||
|
||||
**MCP tool consolidation & Go minimal MCP & Android / macOS parity & TLS out of the box**
|
||||
|
||||
**New features:**
|
||||
- **MCP tools 60 to 54**: the ten read-only `host_list_*` tools merged into `host_inspect(aspects[])`, the three host lists into `list_hosts`, and each window / service pair behind one name; together with the five tools added in this release the manifest settles at 54 entries (49 in `tools/list` with every switch on) and the response shrinks from 193 KB to 169 KB (-12.6%). The old names remain callable aliases, and the degraded `list_processes` / `list_windows` / `list_services` are no longer listed while `McpMachine` is on
|
||||
- **New MCP tools**: `http_probe` (private-network HTTP checks only, no redirects, 64 KB body cap, certificate verification), `read_file` (line-based remote text reads with BOM / UTF-8 / GBK detection, negative offset from the end, whole-file SHA-256), `get_foreground_window` plus a window-info RPC (179/180, `expect_hwnd` / `require_foreground`), `uninstall_host`, `remote_lock_screen`
|
||||
- **Native capture**: `get_screenshot` captures a region, a window or a single monitor at 1:1 (`CLIENT_CAP_SCREEN_REGION`, returning the source rect and scale); `remote_open` can stream only the target window or region; `remote_mouse` accepts window-relative coordinates
|
||||
- **Go minimal MCP**: a stateless `POST /mcp` with bearer auth, nine tools (seven read-only), per-device locks, a global concurrency gate and one audit record per call; 256 KiB terminal ring, `list_files` / `read_file` over the file-manager sub-connection, `get_screenshot` over the main-connection preview RPC
|
||||
- **Android client**: screen preview (accessibility capture on API 30+), activity history, runtime log reporting, TLS hot-switching (OpenSSL 3.5.0 statically linked), master-pushed APK updates, remote chat / terminal / clipboard / lock screen / privacy overlay / uninstall, voice monitoring, and remote-desktop tuning commands that actually take effect (a hardcoded "Good" had stopped adaptive quality from ever starting)
|
||||
- **macOS client, phases 0 and 1**: TLS transport, runtime log reporting, automatic restart once permissions are granted, terminal and process-management capability bits, screen preview, activity history, keyframe requests
|
||||
- **TLS out of the box**: with no certificate configured the server self-signs one (RSA-2048, ten years) the first time it is needed, can export it as PEM, and can embed it in generated clients and delivered DLLs so the first connection is already TLS
|
||||
- **Linux client**: share to another master (forked child instances), transfer to another master (restored on expiry), activity history (X11 sampling with a headless login/shell-history fallback), remembered fullscreen and remote-cursor state
|
||||
- **Windows remote desktop**: multi-monitor capture of the whole virtual desktop, a capture monitor index that survives restarts, a throughput criterion and anti-oscillation for adaptive quality, tuning flags saved per client, injected keys released on blur and disconnect
|
||||
- **Master and web console**: "Run test program" in the Advanced menu (the in-memory client payload loaded inside the master process, guarded by a magic), file-manager transfer history persisted, feature limits aligned with the real menus (57/19/46 items), a group filter in the web device list, TLS and MCP panes in the status bar
|
||||
|
||||
**Improvements:**
|
||||
- MCP contracts now match the handlers: conditional required arguments use `allOf` / `if` / `then`, `outputSchema` matches the returned shape, and the instructions were checked line by line against the code
|
||||
- Text-only MCP clients now see host ids and listing rows; `list_files` lists the whole directory before paging and paths are GBK in both directions
|
||||
- Terminal semantics: a session can be opened or reused implicitly, a timed-out command keeps its session and can be polled, `terminal_close` reclaims explicitly, busy errors name the holder, and cancels can be addressed by id or session_id
|
||||
- Destructive confirmations list the target hosts and default to No; "High speed / Ultra speed" became "High quality / Smooth"; Ctrl+F filters as you type
|
||||
- Chinese process names, registry reads creating empty subkeys, and trial-code replacement, among other refinements
|
||||
|
||||
**Bug fixes:**
|
||||
- Two paths by which a remote peer could terminate the server: the unauthenticated `Content-Length: -1` DoS in httplib and a malformed JPEG reaching libjpeg's `exit()`
|
||||
- Remote desktop audio could go permanently silent (unlocked ring buffer shared across threads, a dropped format packet, Modern Standby resume, endpoint changes)
|
||||
- A quality switch jumped to another monitor, switching back to H.264 froze the view for up to ten seconds, and slow frames made the adaptive controller abstain forever
|
||||
- The web remote view went black after a resolution or quality change, and a web terminal lost every keystroke after a heartbeat reconnect
|
||||
- The remote desktop did not repaint after a window resize; the floating toolbar's quality menu retracted as soon as it opened; injected keys left modifiers stuck
|
||||
- macOS leaked one receive thread per sub-connection (2048 threads after six weeks); a fixed HELL header encoding kept about a third of Release clients off the Go fallback server
|
||||
- Feature limits lost the 40 items above bit 31 on 32-bit builds; uptime read 0 across time zones; the login reserved list could overflow
|
||||
|
||||
### v1.4.2 (2026.10.31)
|
||||
|
||||
**MCP operations suite & WebSocket transport & capture robustness**
|
||||
|
||||
@@ -32,6 +32,8 @@
|
||||
> 本軟體**僅供教育目的及授權使用情境**:組織內遠端 IT 管理、經授權的滲透測試與安全研究、個人裝置管理與技術學習。
|
||||
>
|
||||
> **未經授權存取電腦系統屬違法行為。** 使用者須對遵守所有適用法律承擔全部責任。開發者對任何濫用行為概不負責。
|
||||
>
|
||||
> **二次開發紅線:** 如使用大模型協助對本專案進行二次開發,不得破解本專案,也不得替換本專案的私有函式庫以達到繞過授權的目的。一經發現,授權伺服器將對其**永久列入黑名單**。
|
||||
|
||||
---
|
||||
|
||||
@@ -378,6 +380,38 @@ nohup ./server_linux_amd64 --port 6543 --http-port 9001 > yama.log 2>&1 &
|
||||
|
||||
## 更新日誌
|
||||
|
||||
### v1.4.3 (2026.11.14)
|
||||
|
||||
**MCP 工具面收斂 & Go 極簡 MCP & Android / macOS 能力補齊 & TLS 開箱即用**
|
||||
|
||||
**新功能:**
|
||||
- **MCP 工具收斂 60 → 54**:`host_list_*` 十個唯讀工具合併為 `host_inspect(aspects[])`、三個主機列表合併為 `list_hosts`、視窗與服務控制各只留一個名字;加上本次新增的 5 個工具,清單最終為 54 項(全部開關開啟時 `tools/list` 列出 49 項),回應從 193 KB 降到 169 KB(-12.6%)。舊名保留為可呼叫別名;`McpMachine` 開啟時降級的 `list_processes` / `list_windows` / `list_services` 不再列出
|
||||
- **MCP 新工具**:`http_probe`(僅私網 IP 的 HTTP 檢查,不跟隨重新導向、內文 64 KB、校驗憑證)、`read_file`(逐行讀取遠端文字,BOM / UTF-8 / GBK 自動辨識,負 offset 從尾端讀,回傳整個檔案 SHA-256)、`get_foreground_window` 與視窗資訊 RPC(179/180,`expect_hwnd` / `require_foreground`)、`uninstall_host`、`remote_lock_screen`
|
||||
- **MCP 原生擷取**:`get_screenshot` 支援區域 / 視窗 / 單一螢幕 1:1 擷取(`CLIENT_CAP_SCREEN_REGION`,回傳來源矩形與縮放),`remote_open` 可只推送目標視窗或區域,`remote_mouse` 支援視窗相對座標
|
||||
- **Go 極簡 MCP**:無狀態 `POST /mcp` + Bearer 驗證,9 個工具(唯讀 7 個),每裝置鎖與全域並行閘門、每次呼叫寫稽核;終端 256 KiB 環形緩衝,`list_files` / `read_file` 走檔案管理子連線,`get_screenshot` 走主連線預覽 RPC
|
||||
- **Android 用戶端補齊**:螢幕預覽(API 30+ 無障礙擷取)、活動歷史、執行日誌上報、TLS 熱切換(OpenSSL 3.5.0 靜態連結)、主控推送 APK 升級、遠端交談 / 終端 / 剪貼簿 / 鎖屏 / 隱私遮罩 / 卸載、語音監聽,並讓遠控調校命令真正生效(先前硬編碼 Good 使自適應品質永遠無法啟動)
|
||||
- **macOS 用戶端階段 0 / 1**:TLS 傳輸、執行日誌上報、授權後自動重啟、終端與行程管理能力位、螢幕預覽、活動歷史、關鍵幀請求
|
||||
- **TLS 開箱即用**:未設定憑證時首次需要即自簽(RSA-2048,十年),可在對話框匯出 PEM,也可內嵌進產生的用戶端與下發的 DLL,首連即 TLS
|
||||
- **Linux 用戶端**:分享到另一主控(fork 子實例)、轉移到另一主控(到期自動還原)、活動歷史(有桌面走 X11,無桌面彙整登入與 shell 歷史)、記住全螢幕與遠端游標
|
||||
- **Windows 遠控**:多螢幕改抓整個虛擬桌面、擷取監視器索引跨重啟穩定、自適應品質新增吞吐判據與防振盪、調校開關改為依用戶端儲存、注入按鍵在斷線 / 切換背景時釋放
|
||||
- **主控與 Web**:進階選單「執行測試程式」(載荷在主控行程內載入,帶防誤傷標記)、檔案管理員傳輸歷史落地、功能限制與真實選單對齊(57/19/46 項)、Web 控制台裝置列表分組過濾、狀態列 TLS / MCP 狀態
|
||||
|
||||
**改進:**
|
||||
- MCP 契約與實作對齊:條件必填改 `allOf` / `if` / `then`,`outputSchema` 與實際回傳一致,說明文字逐條對過程式碼
|
||||
- 只交文字區塊的 MCP 用戶端也能看到主機 ID 與列表列;`list_files` 改為列全目錄再分頁,路徑統一 GBK
|
||||
- 終端工作階段語意:可隱式開工作階段、逾時保留並輪詢、`terminal_close` 顯式回收、忙碌時提示佔用者、取消可依 id / session_id 定位
|
||||
- 危險操作確認框列出目標主機且預設「否」;「高速 / 極速」更名為「高畫質 / 流暢」;Ctrl+F 改為即輸即篩
|
||||
- 中文行程名稱顯示、設定讀取建立空登錄子機碼、試用口令覆蓋等一批細節修正
|
||||
|
||||
**Bug 修復:**
|
||||
- 兩個能讓遠端對端打死伺服端的路徑:httplib `Content-Length: -1` 無驗證死迴圈 DoS、畸形 JPEG 觸發 libjpeg `exit()`
|
||||
- 遠控音訊偶發永久靜音(環形緩衝跨執行緒無鎖、格式封包遺失、Modern Standby 還原、端點變更)
|
||||
- 品質切換跳到另一台螢幕、從 RGB565 / DIFF 切回 H.264 凍結最長 10 秒;慢幀下自適應品質永遠棄權
|
||||
- Web 遠端畫面在解析度 / 品質變化後黑屏;Web 終端心跳重連後按鍵全部遺失
|
||||
- 遠端桌面視窗縮放後不重繪;浮動工具列品質選單一打開就收回;注入按鍵卡住修飾鍵
|
||||
- macOS 子連線執行緒洩漏(六週後達 2048 執行緒);HELL 標頭編碼固定導致約三分之一 Release 用戶端登不上 Go fallback
|
||||
- 功能限制在 32 位元主控上遺失 bit 32 以上的 40 項;執行時間跨時區恆顯示 0;登入保留區越界
|
||||
|
||||
### v1.4.2 (2026.10.31)
|
||||
|
||||
**MCP 維運套件 & WebSocket 傳輸 & 擷取畫面健壯性**
|
||||
|
||||
@@ -74,8 +74,28 @@ function Build-GoServer {
|
||||
} else {
|
||||
Join-Path $binDir "YamaGo_x64.exe"
|
||||
}
|
||||
|
||||
# Version/commit metadata injected into serverInfo and get_server_status.
|
||||
# Empty when git is unavailable (source tarball, IDE build) — the server
|
||||
# then reports no version rather than a fabricated one.
|
||||
$gitVersion = ""
|
||||
$gitCommit = ""
|
||||
if (Get-Command git -ErrorAction SilentlyContinue) {
|
||||
$gitVersion = (& git -C $rootDir describe --tags --always --dirty 2>$null | Select-Object -First 1)
|
||||
if ($LASTEXITCODE -ne 0 -or -not $gitVersion) { $gitVersion = "" } else { $gitVersion = "$gitVersion".Trim() }
|
||||
$gitCommit = (& git -C $rootDir rev-parse --short HEAD 2>$null | Select-Object -First 1)
|
||||
if ($LASTEXITCODE -ne 0 -or -not $gitCommit) { $gitCommit = "" } else { $gitCommit = "$gitCommit".Trim() }
|
||||
}
|
||||
$buildinfoPkg = "github.com/yuanyuanxiang/SimpleRemoter/server/go/buildinfo"
|
||||
$ldflagParts = @()
|
||||
# Release strips debug info for smaller binary; Debug keeps symbols.
|
||||
$ldflags = if ($Configuration -eq "Debug") { "" } else { "-s -w" }
|
||||
if ($Configuration -ne "Debug") { $ldflagParts += @("-s", "-w") }
|
||||
if ($gitVersion) { $ldflagParts += @("-X", "$buildinfoPkg.Version=$gitVersion") }
|
||||
if ($gitCommit) { $ldflagParts += @("-X", "$buildinfoPkg.Commit=$gitCommit") }
|
||||
$ldflags = $ldflagParts -join " "
|
||||
if ($gitVersion) {
|
||||
Write-Host "Version: $gitVersion ($gitCommit)" -ForegroundColor DarkGray
|
||||
}
|
||||
|
||||
# Save the caller's Go env so a direct .\build.ps1 invocation does not
|
||||
# leave GOOS=linux behind for later builds in the same shell.
|
||||
@@ -90,6 +110,21 @@ function Build-GoServer {
|
||||
# Cross-compiling for Linux requires a pure-Go build; the server has
|
||||
# no cgo dependencies, so this is the normal configuration.
|
||||
if ($TargetOS -eq "linux") { $env:CGO_ENABLED = "0" }
|
||||
# Refresh the Windows resources before linking: go-winres rewrites the
|
||||
# manifest identity, FileVersion and ProductVersion from the git tag so
|
||||
# Explorer's file properties match the tag while the runtime version
|
||||
# string stays the full `git describe` output. Missing go-winres or a
|
||||
# non-git tree keeps the checked-in .syso files unchanged.
|
||||
if ($TargetOS -eq "windows" -and $gitVersion) {
|
||||
if (Get-Command go-winres -ErrorAction SilentlyContinue) {
|
||||
& go-winres make --in cmd/winres/winres.json --out cmd/rsrc --product-version git-tag --file-version git-tag
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-Host "WARNING: go-winres failed; keeping existing cmd/rsrc_*.syso" -ForegroundColor Yellow
|
||||
}
|
||||
} else {
|
||||
Write-Host "WARNING: go-winres not found; version resources not refreshed (go install github.com/tc-hib/go-winres@latest)" -ForegroundColor Yellow
|
||||
}
|
||||
}
|
||||
if ($ldflags) {
|
||||
& go build -ldflags $ldflags -o $outFile ./cmd
|
||||
} else {
|
||||
|
||||
@@ -809,6 +809,9 @@ DWORD WINAPI StartClient(LPVOID lParam)
|
||||
State& bExit(app.g_bExit);
|
||||
IOCPClient *ClientObject = NewNetClient(&settings, bExit, pubIP);
|
||||
if (nullptr == ClientObject) return -1;
|
||||
// 主连接:登录被接受后发布头加密类型;上一条连接没被登录接受时,重连换下一种类型
|
||||
// 轮转探测。其余 IOCPClient(文件/进程/屏幕等子连接)都跟随这里发布的值。
|
||||
ClientObject->MarkMainLink();
|
||||
CKernelManager* Manager = nullptr;
|
||||
|
||||
if (!app.m_bShared) {
|
||||
|
||||
+129
-10
@@ -27,6 +27,7 @@ inline int WSAGetLastError()
|
||||
#include "IOCPClient.h"
|
||||
#include <assert.h>
|
||||
#include <string>
|
||||
#include <random>
|
||||
#if USING_ZLIB
|
||||
#include "zlib/zlib.h"
|
||||
#define Z_FAILED(p) (Z_OK != (p))
|
||||
@@ -197,6 +198,35 @@ bool IOCPClient::TryHandleAuthResponse(PBYTE buf, ULONG len)
|
||||
}
|
||||
|
||||
|
||||
// HELL 头加密可选类型数:Debug 版与服务端(含 Go fallback)对齐,只到 HeaderEncV6;
|
||||
// Release 版保留全部类型,靠主连接重连轮转去命中后端支持的那几种。
|
||||
static int HeaderEncCount()
|
||||
{
|
||||
#ifdef _DEBUG
|
||||
return HeaderEncV6 + 1;
|
||||
#else
|
||||
return HeaderEncNum;
|
||||
#endif
|
||||
}
|
||||
|
||||
// 构造时的初始类型。原来直接 time(nullptr) % N:同一秒内启动的一批客户端会拿到
|
||||
// 同一个类型,快速重连也反复取到同一个值。
|
||||
// 不持有静态发生器:本函数会被多个并存实例(并发上线/分享)的构造线程调用,无共享
|
||||
// 状态就无需加锁;random_device 个别平台在 /dev/urandom 不可用时会抛异常,退回时钟。
|
||||
static int RandomHeaderEncIndex(int count)
|
||||
{
|
||||
unsigned v = 0;
|
||||
try {
|
||||
std::random_device rd;
|
||||
v = rd();
|
||||
} catch (...) {
|
||||
// 极少数平台取不到 /dev/urandom 会抛异常:退回时钟(纳秒级,够打散同秒启动)。
|
||||
v = (unsigned)std::chrono::steady_clock::now().time_since_epoch().count()
|
||||
^ (unsigned)time(nullptr);
|
||||
}
|
||||
return (int)(v % (unsigned)count);
|
||||
}
|
||||
|
||||
IOCPClient::IOCPClient(const State&bExit, bool exit_while_disconnect, int mask, CONNECT_ADDRESS* conn,
|
||||
const std::string& pubIP, void* main) : g_bExit(bExit)
|
||||
{
|
||||
@@ -230,13 +260,24 @@ IOCPClient::IOCPClient(const State&bExit, bool exit_while_disconnect, int mask,
|
||||
m_DataProcess = NULL;
|
||||
m_ReconnectFunc = NULL;
|
||||
m_masker = mask ? new HttpMask(DEFAULT_HOST) : new PkgMask();
|
||||
#ifdef _DEBUG
|
||||
auto enc = GetHeaderEncoder(HeaderEncType(time(nullptr) % (HeaderEncV6 + 1)));
|
||||
#else
|
||||
auto enc = GetHeaderEncoder(HeaderEncType(time(nullptr) % HeaderEncNum));
|
||||
#endif
|
||||
m_EncoderType = encoder;
|
||||
m_Encoder = encoder ? new HellEncoder(enc, new XOREncoder16()) : new ProtocolEncoder();
|
||||
if (encoder) {
|
||||
const int count = HeaderEncCount();
|
||||
int idx = -1;
|
||||
if (conn) {
|
||||
// 子连接优先继承主连接「已被当前后端接受」的类型(PublishHeaderEncoder)。
|
||||
// 0 表示尚未发布,回退随机,保持原有的打散效果。
|
||||
int published = GetHeaderEncSelect(conn);
|
||||
if (published >= 1 && published <= count)
|
||||
idx = published - 1;
|
||||
}
|
||||
if (idx < 0)
|
||||
idx = RandomHeaderEncIndex(count);
|
||||
m_headerEncIdx.store(idx);
|
||||
m_Encoder = new HellEncoder(GetHeaderEncoder((HeaderEncType)idx), new XOREncoder16());
|
||||
} else {
|
||||
m_Encoder = new ProtocolEncoder();
|
||||
}
|
||||
#ifdef _WIN32
|
||||
WSADATA wsaData;
|
||||
WSAStartup(MAKEWORD(2, 2), &wsaData);
|
||||
@@ -266,6 +307,52 @@ IOCPClient::IOCPClient(const State&bExit, bool exit_while_disconnect, int mask,
|
||||
#endif
|
||||
}
|
||||
|
||||
void IOCPClient::PrepareHeaderEncoderForConnect()
|
||||
{
|
||||
if (!m_EncoderType) {
|
||||
return; // Shine:没有头加密函数可换
|
||||
}
|
||||
const int count = HeaderEncCount();
|
||||
|
||||
if (!m_bMainLink) {
|
||||
// 子连接:跟随主连接最新发布的、已被当前后端接受的类型。一次性子连接(文件/
|
||||
// 进程等只连一次)因此不会自己掷骰子撞上 Go fallback 不认识的 V7~V10。
|
||||
// 取舍:后端切换(C++ 主控挂掉、Go fallback 接管)到主连接重连并重发布之间的
|
||||
// 窗口里,子连接会拿旧值反复碰壁;主连接一发布新值就自愈。这里不自己轮转,是为
|
||||
// 了让「一次性子连接只连一次」这种最常见的情形始终用主连接验证过的值。
|
||||
int published = m_conn ? GetHeaderEncSelect(m_conn) : 0;
|
||||
if (published >= 1 && published <= count) {
|
||||
int idx = published - 1;
|
||||
if (idx != m_headerEncIdx.load(std::memory_order_relaxed)) {
|
||||
m_headerEncIdx.store(idx, std::memory_order_relaxed);
|
||||
m_Encoder->SetHeaderEnc(GetHeaderEncoder((HeaderEncType)idx));
|
||||
}
|
||||
return;
|
||||
}
|
||||
// 主连接尚未发布(例如键盘子连接在主连接登录前就建好了):退化为轮转,见下。
|
||||
}
|
||||
|
||||
// 第一次建连沿用构造时确定的类型(继承值或随机初值)。之后只在「上一条连接没有
|
||||
// 被登录接受」时才换下一种:已被接受说明当前后端解析得了这个类型,重连沿用即可;
|
||||
// 无故轮转只会在 Go fallback 上白丢几轮(V7~V10 会被它拒掉)。
|
||||
// m_loginAcked 由 ConnectServer 在本函数**之后**才清零,所以这里读到的是上一条连接
|
||||
// 的结论(见调用处注释)。
|
||||
if (m_headerEncAttempts.fetch_add(1, std::memory_order_relaxed) > 0
|
||||
&& !m_loginAcked.load(std::memory_order_acquire)) {
|
||||
int idx = (m_headerEncIdx.load(std::memory_order_relaxed) + 1) % count;
|
||||
m_headerEncIdx.store(idx, std::memory_order_relaxed);
|
||||
m_Encoder->SetHeaderEnc(GetHeaderEncoder((HeaderEncType)idx));
|
||||
}
|
||||
}
|
||||
|
||||
void IOCPClient::PublishHeaderEncoder()
|
||||
{
|
||||
// 只有主连接、且确实在用 HELL 头加密时才有意义。
|
||||
if (m_bMainLink && m_EncoderType && m_conn) {
|
||||
SetHeaderEncSelect(m_conn, m_headerEncIdx.load(std::memory_order_relaxed));
|
||||
}
|
||||
}
|
||||
|
||||
void IOCPClient::SetMultiThreadCompress(int threadNum)
|
||||
{
|
||||
#if USING_CTX
|
||||
@@ -443,6 +530,14 @@ BOOL ConnectWithTimeout(SOCKET sock, const struct sockaddr* addr, int timeout_se
|
||||
|
||||
BOOL IOCPClient::ConnectServer(const char* szServerIP, unsigned short uPort)
|
||||
{
|
||||
// 每次建连(含重连)先定下这次要用的 HELL 头加密函数。必须在建 socket / 启动收发
|
||||
// 线程之前完成:后端只在每条连接的**第一个**包上识别并锁定头加密方式(Go 的
|
||||
// parser.go 首包锁存,认不出就 ErrUnsupported 直接断开),换类型只对「下一条连接的
|
||||
// 首包」有意义;此刻旧连接已断开,也就避开了与收发线程争用编码器对象。
|
||||
// 注意顺序:PrepareHeaderEncoderForConnect 要读上一条连接的 m_loginAcked,故它必须是
|
||||
// 本条连接清零登录标志**之前**的第一条语句。
|
||||
PrepareHeaderEncoderForConnect();
|
||||
|
||||
// 登录确认标志只描述「当前这条连接」:任何一次新建连都先清零,避免上一条连接的
|
||||
// 确认结果替新连接背书(协议切换的自动回退靠它判断新入口是否真的登录成功)。
|
||||
m_loginAcked.store(false, std::memory_order_release);
|
||||
@@ -638,7 +733,7 @@ BOOL IOCPClient::ConnectServer(const char* szServerIP, unsigned short uPort)
|
||||
return FALSE;
|
||||
}
|
||||
m_useWs = true;
|
||||
// 注意:这里不能读 m_useTls——无 TLS 的平台上(macOS/Android)它不存在;
|
||||
// 注意:这里不能读 m_useTls——它只在定义了 YAMA_TLS_CHANNEL 的平台上存在;
|
||||
// 本连接实际走的形态由 wsDegraded 区分:WSS 有锚走 TLS,没锚则明文回退。
|
||||
Mprintf("[WS] WebSocket 已就绪: %s:%d%s%s\n", wsHost.c_str(), (int)port,
|
||||
WS_UPGRADE_PATH, wsDegraded ? " (明文,等待信任锚)"
|
||||
@@ -671,6 +766,17 @@ BOOL IOCPClient::ConnectServer(const char* szServerIP, unsigned short uPort)
|
||||
pthread_t id = 0;
|
||||
int ret = pthread_create(&id, nullptr, (void* (*)(void*))IOCPClient::WorkThreadProc, this);
|
||||
if (ret == 0) {
|
||||
// 必须 detach:POSIX 上 CloseHandle / SAFE_CLOSE_HANDLE 是空宏
|
||||
// (common/commands.h:77-78),析构函数里的 SAFE_CLOSE_HANDLE(m_hWorkThread)
|
||||
// 什么都不做,也没有任何地方 pthread_join 过这个线程。未 detach 的 pthread
|
||||
// 退出后不会释放线程结构体和栈,于是**每个 IOCPClient 实例永久泄漏一个线程**
|
||||
// —— 而子连接(屏幕/文件/终端/日志)每次点击都新建一个 IOCPClient。
|
||||
// 泄漏累积到 RLIMIT_NPROC 附近后 pthread_create 开始返回 EAGAIN:
|
||||
// 主连接因为已有线程还活着不受影响,但新开的子连接全部失败,
|
||||
// 表现为「重启客户端就好、点按钮毫无反应」。detach 后线程退出即回收。
|
||||
// 安全性:析构函数仍靠 m_bWorkThread 等待线程收尾;m_hWorkThread 在 POSIX 上
|
||||
// 只当「线程已存在」的标志位用,从不被当作内核句柄解引用。
|
||||
pthread_detach(id);
|
||||
m_bWorkThread = S_RUN;
|
||||
m_bIsRunning = TRUE;
|
||||
// Store pthread_t so subsequent ConnectServer calls (reconnects) find
|
||||
@@ -679,7 +785,16 @@ BOOL IOCPClient::ConnectServer(const char* szServerIP, unsigned short uPort)
|
||||
// the TCP stream and prevent any complete command from being delivered.
|
||||
// SAFE_CLOSE_HANDLE and CloseHandle are no-ops on Android, so the value
|
||||
// is never dereferenced as a kernel handle.
|
||||
m_hWorkThread = reinterpret_cast<HANDLE>(static_cast<uintptr_t>(id));
|
||||
// POSIX 下这个值只当「线程已存在」的非空标志用,从不反向解引用。
|
||||
// 不能用 static_cast<uintptr_t>(id):macOS 的 pthread_t 是
|
||||
// _opaque_pthread_t*(Linux/Android 是整型),指针经整型中转是非法的。
|
||||
// reinterpret_cast 对两种形态都成立(整型→指针 / 指针→指针)。
|
||||
m_hWorkThread = reinterpret_cast<HANDLE>(id);
|
||||
} else {
|
||||
// pthread_create 直接返回错误码(不经 errno):EAGAIN(35)/EPERM(1) 基本就是
|
||||
// 进程/用户的线程数到顶。这条路径原本完全静默——连接看起来「成功」了,
|
||||
// 但没有收包线程,后续 ConnAuth 必然超时,日志里只剩一句"等待响应超时"。
|
||||
Mprintf("[ERROR] pthread_create(WorkThread) failed: ret=%d\n", ret);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -758,9 +873,13 @@ DWORD WINAPI IOCPClient::WorkThreadProc(LPVOID lParam)
|
||||
}
|
||||
SAFE_CLOSE_HANDLE(This->m_hWorkThread);
|
||||
This->m_hWorkThread = NULL;
|
||||
This->m_bWorkThread = S_STOP;
|
||||
This->m_bIsRunning = FALSE;
|
||||
delete[] szBuffer;
|
||||
// 最后一步才发布 S_STOP:析构函数以「m_bWorkThread != S_RUN」判断线程已完全退出,
|
||||
// 看到它之后就会释放成员并返回,调用方随即 delete this。反过来写(先 S_STOP 再
|
||||
// m_bIsRunning)等于给析构函数一个提前放行的窗口——最后那句 m_bIsRunning 会写进
|
||||
// 已释放的内存。此后本函数不得再读写 This 的任何成员。
|
||||
This->m_bWorkThread = S_STOP;
|
||||
|
||||
return 0xDEAD;
|
||||
}
|
||||
@@ -841,7 +960,7 @@ VOID IOCPClient::OnServerReceiving(CBuffer* m_CompressedBuffer, char* szBuffer,
|
||||
Mprintf("[ERROR] Unknown header! this=%p bufLen=%lu, first 16 bytes: %s (useTls=%d tlsReady=%d)\n",
|
||||
this, bufLen, buf.c_str(), (int)m_useTls, (int)m_tls.IsReady());
|
||||
#else
|
||||
// macOS 没有 TlsChannel(TLS 已在 Windows/Linux/Android 客户端实现)
|
||||
// 该平台没有 TlsChannel(YAMA_TLS_CHANNEL 未定义):没有传输层状态可打
|
||||
Mprintf("[ERROR] Unknown header! this=%p bufLen=%lu, first 16 bytes: %s\n",
|
||||
this, bufLen, buf.c_str());
|
||||
#endif
|
||||
|
||||
+34
-5
@@ -11,8 +11,8 @@
|
||||
#pragma comment(lib,"ws2_32.lib")
|
||||
#endif
|
||||
|
||||
// TLS 通道:Windows 走 Schannel,Linux 走 OpenSSL;macOS/Android 下该头为空,
|
||||
// 且不定义 YAMA_TLS_CHANNEL,下方代码自动退回明文。
|
||||
// TLS 通道:Windows 走 Schannel,Linux / Android / macOS 走 OpenSSL(TlsChannelLinux.cpp)。
|
||||
// 其它平台该头为空,且不定义 YAMA_TLS_CHANNEL,下方代码自动退回明文。
|
||||
#include "TlsChannel.h"
|
||||
|
||||
// WebSocket 传输(经反代 443 等受限端口接入)。头文件实现,各平台编译目标无需改动。
|
||||
@@ -70,6 +70,8 @@ public:
|
||||
}
|
||||
virtual void Encode(unsigned char* data, int len, unsigned char* param = 0) {}
|
||||
virtual void Decode(unsigned char* data, int len, unsigned char* param = 0) {}
|
||||
// 只有 HellEncoder 有可替换的头加密函数;Shine 等实现忽略。
|
||||
virtual void SetHeaderEnc(EncFun) {}
|
||||
virtual EncFun GetHeaderEncoder() const
|
||||
{
|
||||
return nullptr;
|
||||
@@ -79,21 +81,27 @@ public:
|
||||
class HellEncoder : public ProtocolEncoder
|
||||
{
|
||||
private:
|
||||
EncFun m_HeaderEnc;
|
||||
// 原子量:主连接重连时会在发送线程/接收线程可能同时使用编码器的时机更换头加密函数,
|
||||
// 只换函数指针(零分配、零释放),读方永远拿到新旧之一,不会 UAF。
|
||||
std::atomic<EncFun> m_HeaderEnc;
|
||||
Encoder *m_BodyEnc;
|
||||
public:
|
||||
HellEncoder(EncFun head, Encoder *body)
|
||||
{
|
||||
m_HeaderEnc = head;
|
||||
m_HeaderEnc.store(head, std::memory_order_relaxed);
|
||||
m_BodyEnc = body;
|
||||
}
|
||||
~HellEncoder()
|
||||
{
|
||||
SAFE_DELETE(m_BodyEnc);
|
||||
}
|
||||
virtual void SetHeaderEnc(EncFun enc) override
|
||||
{
|
||||
m_HeaderEnc.store(enc, std::memory_order_relaxed);
|
||||
}
|
||||
virtual HeaderFlag GetHead() const override
|
||||
{
|
||||
return ::GetHead(m_HeaderEnc);
|
||||
return ::GetHead(m_HeaderEnc.load(std::memory_order_relaxed));
|
||||
}
|
||||
virtual int GetHeadLen() const override
|
||||
{
|
||||
@@ -292,6 +300,17 @@ public:
|
||||
m_subConnAuthClientID = clientID;
|
||||
}
|
||||
|
||||
// 标记本对象是主连接。只有 StartClient 里 NewNetClient() 拿到的那一个会调用;
|
||||
// 只有主连接会在登录被接受后发布头加密类型、并在上一条连接未被登录接受时轮转
|
||||
// 探测,子连接一律跟随发布值(见 PrepareHeaderEncoderForConnect / PublishHeaderEncoder)。
|
||||
void MarkMainLink() { m_bMainLink = true; }
|
||||
|
||||
// 把当前 HELL 头加密类型发布到 CONNECT_ADDRESS 的共享槽位(仅主连接有效)。
|
||||
// 必须在服务端**真正接受登录之后**调用(CMD_MASTERSETTING),不能在 ConnectServer
|
||||
// 返回时就调:握手成功不代表后端解析得了这个头(Go fallback 是读到登录包才拒绝),
|
||||
// 而且子连接的 ConnectServer 也会走到那里,会用自己乱撞的值覆盖发布值。
|
||||
void PublishHeaderEncoder();
|
||||
|
||||
// 内部:在收到的数据帧分发到 manager 之前,尝试识别并消费 TOKEN_CONN_AUTH ack。
|
||||
// 仅在我们正在等待 auth 响应时(m_authPending=true)才消费;否则透传给 manager。
|
||||
bool TryHandleAuthResponse(PBYTE buf, ULONG len);
|
||||
@@ -334,6 +353,12 @@ public:
|
||||
virtual VOID Disconnect(); // 函数支持 TCP/UDP
|
||||
|
||||
protected:
|
||||
// 每次建连前调整 HELL 头加密函数:主连接上一条没被登录接受时换下一种类型轮转探测,
|
||||
// 子连接跟随主连接已发布的类型。必须在建 socket / 启动收发线程之前完成——后端只在
|
||||
// 每条连接的**第一个**包上识别并锁定头加密方式(Go 首包锁存、认不出即断开),所以
|
||||
// 换类型只对「下一条连接的首包」生效;这一步同时读上一条连接的 m_loginAcked,
|
||||
// 因此必须先于 ConnectServer 里的登录标志清零。
|
||||
void PrepareHeaderEncoderForConnect();
|
||||
virtual int ReceiveData(char* buffer, int bufSize, int flags)
|
||||
{
|
||||
// WebSocket 传输:字节流在 WS 帧里,帧层自己处理 TLS(WSS)或裸 socket(WS)
|
||||
@@ -428,6 +453,10 @@ protected:
|
||||
bool m_exit_while_disconnect;
|
||||
PkgMask* m_masker;
|
||||
BOOL m_EncoderType;
|
||||
// HELL 头加密运行态(见 PrepareHeaderEncoderForConnect / PublishHeaderEncoder)
|
||||
std::atomic<int> m_headerEncIdx{0}; // HeaderEncType 下标(仅 HELL 有意义)
|
||||
std::atomic<int> m_headerEncAttempts{0}; // ConnectServer 已调用次数
|
||||
bool m_bMainLink = false; // StartClient 的主连接标记
|
||||
std::string m_sLocPublicIP;
|
||||
CONNECT_ADDRESS *m_conn = NULL;
|
||||
|
||||
|
||||
@@ -49,7 +49,9 @@ BOOL IOCPUDPClient::ConnectServer(const char* szServerIP, unsigned short uPort)
|
||||
if (ret == 0) {
|
||||
m_bWorkThread = S_RUN;
|
||||
m_bIsRunning = TRUE;
|
||||
m_hWorkThread = reinterpret_cast<HANDLE>(static_cast<uintptr_t>(id));
|
||||
// 同 IOCPClient:macOS 的 pthread_t 是 _opaque_pthread_t*,不能经
|
||||
// static_cast<uintptr_t> 中转,reinterpret_cast 对整型/指针两种实现都成立。
|
||||
m_hWorkThread = reinterpret_cast<HANDLE>(id);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -1444,8 +1444,12 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
// 登录已被服务端接受:服务端把本机加入在线列表后才下发 MasterSettings
|
||||
// (2015RemoteDlg.cpp::SendMasterSettings(ctx, ...) 的登录路径)。协议切换的
|
||||
// 自动回退靠这个信号撤销,而不是只看连接是否建立——连接建立只说明握手完成。
|
||||
if (m_ClientObject)
|
||||
if (m_ClientObject) {
|
||||
m_ClientObject->SetLoginAcked(true);
|
||||
// 后端确实按当前头加密类型解析成功了,发布给后续创建的子连接继承
|
||||
// (只有主连接会走到 CMD_MASTERSETTING,见 PublishHeaderEncoder)。
|
||||
m_ClientObject->PublishHeaderEncoder();
|
||||
}
|
||||
if (ulLength > MasterSettingsOldSize) {
|
||||
memcpy(&m_settings, szBuffer + 1, ulLength > sizeof(MasterSettings) ? sizeof(MasterSettings) : MasterSettingsOldSize);
|
||||
if (m_settings.Signature[0] && m_LoginSignature.empty()) {
|
||||
|
||||
+2
-2
@@ -103,7 +103,7 @@ IDR_WAVE WAVE "Res\\msg.wav"
|
||||
//
|
||||
|
||||
VS_VERSION_INFO VERSIONINFO
|
||||
FILEVERSION 1,0,4,2
|
||||
FILEVERSION 1,0,4,3
|
||||
PRODUCTVERSION 1,0,0,1
|
||||
FILEFLAGSMASK 0x3fL
|
||||
#ifdef _DEBUG
|
||||
@@ -121,7 +121,7 @@ BEGIN
|
||||
BEGIN
|
||||
VALUE "CompanyName", "FUCK THE UNIVERSE"
|
||||
VALUE "FileDescription", "A GHOST"
|
||||
VALUE "FileVersion", "1.0.4.2"
|
||||
VALUE "FileVersion", "1.0.4.3"
|
||||
VALUE "InternalName", "ServerDll.dll"
|
||||
VALUE "LegalCopyright", "Copyright (C) 2019-2026"
|
||||
VALUE "OriginalFilename", "ServerDll.dll"
|
||||
|
||||
Binary file not shown.
+14
-9
@@ -6,7 +6,8 @@
|
||||
//
|
||||
// 选型:
|
||||
// - Windows:Schannel(原生 SSPI),零第三方依赖;secur32.lib / crypt32.lib 为系统库。
|
||||
// - Linux:OpenSSL(构建链已因 libsign 链接 libcrypto,另加 libssl 即可)。
|
||||
// - Linux / macOS:OpenSSL(Linux 构建链已因 libsign 链接 libcrypto,另加 libssl 即可;
|
||||
// macOS 需 Homebrew openssl@3,见 macos/CMakeLists.txt)。
|
||||
// 两者都是单向 TLS:客户端只校验服务端证书链到固定的信任锚,不提供客户端证书,
|
||||
// 客户端身份仍由隧道内登录(V1 PwdHmac / V2 ECDSA)承担;均不校主机名(客户端按 IP
|
||||
// 连接),不做吊销检查——与 Windows 版既有语义保持一致。
|
||||
@@ -16,11 +17,12 @@
|
||||
// Send/Recv 对上下文的使用由 m_ctxMtx 互斥,避免重连线程释放上下文时与使用线程产生
|
||||
// use-after-free。本对象作为 IOCPClient 的值成员存在,析构时释放上下文。
|
||||
//
|
||||
// 平台范围:_WIN32(Schannel)、Linux 与 Android(OpenSSL)有实现;macOS 不含任何内容,
|
||||
// 客户端维持明文。这些平台都通过 YAMA_TLS_CHANNEL 宏告知调用方「本平台有 TLS 通道」。
|
||||
// 平台范围:_WIN32(Schannel)、Linux / Android / macOS(OpenSSL)有实现。这些平台都通过
|
||||
// YAMA_TLS_CHANNEL 宏告知调用方「本平台有 TLS 通道」。
|
||||
// Android 复用 Linux 的 OpenSSL 实现(TlsChannelLinux.cpp),唯一差异是信任锚目录改为
|
||||
// App 私有 filesDir(由 TlsSetAnchorDir 注入),语义(单向 TLS1.2 钉扎、fail-closed、
|
||||
// 热重载)与 Linux 完全一致。
|
||||
// 热重载)与 Linux 完全一致。macOS 同样复用这份 OpenSSL 实现且不改目录规则:
|
||||
// ~/.config/ghost/yama-ca.pem 与 macOS 客户端现有的 config.conf 目录一致。
|
||||
#pragma once
|
||||
|
||||
#if defined(_WIN32)
|
||||
@@ -135,7 +137,7 @@ private:
|
||||
std::vector<BYTE> m_pending; // 已解密、未交付给应用层的明文
|
||||
};
|
||||
|
||||
#elif defined(__linux__) // 含 Android:__ANDROID__ 同时定义 __linux__
|
||||
#elif defined(__linux__) || defined(__APPLE__) // Android 同时定义 __linux__;macOS 走同一份 OpenSSL 实现
|
||||
|
||||
#define YAMA_TLS_CHANNEL 1
|
||||
|
||||
@@ -152,15 +154,18 @@ bool TlsEnabled();
|
||||
// (fail-closed),不得静默回退明文。线程安全、幂等。
|
||||
bool TlsLoadError();
|
||||
|
||||
// Windows 版按目标地址区分「用不用内嵌锚」。Linux / Android 客户端没有内嵌锚概念(生成器
|
||||
// 只往 Windows 镜像里写锚块),信任锚一律是配置文件,故这里忽略目标地址,与进程级开关等价。
|
||||
// Windows 版按目标地址区分「用不用内嵌锚」。Linux / Android / macOS 客户端没有内嵌锚概念
|
||||
// (生成器只往 Windows 镜像里写锚块),信任锚一律是配置文件,故这里忽略目标地址,与进程级
|
||||
// 开关等价。
|
||||
inline bool TlsEnabledFor(const std::string&, const std::string&) { return TlsEnabled(); }
|
||||
inline bool TlsLoadErrorFor(const std::string&, const std::string&) { return TlsLoadError(); }
|
||||
|
||||
// 服务端下发信任锚(COMMAND_TLS_ENABLE):把 PEM 正文写入信任锚文件,原子替换、权限 0600。
|
||||
// 写入前先解析验证,不是合法证书就整包拒绝。目录按平台:
|
||||
// Linux:$XDG_CONFIG_HOME/ghost/yama-ca.pem(默认 ~/.config/ghost/yama-ca.pem,无 HOME
|
||||
// 时退回程序目录);
|
||||
// Linux:$XDG_CONFIG_HOME/ghost/yama-ca.pem(默认 ~/.config/ghost/yama-ca.pem);
|
||||
// macOS:~/.config/ghost/yama-ca.pem(与 macos/main.mm 的 config.conf 同目录,不读
|
||||
// XDG_CONFIG_HOME;HOME 兜底也逐字对齐 initConfigPaths:HOME → getpwuid → /tmp);
|
||||
// Linux 无 HOME 时退回程序目录;
|
||||
// Android:App 私有 filesDir/yama-ca.pem(目录由 TlsSetAnchorDir 注入)。
|
||||
// 落盘后用 TlsReload() 立即生效(Windows 客户端在 COMMAND_TLS_ENABLE 里调用同一个
|
||||
// TlsReload(),各平台行为一致)。
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// TlsChannelLinux.cpp — 见 TlsChannel.h 头注释。Linux 与 Android 编译(共用 OpenSSL 实现)。
|
||||
// TlsChannelLinux.cpp — 见 TlsChannel.h 头注释。Linux / Android / macOS 编译(共用 OpenSSL 实现)。
|
||||
//
|
||||
// 与 Windows 的 Schannel 实现语义对齐:
|
||||
// - 单向 TLS 1.2(min=max=1.2,与 SP_PROT_TLS1_2_CLIENT 及两套服务端一致);
|
||||
@@ -9,7 +9,7 @@
|
||||
// 与 Windows 实现的差异:OpenSSL 自己管理 TLS 记录缓冲,不需要 m_raw/m_pending;
|
||||
// 一次性交付不出去的明文留在 SSL 内部,由 SSL_has_pending()/SSL_pending() 暴露给
|
||||
// 接收线程在 select 前优先消费。
|
||||
#if defined(__linux__) // 含 Android:__ANDROID__ 同时定义 __linux__
|
||||
#if defined(__linux__) || defined(__APPLE__) // Android 同时定义 __linux__;macOS 走同一份实现
|
||||
|
||||
#include "TlsChannel.h"
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
|
||||
#include <cerrno>
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
@@ -37,6 +38,11 @@
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#if defined(__APPLE__)
|
||||
#include <mach-o/dyld.h> // _NSGetExecutablePath
|
||||
#include <pwd.h> // getpwuid:与 macos/main.mm 的 HOME 兜底保持一致
|
||||
#endif
|
||||
|
||||
namespace {
|
||||
|
||||
const char* const kAnchorName = "yama-ca.pem";
|
||||
@@ -55,27 +61,58 @@ std::string g_anchorDir; // 信任锚目录,由 TlsSetAnchorDir
|
||||
|
||||
// 配置目录:
|
||||
// Linux:与 LinuxConfig 相同规则($XDG_CONFIG_HOME/ghost 或 ~/.config/ghost);
|
||||
// macOS:固定 ~/.config/ghost(跟随 macos/main.mm 的 config.conf 位置,不吃 XDG_CONFIG_HOME);
|
||||
// Android:App 私有 filesDir(TlsSetAnchorDir 注入),无「程序目录」回退。
|
||||
std::string ConfigDir()
|
||||
{
|
||||
#ifdef __ANDROID__
|
||||
return g_anchorDir;
|
||||
#else
|
||||
const char* home = getenv("HOME");
|
||||
#if defined(__APPLE__)
|
||||
// macOS 不看 XDG_CONFIG_HOME:macos/main.mm 的 initConfigPaths 把 config.conf 固定
|
||||
// 放在 ~/.config/ghost,信任锚必须跟着它走,否则同一台机器会出现两份配置目录。
|
||||
// HOME 兜底顺序也与 initConfigPaths 逐字对齐(HOME → getpwuid()->pw_dir → /tmp):
|
||||
// 手工做成 launchd daemon 时 launchd 不导出 HOME,只查 HOME 会让锚落到「程序目录」,
|
||||
// 而 config.conf 在 pw_dir 下——升级/重装 app bundle 时锚跟着被删,客户端静默退回明文,
|
||||
// 而服务端仍以为这台是 TLS。
|
||||
if (!home || !home[0]) {
|
||||
struct passwd* pw = getpwuid(getuid());
|
||||
if (pw && pw->pw_dir && pw->pw_dir[0])
|
||||
home = pw->pw_dir;
|
||||
}
|
||||
if (!home || !home[0])
|
||||
home = "/tmp";
|
||||
return std::string(home) + "/.config/ghost";
|
||||
#else
|
||||
const char* xdg = getenv("XDG_CONFIG_HOME");
|
||||
if (xdg && xdg[0])
|
||||
return std::string(xdg) + "/ghost";
|
||||
const char* home = getenv("HOME");
|
||||
if (!home || !home[0])
|
||||
return std::string();
|
||||
return std::string(home) + "/.config/ghost";
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
|
||||
// 可执行文件所在目录(readlink /proc/self/exe,失败返回空)。Android 无此概念,返回空。
|
||||
// 可执行文件所在目录(失败返回空)。仅用作「无 HOME」时的回退位置。Android 无此概念。
|
||||
std::string ExeDir()
|
||||
{
|
||||
#ifdef __ANDROID__
|
||||
#if defined(__ANDROID__)
|
||||
return std::string();
|
||||
#elif defined(__APPLE__)
|
||||
// macOS 没有 /proc/self/exe。_NSGetExecutablePath 返回的路径可能含符号链接/相对成分,
|
||||
// 这里只取所在目录、不做规范化——用途只是找同目录的 yama-ca.pem,与 Linux 分支一致。
|
||||
// 注意 size 是 in/out:缓冲区不足时返回 -1,不能读返回后的内容。
|
||||
char buf[4096];
|
||||
uint32_t size = sizeof(buf);
|
||||
if (_NSGetExecutablePath(buf, &size) != 0)
|
||||
return std::string();
|
||||
char* slash = strrchr(buf, '/');
|
||||
if (!slash)
|
||||
return std::string();
|
||||
*slash = '\0';
|
||||
return std::string(buf);
|
||||
#else
|
||||
char buf[4096];
|
||||
ssize_t n = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
|
||||
@@ -91,7 +128,8 @@ std::string ExeDir()
|
||||
}
|
||||
|
||||
// 信任锚候选路径(按优先级),只返回已经存在的那个:
|
||||
// 1) $XDG_CONFIG_HOME/ghost/yama-ca.pem(默认 ~/.config/ghost/yama-ca.pem)
|
||||
// 1) ConfigDir()/yama-ca.pem(Linux 默认 ~/.config/ghost,macOS 固定 ~/.config/ghost,
|
||||
// Android 为 App filesDir)
|
||||
// 2) 可执行文件同目录 yama-ca.pem(兼容手工投递,与 Windows 的 exe 同名文件回退一致)
|
||||
bool FindAnchorPath(std::string& out)
|
||||
{
|
||||
@@ -600,4 +638,4 @@ bool TlsChannel::HasPending() const
|
||||
return SSL_pending(m_ssl) > 0 || SSL_has_pending(m_ssl) == 1;
|
||||
}
|
||||
|
||||
#endif // __linux__(含 Android)
|
||||
#endif // __linux__ / __APPLE__(Linux 含 Android;macOS)
|
||||
@@ -169,9 +169,9 @@ public:
|
||||
|
||||
// 处理 V2 文件数据包
|
||||
// 返回: 0=成功, >0=错误码
|
||||
// reply:主连接(Linux 传 g_pMainClient)。非空时,C2C 传输的最后一个条目处理完会回一包
|
||||
// 落盘结果(TOKEN_C2C_SEND_RESULT),服务端据此把 receiver_ack 变成真实值;
|
||||
// 传 nullptr(macOS 目前没有全局主连接)则保持旧行为,不发回执。
|
||||
// reply:主连接(Linux/macOS 传 g_pMainClient)。非空时,C2C 传输的最后一个条目
|
||||
// 处理完会回一包落盘结果(TOKEN_C2C_RECV_RESULT),服务端据此把 receiver_ack
|
||||
// 变成真实值;传 nullptr 则保持旧行为,不发回执。
|
||||
static int RecvFileChunkV2(const uint8_t* buf, size_t len, uint64_t myClientID,
|
||||
IOCPClient* reply = nullptr)
|
||||
{
|
||||
|
||||
+56
-4
@@ -10,6 +10,7 @@
|
||||
#include <ctime>
|
||||
#include <chrono>
|
||||
#include <climits>
|
||||
#include <cstddef> // offsetof:CONNECT_ADDRESS::szFuture 运行态槽位的对齐断言
|
||||
|
||||
#ifdef _WIN32
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
@@ -137,19 +138,20 @@ inline int isValid_10s()
|
||||
// 无此位 = 老客户端,按系统 ANSI(默认 CP936)解读
|
||||
#define CLIENT_CAP_SCREEN_PREVIEW 0x0004 // 支持屏幕预览(双击在线主机时弹缩略图)
|
||||
#define CLIENT_CAP_C2C_PATHS 0x0008 // 支持按路径清单向另一客户端发送文件(COMMAND_C2C_SEND_FILES,仅 Windows)
|
||||
#define CLIENT_CAP_C2C_RECV_ACK 0x0010 // 作为 C2C 目标端时,落盘完成后回执(TOKEN_C2C_RECV_RESULT,目前仅 Linux)
|
||||
#define CLIENT_CAP_C2C_RECV_ACK 0x0010 // 作为 C2C 目标端时,落盘完成后回执(TOKEN_C2C_RECV_RESULT,Linux/macOS)
|
||||
#define CLIENT_CAP_PROTO_SWITCH 0x0020 // 支持服务端远程切换传输协议(COMMAND_SET_PROTO,仅 Windows)
|
||||
#define CLIENT_CAP_EMBEDDED_ANCHOR 0x0040 // 当前靠「生成时内嵌的 TLS 信任锚」在加密(按运行时状态置位,不是能力声明)
|
||||
#define CLIENT_CAP_VIRTUAL_DESKTOP 0x0080 // 支持按 COMMAND_SCREEN_SPY 参数 buffer[11](wire 索引 12)强制抓取整个虚拟桌面(多显示器远程控制)
|
||||
#define CLIENT_CAP_WINDOW_INFO 0x0100 // 支持 COMMAND_MCP_WINDOW_INFO(带矩形/前后台/最小化状态的窗口列表)与窗口激活(CMD_WINDOW_ACTIVATE_FLAG)
|
||||
#define CLIENT_CAP_SCREEN_REGION 0x0200 // 支持 COMMAND_SCREEN_PREVIEW_REQ 扩展(区域/窗口/显示器原生分辨率截图)
|
||||
#define CLIENT_CAP_APK_UPDATE 0x0400 // 支持接收 COMMAND_UPDATE 下发的 APK 并走系统安装器(仅 Android)
|
||||
#define CLIENT_CAP_SCREEN_CLIPBOARD 0x0800 // 屏幕子连接处理 COMMAND_SCREEN_SET_CLIPBOARD,并把 VK_V 映射成 ACTION_PASTE(仅新版 Android)
|
||||
#define CLIENT_CAP_SCREEN_CLIPBOARD 0x0800 // 屏幕子连接处理 COMMAND_SCREEN_SET_CLIPBOARD,并把 VK_V 映射成 ACTION_PASTE(新版 Android 与 macOS;Linux 只在屏幕子连接里实现了剪贴板,未声明)
|
||||
#define CLIENT_CAP_LOCK_SCREEN 0x1000 // 屏幕子连接处理 COMMAND_SCREEN_CTRL_ALT_DEL(Android 映射为锁屏 GLOBAL_ACTION_LOCK_SCREEN)
|
||||
#define CLIENT_CAP_UNINSTALL 0x2000 // 主连接处理 TOKEN_UNINSTALL(Android 拉起系统卸载确认框;Windows 客户端一直支持但不声明)
|
||||
#define CLIENT_CAP_REMOTE_CHAT 0x4000 // 主连接处理 COMMAND_CHAT(远程交谈子连接;Windows 一直支持但不声明,目前只有新版 Android 声明)
|
||||
#define CLIENT_CAP_TERMINAL 0x8000 // 主连接处理 COMMAND_SHELL(PTY 终端子连接:exec_command / terminal_*;Linux 一直支持但不声明,目前只有新版 Android 声明)
|
||||
#define CLIENT_CAP_TERMINAL 0x8000 // 主连接处理 COMMAND_SHELL(PTY 终端子连接:exec_command / terminal_*;Linux 一直支持但不声明,新版 Android 与 macOS 声明)
|
||||
#define CLIENT_CAP_PRIVACY_OVERLAY 0x10000 // 屏幕子连接处理 COMMAND_SCREEN_BLOCK_INPUT / COMMAND_SCREEN_BLANK(Android 用无障碍全屏 overlay 实现;Windows 一直支持锁定键鼠但不声明这个位)
|
||||
#define CLIENT_CAP_PROCESS 0x20000 // 主连接处理 COMMAND_SYSTEM(系统子连接:COMMAND_PSLIST / COMMAND_KILLPROCESS;Linux/macOS 声明,Windows 一直支持但不声明)
|
||||
|
||||
#define TALK_DLG_MAXLEN 1024 // 最大输入字符长度
|
||||
|
||||
@@ -1157,6 +1159,42 @@ inline bool IsLocalTestClient(const CONNECT_ADDRESS* conn)
|
||||
sizeof(LOCAL_TEST_CLIENT_MAGIC) - 1) == 0;
|
||||
}
|
||||
|
||||
// szFuture 前 sizeof(LOCAL_TEST_CLIENT_MAGIC) 字节被上面的本地测试标记占用;其后从
|
||||
// HEADER_ENC_SELECT_OFFSET 起放一个运行态字段(只在内存里有效,不落盘、不参与分享/
|
||||
// 转移序列化):
|
||||
// int 头加密下标 + 1,0 = 尚未发布(烘焙的 EXE 里 szFuture 全 0)
|
||||
//
|
||||
// 用途:主连接收到 CMD_MASTERSETTING(登录已被后端接受)后,把当前 HELL 头加密类型写
|
||||
// 进来;文件/进程/屏幕等子连接在构造和重连时优先继承它,避免自己随机到 Go fallback
|
||||
// 服务端尚未实现的 HeaderEncV7~V10。该值只当「提示」用:读方必须做范围校验,坏值回退
|
||||
// 随机(下标越界会读穿 GetHeaderEncoder 的方法表)。
|
||||
//
|
||||
// 跨线程:写方是主连接的接收线程(CKernelManager::OnReceive → PublishHeaderEncoder),
|
||||
// 读方是各子连接自己的线程(构造/重连),这里**不做同步**,也不保证读到最新值——
|
||||
// 读到旧值等价于「尚未发布」,回退随机,行为正确。前提是该槽位只承载这种提示语义:
|
||||
// 不要拿它做控制逻辑,也不要放大成多字段协议。目标平台(x86/x64/ARM64)上 4 字节
|
||||
// 对齐的读写不会撕裂,配合上面的范围校验即可。
|
||||
#define HEADER_ENC_SELECT_OFFSET sizeof(LOCAL_TEST_CLIENT_MAGIC)
|
||||
static_assert(HEADER_ENC_SELECT_OFFSET % sizeof(int) == 0, "头加密运行态槽位需 4 字节对齐");
|
||||
static_assert(sizeof(((CONNECT_ADDRESS*)0)->szFuture) >= HEADER_ENC_SELECT_OFFSET + sizeof(int),
|
||||
"CONNECT_ADDRESS::szFuture 空间不足");
|
||||
static_assert(offsetof(CONNECT_ADDRESS, szFuture) % alignof(int) == 0,
|
||||
"CONNECT_ADDRESS::szFuture 需 4 字节对齐");
|
||||
|
||||
inline int GetHeaderEncSelect(const CONNECT_ADDRESS* conn)
|
||||
{
|
||||
int value = 0;
|
||||
if (conn) memcpy(&value, conn->szFuture + HEADER_ENC_SELECT_OFFSET, sizeof(value));
|
||||
return value;
|
||||
}
|
||||
|
||||
inline void SetHeaderEncSelect(CONNECT_ADDRESS* conn, int index)
|
||||
{
|
||||
if (!conn) return;
|
||||
int value = index + 1;
|
||||
memcpy(conn->szFuture + HEADER_ENC_SELECT_OFFSET, &value, sizeof(value));
|
||||
}
|
||||
|
||||
#define FOREVER_RUN 2
|
||||
|
||||
// 客户端程序线程信息结构体, 包含5个成员:
|
||||
@@ -1300,8 +1338,10 @@ typedef struct LOGIN_INFOR {
|
||||
caps |= CLIENT_CAP_SCREEN_REGION;
|
||||
#elif defined(__linux__) && !defined(__ANDROID__)
|
||||
// Linux 客户端作为 C2C 目标端时会回执落盘结果(common/FileTransferV2.h)。
|
||||
// macOS 暂未接线(无全局主连接句柄),不声明——服务端就不会为它空等回执。
|
||||
caps |= CLIENT_CAP_C2C_RECV_ACK;
|
||||
// COMMAND_SYSTEM → SystemManager(/proc 枚举 + kill)。一直有实现,声明出来是为了
|
||||
// 让「这台主机能不能杀进程」有据可查,不必再靠平台名推断。
|
||||
caps |= CLIENT_CAP_PROCESS;
|
||||
#elif defined(__ANDROID__)
|
||||
// 收到服务端下发的 APK 后写盘并拉起系统安装器。老 APK 没有这个分支,
|
||||
// 服务端据此提示「先手动装一次新版」,而不是发一个对方会静默丢弃的包。
|
||||
@@ -1321,6 +1361,18 @@ typedef struct LOGIN_INFOR {
|
||||
// 远程终端(COMMAND_SHELL → PTY 子连接):老 APK 里 COMMAND_SHELL 是空实现,
|
||||
// 服务端据此提前拒绝 exec_command / terminal_*,而不是等子连接超时。
|
||||
caps |= CLIENT_CAP_TERMINAL;
|
||||
#elif defined(__APPLE__)
|
||||
// 终端(COMMAND_SHELL → PTY 子连接)在 macOS 一直是完整实现(zsh/bash 交互 +
|
||||
// resize),以前只是没声明,服务端据此把 exec_command / terminal_* 当作不支持。
|
||||
caps |= CLIENT_CAP_TERMINAL;
|
||||
// 屏幕子连接已处理 COMMAND_SCREEN_SET_CLIPBOARD / GET_CLIPBOARD。
|
||||
caps |= CLIENT_CAP_SCREEN_CLIPBOARD;
|
||||
// COMMAND_SYSTEM → SystemManager(proc_listpids 枚举 + SIGKILL)。老 macOS 构建
|
||||
// 收到 COMMAND_SYSTEM 只打一行日志,服务端据此提前拒绝 kill_process。
|
||||
caps |= CLIENT_CAP_PROCESS;
|
||||
// 作为 C2C 目标端落盘后回执(TOKEN_C2C_RECV_RESULT),走主连接全局句柄。
|
||||
caps |= CLIENT_CAP_C2C_RECV_ACK;
|
||||
// SCREEN_PREVIEW 依赖录屏授权,由 main.mm 在登录前按运行时状态追加(同 Linux)。
|
||||
#endif
|
||||
return caps;
|
||||
}
|
||||
|
||||
+30
-6
@@ -17,6 +17,8 @@
|
||||
#endif
|
||||
|
||||
#include <iostream>
|
||||
#include <cstdio> // fputs/fflush/stderr:macOS 的 mirrorStderr 把每行日志同步写 stderr
|
||||
#include <cstring> // strrchr:getFileName 不依赖调用方先包含 <string.h>
|
||||
#include <fstream>
|
||||
#include <mutex>
|
||||
#include <queue>
|
||||
@@ -77,6 +79,20 @@ public:
|
||||
snprintf(buf, sizeof(buf), "%d", (int)getpid());
|
||||
instance.pid = buf;
|
||||
instance.enable = false;
|
||||
#elif defined(__APPLE__)
|
||||
// macOS:只保留内存 ring + stderr,不另建日志文件。
|
||||
// - ring 是服务端「运行日志」菜单的数据源:COMMAND_QUERY_LOG →
|
||||
// TOKEN_REPORT_LOG,见 common/ClientLogHandler.h;
|
||||
// - stderr 已被 macos/main.mm 重定向到 /tmp/ghost.log(daemon 与 App
|
||||
// bundle 两种启动方式都做),那是现场唯一日志文件,再往
|
||||
// ~/.config/ghost 写一份只会让两边对不上。
|
||||
// 此前 macOS 的 Mprintf 是 NSLog/fprintf,从不经过 Logger,ring 永远是
|
||||
// 空的 —— 服务端点「运行日志」打开后一个字都没有,就是这个原因。
|
||||
char buf[16] = {};
|
||||
snprintf(buf, sizeof(buf), "%d", (int)getpid());
|
||||
instance.pid = buf;
|
||||
instance.enable = false;
|
||||
instance.mirrorStderr = true;
|
||||
#else // Linux
|
||||
char buf[16] = {};
|
||||
snprintf(buf, sizeof(buf), "%d", (int)getpid());
|
||||
@@ -166,6 +182,14 @@ public:
|
||||
logEntry.pop_back();
|
||||
logEntry += '\n';
|
||||
|
||||
// macOS:把同一行镜像到 stderr,也就是 /tmp/ghost.log。ring 只留最近
|
||||
// kMemLogMax 条,而现场排查往往要往前翻,两边保持完全相同的文本(含前缀和
|
||||
// 时间戳),对照时不必换算。
|
||||
if (mirrorStderr) {
|
||||
fputs(logEntry.c_str(), stderr);
|
||||
fflush(stderr);
|
||||
}
|
||||
|
||||
// Always record to in-memory ring buffer regardless of enable flag.
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_memMutex);
|
||||
@@ -262,6 +286,7 @@ private:
|
||||
}
|
||||
std::string logFileName; // 日志文件名
|
||||
bool enable; // 是否启用
|
||||
bool mirrorStderr = false; // macOS:每行同时镜像到 stderr(/tmp/ghost.log)
|
||||
bool threadRun; // 日志线程状态
|
||||
std::queue<std::string> logQueue; // 日志队列
|
||||
std::mutex queueMutex; // 队列互斥锁
|
||||
@@ -383,15 +408,14 @@ inline const char* getFileName(const char* path)
|
||||
#elif defined(_WIN32)
|
||||
#define Mprintf(format, ...) Logger::getInstance().log(getFileName((__FILE__)), __LINE__, (format), __VA_ARGS__)
|
||||
#elif defined(__APPLE__)
|
||||
// macOS: 使用 NSLog 输出到系统日志(可通过 Console.app 查看)
|
||||
// macOS:与 Linux 一样写 Logger —— 内存 ring 供服务端「运行日志」菜单取回
|
||||
// (COMMAND_QUERY_LOG → TOKEN_REPORT_LOG),Logger 初始化时置 mirrorStderr,
|
||||
// 同一行再落到 stderr,也就是 /tmp/ghost.log。不要改回 NSLog/fprintf:那样
|
||||
// ring 永远为空,菜单打开后没有任何内容。
|
||||
#ifdef Mprintf
|
||||
#undef Mprintf
|
||||
#endif
|
||||
#ifdef __OBJC__
|
||||
#define Mprintf(format, ...) NSLog(@"%@", [NSString stringWithFormat:@(format), ##__VA_ARGS__])
|
||||
#else
|
||||
#define Mprintf(format, ...) printf(format, ##__VA_ARGS__)
|
||||
#endif
|
||||
#define Mprintf(format, ...) Logger::getInstance().log(getFileName(__FILE__), __LINE__, format, ##__VA_ARGS__)
|
||||
#elif defined(__ANDROID__)
|
||||
#include <android/log.h>
|
||||
#include <cstdarg>
|
||||
|
||||
@@ -47,6 +47,18 @@ inline void RunSubConnThread(const char* threadName, CreateFn createHandler, OnR
|
||||
void* clientAddr = ClientObject.get();
|
||||
Mprintf(">>> Enter %s [%p]\n", threadName, clientAddr);
|
||||
|
||||
// 传输协议必须显式喂进去,否则子连接与主连接走的不是同一条路:
|
||||
// Linux/macOS 的 IOCPClient 不带 m_conn,ConnectServer 里协议来源是
|
||||
// m_defaultProto(默认 -1 = 明文 TCP)。主连接在 main 里已 SetDefaultProto
|
||||
// (macos/main.mm / linux/main.cpp),子连接漏掉这一步时,配成 WS/WSS 的客户端
|
||||
// 会出现「主连接正常、所有子连接静默按明文直连」——经反代/HTTP 代理接入时,
|
||||
// 明文 TCP 在到达主控之前就被丢掉,服务端连一条 [ConnAuth] 都看不到,
|
||||
// 而客户端只会卡在 "[ConnAuth] 等待响应超时"。见 main.mm 里同一段注释。
|
||||
ClientObject->SetDefaultProto((int)(unsigned char)g_SETTINGS.protoType);
|
||||
Mprintf(">>> %s: proto=%d (%s:%d)\n", threadName,
|
||||
(int)(unsigned char)g_SETTINGS.protoType,
|
||||
g_SETTINGS.ServerIP(), g_SETTINGS.ServerPort());
|
||||
|
||||
// 子连接:开启 auth。Linux/macOS IOCPClient 不带 m_conn,显式传入 g_myClientID。
|
||||
ClientObject->EnableSubConnAuth(true, g_myClientID);
|
||||
|
||||
@@ -61,8 +73,19 @@ inline void RunSubConnThread(const char* threadName, CreateFn createHandler, OnR
|
||||
Sleep(1000);
|
||||
// 清除回调,防止重连线程访问已销毁的 handler
|
||||
ClientObject->setManagerCallBack(nullptr, nullptr, nullptr);
|
||||
} else {
|
||||
// createHandler 返回 nullptr = 本机侧初始化失败(如 macOS 无录屏权限)。
|
||||
// 子连接已经建立、鉴权也已通过,这里不关掉的话它会一直挂着,服务端那边
|
||||
// 表现为「子连接在线但永远不发首包」,而客户端日志里原本一个字都没有。
|
||||
Mprintf("*** %s: handler init failed, dropping sub-connection ***\n", threadName);
|
||||
}
|
||||
} else if (S_CLIENT_NORMAL == g_bExit) {
|
||||
// 只有 g_bExit 仍是 NORMAL 时才算真失败(TCP 连接、握手、ConnAuth 任一环节,
|
||||
// ConnectServer 内部已各自打过具体原因)。这里补一条归属明确的收尾日志,
|
||||
// 否则「子连接没建起来」在日志里只剩一行 Leave,无从判断卡在哪一步。
|
||||
Mprintf("*** %s: ConnectServer failed ***\n", threadName);
|
||||
}
|
||||
// g_bExit 已置位 = 客户端正在退出,子连接没建起来是预期行为,不打错误日志。
|
||||
Mprintf(">>> Leave %s [%p]\n", threadName, clientAddr);
|
||||
} catch (const std::exception& e) {
|
||||
Mprintf("*** %s exception: %s ***\n", threadName, e.what());
|
||||
|
||||
+76
-6
@@ -511,7 +511,7 @@ void CMcpSettingsDlg::OnBnClickedBtnSave()
|
||||
- `structuredContent` 统一附 `total` / `totalAll` / `offset` / `limit` / `hasMore`,与 `McpMachine.cpp` 既有约定一致(`host_list_*` / `list_network_connections` 本来就是这样)。
|
||||
- `content` 摘要统一为「共 N <单位>,本次返回第 a-b 条(还有更多,可用 offset 继续取)。」;`hasMore=false` 时不再出现「继续取」的误导提示;`offset` 越界时明确写「offset 超出范围,本次返回 0 条」。
|
||||
- 实现集中在 `McpInternal.h/.cpp`:`PageWindow` / `ResolvePageWindow` / `ApplyPageWindow` / `WritePageFields` / `AppendPagingProps` / `PageSummary`。
|
||||
- `list_files` 仍受服务端 `ParseFileList` 的 500 条硬限制(`total=500` 且原目录确有更多条目时表示截断,不是服务端分页)。客户端侧不截断、按需扩缓冲一次性回全量;本轮未加 `truncated` 标记(要加得改服务端 `ParseFileList` 的调用约定),仍靠「`total=500` 且 `hasMore`」判断。
|
||||
- `list_files` 整目录解析后再分页:`ParseFileList` 的上限是 100000 条,只用于兜住病态目录;到上限时 `structuredContent.truncated=true`,摘要与 `total` 也会说明 `total` 只是上限内的数量。`total` / `hasMore` 反映真实目录条目数,`offset` 可翻到 500 条之后。分页由服务端完成(`limit` 默认 100、上限 1000),客户端仍一次性回全量。
|
||||
|
||||
---
|
||||
|
||||
@@ -597,7 +597,7 @@ token 只从 `-Token` / env 读取,不落仓库、不打印;无在线主机
|
||||
|
||||
### 10.8 D 批:拒绝也入审计
|
||||
|
||||
动机:所有策略拒绝(只读模式、`Mcp*` 开关关闭、主机不支持某能力)都返回 `-32006`,而审计里只有 `CALL_FAIL`——和「参数错」「主机离线」「超时」混在一起,事后分不清「没人调过」和「被策略拦下」。
|
||||
动机:策略拒绝(只读模式、`Mcp*` 开关关闭,以及老客户端 V2 这类能力缺失)返回 `-32006`;平台/能力位不匹配的多数返回 `-32005`。此前审计里只有 `CALL_FAIL`——和「参数错」「主机离线」「超时」混在一起,事后分不清「没人调过」和「被策略拦下」。
|
||||
|
||||
- 实现放在 `tools/call` 的统一出口(`CMcpServer` 的 HTTP 处理器),不在 24 个 `-32006` 分支里逐个埋点:成功解析响应体后多取 `error.code` / `error.message`,`code == -32006` 就追加一条
|
||||
```
|
||||
@@ -628,7 +628,7 @@ token 只从 `-Token` / env 读取,不落仓库、不打印;无在线主机
|
||||
|
||||
排查「改动到底生效没有」「为什么某个工具被拒」时,原先只能靠 `list_online_hosts` 加 `get_audit_log` 侧面推断;现在有一个服务端自身的状态快照。纯内存、只读、不建子连接。
|
||||
|
||||
返回(`structuredContent.status`):
|
||||
返回(`structuredContent` 顶层,与 outputSchema 字段一一对应;早期版本曾多包一层 `status`,已修):
|
||||
|
||||
| 字段 | 含义 |
|
||||
|---|---|
|
||||
@@ -678,12 +678,12 @@ token 只从 `-Token` / env 读取,不落仓库、不打印;无在线主机
|
||||
| `-32600` | Invalid Request | 缺 `jsonrpc` / `method` / 非法 `tools/call` 结构 | 修正请求 |
|
||||
| `-32601` | Method not found | `method` 不是 `initialize` / `tools/list` / `tools/call` 等 | 修正请求 |
|
||||
| `-32602` | Invalid params | 未知工具名、缺必填参数、参数类型/取值非法、批量 `ids` 超过 50 个、`search_file` 过滤参数非法、文本无法转 GBK | 改参数重试,重试同样的请求不会成功 |
|
||||
| `-32001` | Timeout | 等客户端就绪/等子连接/等搜索结果超时(`timeout_ms` 内没等到) | 可加大 `timeout_ms` 重试;持续出现看主机是否卡住 |
|
||||
| `-32001` | Timeout / execution failure | 多为等客户端就绪/等子连接/等搜索结果超时(`timeout_ms` 内没等到);也用于工具自身失败(`http_probe` 解析失败、目标端未确认写入)与已取消(`Request cancelled`) | 先看 `message`:超时且工具支持 `timeout_ms` 可加大重试;子连接没建立/反复超时通常重试无效;`Request cancelled` 可直接重试;其余按 `message` 处理 |
|
||||
| `-32002` | Host offline / not found | 主机 id 不存在、主连接已断、会话 id 不存在或已关闭 | 先 `list_online_hosts` 刷新再选主机 |
|
||||
| `-32003` | Busy | 该主机已有同类请求在飞(终端/截屏/文件/聊天会话),或同设备重复 `chat_open`。`message` 末尾带 `(tool=..., elapsed=Ns)` 点名占用者 | 用 `mcp_list_sessions` 看全部会话;等前一个结束、先 `*_close`,或 `mcp_cancel_session` 释放 |
|
||||
| `-32004` | Send failed | 命令写入主连接失败(连接刚断) | 重试一次;仍失败按 `-32002` 处理 |
|
||||
| `-32005` | Not supported on this host | 能力限制,改参数也修不好:需要 Windows 的工具用在 LNX/MAC/APK 主机上;`remote_open` 遇到多显示器(阶段一);主机无屏幕预览/控制能力位 | 换主机或换工具;不要改参数重试 |
|
||||
| `-32006` | Policy refused | 只读模式 / 对应 `Mcp*` 开关关闭 / 主机不支持该能力(如 V2 文件传输) | **不要重试**:这是配置决定,需管理员改服务端配置 |
|
||||
| `-32006` | Policy refused | 只读模式 / 对应 `Mcp*` 开关关闭;MFC 端还包括老客户端不支持 V2 文件传输(`download_file` / `upload_file` / `read_file` / `copy_files_c2c`;Go 端这种情况返回 `-32005`) | **不要重试**:开关/只读需管理员改服务端配置,老客户端需升级 |
|
||||
| `-32007` | Not in command whitelist | `exec_command` 的命令不在 `McpCmdWhitelist` 里,或词边界不匹配(`dir` 过、`dirx` 拒) | **不要重试**:换成白名单内的命令,或请管理员加白名单项 |
|
||||
| `-32012` | Rejected by validation | 只覆盖「参数被校验拒绝、改参数可修」:`exec_command` 含 shell 元字符(Windows `&\|<>^`;Linux `&\|<>;` 与反引号、`$(` `${` `!`)或控制字符(含 `\r\n`);`terminal_exec` 含控制字符(含换行),或**老非 PTY 会话**里含 `&`/`\|`,或 POSIX 会话里含裸后台 `&`;路径/参数含非法字符。**`-32008` 是同一语义的历史别名**(早期实现用它,已发布的客户端/文档可能仍在匹配),新代码一律用 `-32012` | 按 `message` 修正参数后重试 |
|
||||
| `-32009` | Target not found | 远端路径/注册表键不存在(win32 `2`/`3`,由新客户端主动回报);`kill_network_connection` 的四元组在当前连接表里查不到(`dry_run` 传假四元组最常见) | 先用 `list_files`/`list_registry`(或 `host_list_network_state`)确认目标存在 |
|
||||
@@ -848,7 +848,7 @@ ECDSA 这条是 MS Software KSP 唯一可行的一条,其余几条均已实测
|
||||
|
||||
### 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]` 的既有摘要文案一字未改。
|
||||
Debug 实例(`Bin\Yama_x64d.exe`,临时端口)实测:`list_all_hosts` 的 `content[1]` 含完整主机 JSON(`id` / `ip` / `last_seen` …),`search_hosts` 空结果时是 `{"hasMore":false,"hosts":[],…}`;`content[0]` 的既有摘要文案一字未改。`get_server_status` 的 `content[1]` 是状态对象本身(与 outputSchema 的顶层字段一致;早期版本多包了一层 `status`,已修)。
|
||||
|
||||
### 14.4 影响面
|
||||
|
||||
@@ -951,6 +951,17 @@ schema 里写明这一点;同时根键分支补上 `path: ""`,让两个分
|
||||
`MessageHandle` 的 `TOKEN_REPORT_LOG` 分支取走首包后会 `CancelIO` 关掉这条连接,回在
|
||||
主连接上就是把主连接关掉(客户端当场掉线)。
|
||||
|
||||
macOS 还有第二层问题,只影响日志内容,2026-11-14 修:处理器虽然接上了,但 `Logger` 的
|
||||
ring 只能被 `Mprintf` 写入,而 macOS 的 `Mprintf` 当时直接走 `NSLog`/`fprintf(stderr)`,
|
||||
从不经过 `Logger`——ring 恒为空,菜单和 `get_client_log` 拿到的都是空快照。现在 macOS 的
|
||||
`Mprintf`(由 `common/logger.h` 定义)与 Linux 一样写 `Logger`(ring;`enable=false` 不另
|
||||
建日志文件),再由 `Logger` 把同一行镜像到 stderr(即 `/tmp/ghost.log`),同一条 Mprintf
|
||||
在文件与菜单里的文本、前缀、时间戳完全一致;ring 只留最近 1000 行,更早的内容只在文件
|
||||
里。`macos/main.mm` 里原先用 `NSLog` 的启动/配置/权限等生命周期行也一并改成 `Mprintf`,
|
||||
否则菜单里看不到现场最常翻的那几行;`ScreenHandler`/`H264Encoder`/`InputHandler` 等 ObjC
|
||||
模块的 `NSLog` 不动,它们和两条直接 `write(2)` 的启动横幅仍只出现在 `/tmp/ghost.log`。
|
||||
MFC 的「运行日志」对话框与 MCP 的 `get_client_log` 走同一条链路,两端同时可用。
|
||||
|
||||
### 18.4 验证与未覆盖
|
||||
|
||||
- 服务端 21:17:21 构建 + 两端客户端重编后实测:`ids` 批量(`get_host_detail` /
|
||||
@@ -1282,3 +1293,62 @@ region 同样要求新 Windows 客户端(桌面尾块是 `CLIENT_CAP_WINDOW_IN
|
||||
客户端),返回 `-32005`;默认整屏目标行为与字节流完全不变。
|
||||
- window/region 目标各自多一次窗口信息 RPC;region 目标还要多等一次
|
||||
`TOKEN_BITMAPINFO` 到达(通常几十毫秒)。
|
||||
|
||||
## 24. 增补(2026-11-14:macOS 客户端能力补齐,阶段 0 + 1)
|
||||
|
||||
macOS 客户端此前有大量「实现了但服务端不认」的功能,断点有三层,缺任何一层都表现为
|
||||
「工具直接 `-32005`」或「发下去以后等超时」:
|
||||
|
||||
1. 客户端**没接线**(`COMMAND_SYSTEM` 只打一行日志,`SystemManager` 的签名也不满足
|
||||
子连接骨架,从未被实例化);
|
||||
2. 接上了但**没声明能力位**(终端、剪贴板、C2C 回执早就在跑,`moduleVersion` 里却一个位都没有);
|
||||
3. 声明了能力位,但服务端**仍按平台表一律拒绝** `MAC`。
|
||||
|
||||
本批把三层一起补齐。
|
||||
|
||||
### 24.1 阶段 0:让已有实现可达
|
||||
|
||||
- **能力位**(`common/commands.h`):新增 `CLIENT_CAP_PROCESS=0x20000`;macOS 的
|
||||
`DefaultCaps()` 声明 `TERMINAL` / `SCREEN_CLIPBOARD` / `PROCESS` / `C2C_RECV_ACK`,
|
||||
Linux 也补声明 `PROCESS`(`SystemManager` 一直在跑,只是没声明)。
|
||||
Windows 一直支持进程管理与终端但从不声明,调用方按平台区分,行为不变。
|
||||
- **`SystemManager`**(`macos/SystemManager.*`):改成派生 `IOCPManager`、构造只收
|
||||
`IOCPClient*`,满足 `common/sub_conn_thread.h` 的 `createHandler` / `OnReceive` 契约;
|
||||
`main.mm` 的 `COMMAND_SYSTEM` 现在真的起子连接(`proc_listpids` 枚举 + `SIGKILL`)。
|
||||
- **C2C 落盘回执**:`DataProcess` 的 `user` 恒为 NULL,因此在 `main.mm` 增加
|
||||
`g_pMainClient`(同 `linux/main.cpp`),作为 V2 接收端回 `TOKEN_C2C_RECV_RESULT`。
|
||||
`download_file` / `upload_file` / `copy_files_c2c` 的 macOS 目标端 `receiver_ack`
|
||||
由恒 `false` 变为真实回执。
|
||||
- **服务端放行**(`McpServer.cpp`):`exec_command` / `terminal_*` 对 `MAC` 要求
|
||||
`SupportsTerminal()`,`kill_process` 要求 `SupportsProcess()`,老 macOS 构建返回
|
||||
`-32005` 并提示升级,而不是发一条没人接的命令后假报 ok;`kToolPlatforms` 同步。
|
||||
- `http_probe` **仍只放行 Windows/Linux**:macOS 终端已可用,但 POSIX 探测命令用了
|
||||
GNU 专有的 `base64 -w`,BSD base64 没有该开关,等换成两平台通用写法再放开。
|
||||
|
||||
### 24.2 阶段 1:POSIX 对齐
|
||||
|
||||
- **屏幕预览**(`macos/ScreenPreview.*`):`CGDisplayCreateImage` → 等比缩放 →
|
||||
`SCREEN_PREVIEW_FMT_BGRX`,与服务端统一编码 JPEG 的 Linux 路径一致(macOS 不做
|
||||
JPEG 编码)。`CLIENT_CAP_SCREEN_PREVIEW` 只在**登录时已授予录屏权限**时声明
|
||||
(`RefreshLoginCaps`,每次重连重判),否则 `get_screenshot` 会一直等超时。
|
||||
- **历史活动**(`macos/ActivityHistory.*`):每秒采一次前台窗口
|
||||
(`CGWindowListCopyWindowInfo`,第一个 `layer 0` 窗口;窗口标题需录屏授权,没有权限
|
||||
时退化为应用名),输出格式与 Windows/Linux 完全一致;`COMMAND_QUERY_ACTIVITY`
|
||||
在主连接一次性快照回 `TOKEN_REPORT_ACTIVITY`,单飞行。
|
||||
- **强制关键帧**:Web 屏幕墙恢复时服务端发 `COMMAND_SCREEN_KEYFRAME_REQ`。
|
||||
Windows 一直支持;本次让 Linux(x264 `X264_TYPE_IDR`)与 macOS(VideoToolbox
|
||||
`kVTEncodeFrameOptionKey_ForceKeyFrame`)也消费它——接收线程只置标志,采集线程在
|
||||
下一帧 `exchange`,编码器实例仍归采集线程独占。抓帧失败时把请求放回去,下一帧再试。
|
||||
Android 仍未实现,属后续项。
|
||||
- **质量等级持久化**(`macos/ScreenHandler.mm`):`CMD_QUALITY_LEVEL` 的 persist 位
|
||||
以前是 `(void)persist` 的 TODO,现在写入 `NSUserDefaults`(键 `GhostQualityLevel`),
|
||||
启动时读回并套用。**不写** `~/.config/ghost/config.conf`:那份配置由 `main.mm`
|
||||
用内存 map 整体重写,单独追加键会被下一次写盘冲掉。
|
||||
- `kToolPlatforms`:`get_screenshot` / `get_activity_history` 增加 `kPlatMac`。
|
||||
|
||||
### 24.3 兼容与代价
|
||||
|
||||
- 老 macOS 构建:终端/进程类工具返回「client is too old ... upgrade」,不再假报成功。
|
||||
- `remote_open` 仍拒绝 `MAC`(屏幕/注入链路的 macOS 实机验证还没做),本批不动。
|
||||
- `mcp/tools.json` 是生成物(`tools/mcp_tools/`),平台表变更后要用跑起来的服务端
|
||||
重新生成。
|
||||
@@ -0,0 +1,860 @@
|
||||
# Go 服务端 MCP 最小工具集设计
|
||||
|
||||
> 版本:v1.0(定稿) 状态:**已实施(M0–M8 全部落地,2026-11-12)** 日期:2026-11-12
|
||||
>
|
||||
> 实施计划与各里程碑验收口径见 `Mcp_Go_Minimal_Implementation_Plan.md`。
|
||||
>
|
||||
> 前置文档:`Mcp_Tool_Optimization_Plan.md`(MFC 侧工具优化,已全部落地)、
|
||||
> `Mcp_FileTransfer_Design.md`(V2 文件传输协议与无头接收端)、
|
||||
> `Mcp_Design.md`(MCP 协议/错误码基线)、`FILE_TRANSFER_V2.md`(V2 协议清单)。
|
||||
>
|
||||
> 适用范围:`server/go` 新增 MCP 端点与 9 个工具。**不改客户端**——所有用到的
|
||||
> 命令与令牌均为 `common/commands.h` 既有定义,客户端已实现。
|
||||
>
|
||||
> 本文与 MFC 侧的差异只有一个来源:**Go 服务端的协议实现面比 MFC 窄**。MFC 有 54 个
|
||||
> 工具,是因为它把 20 多条客户端命令都接进了服务端;Go 目前只接了 4 条。所以这里的
|
||||
> "最小"不是"先做简单的",而是"按 Go 已具备的协议能力面裁剪,剩下的按需补齐"。
|
||||
|
||||
---
|
||||
|
||||
## 0. 结论摘要
|
||||
|
||||
1. **v1 交付 9 个工具**,全部命名、参数、错误码与 MFC 对齐,同一句提示词在两个后端都能跑通:
|
||||
`list_hosts` / `get_host_detail` / `get_server_status` / `get_audit_log` /
|
||||
`get_screenshot` / `terminal_exec` / `terminal_close` / `list_files` / `read_file`。
|
||||
2. **四条设备通道,三种是既有基础设施**:终端(`hub` 已有,只需加哨兵与输出缓冲)、
|
||||
主连接 RPC(`hub.SendToDevice`)、文件管理器子连接(`TOKEN_CONN_AUTH` 已把 clientID
|
||||
钉在 ctx 上,按 clientID 路由即可,**不需要** MFC 那套 pending + CancelIO)。
|
||||
只有 V2 流式子连接的接收端是全新的。
|
||||
3. **`get_screenshot` 走主连接 RPC(`COMMAND_SCREEN_PREVIEW_REQ`),不碰屏幕流。**
|
||||
屏幕流是持续推的 H.264(首帧裸 BGRA),取一帧就得建屏幕子连接、占住每设备唯一的
|
||||
屏幕槽位、用完再拆——代价远大于收益。预览 RPC 是主连接上的一次性请求响应,
|
||||
客户端自己抓屏编码回 JPEG(Linux 客户端回 BGRX,服务端编码)。不占任何槽位。
|
||||
4. **终端槽位是 Go 独有的硬约束**:`hub.go:86` 写明 *at most one web terminal per device*。
|
||||
v1 不做抢占——浏览器开着终端时 MCP 返回 `-32003`,空闲 3 分钟自动释放。
|
||||
这是安全默认,代价是"人在用终端时 AI 用不了",写进工具描述让模型自己换路。
|
||||
5. **MCP 端点零新增端口**:挂在现有 Web 服务的 `/mcp`(`web/server.go:126` 的 mux 里加一行),
|
||||
无状态 JSON-RPC,不引入 `Mcp-Session-Id`。鉴权用单一静态令牌(`YAMA_MCP_TOKEN`),
|
||||
映射到固定 principal `mcp`(role=admin)。
|
||||
6. **明确不做**:`remote_*`、`chat_*`、`host_*`、进程/服务/注册表/窗口枚举、文件写操作、
|
||||
`exec_command`(白名单一次性执行,被 `terminal_exec` 覆盖)、`outputSchema`。
|
||||
|
||||
---
|
||||
|
||||
## 1. 范围
|
||||
|
||||
### 1.1 做
|
||||
|
||||
| 层 | 内容 |
|
||||
|---|---|
|
||||
| 端点 | `POST /mcp`(JSON-RPC 2.0 / MCP 2025-06-18),`initialize` / `notifications/initialized` / `ping` / `tools/list` / `tools/call` |
|
||||
| 鉴权 | `Authorization: Bearer $YAMA_MCP_TOKEN`,常量时间比较 |
|
||||
| 工具 | 9 个(见 §3) |
|
||||
| 审计 | 每次调用一条 `mcp.tool.call` 记录,进既有审计通道 |
|
||||
| 设施 | 每设备单请求互斥、终端会话表、主连接 RPC 请求表、V2 接收端 |
|
||||
|
||||
### 1.2 不做
|
||||
|
||||
| 不做 | 理由 |
|
||||
|---|---|
|
||||
| `remote_open` / `remote_keyboard` / `remote_mouse` 等 | Go 有屏幕流但没有"注入结果回执",做出来无法验证;且属高风险写操作,先不开放给模型 |
|
||||
| `chat_*` | Go 无 `COMMAND_CHAT` 实现 |
|
||||
| `host_inspect` / `host_control_*` / 进程/服务/注册表/窗口枚举 | Go 协议层完全没有这些命令(`protocol/commands.go` 只声明了 4 条命令族) |
|
||||
| 文件写(`delete_path` / `move_path` / `upload_file` / `create_folder`) | V2 上传方向需要服务端作 sender,工作量与本期的接收端不对称;先只读 |
|
||||
| `download_file` | 接收端与 `read_file` 完全共用,v1.1 加约 20 行即可(差别只是落盘后不删)。v1 先只做"读",避免多一个往主控磁盘写文件的入口 |
|
||||
| `exec_command`(白名单一次性执行) | `terminal_exec` 已覆盖同一场景且无白名单摩擦(MFC 实测 `-32007` 全是白名单误拒) |
|
||||
| `outputSchema` | MFC 实测 outputSchema 占 `tools/list` 的 49,320 / 136,692 字节。9 个工具没必要背这个体积 |
|
||||
| 多用户令牌 / 按分组授权 | v1 单 principal;多用户留到 Go 侧真正多租户部署时(见 §12 R6) |
|
||||
|
||||
---
|
||||
|
||||
## 2. 基线
|
||||
|
||||
### 2.1 MFC 侧已交付(可直接对标的参照)
|
||||
|
||||
`mcp/tools.json` 当前 `toolCount=54`(优化前 63),默认配置下可见 21 个。
|
||||
`Mcp_Tool_Optimization_Plan.md` 的八项已全部落地,其中三项对 Go 有直接约束力:
|
||||
|
||||
| MFC 改动 | 对 Go 的约束 |
|
||||
|---|---|
|
||||
| `terminal_exec` 的 `session_id` 可变可选、无会话时隐式创建 | Go 不设 `terminal_open`,`terminal_exec` 隐式建会话 |
|
||||
| 超时保留会话、返回部分输出、`session_id` 轮询续取 | Go 同款语义,见 §6.6 |
|
||||
| `read_file` 复用 `download_file` 的 V2 接收端 | Go 的 `read_file` = 下载到临时目录 + 读 + 删,两者共用一份接收端 |
|
||||
|
||||
### 2.2 Go 侧现状
|
||||
|
||||
`protocol/commands.go:105-140` 声明的命令常量里,真正有发送点的只有三处:
|
||||
|
||||
| 能力 | 状态 | 位置 |
|
||||
|---|---|---|
|
||||
| 屏幕查看 / 控制 / 剪贴板 | 已实现(H.264 流 + 鼠标键盘) | `cmd/main.go` `handleScreenFrame` |
|
||||
| PTY 终端(每设备单会话) | 已实现,**仅浏览器流式转发** | `hub.go:756` / `hub.go:983` / `cmd/main.go:101-109` |
|
||||
| 卸载被控端 | 已实现 | `web/ws_handlers.go:1139` |
|
||||
| 设备 / 用户 / 分组 / 审计 | 已实现 | `hub.ListDevices` / `devicehistory.Offline` / `web/audit_query.go` |
|
||||
| 子连接鉴权(clientID 绑定) | 已实现 | `cmd/main.go` `handleConnAuth` |
|
||||
| 文件管理器(列盘/列目录/读/写) | **完全没有** | — |
|
||||
| 一次性命令执行 | **完全没有** | — |
|
||||
| 屏幕预览 RPC | **完全没有** | — |
|
||||
|
||||
### 2.3 两条可直接复用的结论
|
||||
|
||||
1. **终端是"跑命令"的唯一入口**。MFC 实测 186 次调用里 109 次是 `terminal_exec`
|
||||
(58.6%),且 59% 的命令本质是"读"。Go 没有必要先做一堆专用只读工具,
|
||||
把 `terminal_exec` 做扎实就是最高性价比。
|
||||
2. **但 `read_file` 不能省**。MFC 的优化结论是"`read_file` 是唯一真正的功能缺口"——
|
||||
终端读文件会被 PTY 回显、ANSI 转义、ConPTY 重绘污染,`.env` 这类文件读出来是脏的。
|
||||
Go 既然要上文件管理器,就一次做对。
|
||||
|
||||
---
|
||||
|
||||
## 3. 工具集
|
||||
|
||||
### 3.1 清单
|
||||
|
||||
| # | 工具 | 通道 | 只读 | 依赖能力位 |
|
||||
|---:|---|---|:--:|---|
|
||||
| 1 | `list_hosts` | 本机 | ✅ | — |
|
||||
| 2 | `get_host_detail` | 本机 | ✅ | — |
|
||||
| 3 | `get_server_status` | 本机 | ✅ | — |
|
||||
| 4 | `get_audit_log` | 本机 | ✅ | — |
|
||||
| 5 | `get_screenshot` | 主连接 RPC | ✅ | `CLIENT_CAP_SCREEN_PREVIEW` |
|
||||
| 6 | `terminal_exec` | 终端子连接 | ❌ | — |
|
||||
| 7 | `terminal_close` | 终端子连接 | ❌ | — |
|
||||
| 8 | `list_files` | 文件管理器子连接 | ✅ | — |
|
||||
| 9 | `read_file` | V2 流式子连接 | ✅ | —(见 §5.4 的说明) |
|
||||
|
||||
`YAMA_MCP_READONLY=1` 时只暴露 1/2/3/4/5/8/9 七个(6/7 隐藏)。
|
||||
|
||||
### 3.2 逐个定义
|
||||
|
||||
本节只用于阅读;**参数名与返回字段的唯一契约是 `mcp/tools.json` 的 `inputSchema` /
|
||||
`outputSchema`**(M1 起 `tools/list` 原样返回这些定义)。Go 取不到的字段省略,不伪造。
|
||||
|
||||
#### `list_hosts`
|
||||
|
||||
```jsonc
|
||||
// input(全部可选)
|
||||
{ "client_type": "EXE", "group": "asm", "include_offline": false, "ip": "10.",
|
||||
"limit": 100, "name": "ASM-", "offset": 0, "online": true, "os": "Windows",
|
||||
"query": "asm" }
|
||||
// output.structuredContent
|
||||
{ "hosts": [ /* ... */ ], "total": 7, "totalAll": 9, "limit": 100, "offset": 0, "hasMore": false }
|
||||
```
|
||||
|
||||
`client_type/group/ip/os` 为大小写不敏感子串过滤;`name` 只匹配计算机名,`query` 同时匹配
|
||||
计算机名、备注与 IP;`online=true`(默认)只列在线,`false` 只列历史中存在但当前离线的;
|
||||
`include_offline=true` 时再合并 `devicehistory.Store.Offline(online)`。`total` 是过滤后命中数,
|
||||
`totalAll` 是过滤前总数,`hasMore` 表示同一条件下还有下一页。
|
||||
|
||||
`hosts[]` 的字段按 `outputSchema`:`id/name/group/version/clientType/os/ip/rtt/activeWindow/
|
||||
screen/online/last_seen`,以及 hub 或历史记录里确有的 `location/install_time`;两个服务端都
|
||||
没有 `authStatus/tls/remark`,不输出。离线历史条目不存 `clientType`,也没有 `rtt/activeWindow`。
|
||||
|
||||
#### `get_host_detail`
|
||||
|
||||
```jsonc
|
||||
{ "id": "7888521104752806905" } // 或 { "ids": ["…", "…"] }(≤50 台,批量)
|
||||
```
|
||||
|
||||
单台返回 `{ host: {...} }`;批量返回 `{ tool, total, succeeded, failed, skipped, results[] }`。
|
||||
`host.capabilities` 由 `protocol.SupportsCap` 逐位解出,字段名与 schema 一致:
|
||||
`screenPreview / screenRegion / windowInfo / fileTransferV2 / c2cPaths / registry /
|
||||
remoteControl / platform`。
|
||||
|
||||
注意**不要把 `v2` 放进 capabilities**:`CLIENT_CAP_V2` 在 `DefaultCaps()` 里全平台恒真
|
||||
(`common/commands.h:1289`),列出来只会误导模型。
|
||||
|
||||
#### `get_server_status`
|
||||
|
||||
无参。返回字段按 `outputSchema`:`version / uptime_sec / hosts / sessions / port / bind /
|
||||
switches / blocked_auth_ips / exe_build_time / app_name`。Go v1 只填能如实取到的:
|
||||
`version`(buildinfo)、`uptime_sec`、`hosts`(在线/历史计数)、`sessions`(MCP 活动调用,
|
||||
M3 起)、`port`、`bind`;其余属 MFC 专有,直接不给(schema 的 `required` 为空)。
|
||||
|
||||
`version` 取 `-ldflags -X` 注入的 `buildinfo.Version`——**Go 侧目前没有版本变量**
|
||||
(`cmd/main.go` 里查不到),需要新增 `buildinfo` 包并在 `Makefile` / `build.ps1` 里注入;
|
||||
拿不到时返回空串,不要伪造。`commit` 只用于日志与排障,不塞进 schema 未定义的返回字段。
|
||||
|
||||
#### `get_audit_log`
|
||||
|
||||
```jsonc
|
||||
{ "keyword": "terminal", "type": "mcp", "limit": 100, "offset": 0 }
|
||||
```
|
||||
复用 `web/audit_query.go` 的查询器(M2 抽成 `auditquery`),返回
|
||||
`{ entries, total, totalAll, limit, offset, hasMore }`。**没有 `since`**:MFC 的 schema 里就没有。
|
||||
|
||||
#### `get_screenshot`
|
||||
|
||||
```jsonc
|
||||
{ "id": "...", "max_width": 1024 }
|
||||
// output: content[] 里一项 image(mimeType=image/jpeg, base64 data)
|
||||
// structuredContent: { image: { mimeType, width, height, bytes },
|
||||
// capture: { mode, x, y, width, height, scale, native } }
|
||||
```
|
||||
`max_width` 钳制到 `[64,1920]`;缺省/0 时 Go v1 固定 1024(没有 MFC 的 RTT 自适应档位)。
|
||||
`mode=region/window/monitor` 与 `hwnd/x/y/width/height` 需要 `CLIENT_CAP_SCREEN_REGION` 扩展,
|
||||
M5 之前传任一参数都返回 `-32005` 并在 message 里点名。细节见 §7。
|
||||
|
||||
#### `terminal_exec`
|
||||
|
||||
```jsonc
|
||||
// 执行
|
||||
{ "id": "...", "command": "sc query AssemblyManager", "timeout_ms": 20000, "session_id": "..." }
|
||||
// 轮询(不带 command)
|
||||
{ "id": "...", "session_id": "s-3f2a", "timeout_ms": 20000 }
|
||||
// output
|
||||
{ "session_id": "s-3f2a", "stdout": "...", "done": true, "exit_code": 0,
|
||||
"is_pty": true, "reused": false, "truncated": false, "dropped_bytes": 0, "elapsed_ms": 412 }
|
||||
```
|
||||
超时未完成时 `done=false`、无 `exit_code`;`stdout` 是已产生的部分输出,**会话保留**,
|
||||
用同一 `session_id` 轮询。`max_output_bytes`(1024..1048576,默认 65536)按行截断并置
|
||||
`truncated`,剩余内容下次轮询取。
|
||||
|
||||
#### `terminal_close`
|
||||
|
||||
```jsonc
|
||||
{ "id": "...", "session_id": "s-3f2a" } // 幂等:会话不存在也返回成功
|
||||
```
|
||||
|
||||
#### `list_files`
|
||||
|
||||
```jsonc
|
||||
{ "id": "...", "path": "C:\\ProgramData\\AssemblyManager", "limit": 100, "offset": 0 }
|
||||
// output
|
||||
{ "files": [ { "name": "settings.ini", "isDir": false, "size": 1204, "mtime": 1699999999 } ],
|
||||
"total": 42, "totalAll": 42, "limit": 100, "offset": 0, "hasMore": false }
|
||||
```
|
||||
`path` 为空时返回盘符列表 `{ drives: [{ drive, typeName, fileSystem, totalMB, freeMB }] }`。
|
||||
批量传 `ids` 时结果按台汇总在 `results` 里。注意返回数组字段是 `files`,不是 `entries`。
|
||||
|
||||
#### `read_file`
|
||||
|
||||
```jsonc
|
||||
{ "id": "...", "path": "C:\\ProgramData\\AssemblyManager\\.env",
|
||||
"offset": 0, "limit": 2000, "max_bytes": 262144, "encoding": "auto" }
|
||||
// output
|
||||
{ "path": "...", "size": 4096, "encoding": "utf-8", "eol": "lf",
|
||||
"lines_total": 120, "offset": 0, "lines_returned": 120,
|
||||
"text": "IR_ENDPOINT=...", "sha256": "...", "truncated": false }
|
||||
```
|
||||
|
||||
**行语义**:`offset` 是起始行(0 基,负数表示末尾 N 行),`limit` 是行数(1..200000,默认
|
||||
2000),`max_bytes` 是本次返回文本的字节上限(1024..2097152,默认 262144=256KB),
|
||||
超出按行截断并置 `truncated`。`encoding`:`auto`(BOM → UTF-8 合法性 → GBK 回退)/
|
||||
`utf-8` / `gbk` / `gb18030` / `latin1`;`eol` 为 `crlf/lf/cr/mixed/none`。
|
||||
|
||||
**整文件上限 2 MiB**(`YAMA_MCP_READ_MAX`):V2 下载没有区间参数,只能整文件拉,超过就拒绝
|
||||
(`-32602`)。`offset`/`limit` 是下载后的窗口裁剪,绕不过这个门。
|
||||
|
||||
### 3.3 文本块(`content[].text`)
|
||||
|
||||
`structuredContent` 是权威数据,但部分 MCP 客户端只把 `content[].text` 交给模型,
|
||||
`structuredContent` 不会出现在模型上下文里。因此列表类工具的文本块不能只有「共 N 台」
|
||||
这样的汇总——主机 64 位 id 是 `read_file`、`get_host_detail`、`terminal_exec` 等后续调用
|
||||
的寻址键,模型拿不到就等于工具不可用。
|
||||
|
||||
| 工具 | 汇总行之后 |
|
||||
|---|---|
|
||||
| `list_hosts` | 表头 `id name ip group os online clientType last_seen`,随后每台一行 |
|
||||
| `get_host_detail` | 单台:主机 JSON(compact);批量:`id ok detail`,成功行是主机 JSON,失败行是错误信息 |
|
||||
| `list_files` | 盘符 `drive typeName fileSystem totalMB freeMB`;目录 `name isDir size mtime` |
|
||||
| `get_audit_log` | `time type msg`,`msg` 是去掉信封字段后的 compact JSON |
|
||||
|
||||
列用制表符分隔,首列一定是后续调用的寻址键(主机 id / 文件名)。单元格内的制表符与换行
|
||||
替换成空格,精确值以 `structuredContent` 为准;空值显示 `-`。分页只渲染当前页,不会把
|
||||
全表塞进文本块。
|
||||
|
||||
MFC 端不需要同样的改动:`McpInternal.cpp` 的 `BuildResult` 会把整个
|
||||
`structuredContent` 作为**第二个** `type:"text"` 项追加到 `content`(除非 builder 用
|
||||
`SetStructuredTextPayload` 指定了更小的载荷)。实测线上 `list_hosts` / `get_audit_log`
|
||||
的 `content[1]` 已是完整 JSON(含主机 id),文本型客户端本来就能拿到。Go 的
|
||||
`newToolResult` 只写一个 text 项,所以把行放进第一项。
|
||||
|
||||
---
|
||||
|
||||
## 4. 端点
|
||||
|
||||
### 4.1 `POST /mcp`
|
||||
|
||||
在 `web/server.go:126` 起的 mux 里加一行:
|
||||
|
||||
```go
|
||||
mux.HandleFunc("/mcp", s.mcp.Handle)
|
||||
```
|
||||
|
||||
**不能复用 `s.requireBearer`**:它校验的是浏览器会话令牌(`s.auth.ValidateToken`),
|
||||
MCP 用的是独立的静态令牌,两套凭据语义不同。鉴权在 `mcp.Handle` 内部自己做
|
||||
(§4.2)。`basePath` 由 `s.mount` 统一处理,`/mcp` 不需要自己感知前缀。
|
||||
|
||||
协议形态:
|
||||
|
||||
| 项 | 取值 |
|
||||
|---|---|
|
||||
| 协议版本 | `2025-06-18`(与 MFC `tools.json` 的 `protocolVersion` 一致) |
|
||||
| 会话 | **无状态**。不生成、不校验 `Mcp-Session-Id` |
|
||||
| `POST` 响应 | `Content-Type: application/json`,单条 JSON-RPC 响应 |
|
||||
| `GET /mcp` | `405 Method Not Allowed`(v1 无服务端主动推送流;MCP 规范允许此返回) |
|
||||
| `DELETE /mcp` | `405` |
|
||||
| 批量请求 | 不支持(数组入参返回 `-32600`) |
|
||||
| 通知(无 `id`) | 一律 `204 No Content`,不返回体 |
|
||||
|
||||
无状态的代价是**没有 `notifications/progress` / `notifications/cancelled`**。
|
||||
取消靠 HTTP 请求断开——`r.Context()` 被取消时,处理函数释放设备锁、终端会话按
|
||||
§6.6 处理(不销毁)。这与 MFC 的 `-32800 请求被取消` 语义对齐。
|
||||
|
||||
### 4.2 令牌
|
||||
|
||||
```
|
||||
YAMA_MCP_TOKEN=<32 位十六进制> # 必填;未设置 = MCP 端点不注册(/mcp 返回 404)
|
||||
YAMA_MCP_READONLY=1 # 可选,只读模式(隐藏 terminal_exec / terminal_close)
|
||||
YAMA_MCP_TERM_IDLE=180 # 可选,终端会话空闲回收秒数
|
||||
YAMA_MCP_MAX_CONCURRENCY=16 # 可选,全局并发上限
|
||||
YAMA_MCP_READ_MAX=2097152 # 可选,read_file 文件大小门(字节,默认 2 MiB)
|
||||
```
|
||||
|
||||
- 未设置时**不注册路由**,并在启动日志打一行 `MCP endpoint disabled: YAMA_MCP_TOKEN not set`。
|
||||
不自动生成——生成的令牌若只落在日志里,等于没有密钥管理。
|
||||
- 比较用 `subtle.ConstantTimeCompare`,长度不等直接失败(不 leak 长度)。
|
||||
- principal 固定为 `{actor: "mcp", role: "admin"}`。审计记录里 `actor=mcp`,
|
||||
`source=mcp`,与浏览器会话(`actor=<username>`)可区分。
|
||||
- 不做失败计数封禁:令牌是 32 位十六进制(128 bit),且端点不对外暴露时无爆破面。
|
||||
若将来暴露到公网,按 `web/ws_handlers.go` 的登录节流同款加计数(记入 §12 R6)。
|
||||
|
||||
### 4.3 错误码
|
||||
|
||||
与 MFC 完全对齐(`McpServer.cpp:296-312` 的官方说明),Go 侧只实现用得到的:
|
||||
|
||||
| 码 | 语义 | Go 侧触发点 |
|
||||
|---:|---|---|
|
||||
| `-32001` | 超时 | 等子连接/等响应超时;`done=false` 不算此码 |
|
||||
| `-32002` | 主机离线或不存在 | `hub.IsOnline` 为假 |
|
||||
| `-32003` | 主机忙 | 设备锁被占 / 终端槽位被浏览器持有 |
|
||||
| `-32004` | 命令未送达 | `hub.SendToDevice` 返回错误 |
|
||||
| `-32005` | 主机不支持该能力 | 缺 `CLIENT_CAP_SCREEN_PREVIEW`(截屏);非 PTY 客户端用 `terminal_exec` |
|
||||
| `-32006` | 策略拒绝 | 只读模式下调用写工具 |
|
||||
| `-32009` | 目标不存在 | `list_files` 的 `TOKEN_FILE_LIST_ERROR` 且 win32err∈{2,3} |
|
||||
| `-32010` | 权限不足 | `TOKEN_FILE_LIST_ERROR` 且 win32err=5 |
|
||||
| `-32602` | 参数错误 | schema 校验失败 |
|
||||
| `-32601` | 方法不存在 | 未知 method / 未知工具名 |
|
||||
| `-32000` | 内部错误 | 其余 |
|
||||
|
||||
### 4.4 审计
|
||||
|
||||
每次 `tools/call` 产出一条记录,字段沿用 `web/audit.go` 的形状:
|
||||
|
||||
```
|
||||
event=mcp.tool.call actor=mcp role=admin source=mcp
|
||||
tool=<name> device=<id|-> ok=<bool> code=<err|0> ms=<duration>
|
||||
args=<截断到 512 字节的摘要> result=<ok 时的体积摘要 / 失败时的 message>
|
||||
```
|
||||
|
||||
`args` 里的敏感值(`command` 全文可能含密码)**不入审计**——只记命令首词与长度,
|
||||
与 MFC 的做法一致(MFC 审计只记 `host <id> <tool>`)。完整命令进 `debug` 级日志。
|
||||
|
||||
---
|
||||
|
||||
## 5. 四条设备通道
|
||||
|
||||
```
|
||||
MCP client ──HTTP POST /mcp──▶ mcp.Server
|
||||
├─ 本机:hub.ListDevices / devicehistory / audit_query
|
||||
├─ 主连接 RPC SendToDevice(247) ─────────▶ 设备主连接
|
||||
├─ 终端 OpenTerminalSession ───────▶ 终端子连接
|
||||
├─ 文件管理器 COMMAND_LIST_DRIVE(1) ─────▶ 文件管理器子连接
|
||||
└─ V2 CMD_DOWN_FILES_V2(94) ─────▶ V2 流式子连接
|
||||
```
|
||||
|
||||
### 5.1 主连接 RPC(`get_screenshot`)
|
||||
|
||||
请求走 `hub.SendToDevice(deviceID, pkt)`,响应在 `cmd/main.go` 的 `OnReceive`
|
||||
里按 `data[0] == TOKEN_SCREEN_PREVIEW_RSP` 分派。**不走子连接,不占任何槽位。**
|
||||
|
||||
需要一个请求表:
|
||||
|
||||
```go
|
||||
type pendingRPC struct {
|
||||
reqID uint16
|
||||
ch chan []byte // 缓冲 1,迟到的响应写不进去就丢弃
|
||||
}
|
||||
m := map[uint64]*pendingRPC{} // key = deviceID(每设备同时只允许一个,与设备锁一致)
|
||||
```
|
||||
|
||||
`reqID` 用 `atomic.Uint32` 自增后取低 16 位;**必须校验响应里的 `reqId` 与在途请求一致**,
|
||||
否则丢弃——MFC 的 `TakePreviewResponse(devId, reqId, ...)` 就是干这个的
|
||||
(`2015RemoteDlg.cpp:7520`),原因是主连接上可能同时有别的预览在飞。
|
||||
|
||||
### 5.2 终端子连接(`terminal_exec` / `terminal_close`)
|
||||
|
||||
完全复用 `hub` 现有设施,**不改 hub**:
|
||||
|
||||
| 动作 | 调用 |
|
||||
|---|---|
|
||||
| 开会话 | `hub.OpenTerminalSession(deviceID)`;已存在返回 `ErrTerminalBusy` |
|
||||
| 等就绪 | 订阅 `EventHandler.OnTerminalReady(deviceID, isPTY)` |
|
||||
| 发输入 | `hub.SendToTerminal(deviceID, bytes)`;行尾按 §6.4 区分 `\n` / `\r\n` |
|
||||
| 收输出 | 订阅 `EventHandler.OnTerminalData(deviceID, packet)`,剥掉 4 字节 `TRM1` 前缀 |
|
||||
| 关会话 | `hub.CloseTerminalSession(deviceID)` |
|
||||
|
||||
`mcp.Server` 在启动时 `hub.Subscribe(self)` 一次,作为常驻订阅者;
|
||||
只有"当前有 MCP 终端会话的设备"才把数据写进环形缓冲,其余直接丢弃(零开销)。
|
||||
|
||||
### 5.3 文件管理器子连接(`list_files`)
|
||||
|
||||
时序:
|
||||
|
||||
```
|
||||
MCP ──▶ 主连接: COMMAND_LIST_DRIVE(1) [1 字节]
|
||||
客户端 ──▶ 新子连接(EnableSubConnAuth)
|
||||
└─ TOKEN_CONN_AUTH(246) ──▶ Go: 校验 + 把 clientID 钉在 ctx 上 + 回 ack
|
||||
└─ TOKEN_DRIVE_LIST(103) ──▶ Go: 解析盘符(子连接保持打开)
|
||||
MCP ──▶ 同一子连接: COMMAND_LIST_FILES(2) [cmd][path\0]
|
||||
└─ TOKEN_FILE_LIST(104) ──▶ Go: 解析目录项
|
||||
或 TOKEN_FILE_LIST_ERROR(171) ──▶ Go: 按 win32err 翻译
|
||||
└─ Go: 关子连接(COMMAND_BYE → 500ms → Close)
|
||||
```
|
||||
|
||||
注意 `TOKEN_DRIVE_LIST` 到达后**不能立刻关子连接**——列目录还要在同一个子连接上发
|
||||
`COMMAND_LIST_FILES`。MFC 的注释写得很明确:*此时不关子链接,交给 TOKEN_FILE_LIST
|
||||
分支收尾*(`2015RemoteDlg.cpp:7647`)。
|
||||
|
||||
关键点:
|
||||
|
||||
- **子连接带 ConnAuth**(`client/KernelManager.cpp:1773` 对 `COMMAND_LIST_DRIVE`
|
||||
调了 `EnableSubConnAuth()`),所以 `handleConnAuth` 已把 `ClientID` 钉在 ctx 上,
|
||||
Go **不需要** MFC 那套 `IsPending(devId)` 守卫。按 `ctx.GetInfo().ClientID` 路由即可。
|
||||
- 子连接由客户端创建、**由服务端关闭**(MFC 注释:*此时不关子链接,交给
|
||||
TOKEN_FILE_LIST 分支收尾*)。关闭用 `hub` 同款优雅关闭:发 `COMMAND_BYE(204)`,
|
||||
500 ms 后 `ctx.Close()`。
|
||||
- `TOKEN_DRIVE_LIST` 与 `TOKEN_FILE_LIST` 的记录格式见附录 A,直接照 MFC 的
|
||||
`ParseDriveList` / `ParseFileList`(`McpServer.cpp:506/548`)移植。
|
||||
- 文件名是**客户端 ANSI**,用 `protocol.DecodeClientString(data, hub.Capability(id), "")` 解码。
|
||||
|
||||
### 5.4 V2 流式子连接(`read_file`)
|
||||
|
||||
时序:
|
||||
|
||||
```
|
||||
MCP ──▶ 主连接: COMMAND_LIST_DRIVE(1)
|
||||
└─ 文件管理器子连接建立(同 §5.3)
|
||||
MCP ──▶ 文件管理器子连接: CMD_DOWN_FILES_V2(94) [cmd][targetDir\0][path\0][\0]
|
||||
└─ 服务端关掉文件管理器子连接
|
||||
客户端 ──▶ 新子连接(EnableSubConnAuth)
|
||||
└─ COMMAND_SEND_FILE_V2(85) × N ──▶ Go: 校验路径 → 落盘
|
||||
└─ COMMAND_FILE_COMPLETE_V2(91) ──▶ Go: 校验 SHA-256 → 完成
|
||||
MCP: 读临时文件 → 返回 → 删临时目录
|
||||
```
|
||||
|
||||
- `targetDir` 是**主控本机**的保存目录,由服务端指定;客户端把它拼进每个 chunk 的
|
||||
`filename` 回填。所以服务端必须用一个**每次请求新建的临时目录**
|
||||
(`os.MkdirTemp("", "yama-mcp-read-*")`),并在 `defer` 里 `RemoveAll`。
|
||||
- **路径校验是硬性安全要求**:`filename` 由客户端提供,必须校验它落在 `targetDir` 之内
|
||||
(**用 `filepath.Rel` 判越界,不能用字符串前缀比较**,见 §8.3),否则拒收并中止传输。
|
||||
没有这一步,被控端可以把任意文件写到主控磁盘任意位置。
|
||||
- **能力检查只作诊断兜底**。`CLIENT_CAP_V2` 在 `common/commands.h:1289` 的
|
||||
`DefaultCaps()` 里被**所有现代客户端无条件声明**,拿它做真门等于没门。Go 侧保留
|
||||
`SupportsCap(…, CLIENT_CAP_V2)` 检查的唯一作用,是让"能力串为空"的极老客户端直接
|
||||
得到 `-32005`,而不是等到 94 号命令静默超时(见下一条)。MFC 侧的 V2 是**服务端
|
||||
开关**(`2015RemoteDlg.cpp:2822` 的 `EnableFileV2`,默认关),不是客户端能力;
|
||||
Go 侧不搬这个开关,恒用 V2。
|
||||
- 真正的失败模式是**老客户端不认识 94 号命令**:它收到 `CMD_DOWN_FILES_V2` 后
|
||||
不建子连接、不回任何包,表现为 `-32001` 超时。工具描述里要写明这条,
|
||||
避免模型反复重试。
|
||||
|
||||
---
|
||||
|
||||
## 6. 终端会话
|
||||
|
||||
### 6.1 会话对象
|
||||
|
||||
```go
|
||||
type termSession struct {
|
||||
id string // "s-" + 6 位 hex
|
||||
deviceID string
|
||||
isPTY bool
|
||||
createdAt time.Time
|
||||
lastUsed time.Time
|
||||
|
||||
mu sync.Mutex
|
||||
buf []byte // 环形,cap 256 KiB
|
||||
base uint64 // buf[0] 的绝对偏移
|
||||
total uint64 // 累计写入字节
|
||||
delivered uint64 // 已交付给客户端的绝对偏移
|
||||
|
||||
pending *pendingCmd // 在途命令;nil = 空闲
|
||||
}
|
||||
|
||||
type pendingCmd struct {
|
||||
sentinel string
|
||||
deadline time.Time
|
||||
done bool
|
||||
exitCode int
|
||||
raw []byte // 从 sentinel 之前回切出的原始片段
|
||||
}
|
||||
```
|
||||
|
||||
### 6.2 租约与争用
|
||||
|
||||
- `hub.OpenTerminalSession` 本身就是互斥(`ErrTerminalBusy`),MCP 直接复用它。
|
||||
- 撞上 `ErrTerminalBusy` → `-32003`,message 写
|
||||
`terminal busy: another viewer (web console or another MCP call) holds it; retry later`。
|
||||
- **v1 不做抢占**。理由:抢占会把正在敲命令的人踢下线,而模型无法判断"人是不是在忙"。
|
||||
需要抢占时由运维在 Web 控制台关掉那个终端。
|
||||
- 空闲释放:`lastUsed` 超过 `YAMA_MCP_TERM_IDLE`(默认 180 s)由后台 ticker 调
|
||||
`CloseTerminalSession`。这是防止模型忘了 `terminal_close` 把人的终端锁死。
|
||||
|
||||
### 6.3 环形缓冲与游标
|
||||
|
||||
- 容量 256 KiB,超出丢弃最旧数据,`base` 前移,丢弃量记 `droppedBytes` 并在
|
||||
返回体里体现(`truncated=true`)。
|
||||
- 绝对偏移 `total` 单调递增,`offset` 参数与返回里的 `offset` 都用绝对偏移。
|
||||
- 缓冲随会话存在:会话关闭(`terminal_close` / 空闲回收 / 设备掉线)时整体释放。
|
||||
|
||||
### 6.4 哨兵与退出码
|
||||
|
||||
沿用 MFC 的两种形态(`McpServer.cpp:3991-3998`),**必须分两行下发**:
|
||||
|
||||
| 客户端 | 下发 | 哨兵 |
|
||||
|---|---|---|
|
||||
| POSIX PTY(Linux/Android) | `cmd\n` + `echo "__MCP_DONE_<id>__$?"\n` | `__MCP_DONE_<id>__<n>` |
|
||||
| ConPTY(新 Windows) | `cmd\r\n` + `echo __MCP_DONE_<id>__%errorlevel%\r\n` | 同上 |
|
||||
|
||||
为什么要分两行:`rem` / `cmd` / `exit` / `if` / `for` 这类"吞行"命令会把同一行后面的
|
||||
内容一起吞掉(MFC 的 P1 教训)。分两行后哨兵独立执行,退出码才可信。
|
||||
|
||||
`<id>` 用 6 位随机 hex,每次命令重新生成——避免上一条命令的输出里残留同名哨兵被误命中。
|
||||
|
||||
### 6.5 输出清洗
|
||||
|
||||
三段清洗,顺序不能变(MFC `McpServer.cpp:3946-4040`):
|
||||
|
||||
1. **剥回显**:PTY 会把输入整行回显。删掉命令行本身与哨兵行。
|
||||
2. **剥 ANSI**:`\x1b[...m`、`\x1b[?25h/l` 等 CSI/OSC 序列。
|
||||
3. **剥哨兵**:把哨兵文本及其后的退出码切掉,`exit_code` 单独解析。
|
||||
|
||||
ConPTY 是"屏幕渲染流"而不是字节流,光标重绘会让同一行出现两次,剥完 VT 后
|
||||
文字会重复(MFC 实测 `rem hello` 只剩哨兵、`cmd /c echo abc` 变成
|
||||
`abc__MCP_DONE_x__0`)。**这三段必须整体移植,不能自己重写**——这是踩过坑的代码。
|
||||
|
||||
### 6.6 轮询模式
|
||||
|
||||
`terminal_exec` 不带 `command`、只带 `session_id` 时进入轮询:从 `delivered` 开始
|
||||
取增量,等到 `done` 或超时。
|
||||
|
||||
- 超时**不销毁会话**(MFC 优化的核心结论):命令可能还在跑,销毁等于毁掉现场
|
||||
(cwd、环境变量、后台任务)。MFC 在优化前两次 `-32002` 都是这么来的。
|
||||
- HTTP 请求被客户端断开(`r.Context()` done)时同样只标记放弃,不动会话。
|
||||
- 会话内已有在途命令时,再带 `command` 调用 → `-32003`(同一会话单命令)。
|
||||
|
||||
### 6.7 平台范围
|
||||
|
||||
**v1 只支持 PTY 客户端**(ConPTY / POSIX PTY)。老的非 PTY cmd-pipe 路径
|
||||
(`TOKEN_SHELL_START(128)`)在 `OnTerminalReady` 里能识别(`isPTY=false`),
|
||||
此时 `terminal_exec` 直接返回 `-32005` 并在 message 里说明"该客户端版本不支持"。
|
||||
|
||||
理由:非 PTY 路径的回显跳过依赖"按写入长度跳过",且单行哨兵会被吞行命令吃掉,
|
||||
Go 侧没有实测数据支撑,先不开放比做错好。
|
||||
|
||||
若客户端根本不支持 shell(`COMMAND_SHELL` 发出后迟迟没有子连接),
|
||||
`OpenTerminalSession` 会一直停在 pending,表现为 `-32001` 超时。这里**不设能力门**——
|
||||
`CLIENT_CAP_TERMINAL` 只有新版 Android 声明,Windows/Linux 一直支持却不声明
|
||||
(`common/commands.h:151` 的注释),拿它做门会误拒所有桌面客户端。message 里加一句
|
||||
"若反复超时,可能该客户端版本不支持远程 shell"。
|
||||
|
||||
---
|
||||
|
||||
## 7. `get_screenshot`
|
||||
|
||||
### 7.1 为什么不用屏幕流
|
||||
|
||||
屏幕流是 H.264:`TOKEN_FIRSTSCREEN(116)` 是裸 BGRA 首帧,之后全是
|
||||
`TOKEN_NEXTSCREEN(117)` / `TOKEN_KEYFRAME(134)` 的编码帧。**不采用首帧方案**,原因不是
|
||||
解码(首帧本来就是裸的),而是**代价**:拿首帧必须先发 `COMMAND_SCREEN_SPY` 建立屏幕
|
||||
子连接、等客户端绑定、等首帧到达,用完还要拆——它占着每设备唯一的屏幕会话槽位,
|
||||
和正在看画面的人直接冲突,而且拆不干净就会一直推流。
|
||||
|
||||
`COMMAND_SCREEN_PREVIEW_REQ(247)` 是**主连接 RPC**:客户端自己抓屏、自己缩放、
|
||||
自己编码 JPEG 回包(`TOKEN_SCREEN_PREVIEW_RSP(248)`),不建子连接、不占槽位、
|
||||
一次请求一次响应。这是 MFC `get_screenshot` 的既有实现
|
||||
(`McpServer.cpp:2199`、`2015RemoteDlg.cpp:10449`),Go 照做即可。
|
||||
|
||||
### 7.2 请求 / 响应
|
||||
|
||||
```c
|
||||
struct ScreenPreviewReq { // 8 字节
|
||||
uint8_t cmd; // 247
|
||||
uint16_t reqId;
|
||||
uint16_t maxWidth;
|
||||
uint8_t jpegQuality; // 1..100
|
||||
uint16_t reserved;
|
||||
};
|
||||
|
||||
struct ScreenPreviewRspHeader { // 16 字节
|
||||
uint8_t token; // 248
|
||||
uint16_t reqId;
|
||||
uint8_t status; // 0=OK 1=抓屏失败 2=编码失败 3=不支持 4=目标无效
|
||||
uint8_t format; // 0=JPEG 3=BGRX
|
||||
uint16_t width, height;
|
||||
uint32_t bytes;
|
||||
uint8_t reserved[3];
|
||||
// 后接 data[bytes],可选再跟 ScreenCaptureMeta
|
||||
};
|
||||
```
|
||||
|
||||
v1 只发 8 字节基础请求(等价于整虚拟桌面),**不发 v2 扩展**——`region/window/monitor`
|
||||
需要 `CLIENT_CAP_SCREEN_REGION`,属后续增强。
|
||||
|
||||
参数映射:`max_width` 钳制到 `[64, 1920]`,缺省/0 时 Go v1 固定 1024;`jpegQuality` 固定 80。
|
||||
|
||||
### 7.3 BGRX → JPEG
|
||||
|
||||
Linux 客户端没有 JPEG 编码库,回 `format=3`(BGRX,自上而下逐行、每像素 4 字节
|
||||
`B,G,R,X`,无行填充,`bytes == width*height*4`)。Go 用标准库转:
|
||||
|
||||
```go
|
||||
img := image.NewRGBA(image.Rect(0, 0, w, h))
|
||||
for i := 0; i < w*h; i++ {
|
||||
img.Pix[i*4+0] = src[i*4+2] // R ← B
|
||||
img.Pix[i*4+1] = src[i*4+1] // G
|
||||
img.Pix[i*4+2] = src[i*4+0] // B ← R
|
||||
img.Pix[i*4+3] = 0xFF
|
||||
}
|
||||
jpeg.Encode(&buf, img, &jpeg.Options{Quality: 80})
|
||||
```
|
||||
|
||||
`bytes != w*h*4` 时按畸形包丢弃(返回 `-32000`)。
|
||||
|
||||
### 7.4 能力门与超时
|
||||
|
||||
- 缺 `CLIENT_CAP_SCREEN_PREVIEW(0x0004)` → `-32005`。
|
||||
MFC 同款门(描述里写明"老客户端返回 -32005")。
|
||||
- 超时 8 s。**不做取消**:MFC 明确写了"屏幕预览 = 主连接 RPC,不能 CancelIO"
|
||||
(`2015RemoteDlg.cpp:7514`)。超时后把请求表项删掉,迟到的响应按 `reqId` 不匹配丢弃。
|
||||
- 响应 `status != 0` 时按码翻译:1/2 → `-32000`(带 status 文案),3 → `-32005`,
|
||||
4 → `-32602`。
|
||||
|
||||
---
|
||||
|
||||
## 8. 文件工具
|
||||
|
||||
### 8.1 `list_files`
|
||||
|
||||
见 §5.3。解析细节:
|
||||
|
||||
- `TOKEN_DRIVE_LIST`:`[token][letter:1][type:1][totalMB:4][freeMB:4][typeName\0][fileSystem\0]` 循环,
|
||||
`letter=='\0'` 终止。
|
||||
- `TOKEN_FILE_LIST`:`[token]([attr:1][name\0][sizeHigh:4][sizeLow:4][ftLow:4][ftHigh:4])*`,
|
||||
空名终止(尾部零填充)。`attr & 0x10` 为目录。
|
||||
- `TOKEN_FILE_LIST_ERROR`:`[token][win32err:4 LE]`,按 §4.3 映射。这是**新客户端**才有的
|
||||
失败回执;老客户端路径不存在时直接不回包,表现为 `-32001` 超时(message 里要提示
|
||||
"路径可能不存在,先用 list_files 确认")。
|
||||
|
||||
`total` 与本次返回条数分开:客户端一次返回全部,服务端做 `limit`/`offset` 窗口裁剪并在
|
||||
`structuredContent` 里如实给出 `total`/`totalAll`/`hasMore`(与 MFC 的分页语义一致)。
|
||||
|
||||
### 8.2 `read_file`
|
||||
|
||||
见 §5.4。落盘完成后:
|
||||
|
||||
1. 校验 SHA-256(`COMMAND_FILE_COMPLETE_V2` 里带的 32 字节)。
|
||||
2. 按 `encoding` 解码全文(`auto`:BOM → 严格 UTF-8 → GBK 回退;`gb18030`/`latin1` 显式指定)。
|
||||
3. 按行切分,按 `offset`(0 基,负数=末尾 N 行)/`limit`/`max_bytes` 取窗口;`max_bytes`
|
||||
按行边界截断,避免切坏 UTF-8/GBK 多字节字符。
|
||||
4. 返回 `text` + `size` + `encoding` + `eol` + `lines_total` + `offset` + `lines_returned` +
|
||||
`truncated` + `sha256`。
|
||||
5. `defer os.RemoveAll(tmpDir)`。
|
||||
|
||||
**大小门**:`CMD_DOWN_FILES_V2` **没有区间参数,只能整文件下载**,所以大小门必须卡在
|
||||
下载前——在首个 `COMMAND_SEND_FILE_V2` chunk 里读 `fileSize`,超过
|
||||
`YAMA_MCP_READ_MAX`(默认 2 MiB,与 MFC 的 `kReadFileSizeGate` 一致)立即中止传输、
|
||||
删临时目录、返回 `-32602`,message 说明"文件超过 2 MiB,本工具不支持"。不要先落盘
|
||||
200 MB 再报错。
|
||||
|
||||
`offset` / `limit` 是**下载完成之后**对返回窗口的裁剪(`limit` 默认 256 KiB、
|
||||
上限 4 MiB),不能用来绕过大小门——大文件在 Go 侧目前无解,这是协议限制,
|
||||
工具描述里要写明。
|
||||
|
||||
### 8.3 路径校验(安全,必读)
|
||||
|
||||
V2 的 `filename` 由客户端提供。必须:
|
||||
|
||||
```go
|
||||
clean := filepath.Clean(filepath.Join(targetDir, filepath.FromSlash(name)))
|
||||
rel, err := filepath.Rel(targetDir, clean)
|
||||
if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) {
|
||||
abortTransfer() // 拒收并中止
|
||||
}
|
||||
```
|
||||
|
||||
`filepath.HasPrefix` 字符串前缀比较不够——`/tmp/ab` 会匹配 `/tmp/abc`。用 `filepath.Rel` 判越界。
|
||||
|
||||
同理 `list_files` 的 `path` 与 `read_file` 的 `path` 不做本地校验(它们在远端),
|
||||
但**不允许包含 NUL 与换行**——那会截断/拆开 C 字符串协议字段。
|
||||
|
||||
---
|
||||
|
||||
## 9. 并发、配额、生命周期
|
||||
|
||||
| 项 | 规则 |
|
||||
|---|---|
|
||||
| 每设备单请求 | `map[deviceID]*sync.Mutex` 的 `TryLock`;占用返回 `-32003`,message 带占用工具名与已持续时长 |
|
||||
| 全局并发 | `YAMA_MCP_MAX_CONCURRENCY`(默认 16)信号量;超出直接 `-32003` |
|
||||
| 单次请求上限 | `terminal_exec` 120 s,`read_file` 120 s,`get_screenshot` 8 s,其余 10 s |
|
||||
| 设备锁释放 | `defer` 释放;HTTP ctx 取消也走同一条 defer |
|
||||
| 终端空闲回收 | ticker 30 s 扫一次,`lastUsed` 超 180 s 关闭 |
|
||||
| 进程退出 | `mcp.Server.Close()` 关闭所有终端会话(避免留下孤儿 shell 子连接) |
|
||||
|
||||
设备锁的粒度是"整台设备"而不是"每通道",与 MFC 一致(`-32003` 说明里写明
|
||||
"列表、截屏、文件、管理动作共用这一道锁")。理由是主连接 RPC 与子连接命令
|
||||
在客户端侧可能共用同一份状态,并发只会让现场更难读。
|
||||
|
||||
---
|
||||
|
||||
## 10. 代码结构与依赖方向
|
||||
|
||||
```
|
||||
server/go/mcp/
|
||||
server.go # /mcp handler、JSON-RPC 分发、鉴权、tools/list
|
||||
tools.go # //go:embed tools_minimal.json;只读过滤、工具表
|
||||
tools_minimal.json # gen_go_tools.py 从 mcp/tools.json 抽取的 9 个工具(勿手改)
|
||||
tools_local.go # list_hosts / get_host_detail / get_server_status / get_audit_log
|
||||
tools_term.go # terminal_exec / terminal_close
|
||||
errors.go # 错误码 + JSON-RPC 错误映射
|
||||
audit.go # mcp.tool.call 审计
|
||||
lock.go # 设备锁 + 全局信号量
|
||||
session.go # 终端会话表、空闲回收
|
||||
term.go # 哨兵、环形缓冲
|
||||
clean.go # 终端输出清洗(逐字节移植 MFC 的 CleanTerminalOutput)
|
||||
screen.go # 主连接预览 RPC
|
||||
filemgr.go # 文件管理器子连接(list_files)
|
||||
filev2.go # V2 流式接收端(read_file)
|
||||
```
|
||||
|
||||
依赖方向(无环):
|
||||
|
||||
```
|
||||
cmd/main.go ──▶ web ──▶ mcp ──▶ hub ──▶ connection / protocol
|
||||
│ └──▶ devicehistory
|
||||
└──▶ wsauth
|
||||
```
|
||||
|
||||
- `mcp` 只 import `hub` / `protocol` / `devicehistory` / `logger`,**不 import `web`**。
|
||||
- **构造顺序**:`mcp.Server` 在 `cmd/main.go` 里先建,再分别注入两侧——
|
||||
`web.New(...).WithMCP(mcpSrv)`(沿用 `WithDeviceHistory` / `WithConfig` 的链式风格,
|
||||
`web/server.go:94`),以及 `MyHandler.mcp = mcpSrv`(TCP 分派侧)。
|
||||
这样 `web` 和 `cmd` 都只依赖 `mcp`,不存在 `mcp → web` 的反向依赖。
|
||||
- TCP 侧的分派(`cmd/main.go` 的 `OnReceive`)按到达的连接分成三组,未命中在途请求就丢弃:
|
||||
- `mcp.Server.OnPacket`:`TokenScreenPreviewRsp(248)`(主连接上的截图 RPC 回包)
|
||||
- `mcp.Server.OnFilePacket`:`TokenDriveList(103)` / `TokenFileList(104)` /
|
||||
`TokenFileListError(171)`(文件管理器子连接)
|
||||
- `mcp.Server.OnTransferPacket`:`CommandSendFileV2(85)` / `CommandFileCompleteV2(91)`
|
||||
(独立数据子连接或 POSIX 的文件管理器子连接)与 `TokenDownloadError(173)`
|
||||
|
||||
**为什么 embed 一份生成的 `tools_minimal.json`、而不是手写或直接引用 `mcp/tools.json`**:
|
||||
`mcp/tools.json` 在仓库根,`//go:embed` 不能引用父目录;手写 9 个 schema 又无法证明
|
||||
与 MFC 的 JSON 一致。所以由 `tools/mcp_tools/gen_go_tools.py` 从 `mcp/tools.json` 原样
|
||||
抽取(保持顺序,只留 name/description/inputSchema/outputSchema)生成 go 包内的副本并
|
||||
嵌入二进制——改工具定义必须改 `mcp/tools.json` 再重新生成,不存在两份手写文字漂移的余地。
|
||||
两道防漂移检查:`gen_go_tools.py --check`(生成副本是否为最新)与
|
||||
`verify_tools.py --subset`(线上 `tools/list` 是否与 `mcp/tools.json` 同名工具逐字段
|
||||
一致、名字集合是否恰好 9 个/只读 7 个)。
|
||||
|
||||
---
|
||||
|
||||
## 11. 施工顺序与验收
|
||||
|
||||
| 序 | 内容 | 依赖 | 可独立验收 |
|
||||
|---:|---|---|---|
|
||||
| 1 | `mcp` 包骨架 + `/mcp` + 鉴权 + `initialize`/`ping`/`tools/list` | — | ✅ `curl` 打通 |
|
||||
| 2 | 4 个本机只读工具(`list_hosts`/`get_host_detail`/`get_server_status`/`get_audit_log`) | 1 | ✅ 不碰设备即可测 |
|
||||
| 3 | 设备锁 + 全局信号量 + 审计 | 1 | ✅ |
|
||||
| 4 | 终端会话表 + 订阅 + 环形缓冲 | 3 | ✅ 浏览器开终端时能观察到缓冲 |
|
||||
| 5 | 哨兵 + 输出清洗 + `terminal_exec` 执行/轮询 | 4 | ✅ 对照 MFC 同款命令的输出现象 |
|
||||
| 6 | `terminal_close` + 空闲回收 | 5 | ✅ |
|
||||
| 7 | 主连接 RPC 请求表 + `get_screenshot` | 3 | ✅ |
|
||||
| 8 | 文件管理器子连接 + `list_files` | 3 | ✅ |
|
||||
| 9 | V2 接收端 + `read_file` + 路径校验 | 8 | ✅ |
|
||||
| 10 | `verify_tools.py --subset` | 1 | ✅ |
|
||||
|
||||
**整体验收**(用同一套 ASM 工位任务重跑):
|
||||
|
||||
- 9 个工具全部可调用,`tools/list` 响应 < 24 KB(无 outputSchema 的直接收益)
|
||||
- `terminal_exec` 连续 20 条命令零失败;超时后轮询能取回完整输出
|
||||
- 浏览器开着终端时 `terminal_exec` 返回 `-32003` 而不是把人的会话踢掉
|
||||
- `read_file` 读 `.env`(含单引号、CRLF)字节级一致,SHA-256 与远端 `sha256sum` 相同
|
||||
- `get_screenshot` 在 Windows / Linux 各出一张图,Linux 走 BGRX→JPEG 分支
|
||||
- 审计里每次调用一条 `mcp.tool.call`,`device`/`tool`/`code`/`ms` 齐全
|
||||
|
||||
---
|
||||
|
||||
## 12. 风险与未决
|
||||
|
||||
| # | 风险 | 影响 | 处置 |
|
||||
|---:|---|---|---|
|
||||
| R1 | 哨兵清洗移植不完整 | 输出带垃圾/退出码错 | 按 MFC 三段顺序整体移植,用 MFC 记录的实测样例做 Go 单测(`rem hello`、`cmd /c echo abc`、`type .env`) |
|
||||
| R2 | 终端槽位被 MCP 长期占用 | 人用不了终端 | 空闲 180 s 回收 + `-32003` 明确告知 + 工具描述写明 |
|
||||
| R3 | 老客户端不认识 `CMD_DOWN_FILES_V2(94)` | `read_file` 静默超时 | 工具描述写明"超时可能是不支持 V2 的旧客户端";§5.4 |
|
||||
| R4 | 老客户端缺 `CLIENT_CAP_UTF8` | 文件名 GBK 解码 | 新客户端 `DefaultCaps()` 恒带此位(`commands.h:1289`),只有很老的客户端会缺;与既有 `activeWindow` 路径同源,后续在 `hub.DeviceInfo` 暴露 `clientType` 后一并修 |
|
||||
| R5 | 非 PTY 老客户端 | 无法用 `terminal_exec` | v1 明确 `-32005`,描述里说明 |
|
||||
| R6 | 多用户 / 分组授权缺失 | 所有 MCP 调用都是 admin | v1 明确单 principal;多租户部署前必须补 token 表 + `allowedGroups` 校验 |
|
||||
| R7 | 无 `notifications/progress` | 长任务(`read_file` 大文件)模型以为卡死 | 工具描述写明预期耗时;v2 再上 SSE |
|
||||
| R8 | `read_file` 只能整文件下载,2 MiB 封顶 | 读大日志无解 | 与 MFC 同款限制(`kReadFileSizeGate`)。绕法是 `terminal_exec` + `tail`,工具描述里给出这个替代路径 |
|
||||
|
||||
---
|
||||
|
||||
## 附录 A:协议速查
|
||||
|
||||
| 名称 | 值 | 方向 | 载荷 |
|
||||
|---|---:|---|---|
|
||||
| `COMMAND_LIST_DRIVE` | 1 | S→C 主连接 | `[cmd]` |
|
||||
| `COMMAND_LIST_FILES` | 2 | S→C 文件子连接 | `[cmd][path\0]` |
|
||||
| `COMMAND_SCREEN_SPY` | 16 | S→C 主连接 | `[cmd]` |
|
||||
| `COMMAND_BYE` | 204 | S→C 任意 | `[cmd]` |
|
||||
| `COMMAND_SCREEN_PREVIEW_REQ` | 247 | S→C 主连接 | `ScreenPreviewReq`(8B) |
|
||||
| `COMMAND_SEND_FILE_V2` | 85 | C→S V2 子连接 | `FileChunkPacketV2`(77B)+ name + data |
|
||||
| `COMMAND_FILE_COMPLETE_V2` | 91 | C→S V2 子连接 | `FileCompletePacketV2`(69B) |
|
||||
| `CMD_DOWN_FILES_V2` | 94 | S→C 文件子连接 | `[cmd][targetDir\0][path\0][\0]` |
|
||||
| `TOKEN_DRIVE_LIST` | 103 | C→S 文件子连接 | `[token]` + 盘符记录 |
|
||||
| `TOKEN_FILE_LIST` | 104 | C→S 文件子连接 | `[token]` + 文件记录 |
|
||||
| `TOKEN_FILE_LIST_ERROR` | 171 | C→S 文件子连接 | `[token][win32err:4 LE]` |
|
||||
| `TOKEN_CONN_AUTH` | 246 | C→S 子连接 | `ConnAuthPacket`(512B) |
|
||||
| `TOKEN_SCREEN_PREVIEW_RSP` | 248 | C→S 主连接 | `ScreenPreviewRspHeader`(16B)+ data |
|
||||
|
||||
`FileChunkPacketV2` 字段:`cmd(1) transferID(8) srcClientID(8) dstClientID(8)
|
||||
fileIndex(4) totalFiles(4) fileSize(8) offset(8) dataLength(8) nameLength(8)
|
||||
flags(2) checksum(2) reserved(8)` = 77 字节。
|
||||
|
||||
---
|
||||
|
||||
## 附录 B:自审记录
|
||||
|
||||
写完初稿后按"每个结论都必须能在代码里指到行"重核了一遍,发现并修掉以下问题:
|
||||
|
||||
| # | 问题 | 处置 |
|
||||
|---:|---|---|
|
||||
| 1 | 初稿写"文件管理器子连接不带 ConnAuth,需要 pending 标记",照搬了 MFC 的做法 | **错**。`client/KernelManager.cpp:1773` 对 `COMMAND_LIST_DRIVE` 调了 `EnableSubConnAuth()`,Go 的 `handleConnAuth` 已把 clientID 钉在 ctx 上。改为按 clientID 路由,删掉 pending 方案,省掉一个 hub 改动 |
|
||||
| 2 | 初稿把 `get_screenshot` 设计成"抓 `TOKEN_FIRSTSCREEN` 原始帧" | **改**。`TOKEN_FIRSTSCREEN` 虽注释为 raw BGRA,但它依附于屏幕会话(占槽位、要建子连接)。改用 `COMMAND_SCREEN_PREVIEW_REQ` 主连接 RPC——与 MFC 一致,不占任何槽位 |
|
||||
| 3 | 初稿写"终端槽位需要给 hub 加 owner 字段" | **简化**。`hub.OpenTerminalSession` 的 `ErrTerminalBusy` 本身就是互斥,v1 不抢占就不需要 owner。删掉 hub 改动,v1 对 `hub` **零改动** |
|
||||
| 4 | 初稿写 `read_file` 用 `filepath.HasPrefix` 校验路径 | **错**。字符串前缀会让 `/tmp/ab` 匹配 `/tmp/abc`。改为 `filepath.Rel` 判越界 |
|
||||
| 5 | 初稿漏了非 PTY 客户端的处理 | **补** §6.7:v1 明确 `-32005`,不做半吊子支持 |
|
||||
| 6 | 初稿写"审计记录完整 command" | **改**。命令全文可能含密码,改为只记首词与长度,全文进 debug 日志 |
|
||||
| 7 | 初稿的 `list_files` 没写 `total` 与 `returned` 的区别 | **补** §8.1,避免模型把截断当成"目录里只有这么多" |
|
||||
| 8 | 初稿写"`terminal_exec` 的 reqId 用时间戳" | **改**。时间戳在并发下会撞;改 `atomic.Uint32` 取低 16 位,并**必须**校验响应 reqId(MFC `TakePreviewResponse` 同款) |
|
||||
| 9 | 初稿把 `get_screenshot` 的 `max_width` 固定 1600 | **改** 为可传,钳制 `[320,3840]`,与 MFC 的 `max_width` 参数对齐 |
|
||||
| 10 | 初稿没写"客户端 V2 开关关闭会静默超时" | **改**。核查后发现 V2 开关是**服务端**的(`2015RemoteDlg.cpp:2822` `EnableFileV2`,默认关),不是客户端。且 `CLIENT_CAP_V2` 在 `DefaultCaps()` 里全平台无条件声明,做门等于没门。改为"无能力门 + 老客户端不认识 94 号命令会静默超时",见 §5.4 |
|
||||
| 11 | 初稿把 `read_file` 的能力门写成 `CLIENT_CAP_V2` | **删**。同 #10,该位恒为真。表格与 §5.4 一并改 |
|
||||
| 12 | 初稿写 `/mcp` 用 `s.requireBearer` 包一层 | **错**。`requireBearer` 校验的是浏览器会话令牌(`web/server.go:269` 的 `s.auth.ValidateToken`),MCP 静态令牌过不去。改为 `mux.HandleFunc("/mcp", s.mcp.Handle)`,鉴权在 handler 内做 |
|
||||
| 13 | 初稿写"`mcp` 在 `web.Start()` 里构造" | **错**。TCP 侧 `cmd/main.go` 的 `OnReceive` 也要把包转给 `mcp`,两边需要同一实例。改为在 `cmd/main.go` 先建,再 `web.New(...).WithMCP(srv)` + `MyHandler.mcp = srv` |
|
||||
| 14 | 初稿写"非 PTY 客户端 `-32005`",但没说"根本不支持 shell 的客户端怎么办" | **补** §6.7:不设能力门(`CLIENT_CAP_TERMINAL` 只有 Android 声明),走 `-32001` 超时 + message 提示 |
|
||||
| 15 | §5.3 时序图自相矛盾:`TOKEN_DRIVE_LIST` 后写"关子连接",下一行又写"同一子连接"发 `COMMAND_LIST_FILES` | **改**。列目录必须复用同一个子连接(`2015RemoteDlg.cpp:7647` 的注释),改为"保持打开,`TOKEN_FILE_LIST` 分支收尾" |
|
||||
| 16 | §5.4 仍写 `filepath.HasPrefix` 校验路径,与 §8.3 自相矛盾 | **改**。统一指向 §8.3 的 `filepath.Rel` 判越界 |
|
||||
| 17 | §7.1 说"屏幕流全是 H.264",据此否掉首帧方案 | **错两处**:首帧 `TOKEN_FIRSTSCREEN` 本来就是裸 BGRA,不需要解码;否掉它的真正理由是**要建屏幕子连接、占唯一槽位、还要拆**。改为按代价论证 |
|
||||
| 18 | §8.2 建议大文件"直接用 `download_file`" | **错**。`download_file` 在 v1 不做(§1.2),不能建议一个不存在的工具。改为"卡在下载前的大小门 + 用 `terminal_exec` 兜底" |
|
||||
| 19 | §8.2 只说"`limit` 上限 4 MiB",没意识到 V2 是整文件下载 | **补**。`CMD_DOWN_FILES_V2` 无区间参数,大小门必须卡在首个 chunk 的 `fileSize` 上(2 MiB,与 MFC `kReadFileSizeGate` 一致),否则会先落盘再报错 |
|
||||
| 20 | §3.2 `get_server_status` 返回 `version`/`commit`,但 Go 侧没有这两个变量 | **补**。`cmd/main.go` 查不到版本常量,需新增 `var version, commit string` + Makefile `-X` 注入;拿不到返回空串 |
|
||||
| 21 | §3.2 `get_host_detail.capabilities` 里列了 `v2` | **删**。该位全平台恒真(同 #10),列出来误导模型。换成 `utf8`/`screen_preview`/`screen_region`/`window_info` |
|
||||
| 22 | §5.2 写死 `SendToTerminal(cmd+"\n")`,与 §6.4 的 ConPTY `\r\n` 冲突 | **改** 为按平台分行尾 |
|
||||
| 23 | §3.2 的输入/输出形状是自造结构,与 `mcp/tools.json` 不一致(`online_only`、`entries`、`since`、`bytes_read`、`output`、capabilities 下划线命名、`max_width` 1600/[320,3840]) | **改**。已确认 `mcp/tools.json` 是唯一契约,§3.2 按 `inputSchema`/`outputSchema` 重写:`list_files` 返回 `files`、`read_file` 为行语义、审计无 `since`、capabilities 用 camelCase、`max_width` 钳制 `[64,1920]` 默认 1024;M1 起 `tools/list` 原样回显该 schema |
|
||||
|
||||
**结论**:以上 23 处已全部修入正文,无遗留。v1 对 `server/go` 的改动是
|
||||
**新增 `mcp` 包 + `web/server.go` 一行路由 + `web.Server` 一个 `WithMCP` + `cmd/main.go` 六个 case + `protocol` 六个常量 + 两个版本变量**,
|
||||
`hub` 零改动。
|
||||
@@ -0,0 +1,545 @@
|
||||
# Go 服务端 MCP 实施计划
|
||||
|
||||
> 版本:v1(草稿,待评审) 日期:2026-11-12
|
||||
>
|
||||
> 依据:`docs/Mcp_Go_Minimal_Design.md` v1.0(下称"设计文档")。
|
||||
> 本文只回答**怎么施工**:顺序、改动面、完成定义、验证手段、提交边界。
|
||||
> 设计取舍一律以设计文档为准,本文不重复论证;与设计文档不一致的地方在 §1 单列。
|
||||
>
|
||||
> 工作方式:沿用本项目既有节奏——**做一段、验一段、审一段、提交一段**,每段一个可独立
|
||||
> 回滚的提交。Go 侧提交前缀用仓库既有约定 `Feature(Go):` / `Fix(Go):`。
|
||||
|
||||
---
|
||||
|
||||
## 0. 交付面与总量
|
||||
|
||||
| 类别 | 内容 | 规模 |
|
||||
|---|---|---:|
|
||||
| 新包 | `server/go/mcp/`(server / tools / errors / audit / lock / session / term / screen / filemgr / filev2) | ≈2,300 行(含测试 ≈900) |
|
||||
| 抽包 | `server/go/auditquery/`(从 `web/audit_query.go` 提出查询器,见 §1.1) | ≈180 行搬移 |
|
||||
| 接线 | `web/server.go`(`WithMCP` + 一行路由)、`cmd/main.go`(构造/注入/六个 case/版本变量)、`protocol/commands.go`(常量)、`build.ps1` + `Makefile`(`-X` 注入) | ≈120 行 |
|
||||
| 工具校验 | `tools/mcp_tools/verify_tools.py` 增 `--subset` | ≈80 行 |
|
||||
| 文档 | `deploy/yama-server.env.example` 补 5 个变量;`docs/Mcp_Go_Minimal_Design.md` 状态改"已实施" | — |
|
||||
|
||||
**8 个提交,8 个里程碑,预估 62 小时**(明细见 §3 / §7)。`hub` 零改动——这是设计文档
|
||||
自审后的结论,本计划沿用;若施工中发现必须改 `hub`,先停下来改设计文档。
|
||||
|
||||
---
|
||||
|
||||
## 1. 开工前必须先定的 5 件事
|
||||
|
||||
这 5 项都会阻塞某个里程碑,且都需要一次性拍板。建议按顺序在本计划评审时定掉。
|
||||
|
||||
### 1.1 `get_audit_log` 的代码复用方式(阻塞 M2)
|
||||
|
||||
设计文档 §3.2 要求"复用 `web/audit_query.go` 的查询器",§10 又要求"`mcp` 不 import `web`"。
|
||||
两者冲突:查询器 `queryAuditLog` 及其类型/过滤/时间解析全是 `web` 包私有(`web/audit_query.go:158-328`)。
|
||||
|
||||
| 方案 | 做法 | 代价 |
|
||||
|---|---|---|
|
||||
| **A(推荐)** | 新增 `server/go/auditquery` 包,把 `queryAuditLog` + `auditQueryRequest/Result` + `auditRecordMatches` / `auditEventFilterMatches` / `auditStringField` / `parseAuditTime` / `clamp*` 整体搬过去并导出(`Scan(path string, q Query) (Result, error)`);`web/audit_query.go` 只留 handler 与回包整形 | 搬移 + `web/audit_query_test.go`(294 行)机械改调用名;依赖方向保持不变 |
|
||||
| B | `mcp` 自己实现一个精简扫描器(keyword/type/limit/offset) | 少动 `web`,但审计格式一旦变就有两份实现 |
|
||||
| C | `mcp` import `web` | 破环:`web → mcp` 已存在(`WithMCP`),反向成环直接编译失败 |
|
||||
|
||||
**已确认:采用 A**。M2 的第一步就是搬包,`go test ./web/...` 全绿后再写工具。
|
||||
|
||||
### 1.2 版本号与提交号注入(阻塞 M2 的 `get_server_status`)
|
||||
|
||||
`cmd/main.go` 目前没有版本常量(全文件 grep 不到)。**已确认**的做法:
|
||||
|
||||
- 新增 `server/go/buildinfo`,只放 `var Version, Commit string`(零值空串)+ `Snapshot()`。
|
||||
不塞 `main`:`mcp` 不能依赖 `main`,也不该为两个字符串在装配链上多传两层。
|
||||
- 注入:`-X github.com/yuanyuanxiang/SimpleRemoter/server/go/buildinfo.Version=…`,同样注入 `.Commit`。
|
||||
取值 `Version=$(git describe --tags --always --dirty)`、`Commit=$(git rev-parse --short HEAD)`
|
||||
(现在是 `v1.4.2-72-g425d737-dirty` / `425d737`)。
|
||||
- `build.ps1`:Debug/Release **都**拼 `-X`(Debug 只是不剥符号);`Makefile` 的 `LDFLAGS`
|
||||
用 `$(shell git …)` 同步。
|
||||
- 取不到(无 git、源码包构建)就保持空串,`get_server_status` 原样返回空串,**不伪造**。
|
||||
- Windows 资源同步:`cmd/winres/winres.json` 里的版本号改成占位,构建前跑
|
||||
`go-winres make --in cmd/winres/winres.json --out cmd/rsrc --product-version git-tag --file-version git-tag`
|
||||
(实测会把 manifest identity / FileVersion / ProductVersion 三处一起覆盖成 `1.4.2`);
|
||||
`go-winres` 不存在时警告并跳过。`server/go/cmd/*.syso` 加进 `.gitignore`,不再出现在
|
||||
`git status` 里。文件属性 = 干净 tag,运行时 `version` = `git describe` 全串,各司其职。
|
||||
|
||||
### 1.3 工具 schema 用哪一份(阻塞 M2/M5/M6/M7)
|
||||
|
||||
设计文档 §3.2 给的参数集与 `mcp/tools.json`(MFC 现网 schema)**并不完全一致**:
|
||||
|
||||
| 工具 | 设计文档 §3.2 | `mcp/tools.json` 实际 |
|
||||
|---|---|---|
|
||||
| `list_hosts` | `group` `name` `online_only` `limit` `offset` | `client_type` `group` `include_offline` `ip` `limit` `name` `offset` `online` `os` `query` |
|
||||
| `get_host_detail` | `id` | `id` `ids` |
|
||||
| `get_audit_log` | `keyword` `type` `since` `limit` `offset` | `keyword` `limit` `offset` `type` |
|
||||
| `get_screenshot` | `id` `max_width` | `id` `max_width` `height` `hwnd` `mode` `monitor` `width` `x` `y` |
|
||||
| `terminal_exec` | 一致 | 一致 |
|
||||
| `terminal_close` | `session_id` | `id` `session_id` |
|
||||
| `list_files` | `id` `path` `limit` | `id` `ids` `limit` `offset` `path` |
|
||||
| `read_file` | `id` `path` `offset` `limit` `encoding` | 同 + `max_bytes` |
|
||||
|
||||
设计文档自称"全部命名、参数、错误码与 MFC 对齐",实际只有 naming 与错误码对齐。
|
||||
**已确认:`mcp/tools.json` 是唯一契约**——`name` / `description` / `inputSchema` /
|
||||
`outputSchema` 和工具顺序都按它来(`verify_tools.py:12` 的比对口径)。
|
||||
|
||||
- 9 个工具的这四份字段由 `tools/mcp_tools/gen_go_tools.py` 从 `mcp/tools.json` 抽取(保持相对顺序),
|
||||
写到 `server/go/mcp/tools_minimal.json`,Go 侧 `//go:embed` 原样回 `tools/list`;脚本支持
|
||||
`--check`(子集与抽取结果不等则非零退出),加一个 Go 单测锁名字与顺序。
|
||||
- `tools.json` 里没有 `annotations`,MFC 也不发,Go 不发(M1 的测试相应改为"不带 annotations")。
|
||||
- 输出按对应 `outputSchema` 的字段名组装,**不套用设计文档 §3.2 的自造形状**。
|
||||
|
||||
| 参数 | Go 侧处理 |
|
||||
|---|---|
|
||||
| `list_hosts` 全部 10 个 | 全部实现(`DeviceInfo` 上做字符串过滤,成本可忽略) |
|
||||
| `get_host_detail.ids` | 实现批量(≤50),按 `outputSchema` 的 `{tool,total,succeeded,failed,skipped,results[]}` 汇总 |
|
||||
| `get_audit_log` | `keyword` / `type`(映射 `auditquery.Event`)/ `limit` / `offset`;**没有 `since`**(MFC 的 schema 里就没有) |
|
||||
| `get_screenshot` 的非整屏参数 | `mode=region/window/monitor` 或 `hwnd/x/y/width/height` 任一出现 → `-32005`,报文点名参数并说明需要 `CLIENT_CAP_SCREEN_REGION` 扩展请求;不静默忽略 |
|
||||
| `get_screenshot.max_width` | 钳制 `[64,1920]`(schema 与 `McpServer.cpp:3386` 一致);缺省/0 → Go v1 固定 1024(没有 MFC 的 RTT 自适应档位) |
|
||||
| `terminal_close.id` | 必需;用于定位设备,`session_id` 用于匹配会话 |
|
||||
| `list_files` 的 `id/ids/path/limit/offset` | 全部实现;`offset` 是服务端在完整列表上做窗口裁剪;批量走 results 汇总 |
|
||||
| `read_file` 的语义 | **行语义**:`offset` 起始行(负数=末尾 N 行)、`limit` 行数、`max_bytes` 字节上限;`encoding` 支持 `auto/utf-8/gbk/gb18030/latin1` |
|
||||
| 输出字段 | `list_hosts` → `hosts/total/totalAll/limit/offset/hasMore`;`list_files` → `files`(不是 `entries`)/`drives`;`get_host_detail.capabilities` → `screenPreview/screenRegion/windowInfo/fileTransferV2/c2cPaths/registry/remoteControl/platform`;`read_file` → `encoding/eol/lines_total/lines_returned/sha256/size/text/truncated` |
|
||||
| hub 没有的字段 | `authStatus/tls/location/install_time/remark` 不伪造、直接不给(`outputSchema` 只强制 `hosts`) |
|
||||
|
||||
`read_file` 的整文件下载仍受 `YAMA_MCP_READ_MAX`(2 MiB)硬门约束,超过 → `-32602`(schema 描述同款口径)。
|
||||
|
||||
### 1.4 测试环境与"真机"路径(阻塞 M4 起的全部验收)
|
||||
|
||||
**已确认并已由 M0 实测**(详见 §4.3):本机真客户端用 **`x64\Debug\ghost.exe`**,
|
||||
`TestRun.exe` 不可用(依赖 `ServerDll.dll` 内存加载;Release 版从非安装路径启动会走安装
|
||||
流程并自删)。Go 服务端默认 **trial** 签名即可,客户端已上线;屏幕/文件能力是否解锁
|
||||
在 M5/M6 实测(`YAMA_LICENSE_DISABLED=1` 的 NoOp 会让客户端拒绝这两类功能,不要用于
|
||||
M5 之后的验收)。
|
||||
|
||||
### 1.5 只读模式下的工具集合(阻塞 M8)
|
||||
|
||||
`YAMA_MCP_READONLY=1` 时 `tools/list` 只出 7 个。`--subset` 必须支持"期望集合 7 或 9"两种,
|
||||
由环境变量或 `--readonly` 参数决定;不能写成硬编码 9。
|
||||
|
||||
---
|
||||
|
||||
## 2. 里程碑与提交边界
|
||||
|
||||
| 里程碑 | 提交标题(建议) | 设计文档 § | 依赖 | 完成定义(可验收) | 预估 |
|
||||
|---|---|---|---|---:|
|
||||
| M1 | `Feature(Go): MCP endpoint with bearer auth and tools/list` | §4、§3.1 | — | `curl` 打通 initialize/ping/tools/list;错误令牌 401;GET 405;通知 204 | 6h |
|
||||
| M2 | `Feature(Go): four local MCP read tools and a shared audit query package` | §3.2、§1.1 | M1 | 4 个工具返回真实数据;`go test ./web/...` 与新增用例全绿 | 10h |
|
||||
| M3 | `Feature(Go): per-device locks, concurrency cap and MCP audit trail` | §9、§4.4 | M1 | 并发调用返回 -32003;每次调用一条 `mcp.tool.call` | 4h |
|
||||
| M4a | `Feature(Go): MCP terminal sessions with a ring buffer` | §6.1-§6.3 | M3 | 会话表 + 订阅 + 缓冲;浏览器开终端时 MCP 返回 -32003 | 6h |
|
||||
| M4b | `Feature(Go): terminal_exec with sentinel cleaning and polling` | §6.4-§6.6 | M4a | 20 条连续命令零失败;超时后轮询取回完整输出 | 8h |
|
||||
| M4c | `Feature(Go): terminal_close, idle sweep and legacy-client guard` | §6.2、§6.7 | M4b | 关闭幂等;空闲 180s 回收;非 PTY 返回 -32005 | 2h |
|
||||
| M5 | `Feature(Go): get_screenshot over the maintenance-free preview RPC` | §7 | M3 | Windows/Linux 各出一张图;BGRX 分支有单测 | 6h |
|
||||
| M6 | `Feature(Go): list_files over the file-manager sub-connection` | §5.3、§8.1 | M3 | 盘符/目录/错误三种路径;老客户端超时有明确 message | 8h |
|
||||
| M7 | `Feature(Go): read_file over the V2 stream receiver` | §5.4、§8.2-§8.3 | M6 | `.env` 字节一致且 SHA-256 匹配;路径穿越全部拒收 | 10h |
|
||||
| M8 | `Feature(Go): verify_tools --subset and MCP deployment docs` | §10、§4.2 | M1 | 9(或 7)个工具的 schema/description 与 `tools.json` 严格一致 | 3h |
|
||||
|
||||
M4 拆成三个提交是因为它占全量工作量的 1/4,一次提交无法审查;其余里程碑按设计文档
|
||||
§11 的 10 个施工序合并(§11 的 3 并进 M3,4/5/6 并成 M4a/b/c,7 是 M5,8 是 M6,9 是 M7,10 是 M8)。
|
||||
|
||||
---
|
||||
|
||||
## 3. 里程碑细则
|
||||
|
||||
### M1 骨架与鉴权(设计 §4)
|
||||
|
||||
**新增文件**
|
||||
|
||||
```
|
||||
server/go/mcp/server.go // Config、Server、New、Enabled、Handle、Close
|
||||
server/go/mcp/jsonrpc.go // 请求/响应结构、错误对象、批量拒绝
|
||||
server/go/mcp/tools.go // //go:embed tools_minimal.json,tools/list 原样返回
|
||||
server/go/mcp/tools_minimal.json // gen_go_tools.py 从 mcp/tools.json 抽取的 9 个工具
|
||||
server/go/mcp/errors.go // -32001…-32602 常量与 message 模板
|
||||
tools/mcp_tools/gen_go_tools.py // 抽取脚本,--check 模式供验收
|
||||
```
|
||||
|
||||
**实现要点**
|
||||
|
||||
1. `Config` 从环境变量读全(`cmd/main.go` 解析后传入,`mcp` 包不直接读 env):
|
||||
`Token` / `Readonly` / `TermIdle` / `MaxConcurrency` / `ReadMax`。
|
||||
2. `Handle` 分支表:`POST` 之外一律 `405`(带 `Allow: POST`);无 `id` 的通知 `204`;
|
||||
数组入参 `-32600`;未知 `method` `-32601`;`tools/call` 未知工具名 `-32601`。
|
||||
3. 鉴权:`subtle.ConstantTimeCompare`,长度不等直接失败;缺令牌 → `401` +
|
||||
`WWW-Authenticate: Bearer realm="mcp"`,不带 JSON-RPC 体(规范要求传输层失败)。
|
||||
4. 体积:`http.MaxBytesReader(w, r.Body, 8<<20)`,超限 `413`。
|
||||
5. `initialize` 回 `protocolVersion=2025-06-18`、`capabilities.tools={listChanged:false}`、
|
||||
`serverInfo={name:"yama", version:<build>}`、`instructions=<Go 后端差异说明>`。
|
||||
`serverInfo.name` 与 MFC 一致,Go 差异只写 `instructions`——避免客户端按 name 分叉。
|
||||
6. 路由注册:`web/server.go` 加 `WithMCP`,`Start()` 里
|
||||
`if s.mcp != nil && s.mcp.Enabled() { mux.HandleFunc("/mcp", s.mcp.Handle) }`,
|
||||
否则打一行 `MCP endpoint disabled: YAMA_MCP_TOKEN not set`。
|
||||
7. `cmd/main.go`:在 `web.New(...)` 之前构造 `mcpSrv`,再 `.WithMCP(mcpSrv)` +
|
||||
`handler.mcp = mcpSrv`(`MyHandler` 加字段);`mcp` 只依赖 `hub`/`protocol`/`devicehistory`/`logger`。
|
||||
|
||||
**测试**(`mcp/server_test.go`,`httptest` + fake hub)
|
||||
|
||||
- 令牌:正确 / 错误 / 长度不同 / 缺失 → 200 / 401 / 401 / 401。
|
||||
- 方法:`initialize`、`ping`、`tools/list`、`notifications/initialized`(204)、未知方法(-32601)。
|
||||
- 形态:批量数组 → -32600;GET/DELETE → 405;超大体 → 413。
|
||||
- `tools/list`:数目与 `Readonly` 相符;工具定义与 `tools_minimal.json` 逐字一致且顺序不变
|
||||
(无 `annotations`,与 MFC 一致)。
|
||||
|
||||
**验收命令**
|
||||
|
||||
```bash
|
||||
cd server/go
|
||||
go build ./... && go test ./mcp/...
|
||||
curl -s -X POST localhost:18090/mcp -H "Authorization: Bearer $YAMA_MCP_TOKEN" \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
|
||||
```
|
||||
|
||||
### M2 本机只读四工具(设计 §3.2)
|
||||
|
||||
**改动**
|
||||
|
||||
1. 先做 §1.1 的 `auditquery` 抽包:搬移 → `web` 改调用 → `go test ./web/...` 全绿。
|
||||
2. 新增 `mcp/tools_local.go`:
|
||||
- `list_hosts`:`hub.ListDevices()` + `history.Offline(onlineSet)` 合并;`include_offline`
|
||||
决定是否并入历史;`online/ip/os/group/name/client_type/query` 全为过滤(`name`/`query`
|
||||
大小写不敏感子串);按 `outputSchema` 返回 `{hosts,total,totalAll,limit,offset,hasMore}`,
|
||||
host 字段按 schema 命名组装,hub/历史里确有的 `location/install_time/screen/version` 照填,
|
||||
两边都没有的 `authStatus/tls/remark` 不伪造。
|
||||
- `get_host_detail`:`id` 或 `ids`(≤50,批量走 `{tool,total,succeeded,failed,skipped,results[]}`);
|
||||
`capabilities{screenPreview,screenRegion,windowInfo,fileTransferV2,c2cPaths,registry,remoteControl,platform}`
|
||||
(`protocol.SupportsCap` 逐位)——**不含 `v2`**(恒真,列出来误导)。
|
||||
- `get_server_status`:按 `outputSchema` 的字段名组装,Go 只填能如实取到的
|
||||
`version / uptime_sec / hosts / sessions / port / bind`(其余 MFC 专有字段不给);
|
||||
`version` 取 `buildinfo`(§1.2),`uptime_sec` 用 `mcp.Config.StartedAt`,`commit`
|
||||
只进日志,不塞进 schema 未定义的返回字段。
|
||||
- `get_audit_log`:`auditquery.Scan`;`type` 映射事件过滤;无 `since`。
|
||||
3. `buildinfo` 包 + `build.ps1` / `Makefile` 的 `-X` + winres 重建(§1.2)。
|
||||
|
||||
**测试**(`mcp/tools_local_test.go`)
|
||||
|
||||
- `devicehistory.New(t.TempDir()+"/devices.json", 10, log)` + `hub.Register` 造 3 台在线、2 台历史
|
||||
离线;断言过滤/分页,以及 `total`(命中数)、`totalAll`(过滤前)、`hasMore` 三者分离。
|
||||
- `get_host_detail` 的能力位:给一个 capability 串(含/不含 `0x0004`)两种。
|
||||
- `get_audit_log`:用 `logger.Audit` 写临时文件后查询(`auditquery` 的用例在搬包时一并迁)。
|
||||
|
||||
### M3 锁、并发与审计(设计 §9、§4.4)
|
||||
|
||||
**新增** `mcp/lock.go`、`mcp/audit.go`。
|
||||
|
||||
1. 设备锁:`map[string]*sync.Mutex` + `TryLock`,占用即 `-32003`,message 带占用工具名与
|
||||
已持续时长(`since` 记录在持锁结构里)。
|
||||
2. 全局信号量:`chan struct{}` 容量 `MaxConcurrency`,`TryAcquire` 失败 `-32003`。
|
||||
3. 审计:每次 `tools/call` 一条 `log.Audit("mcp.tool.call", …)`,字段
|
||||
`actor=mcp role=admin source=mcp tool device ok code ms args=<首词+长度> result=<体积摘要>`;
|
||||
**不记命令全文**(进 debug 日志)。HTTP `r.Context()` 取消同样走 defer 释放锁。
|
||||
|
||||
**测试**:并发两个同设备调用 → 第二个 -32003;`close(cancel)` 后锁被释放;审计行字段齐全
|
||||
(读临时审计文件断言)。
|
||||
|
||||
### M4a 终端会话(设计 §6.1-§6.3)
|
||||
|
||||
**新增** `mcp/session.go`(会话表 + 空闲回收)、`mcp/term.go`(环形缓冲 + 哨兵检测骨架)。
|
||||
|
||||
1. `mcp.Server` 实现 `hub.EventHandler` 全接口(`OnDeviceOnline/Offline/Update`、
|
||||
`OnScreenFrame`、`OnResolutionChange`、`OnCursorChange`、`OnClipboardText`、
|
||||
`OnTerminalReady/Data/Closed`),只有终端三个方法做事,其余空实现;
|
||||
`cmd/main.go` 里 `deviceHub.Subscribe(mcpSrv)`,退出时 `hub.Unsubscribe` + `Close()`。
|
||||
2. `OnTerminalData` 在 TCP 读循环上执行,**必须不阻塞**:只做"查会话 → 追加环形缓冲 →
|
||||
剥 4 字节 `TRM1` 前缀 → 哨兵扫描 → `sync.Cond` 唤醒",任何长操作都不允许(设计 §6.3)。
|
||||
非 MCP 会话的设备直接丢弃(零开销)。
|
||||
3. 环形缓冲 256 KiB + `base/total/delivered` 绝对偏移;溢出丢最旧并累计 `droppedBytes`。
|
||||
4. 会话表 key 用 `deviceID`;`session_id` 为 `"s-"+6hex`;对外只暴露 `session_id`。
|
||||
|
||||
**测试**:`hub.PublishTerminalData` 灌 1 MB → 缓冲不涨、`truncated` 语义正确;关闭后释放;
|
||||
浏览器(另建一个订阅者 `OpenTerminalSession`)占用时 `OpenSession` 返回 busy。
|
||||
|
||||
### M4b `terminal_exec` 执行与轮询(设计 §6.4-§6.6)
|
||||
|
||||
1. 打开:`hub.OpenTerminalSession(deviceID)`;`ErrTerminalBusy` → `-32003`;等
|
||||
`OnTerminalReady`(带超时 → `-32001`);非 PTY → `-32005`(M4c 收紧)。
|
||||
2. 下发:行尾按 `isPTY`/平台(设计 §6.4 的表);`hub.SendToTerminal`。
|
||||
3. 清洗三段**整体移植**:`StripEchoedInput` → `StripAnsi` → `StripSentinelText`
|
||||
(对应 MFC `McpServer.cpp:3946-4040`),顺序不可换。Go 侧用表驱动单测锁住行为。
|
||||
4. 等待与交付:`done`/`closed`/超时三分支;超时**不销毁会话**,`delivered` 游标支持
|
||||
`terminal_exec` 不带 `command` 的轮询;`max_output_bytes` 按行截断(保留换行)并置
|
||||
`truncated`(防止把 UTF-8/GBK 多字节字符切坏)。
|
||||
5. 返回体:`{session_id, output, exit_code?, done, offset, truncated, is_pty, reused}`。
|
||||
|
||||
**单测**(表驱动,样例来自 MFC 实测)
|
||||
`rem hello`、`cmd /c echo abc`、`type .env`、SPAM 循环、`ping -n 30` 超时后轮询、
|
||||
`cmd /\c` 折行回显、退出码 0/1 与非 PTY 单行哨兵。
|
||||
|
||||
**集成**(假设备,§4.2):模拟 `TOKEN_TERMINAL_START` → 输出 → 哨兵,断言 `exit_code`。
|
||||
|
||||
### M4c 关闭、回收与老客户端(设计 §6.2、§6.7)
|
||||
|
||||
1. `terminal_close`:**幂等**(会话不存在也 200);只关 MCP 自己创建的会话(`hub.CloseTerminalSession`
|
||||
只有在会话表里有该设备且 `hub.TerminalIsPTY` 一致时才调用,避免误关浏览器会话——实现上
|
||||
以"会话表命中"为准)。
|
||||
2. 在途命令被 `terminal_close` 撞上:对齐 C++ 的 `waiters` 教训(`McpServer.cpp:12611`)——
|
||||
置 `closed` 唤醒等待者交付剩余缓冲,无等待者则立即擦会话并 `CloseTerminalSession`。
|
||||
3. 空闲回收 ticker 30s 扫一次,`lastUsed > TermIdle` 关闭;`Close()` 关掉全部会话。
|
||||
4. 非 PTY(`TOKEN_SHELL_START`)→ `terminal_exec` 直接 `-32005`,message 写明"该客户端版本
|
||||
不支持 PTY 会话"。不支持 shell 的客户端不设能力门,超时文案带一句提示(设计 §6.7)。
|
||||
|
||||
**测试**:closing 幂等;关闭后立刻重开 <1s;空闲回收(把 `TermIdle` 调成 100ms);
|
||||
在途关闭与无等待者两条分支(各一个用例)。
|
||||
|
||||
### M5 `get_screenshot`(设计 §7)
|
||||
|
||||
**新增** `mcp/screen.go`;`protocol/commands.go` 加 `CommandScreenPreviewReq=247`、
|
||||
`TokenScreenPreviewRsp=248`;`cmd/main.go` `OnReceive` 加两个 case 转 `mcp.OnPacket`。
|
||||
|
||||
1. 请求表 `map[deviceID]*pendingPreview{reqID uint16; ch chan []byte}`,
|
||||
`reqID` 用 `atomic.Uint32` 取低 16 位;**响应 reqID 不匹配直接丢弃**(对齐 MFC
|
||||
`TakePreviewResponse`)。
|
||||
2. 能力门:缺 `protocol.ClientCapScreenPreview` → `-32005`。
|
||||
3. 8 字节请求体;`max_width` 钳制 `[64,1920]`、缺省/0 → 1024;`jpegQuality` 固定 80。
|
||||
4. 响应:`status != 0` → 1/2 `-32000`、3 `-32005`、4 `-32602`;`format=0` 直接返回 JPEG,
|
||||
`format=3`(BGRX)→ 先 `image.RGBA` 再 `jpeg.Encode`;`bytes != w*h*4` 视为畸形包 `-32000`。
|
||||
5. 超时 8s,超时删表项,**不 CancelIO**(主连接 RPC,MFC 同款)。
|
||||
6. 返回 `content[]` 一项 `image`(base64 JPEG)+ `structuredContent{width,height,bytes,format,source}`。
|
||||
|
||||
**测试**:JPEG 魔数(`FF D8 FF`)、BGRX→JPEG 像素抽样、reqID 错包被丢弃、status 映射、
|
||||
超时。
|
||||
|
||||
### M6 `list_files`(设计 §5.3、§8.1)
|
||||
|
||||
**新增** `mcp/filemgr.go`;`protocol` 加 `CommandListDrive=1`、`CommandListFiles=2`、
|
||||
`TokenDriveList=103`、`TokenFileList=104`、`TokenFileListError=171`(**加一个常量唯一性单测**:
|
||||
新值不得与既有 `protocol` 常量重复,`103/104` 紧邻 `TOKEN_LOGIN=102`,值写错会吃主连接登录包)。
|
||||
|
||||
1. 主连接 `hub.SendToDevice(dev, []byte{CommandListDrive})`;等文件子连接:在
|
||||
`OnReceive` 顶部(终端 short-circuit 之后)先喂 `mcp.OnPacket(ctx, data)`,`mcp` 按
|
||||
`ctx.GetInfo().ClientID` 找到 pending 请求并**记住 ctx**(后续 `COMMAND_LIST_FILES` 要用它)。
|
||||
2. `TOKEN_DRIVE_LIST` 到达后**不关子连接**,同一 ctx 下发 `[CommandListFiles][path\0]`;
|
||||
`TOKEN_FILE_LIST` / `TOKEN_FILE_LIST_ERROR` 才收尾。
|
||||
3. 解析按设计附录 A;`attr & 0x10` 判目录;文件名 `protocol.DecodeClientString(data, capability, "")`。
|
||||
4. 错误映射:`win32err ∈ {2,3}` → `-32009`;`5` → `-32010`;其它 → `-32000`。
|
||||
老客户端无 `TOKEN_FILE_LIST_ERROR` → 超时;message 提示"路径可能不存在,先列目录确认"。
|
||||
5. 收尾:`COMMAND_BYE` → 500ms → `ctx.Close()`(`hub` 同款优雅关闭)。
|
||||
|
||||
**测试**:盘符/文件/错误三种黄金字节(照 MFC `ParseDriveList`/`ParseFileList` 的样例抓真实包,
|
||||
存为 `testdata/*.bin`);`offset/limit` 语义;客户端中途断开 → `-32001` 且 pending 表被清。
|
||||
|
||||
### M7 `read_file`(设计 §5.4、§8.2-§8.3)
|
||||
|
||||
**新增** `mcp/filev2.go`;`protocol` 加 `CommandSendFileV2=85`、`CommandFileCompleteV2=91`、
|
||||
`CmdDownFilesV2=94`;`cmd/main.go` 加两个 case。
|
||||
|
||||
1. 流程:列盘(复用 M6 的子连接)→ 同一子连接发 `[CmdDownFilesV2][targetDir\0][path\0][\0]`
|
||||
→ 服务端关掉文件子连接 → 客户端建 V2 子连接(`ConnAuth` 已钉 `ClientID`)→
|
||||
`COMMAND_SEND_FILE_V2 × N` → `COMMAND_FILE_COMPLETE_V2`。
|
||||
2. `targetDir := os.MkdirTemp("", "yama-mcp-read-*")`,`defer os.RemoveAll`。
|
||||
3. **大小门**:首个 chunk 的 `fileSize` 超 `ReadMax` → 立即中止、删目录、`-32602`
|
||||
(不要先落盘再报错)。
|
||||
4. **路径校验**(安全,必须单测):`filepath.Clean(filepath.Join(targetDir, FromSlash(name)))`
|
||||
+ `filepath.Rel` 判越界;另拒 NUL / 换行;`name` 允许客户端回填为相对路径。
|
||||
5. SHA-256 校验(完成包 32 字节)→ 编码判定(BOM → `utf8.Valid` → 回退
|
||||
`simplifiedchinese.GBK`,`latin1` 逐字节)→ 按行切分并取
|
||||
`offset`/`limit`/`max_bytes` 窗口 → 返回
|
||||
`{path,size,encoding,eol,lines_total,offset,lines_returned,truncated,text,sha256}`。
|
||||
6. 超时/断流:`-32001`;工具描述写明"超时可能是不支持 V2 的旧客户端"(设计 R3)。
|
||||
|
||||
**测试**:路径穿越用例集(`../x`、`..\\..\\x`、绝对路径、UNC、混合分隔符、`a/../../b`);
|
||||
大小门;SHA 不符;GBK 文件;负 offset;`transferID` 不匹配的迟到 chunk 被丢弃。
|
||||
|
||||
### M8 校验工具与文档(设计 §10)
|
||||
|
||||
1. `verify_tools.py --subset <tools.json> [token] [port] [--readonly]`:
|
||||
抓 Go 服务端 `tools/list`,与 `tools.json` 同名工具逐字段比 `description` / `inputSchema` /
|
||||
`outputSchema`(与 `verify_tools.py` 的 `FIELDS` 口径一致);名字集合必须恰好等于
|
||||
期望的 9(或 7),多一个少一个都失败。
|
||||
2. 同批更新:`deploy/yama-server.env.example` 加 `YAMA_MCP_TOKEN` / `YAMA_MCP_READONLY` /
|
||||
`YAMA_MCP_TERM_IDLE` / `YAMA_MCP_MAX_CONCURRENCY` / `YAMA_MCP_READ_MAX`;
|
||||
设计文档状态改"已实施"。
|
||||
|
||||
---
|
||||
|
||||
## 4. 测试与验证
|
||||
|
||||
### 4.1 三档测试
|
||||
|
||||
| 档 | 跑什么 | 覆盖 | 何时跑 |
|
||||
|---|---|---|---|
|
||||
| 1 纯函数单测 | 清洗三段、哨兵、环形缓冲、解析器、路径校验、schema 校验、JSON-RPC | 全部逻辑分支 | 每次提交 |
|
||||
| 2 假设备集成(进程内) | 真 `hub` + 假设备 ctx + `httptest` 的 `/mcp` | 九工具端到端、并发、取消、审计 | 每次提交 |
|
||||
| 3 真客户端 smoke | `x64\Debug\ghost.exe`(§4.3)或 Linux ghost → 本机 Go 服务端 | 真实 PTY/文件/截屏链路 | 每个里程碑收尾 + 整体验收 |
|
||||
|
||||
档 2 是主力:不依赖网络、可在 CI 跑,且能精确控制入站包的字节。
|
||||
|
||||
### 4.2 假设备 harness(`mcp/harness_test.go`)
|
||||
|
||||
```go
|
||||
h := hub.New()
|
||||
sent := make(chan []byte, 16) // 出站包,带缓冲 channel 避免数据竞争
|
||||
h.SetSender(func(ctx *connection.Context, data []byte) error {
|
||||
sent <- append([]byte(nil), data...); return nil
|
||||
})
|
||||
cfg := logger.DefaultConfig(); cfg.Level = logger.LevelError
|
||||
mcpSrv := mcp.New(mcpCfg, h, history, logger.New(cfg))
|
||||
unsubscribe := h.Subscribe(mcpSrv) // Subscribe 返回退订闭包(hub 没有 Unsubscribe 方法)
|
||||
ts := httptest.NewServer(http.HandlerFunc(mcpSrv.Handle))
|
||||
// 假设备:拿到 sent 里的 COMMAND_SHELL 后,模拟回 TOKEN_TERMINAL_START 与输出:
|
||||
mcpSrv.OnPacket(devCtx, append([]byte{protocol.TokenTerminalStart}, ...))
|
||||
h.PublishTerminalData(devID, []byte("hello\r\n__MCP_DONE_ab12cd__0\r\n"))
|
||||
```
|
||||
|
||||
要点:
|
||||
- 造设备:`h.Register(&hub.Device{ID:"dev", PeerIP:"10.0.0.1"}, devCtx)`;
|
||||
`devCtx` 的 `Info.ClientID` 按子连接需要设置(模拟 `handleConnAuth` 的钉值)。
|
||||
- `sent` 用带缓冲 channel(上面写法),测试里 `select` 带超时地读,不 sleep。
|
||||
- 收尾:`defer unsubscribe()` + `defer mcpSrv.Close()`;再断言没有残留会话
|
||||
(`mcpSrv.SessionCount()==0`,为此在会话表上留一个只读访问器给测试用)。
|
||||
|
||||
### 4.3 真客户端 smoke(M0 已实测,2026-11-12)
|
||||
|
||||
**结论:Windows 真客户端用 `x64\Debug\ghost.exe`,`TestRun.exe` 不可用。**
|
||||
|
||||
- `test.cpp` 用 `MemoryDllRunner` 加载同目录的 `ServerDll.dll`(`client/test.cpp:448`);
|
||||
没有它时静默每 3 秒重试,Go 侧也没有这条内存 DLL 链路。
|
||||
- Release `TestRun.exe` 从非安装路径启动时 `RegisterStartup()` 返回 0 → `self_del()`
|
||||
自删(`client/test.cpp:323-334`);M0 第一次尝试确实删掉了 `release\TestRun.exe`,
|
||||
已用 Release 重建恢复(359936 → 425472 字节)。`-cmd=0` 绕不过安装流程。
|
||||
- Release `ghost.exe` 同样会走安装流程(dst = `%ProgramData%\Windows Ghost\WinGhost.exe`),
|
||||
因此本机测试统一用 Debug ghost:`RegisterStartup` 在 `_DEBUG` 下直接返回 1(`reg_startup.c:413`)。
|
||||
|
||||
**M0 实测记录**:
|
||||
|
||||
- 服务端 `Bin\YamaGo_x64.exe -port 16543 -http-port 18090`(18080 被 python/wslrelay 占用),
|
||||
`YAMA_DEVICES_FILE` 指向临时文件;默认签名模式 **TRIAL**(`https://web.just-do-it.icu:8080`)。
|
||||
- `x64\Debug\ghost.exe 127.0.0.1 16543` → 10 秒内设备上线:
|
||||
`event=device.online computer=A6/default device_id=445427540237756328 os="Windows 11"`,
|
||||
`devices.json` 写入 `first_seen/last_seen`,服务端无错误日志。
|
||||
- 清理:Debug ghost 的 `SetSelfStart` 会在 `HKCU\...\Run` 写一条哈希名,按运行前快照删除新增项;
|
||||
用户既有的 `Client Demo` 计划任务与 `C:\ProgramData\Client Demo\ClientDemo.exe` 未被改动。
|
||||
- 待办:trial 签名下客户端是否解锁屏幕/文件能力,要在 M5/M6 端到端确认
|
||||
(`YAMA_LICENSE_DISABLED=1` 的 NoOp 已知会被客户端拒绝)。
|
||||
|
||||
```powershell
|
||||
cd C:\github\YAMA
|
||||
.\build.ps1 -GoServer -Config Debug
|
||||
$msb = "C:\Program Files\Microsoft Visual Studio\18\Insiders\MSBuild\Current\Bin\MSBuild.exe"
|
||||
& $msb client\ghost_vs2015.vcxproj -p:Configuration=Debug -p:Platform=x64 -p:SolutionDir=C:/github/YAMA/ -m -v:m
|
||||
$env:YAMA_MCP_TOKEN="<32hex>"; $env:YAMA_DEVICES_FILE="$env:TEMP\yama_m0\devices.json"
|
||||
Start-Process .\Bin\YamaGo_x64.exe -ArgumentList '-port','16543','-http-port','18090'
|
||||
Start-Process .\x64\Debug\ghost.exe -ArgumentList '127.0.0.1','16543'
|
||||
curl -s -X POST localhost:18090/mcp -H "Authorization: Bearer $env:YAMA_MCP_TOKEN" ...
|
||||
```
|
||||
|
||||
注意:Debug ghost 的 `Mprintf` 走 `TRACE`(`common/logger.h:379`),客户端侧没有日志文件,
|
||||
验收以服务端 audit/日志为准。
|
||||
|
||||
### 4.4 与 MFC 的对照验收
|
||||
|
||||
同一批命令在两个后端各跑一遍,比对 `exit_code` 与清洗后的文本(不一致就是移植缺陷):
|
||||
|
||||
```
|
||||
sc query AssemblyManager rem hello cmd /c echo abc
|
||||
type C:\...\.env ping -n 30 127.0.0.1 for /L %i in (1,1,1000000) do @echo SPAM-%i
|
||||
```
|
||||
|
||||
### 4.5 每个提交前必跑
|
||||
|
||||
```bash
|
||||
cd server/go
|
||||
gofmt -l . ; go vet ./... ; go test ./... ; go test -race ./mcp/...
|
||||
go build ./cmd
|
||||
```
|
||||
|
||||
MFC 侧测试:M0–M8 的改动全在 `server/go`、`tools/mcp_tools` 与文档,**没有触碰任何
|
||||
C++ / 客户端文件**(`git diff --name-only 5f124fc..HEAD` 可证),因此原计划的
|
||||
`verify_live_6555.py` 回归没有对象。注意:本机在跑的 Release `Yama_x64.exe` 是更早的
|
||||
构建(`tools/list` 仍是 `list_online_hosts` 旧名),按约束未重启它;这与本次改动无关,
|
||||
也不影响上述结论。
|
||||
|
||||
---
|
||||
|
||||
## 5. 整体验收(对齐设计 §11)
|
||||
|
||||
验收日期 2026-11-12。现场:`Bin\YamaGo_x64.exe -port 16543 -http-port 18090` +
|
||||
`x64\Debug\ghost.exe`(Windows 11)+ WSL Ubuntu 24.04 ghost,临时 token/devices/audit。
|
||||
|
||||
- [x] 9 个工具全部可调用;`tools/list` 响应 < 24 KB
|
||||
—— 22578 B(只读 18288 B);九个工具逐一实调通过
|
||||
- [x] `terminal_exec` 连续 20 条命令零失败;超时后轮询取回完整输出
|
||||
—— 同一会话 20 条 `echo ACCEPT_n` 全部取回哨兵(M4b 另有超时轮询实测)
|
||||
- [x] 浏览器开着终端时 `terminal_exec` → `-32003`,人的会话不受影响
|
||||
—— `session_test.go:192` 证明浏览器持租约时返回 `ErrTerminalBusy`,
|
||||
`tools_term.go:273` 映射为 `-32003`;另有 `terminal_close` 不动浏览器租约的用例
|
||||
- [x] `read_file` 读 `.env` 字节级一致,SHA-256 与远端 `sha256sum` 相同
|
||||
—— Windows 与 WSL 两边分别实测(M7);本轮 CRLF/单引号样本再验一次
|
||||
- [x] `get_screenshot` Windows / Linux 各一张,Linux 走 BGRX→JPEG
|
||||
—— Windows 1024x304 JPEG 本轮实测;Linux 在 M5 实测(WSLg 下画面全黑是
|
||||
Xwayland 的已知限制,屏幕子连接与 BGRX→JPEG 链路本身通过)
|
||||
- [x] 审计每次 `mcp.tool.call` 一条,`device`/`tool`/`code`/`ms` 齐全
|
||||
—— 本轮 30 条,样例含 `"device"`/`"tool"`/`"code"`/`"ms"`
|
||||
- [x] `verify_tools.py --subset` 通过(9 个 / 只读 7 个两种模式)
|
||||
—— 读写 9、`YAMA_MCP_READONLY=1` 7 均 PASS;两种反向错配均按预期 FAIL
|
||||
- [x] `go test -race ./mcp/...` 无数据竞争
|
||||
- [ ] `hub` 零改动 —— **不成立且不可取**:`hub` 新增 `SendToConn`(M6,往任意子连接
|
||||
回包必须走编码器)与终端租约代数 `terminalGen` / `OpenTerminalSessionLease`
|
||||
(M4a,防止失去租约的查看者关掉别人的 shell)。两项都是设计遗漏、实现阶段补的,
|
||||
均有单测;`hub` 原有对外行为不变。
|
||||
|
||||
---
|
||||
|
||||
## 6. 风险(在设计 R1-R8 之上新增)
|
||||
|
||||
| # | 风险 | 影响 | 处置 |
|
||||
|---:|---|---|---|
|
||||
| R9 | `OnTerminalData` 在 TCP 读循环上阻塞 | 整个设备通道卡死(浏览器画面/终端一起停) | 只做内存追加与唤醒;缓冲满丢最旧;禁止在回调里调用 `hub` 的会加锁方法 |
|
||||
| R10 | 文件子连接 ctx 生命周期 | 客户端中途断开 → 后续发送到已关闭 ctx / pending 表泄漏 | pending 表带超时与 `OnDisconnect` 清理;发送失败即失败收尾 |
|
||||
| R11 | `103/104` 常量与主连接 token 相邻 | 值写错会把登录包当文件列表(反之亦然) | 常量唯一性单测 + 解析前校验最小长度 |
|
||||
| R12 | Windows 路径与 `filepath.Rel` | 路径穿越(被控端写主控任意位置) | 单测覆盖 `..`/绝对路径/UNC/混合分隔符;拒 NUL 与换行 |
|
||||
| R13 | 客户端断开(`r.Context()`)后锁未释放 | 设备永久 `-32003` | `defer` 释放;单测用 cancel 验证 |
|
||||
| R14 | 单测 goroutine 泄漏 | `-race` 偶发失败 | `Close()` 幂等;测试里 `defer Close()` |
|
||||
| R15 | 真机 smoke 用 Debug ghost,与 Release 客户端有差异 | 安装/许可行为可能在 Release 上不同,本地验收未覆盖 | M0 已确认 Debug ghost 可上线;M5/M6 用 trial 签名验证屏幕/文件能力;交付说明写明该差异 |
|
||||
|
||||
---
|
||||
|
||||
## 7. 工时估算
|
||||
|
||||
| 里程碑 | 编码 | 测试 | 小计 |
|
||||
|---|---:|---:|---:|
|
||||
| M1 | 3h | 3h | 6h |
|
||||
| M2 | 6h | 4h | 10h |
|
||||
| M3 | 2h | 2h | 4h |
|
||||
| M4a | 4h | 2h | 6h |
|
||||
| M4b | 5h | 3h | 8h |
|
||||
| M4c | 1h | 1h | 2h |
|
||||
| M5 | 4h | 2h | 6h |
|
||||
| M6 | 5h | 3h | 8h |
|
||||
| M7 | 6h | 4h | 10h |
|
||||
| M8 | 2h | 1h | 3h |
|
||||
| 整体联调 + 真机验收 | — | — | 6h(含在 §5) |
|
||||
| **合计** | **38h** | **25h** | **≈63h ≈ 8 人日** |
|
||||
|
||||
---
|
||||
|
||||
## 附录 A:`protocol/commands.go` 新增常量
|
||||
|
||||
| 常量 | 值 | 方向 | 里程碑 |
|
||||
|---|---:|---|---|
|
||||
| `CommandListDrive` | 1 | S→C 主连接 | M6 |
|
||||
| `CommandListFiles` | 2 | S→C 文件子连接 | M6 |
|
||||
| `CommandSendFileV2` | 85 | C→S V2 子连接 | M7 |
|
||||
| `CommandFileCompleteV2` | 91 | C→S V2 子连接 | M7 |
|
||||
| `CmdDownFilesV2` | 94 | S→C 文件子连接 | M7 |
|
||||
| `TokenDriveList` | 103 | C→S 文件子连接 | M6 |
|
||||
| `TokenFileList` | 104 | C→S 文件子连接 | M6 |
|
||||
| `TokenFileListError` | 171 | C→S 文件子连接 | M6 |
|
||||
| `CommandScreenPreviewReq` | 247 | S→C 主连接 | M5 |
|
||||
| `TokenScreenPreviewRsp` | 248 | C→S 主连接 | M5 |
|
||||
|
||||
## 附录 B:环境变量
|
||||
|
||||
| 变量 | 默认 | 说明 | 引入里程碑 |
|
||||
|---|---|---|---|
|
||||
| `YAMA_MCP_TOKEN` | 空(端点不注册) | 32 位十六进制静态令牌 | M1 |
|
||||
| `YAMA_MCP_READONLY` | 0 | 隐藏 `terminal_exec` / `terminal_close` | M1 |
|
||||
| `YAMA_MCP_TERM_IDLE` | 180 | 终端会话空闲回收秒数 | M4c |
|
||||
| `YAMA_MCP_MAX_CONCURRENCY` | 16 | 全局并发上限 | M3 |
|
||||
| `YAMA_MCP_READ_MAX` | 2097152 | `read_file` 大小门(字节) | M7 |
|
||||
|
||||
## 附录 C:提交前自检清单(每个里程碑)
|
||||
|
||||
1. `gofmt -l .` 无输出;`go vet ./...` 干净。
|
||||
2. `go test ./...` 与 `go test -race ./mcp/...` 全绿。
|
||||
3. 新增的每个错误码都有触发它的单测(错误码不是装饰)。
|
||||
4. 新增的每条审计事件都能在临时审计文件里被 `get_audit_log` 查到。
|
||||
5. 提交标题用 `Feature(Go):` / `Fix(Go):`,正文说明"为什么",trailer 用当前会话模型名。
|
||||
6. 未推送前发现问题用 `--amend`/squash,不堆补丁提交。
|
||||
@@ -1,6 +1,6 @@
|
||||
# 传输层单向 TLS 加密设计(按需加密)
|
||||
|
||||
> 版本:v0.8 · 状态:**Go 服务端 + Windows/Linux/Android 客户端已实现并验证;Linux/Android 客户端支持下发即时热切换;MFC 主控端见 `TransportTLS_MFCServer_Design.md`;macOS 未接入** · 日期:2026-11-11(Android 客户端接入 + 热切换)
|
||||
> 版本:v0.9 · 状态:**Go 服务端 + Windows/Linux/Android 客户端已实现并验证;Linux/Android 客户端支持下发即时热切换;macOS 客户端已按同一模式实现(2026-11-14,待 Mac 实机构建验证);MFC 主控端见 `TransportTLS_MFCServer_Design.md`** · 日期:2026-11-14(macOS 客户端接入)
|
||||
> 目标:让 YAMA 设备端口(TCP 6543)在继续兼容老客户端(明文/XOR)的同时,允许新客户端在拿到证书后按需开启**单向 TLS** 加密传输。
|
||||
> 本期范围:**Go 服务端(`server/go`)+ Windows 客户端 + Linux 客户端 + Android 客户端**。
|
||||
>
|
||||
@@ -23,8 +23,7 @@
|
||||
- 不做 **mTLS / 客户端证书**:单向 TLS 不验证客户端证书,客户端身份仍由隧道内的现有登录(`PwdHmac` V1 / `ECDSA` V2)承担。
|
||||
- 不做传输层 PSK(`YAMA_TRANSPORT_KEY`)方案——本设计改用证书,更贴合「颁发证书」的运维模型。
|
||||
- 不改应用层协议(flag 帧格式 / XOR / zstd),不做「TLS 内去掉 XOR」的二次精简(后续可选)。
|
||||
- Windows 客户端**不做**加密开关的运行时热切换(证书只在进程启动时读取一次,改配置需重启——这正是需求)。Linux / Android 客户端例外:服务端下发 166/167 后立即重载信任锚并重连切换(§6.6 / §6.7),语义差异见该两节。
|
||||
- macOS 客户端的 TLS 接入不在本期(Linux / Android 客户端已按同一模式接入,见 §6.6 / §6.7)。
|
||||
- Windows 客户端**不做**加密开关的运行时热切换(证书只在进程启动时读取一次,改配置需重启——这正是需求)。Linux / Android / macOS 客户端例外:服务端下发 166/167 后立即重载信任锚并重连切换(§6.6 / §6.7 / §6.8),语义差异见该三节。
|
||||
- 不做 **MFC 服务端(`server/2015Remote`)的 TLS 接入**——本期只做 Go 服务端(`server/go`),MFC 主控端延后到阶段 3。
|
||||
|
||||
## 2. 现状与复用
|
||||
@@ -194,6 +193,8 @@ Linux 无注册表,信任锚按:① `$XDG_CONFIG_HOME/ghost/yama-ca.pem`(
|
||||
|
||||
Android 同样无注册表,信任锚为 App 私有 `context.filesDir/yama-ca.pem`(目录由 `TlsSetAnchorDir()` 在 `nativeInit` 注入,见 §6.7),无程序目录回退;存在即视为已配置、fail-closed。与 Linux 共用 `client/TlsChannelLinux.cpp` 实现。
|
||||
|
||||
macOS 无注册表,信任锚为 `~/.config/ghost/yama-ca.pem`(与 `macos/main.mm` 的 `config.conf` 同目录;**不看 `XDG_CONFIG_HOME`**,保持与 macOS 客户端既有配置路径一致)→ ② 程序目录(`_NSGetExecutablePath`)`yama-ca.pem`。存在即视为已配置、fail-closed。与 Linux/Android 共用 `client/TlsChannelLinux.cpp` 实现(见 §6.8)。
|
||||
|
||||
### 6.2 TLS 栈选型(已定:Schannel)
|
||||
|
||||
- **已选 Schannel(Windows 原生 SSPI)**:零第三方依赖/零额外 DLL 部署,`secur32.lib`/`crypt32.lib` 均为系统库(`secur32.lib` 已在 `CFFmpegH264Encoder.cpp:38` 链接)。
|
||||
@@ -230,7 +231,7 @@ Schannel 流模式(`ISC_REQ_STREAM`)下,`DecryptMessage` 会把输入的
|
||||
### 6.6 Linux 客户端实现(OpenSSL,2026-10-28)
|
||||
|
||||
- **选型**:OpenSSL(`libssl`)。Linux 构建早已因 `libsign.a` 链接 `libcrypto`,只多链一个 `OpenSSL::SSL`,不引入新的运行时依赖包(同一 OpenSSL 3 包提供 `libcrypto.so.3` / `libssl.so.3`)。
|
||||
- **代码组织**:`client/TlsChannel.h` 按平台分派(`_WIN32` → Schannel,`__linux__` → OpenSSL,含 Android,见 §6.7),Windows 分支内容不变;实现文件为 `client/TlsChannelLinux.cpp`。`YAMA_TLS_CHANNEL` 宏标注「本平台有 TLS 通道」,`IOCPClient` 用它替代原先的 `#ifdef _WIN32`,因此主连接与子连接共用同一接线点。macOS 不定义该宏,维持明文。
|
||||
- **代码组织**:`client/TlsChannel.h` 按平台分派(`_WIN32` → Schannel,`__linux__`(含 Android,见 §6.7)与 `__APPLE__`(macOS,见 §6.8)→ OpenSSL),Windows 分支内容不变;实现文件为 `client/TlsChannelLinux.cpp`。`YAMA_TLS_CHANNEL` 宏标注「本平台有 TLS 通道」,`IOCPClient` 用它替代原先的 `#ifdef _WIN32`,因此主连接与子连接共用同一接线点。
|
||||
- **语义对齐**:`TLS 1.2` 钉扎(min=max,与 `SP_PROT_TLS1_2_CLIENT` 及两套服务端一致);单向 TLS、不提供客户端证书、不校主机名、不做吊销检查;`SSL_VERIFY_PEER` + 只含信任锚的 `X509_STORE`(不含系统根库,严格钉扎),握手内完成链校验,失败即断开(fail-closed)。
|
||||
- **缓冲差异**:OpenSSL 自己管理记录缓冲,不需要 Schannel 的 `m_raw`/`m_pending`;一次 `SSL_read` 交付不完的明文留在 `SSL` 内部,接收线程在 `select` 前用 `SSL_pending() || SSL_has_pending()` 优先消费,否则剩余字节会被 2 秒 `select` 超时卡住。
|
||||
- **下发/撤销**:`COMMAND_TLS_ENABLE`(166) 的 PEM 正文写入 `~/.config/ghost/yama-ca.pem`(目录 0700、文件 0600、临时文件 + rename 原子替换);`COMMAND_TLS_DISABLE`(167) 删除该文件(含程序目录同名回退文件)。写入前先用 OpenSSL 解析一遍,不是合法证书就整包拒绝并保留原状态。
|
||||
@@ -241,7 +242,7 @@ Schannel 流模式(`ISC_REQ_STREAM`)下,`DecryptMessage` 会把输入的
|
||||
- 热重载遇到坏锚时**保留原状态**并记日志,不把正在工作的客户端打死(下次启动仍按 fail-closed 语义)。
|
||||
- 重连由 `DataProcess`(接收线程)只置 `g_needReconnect` 标志,由主心跳线程 `Disconnect()` 后走外层重连循环——避免在接收线程里关 socket 与主线程发送竞争。
|
||||
- **代价**:此刻若正处于远程桌面/文件传输会话,主连接重建会中断该会话(子连接随之失效)。这是「立即生效」的固有代价。
|
||||
- **上报**:登录 `szReserved[19]`(`RES_TLS`)填 `TlsEnabled() ? 1 : 0`,主控端主机信息显示 Y/N。热切换后重连会重新登录,登录前用 `RefreshLoginTls()` 刷新该字段,主控端在线列表的 TLS 列随之翻转。
|
||||
- **上报**:登录 `szReserved[19]`(`RES_TLS`)填 `TlsEnabled() ? 1 : 0`,主控端主机信息显示 Y/N。热切换后重连会重新登录,登录前用 `RefreshLoginTls()` 刷新该字段,主控端在线列表的 TLS 列随之翻转。Android 同。
|
||||
|
||||
### 6.7 Android 客户端实现(OpenSSL,2026-11-11)
|
||||
|
||||
@@ -252,6 +253,22 @@ Schannel 流模式(`ISC_REQ_STREAM`)下,`DecryptMessage` 会把输入的
|
||||
- **OpenSSL 构建**:Android 的 `libsign.a` 用便携纯 C SHA256、不含 OpenSSL,故需新交叉编译 `libssl.a`/`libcrypto.a`。`android/build_openssl_android.sh`(已并入 `build_android_libs.ps1`,可 `-OpenSslOnly` 单跑)用 NDK clang + MSYS2 perl/make 按 ABI(arm64-v8a / armeabi-v7a / x86 / x86_64,API 21)构建 OpenSSL 3.5.0 静态库(`no-shared no-apps no-legacy` 等裁剪);产物落 `app/src/main/cpp/lib/<ABI>/`,`opensslconf.h` 各架构不同故头文件也按 ABI 存放。CMake 链接 `libssl.a`+`libcrypto.a`,并用 `-Wl,--exclude-libs,ALL` 不让静态库符号泄出 `libyama.so`(与 Java 层 Conscrypt 隔离;JNI 入口来自目标文件,不受影响)。
|
||||
- **Windows 构建坑(已解决)**:Git for Windows 的精简 perl 缺 Configure 所需模块,且其 bash/env 会抢占 PATH——跨 MSYS 运行时传子进程丢环境变量(Configure 拿不到 `ANDROID_NDK_ROOT`),脚本改用 `#!/bin/bash` 并把 MSYS2 `/usr/bin` 置顶;NDK 自带原生 make 不认 Makefile 里的 `/c/...` 路径,须用 MSYS2 make(`pacman -S make`)。
|
||||
|
||||
### 6.8 macOS 客户端实现(OpenSSL,2026-11-14)
|
||||
|
||||
- **选型 / 代码组织**:复用 Linux/Android 的 OpenSSL 实现。`client/TlsChannel.h` 的平台分支由 `__linux__` 放宽为 `__linux__ || __APPLE__`,`TlsChannelLinux.cpp` 的编译守卫同步放宽(该文件本就是 OpenSSL + POSIX,无 Linux 专有调用);`YAMA_TLS_CHANNEL` 随之在 macOS 生效,主连接/子连接共用与 Linux 相同的接线点(`IOCPClient`)。**服务端零改动**。
|
||||
- **平台差异点(都在 `TlsChannelLinux.cpp` 内条件编译)**:
|
||||
- **配置目录**:`ConfigDir()` 在 Apple 上**不读 `XDG_CONFIG_HOME`**,HOME 兜底顺序与 `macos/main.mm` 的 `initConfigPaths` 逐字对齐(`HOME` → `getpwuid()->pw_dir` → `/tmp`),最终都是 `<home>/.config/ghost`——否则信任锚和 `config.conf` 会落在两个目录(launchd daemon 不导出 `HOME` 时尤其明显:锚落到程序目录,重装 app bundle 时跟着被删,客户端静默退回明文而服务端仍以为它是 TLS)。
|
||||
- **程序目录回退**:`ExeDir()` 用 `_NSGetExecutablePath`(`<mach-o/dyld.h>`)截取目录;Linux 继续用 `/proc/self/exe`,Android 仍返回空。
|
||||
- **`SIGPIPE`**:`macos/main.mm` 启动时已 `signal(SIGPIPE, SIG_IGN)`(WSS 引入时加的),TLS 写入对端已关时不会直接杀掉进程。
|
||||
- **热切换接线(`macos/main.mm`)**:与 Linux 同一套语义。`DataProcess` 收到 `COMMAND_TLS_ENABLE`(166) → `TlsTrustAnchorSave()`;`COMMAND_TLS_DISABLE`(167) → `TlsTrustAnchorRemove()`;两者随后都走 `ApplyTlsAnchorChange()`:`TlsReload()` 重建 `SSL_CTX`,只在传输方式真的变化(明文↔TLS)时置 `g_needReconnect`(接收线程只置标志),主心跳循环每秒检查、`Disconnect()` 后由外层重连循环用新传输方式重连。仅换锚不打断现有会话。
|
||||
- **上报**:登录 `szReserved[19]`(`RES_TLS`)填 `TlsEnabled() ? 1 : 0`;重连登录前用 `RefreshLoginTls()` 刷新(`logInfo` 启动时填一次、之后复用)。顺带修掉一个既有缺陷:分组变更重发登录时 `fillLoginInfo()` 会被再次调用,而 `AddReserved()` 是追加语义,原先会把整套保留字段再拼一遍,导致服务端按 `LOGIN_RES` 下标读到错位/重复字段——现在 `fillLoginInfo()` 入口先清空 `szReserved`。
|
||||
- **构建(`macos/CMakeLists.txt` / `build.sh`)**:
|
||||
- 源码列表加入 `client/TlsChannelLinux.cpp`;链接 `OpenSSL::SSL`、`OpenSSL::Crypto`。
|
||||
- Homebrew 的 `openssl@3` 不在 CMake 默认搜索路径,`CMakeLists.txt` 自动探测 `/opt/homebrew/opt/openssl@3`(及其它常见前缀),找不到直接 `FATAL_ERROR` 并提示 `brew install openssl@3`,也可 `-DOPENSSL_ROOT_DIR=...` 指定。
|
||||
- 有静态库(`libssl.a`/`libcrypto.a`)时优先静态链接(`OPENSSL_USE_STATIC_LIBS`),避免发布包还得让目标 Mac 装 Homebrew OpenSSL;只有动态库时给 `WARNING`,需自行把 dylib 放进 `Contents/Frameworks`。
|
||||
- 目标为 **arm64 单架构**(Homebrew OpenSSL 只有本机架构,保留 x86_64 slice 会链接失败)、部署目标 macOS 11.0。`build.sh` 通过命令行显式传 `-DCMAKE_OSX_ARCHITECTURES=arm64 -DCMAKE_OSX_DEPLOYMENT_TARGET=11.0`——这两个是 CMake **cache 变量**,在已存在的 `build/` 目录里改了 `CMakeLists.txt` 也不会生效,必须命令行覆盖或删目录重建。
|
||||
- **注意**:macOS 客户端在线升级仍不支持(服务端 `OnOnlineUpdate` 无 MAC 分支),升级 TLS 相关代码需重新 `macos/build.sh` 并按 `macos/install.sh` 部署(会重置 TCC 授权)。
|
||||
|
||||
## 7. 兼容矩阵
|
||||
|
||||
| 客户端 | 服务端行为 | 结果 |
|
||||
@@ -337,6 +354,7 @@ Android 客户端:信任锚写入 App 私有 `filesDir/yama-ca.pem`(经 166/
|
||||
- **阶段 2(Windows 客户端)**:证书检测 + TLS 栈 + fail-closed。
|
||||
- **阶段 2b(Linux 客户端)**:OpenSSL 实现,复用同一接线点与协议语义(2026-10-28 完成)。
|
||||
- **阶段 2c(Android 客户端)**:复用 Linux OpenSSL 实现,NDK 按 ABI 交叉编译 OpenSSL,热切换(2026-11-11 完成)。
|
||||
- **阶段 2d(macOS 客户端)**:复用 Linux OpenSSL 实现(`__APPLE__` 分支 + `_NSGetExecutablePath`),Homebrew OpenSSL 静态链接,热切换(2026-11-14 完成代码,待 Mac 实机验证)。
|
||||
- **阶段 3(MFC 服务端 `server/2015Remote`,延后)**:与 Go 服务端同款的 TLS 检测 + 解包接入。设计稿见 `docs/TransportTLS_MFCServer_Design.md`。
|
||||
- **回滚**:服务端清空 `YAMA_TLS_CERT/KEY` 即回到纯明文;客户端删除注册表 `tls_cert` 值(或 `yama-ca.pem` 文件)即回明文。
|
||||
|
||||
@@ -345,4 +363,4 @@ Android 客户端:信任锚写入 App 私有 `filesDir/yama-ca.pem`(经 166/
|
||||
1. ~~客户端 TLS 栈最终选型~~ → **已定 Schannel**(见 §6.2,2026-10-13 落地)。
|
||||
2. ~~信任锚文件固定名(`yama-ca.pem`)是否需可配置~~ → **已改为注册表 `tls_cert` 值优先、文件回退**(见 §6.1/§9.3,2026-10-14)。
|
||||
3. 是否同步把「TLS 内去掉 XOR」列为后续精简项(当前保留 XOR,换取零协议改动)。
|
||||
4. ~~Linux / macOS / Android 客户端的 TLS 接入排期~~ → **Linux(2026-10-28)、Android(2026-11-11)已接入**(均 OpenSSL、支持热切换);macOS 待定(需 Security.framework 或自带 OpenSSL)。
|
||||
4. ~~Linux / macOS / Android 客户端的 TLS 接入排期~~ → **Linux(2026-10-28)、Android(2026-11-11)、macOS(2026-11-14)已接入**(均 OpenSSL、支持热切换)。
|
||||
@@ -112,7 +112,7 @@ Host 头同理:用**配置里的地址(域名)**,而不是解析后的 I
|
||||
| 有锚但加载失败(损坏/为空) | 拒绝连接(fail-closed)——管理员已「颁发」证书,不能静默回退明文 |
|
||||
| 无锚 + `PROTO_WS` | 明文(本来如此) |
|
||||
| 有锚 + `PROTO_WS` | **仍是明文**(显式选择的形态,见下) |
|
||||
| 平台无 TLS(macOS 未定义 `YAMA_TLS_CHANNEL`)+ `PROTO_WSS` | 直接断开并打日志:没有热切换路径,回退只会让人误以为在加密 |
|
||||
| 平台无 TLS(未定义 `YAMA_TLS_CHANNEL`)+ `PROTO_WSS` | 直接断开并打日志:没有热切换路径,回退只会让人误以为在加密 |
|
||||
| WS 握手失败 | 断开,`Mprintf` 里带上服务端返回的状态行 |
|
||||
|
||||
回退的判据是「本机**根本没有**信任锚」这一可观测状态,而不是握手中途失败——TLS 握手
|
||||
@@ -415,7 +415,7 @@ server {
|
||||
升级线程里才有。若这是硬性合规要求,需单独评估(本特性未改变这一点,只是让它的漏检更
|
||||
容易发生)。
|
||||
- 裸 `PROTO_WS` 是明文,只适合内网或回环(nginx 已在同一台机器上终止 TLS 的情形用 WSS 即可)。
|
||||
- macOS 客户端没有 TLS 实现,只能选 `PROTO_WS`(明文),走不了 443(Linux / Android 已有 TLS,见 `TransportTLS_Design.md` §6.6 / §6.7)。
|
||||
- macOS 客户端自 2026-11-14 起也有 TLS(与 Linux/Android 同一 OpenSSL 实现,见 `TransportTLS_Design.md` §6.8),WSS 与 Linux 行为一致;更早的 macOS 构建仍只能选 `PROTO_WS`(明文),走不了 443。
|
||||
- 经反代接入时地址只应填**一个域名**(多地址取第一个做 Host/SNI)。
|
||||
- 不改应用协议、不改 MCP、不改 Web 控制台。
|
||||
|
||||
|
||||
+30
-3
@@ -556,6 +556,13 @@ public:
|
||||
}
|
||||
break;
|
||||
|
||||
case COMMAND_SCREEN_KEYFRAME_REQ:
|
||||
// Web 屏幕墙恢复/新加入者请求:下一帧强制 IDR。只置标志,
|
||||
// 编码器实例归采集线程所有(COMMAND_SCREEN_KEYFRAME_REQ 与 CMD_QUALITY_LEVEL
|
||||
// 一样在屏幕子连接的接收线程上处理)。
|
||||
m_keyframeRequested.store(true);
|
||||
break;
|
||||
|
||||
case COMMAND_SCREEN_SET_CLIPBOARD:
|
||||
// 服务端设置剪贴板: [cmd:1][text:N]
|
||||
if (size > 1) {
|
||||
@@ -967,6 +974,9 @@ private:
|
||||
LinuxConfig m_config; // 配置持久化 (~/.config/ghost/config.conf)
|
||||
std::atomic<int> m_bFullScreen; // 全屏偏好(主控端下发,随 ScreenSettings 上报)
|
||||
std::atomic<int> m_bRemoteCursor; // 远程光标偏好(同上)
|
||||
// Web 端请求下一帧强制 IDR(COMMAND_SCREEN_KEYFRAME_REQ)。接收线程置位、
|
||||
// 采集线程消费:编码器实例只在采集线程里创建/销毁,接收线程不能直接碰。
|
||||
std::atomic<bool> m_keyframeRequested{false};
|
||||
|
||||
// H264 编码器
|
||||
std::unique_ptr<X264Encoder> m_h264Encoder;
|
||||
@@ -1068,6 +1078,18 @@ private:
|
||||
// 发送 H264 编码帧
|
||||
void SendH264Frame(bool forceKeyframe = false)
|
||||
{
|
||||
// 强制 IDR 请求在调用点已经 exchange 掉,只有真的把这一帧编出来才算消费成功。
|
||||
// 中途任何提前返回(抓屏失败 / 没连接 / 编码器开不起来 / 编码失败)都把它还回去,
|
||||
// 否则 Web 端要等编码器下一次自然 IDR(最长一个 GOP)才能解出画面。
|
||||
struct RearmOnFailure {
|
||||
std::atomic<bool>& flag;
|
||||
bool force;
|
||||
bool consumed;
|
||||
RearmOnFailure(std::atomic<bool>& f, bool force_)
|
||||
: flag(f), force(force_), consumed(false) {}
|
||||
~RearmOnFailure() { if (force && !consumed) flag.store(true); }
|
||||
} rearm(m_keyframeRequested, forceKeyframe);
|
||||
|
||||
if (!CaptureScreen(m_currFrame)) return;
|
||||
if (!m_client) return;
|
||||
|
||||
@@ -1096,7 +1118,7 @@ private:
|
||||
int result = m_h264Encoder->encode(
|
||||
m_currFrame.data(), 32, m_bmpHeader.biWidth * 4,
|
||||
m_bmpHeader.biWidth, m_bmpHeader.biHeight,
|
||||
&encodedData, &encodedSize, 1);
|
||||
&encodedData, &encodedSize, 1, forceKeyframe);
|
||||
|
||||
if (result != 0 || !encodedData || encodedSize == 0) {
|
||||
return;
|
||||
@@ -1117,6 +1139,7 @@ private:
|
||||
|
||||
memcpy(&packet[headerSize], encodedData, encodedSize);
|
||||
m_client->Send2Server((char*)packet.data(), packet.size());
|
||||
rearm.consumed = true;
|
||||
}
|
||||
|
||||
// 差异比较算法(支持 DIFF/RGB565/GRAY)
|
||||
@@ -1333,10 +1356,13 @@ private:
|
||||
if (algo != currentAlgo) {
|
||||
currentAlgo = algo;
|
||||
if (algo == ALGORITHM_H264) {
|
||||
// 切换到 H264,发送关键帧
|
||||
// 切换到 H264,发送关键帧;这一帧本身就是关键帧,
|
||||
// 挂起的强制 IDR 请求顺手清掉,别下一帧再打一次。
|
||||
m_keyframeRequested.store(false);
|
||||
SendH264Frame(true);
|
||||
} else {
|
||||
// 切换离开 H264,关闭编码器并发送完整帧
|
||||
m_keyframeRequested.store(false); // 关键帧请求对非 H264 无意义
|
||||
if (m_h264Encoder) {
|
||||
m_h264Encoder->close();
|
||||
m_h264Encoder.reset();
|
||||
@@ -1346,7 +1372,8 @@ private:
|
||||
} else {
|
||||
// 正常帧
|
||||
if (algo == ALGORITHM_H264) {
|
||||
SendH264Frame(false);
|
||||
// 服务端的强制 IDR 请求在这里消费:下一帧就是关键帧。
|
||||
SendH264Frame(m_keyframeRequested.exchange(false));
|
||||
} else {
|
||||
SendDiffFrame();
|
||||
}
|
||||
|
||||
+6
-1
@@ -165,12 +165,13 @@ public:
|
||||
* @param outData Output: pointer to encoded H264 data
|
||||
* @param outSize Output: size of encoded data
|
||||
* @param direction 1 = normal, -1 = vertical flip
|
||||
* @param forceKeyframe true = 本帧强制 IDR(服务端 COMMAND_SCREEN_KEYFRAME_REQ)
|
||||
* @return 0 on success, negative on error
|
||||
*/
|
||||
int encode(uint8_t* bgra, uint8_t bpp, uint32_t stride,
|
||||
uint32_t width, uint32_t height,
|
||||
uint8_t** outData, uint32_t* outSize,
|
||||
int direction = 1)
|
||||
int direction = 1, bool forceKeyframe = false)
|
||||
{
|
||||
if (!m_encoder || !m_picIn || !fn_x264_encoder_encode) {
|
||||
return -1;
|
||||
@@ -197,9 +198,13 @@ public:
|
||||
}
|
||||
|
||||
// Encode
|
||||
// Web 端新加入/恢复时服务端会发 COMMAND_SCREEN_KEYFRAME_REQ:把本帧标成 IDR,
|
||||
// 参考链立即重建,不必等 keyint_max(15 秒)后的下一个关键帧。
|
||||
m_picIn->i_type = forceKeyframe ? X264_TYPE_IDR : X264_TYPE_AUTO;
|
||||
x264_nal_t* pNal = nullptr;
|
||||
int iNal = 0;
|
||||
int encodeSize = fn_x264_encoder_encode(m_encoder, &pNal, &iNal, m_picIn, m_picOut);
|
||||
m_picIn->i_type = X264_TYPE_AUTO; // 只对这一帧有效
|
||||
|
||||
if (encodeSize < 0) {
|
||||
return -4;
|
||||
|
||||
+26
-10
@@ -9,6 +9,7 @@
|
||||
#include <string.h>
|
||||
#include <termios.h>
|
||||
#include <thread>
|
||||
#include <system_error> // std::system_error:SpawnSubConnWorker 捕获线程创建失败
|
||||
#include <fcntl.h>
|
||||
#include <atomic>
|
||||
#include <mutex>
|
||||
@@ -647,6 +648,26 @@ static void ActivityReportThread()
|
||||
g_activityReportsInFlight.fetch_sub(1, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
// 子连接 worker 的唯一启动点(与 macos/main.mm 的 SpawnSubConnWorker 同语义)。
|
||||
// 线程创建失败(RLIMIT_NPROC 到顶时 pthread_create 返回 EAGAIN/EPERM,std::thread
|
||||
// 构造抛 std::system_error)必须在这里接住:否则异常穿过 DataProcess 落到
|
||||
// OnServerReceiving 的 catch(...),日志里只剩一行笼统的
|
||||
// "[ERROR] OnServerReceiving catch an error",同一批 recv 里的其它完整包也会被丢弃。
|
||||
// 表现是「点了终端/桌面/文件毫无反应,连收到命令的日志都没有」。
|
||||
static void SpawnSubConnWorker(const char* name, void* (*entry)(void*))
|
||||
{
|
||||
Mprintf("** Received '%s' command, spawning worker ***\n", name);
|
||||
try {
|
||||
std::thread(entry, nullptr).detach();
|
||||
} catch (const std::system_error& e) {
|
||||
// pthread_create 的返回值被 libc++/libstdc++ 直接包进 error_code,errno 不可信
|
||||
Mprintf("*** spawn '%s' worker FAILED: %s (code=%d) ***\n",
|
||||
name, e.what(), e.code().value());
|
||||
} catch (const std::exception& e) {
|
||||
Mprintf("*** spawn '%s' worker FAILED: %s ***\n", name, e.what());
|
||||
}
|
||||
}
|
||||
|
||||
int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
|
||||
{
|
||||
if (szBuffer == nullptr || ulLength == 0)
|
||||
@@ -662,22 +683,17 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
|
||||
Mprintf("*** [%p] Received Bye-Bye command ***\n", user);
|
||||
g_bExit = S_CLIENT_EXIT;
|
||||
} else if (szBuffer[0] == COMMAND_SHELL) {
|
||||
std::thread(ShellworkingThread, nullptr).detach();
|
||||
Mprintf("** [%p] Received 'SHELL' command ***\n", user);
|
||||
SpawnSubConnWorker("SHELL", ShellworkingThread);
|
||||
} else if (szBuffer[0] == COMMAND_SCREEN_SPY) {
|
||||
std::thread(ScreenworkingThread, nullptr).detach();
|
||||
Mprintf("** [%p] Received 'SCREEN_SPY' command ***\n", user);
|
||||
SpawnSubConnWorker("SCREEN_SPY", ScreenworkingThread);
|
||||
} else if (szBuffer[0] == COMMAND_SYSTEM) {
|
||||
std::thread(SystemManagerThread, nullptr).detach();
|
||||
Mprintf("** [%p] Received 'SYSTEM' command ***\n", user);
|
||||
SpawnSubConnWorker("SYSTEM", SystemManagerThread);
|
||||
} else if (szBuffer[0] == COMMAND_LIST_DRIVE) {
|
||||
std::thread(FileManagerThread, nullptr).detach();
|
||||
Mprintf("** [%p] Received 'LIST_DRIVE' command ***\n", user);
|
||||
SpawnSubConnWorker("LIST_DRIVE", FileManagerThread);
|
||||
} else if (szBuffer[0] == COMMAND_QUERY_LOG) {
|
||||
// 与 Windows 端一致:回日志必须开子连接。服务端取走首包后 CancelIO 关的是
|
||||
// 子连接;若回在主连接上,被关掉的就是主连接本身。
|
||||
std::thread(ClientLogThread, nullptr).detach();
|
||||
Mprintf("** [%p] Received 'QUERY_LOG' command ***\n", user);
|
||||
SpawnSubConnWorker("QUERY_LOG", ClientLogThread);
|
||||
} else if (szBuffer[0] == COMMAND_QUERY_ACTIVITY) {
|
||||
// 历史活动:主连接一次性快照(无子连接),有桌面走窗口采样,无桌面走登录+命令记录。
|
||||
// 已经有报表在飞就丢掉这一次(服务端每主机单飞行,连点也只是重复请求)
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
#pragma once
|
||||
// macOS 客户端的「历史活动」采样器(服务端 COMMAND_QUERY_ACTIVITY → TOKEN_REPORT_ACTIVITY)。
|
||||
//
|
||||
// 后台每秒采样一次前台窗口(CGWindowListCopyWindowInfo 取最前面的 layer 0 窗口),
|
||||
// 输出格式与 Windows/Linux 端完全一致,服务端 CActivityDialog 与 MCP
|
||||
// get_activity_history 都只按行切分纯文本,不需要改:
|
||||
// [2026-11-14 10:00:00] [Safari - GitHub] 12s
|
||||
// 停留不足 5 秒的一闪而过不记录;同一条记录里的窗口标题会跟着更新
|
||||
// (浏览器切标签页标题常变,但窗口没换,仍算同一段停留)。
|
||||
//
|
||||
// 与 Windows/Linux 一样各平台独立实现:Linux 那份要 X11,macOS 这份要 CGWindowList +
|
||||
// NSWorkspace,共用的只有输出格式。
|
||||
#include <atomic>
|
||||
#include <deque>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
class MacActivityHistory
|
||||
{
|
||||
public:
|
||||
static MacActivityHistory& Instance();
|
||||
|
||||
// 启动后台采样线程(幂等)。应当在进程启动后尽早调用,历史从那一刻开始攒;
|
||||
// 查询时才启动的话,第一次查到的永远是空表。
|
||||
void Start();
|
||||
|
||||
// 进程退出时收线程;可以再次 Start(与 Linux 端一样保留这个能力)
|
||||
void Stop();
|
||||
|
||||
// 最新在前,每行一条;进行中的窗口(驻留已达阈值)排在最前
|
||||
std::string Dump() const;
|
||||
|
||||
// 还没有够 5 秒的记录时的说明,避免对话框全空
|
||||
static std::string EmptyText();
|
||||
|
||||
private:
|
||||
MacActivityHistory() = default;
|
||||
~MacActivityHistory() { Stop(); }
|
||||
MacActivityHistory(const MacActivityHistory&) = delete;
|
||||
MacActivityHistory& operator=(const MacActivityHistory&) = delete;
|
||||
|
||||
void Loop();
|
||||
|
||||
private:
|
||||
mutable std::mutex m_mutex;
|
||||
std::deque<std::string> m_records; // 已完成记录,最新在前
|
||||
std::string m_curTitle;
|
||||
std::string m_curStartTime;
|
||||
int m_curDwellSec = 0;
|
||||
|
||||
std::atomic<bool> m_running{ false };
|
||||
std::atomic<bool> m_started{ false };
|
||||
std::thread m_thread;
|
||||
};
|
||||
@@ -0,0 +1,233 @@
|
||||
#import "ActivityHistory.h"
|
||||
|
||||
#import <CoreGraphics/CoreGraphics.h>
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <unistd.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <ctime>
|
||||
|
||||
#include "../common/logger.h" // Mprintf(Start 失败要留痕)
|
||||
|
||||
// 与 Windows 端 client/ActivityHistory.h、Linux 端 linux/LinuxActivityHistory.h 一致
|
||||
#ifndef ACTIVITY_MIN_DWELL_SEC
|
||||
#define ACTIVITY_MIN_DWELL_SEC 5 // 一闪而过阈值(秒):驻留低于此值不记录
|
||||
#endif
|
||||
#ifndef ACTIVITY_HISTORY_MAX
|
||||
#define ACTIVITY_HISTORY_MAX 500 // 内存保留的最大记录条数
|
||||
#endif
|
||||
|
||||
namespace {
|
||||
|
||||
struct ProbeResult
|
||||
{
|
||||
uint64_t id = 0; // 窗口号(CGWindowNumber),0 表示空闲/无窗口
|
||||
std::string title;
|
||||
};
|
||||
|
||||
std::string CFStrToUtf8(CFStringRef s)
|
||||
{
|
||||
if (!s) return std::string();
|
||||
char buf[1024] = {};
|
||||
if (!CFStringGetCString(s, buf, sizeof(buf), kCFStringEncodingUTF8)) return std::string();
|
||||
return std::string(buf);
|
||||
}
|
||||
|
||||
// 按字节截断可能切在多字节字符中间,而服务端要按 UTF-8 转 GBK(对话框)或
|
||||
// 塞进 JSON(MCP),半截字符会变成乱码/非法 JSON。返回可以安全截断的位置。
|
||||
// 与 linux/LinuxActivityHistory.h 的 Utf8Boundary 同实现。
|
||||
size_t Utf8Boundary(const std::string& s)
|
||||
{
|
||||
const size_t n = s.size();
|
||||
size_t i = n;
|
||||
while (i > 0 && n - i < 3 && ((unsigned char)s[i - 1] & 0xC0) == 0x80) --i;
|
||||
if (i == 0) return n;
|
||||
const unsigned char c = (unsigned char)s[i - 1];
|
||||
size_t need = 1;
|
||||
if ((c & 0x80) == 0) need = 1;
|
||||
else if ((c & 0xE0) == 0xC0) need = 2;
|
||||
else if ((c & 0xF0) == 0xE0) need = 3;
|
||||
else if ((c & 0xF8) == 0xF0) need = 4;
|
||||
return (n - (i - 1) >= need) ? n : i - 1;
|
||||
}
|
||||
|
||||
// 控制字符换成空格(换行会破坏「每行一条」),可选截断
|
||||
std::string CleanLine(const std::string& s, size_t maxLen = 512)
|
||||
{
|
||||
std::string out;
|
||||
out.reserve(std::min(s.size(), maxLen));
|
||||
bool cut = false;
|
||||
for (char c : s) {
|
||||
unsigned char uc = (unsigned char)c;
|
||||
out += (uc < 0x20 || uc == 0x7f) ? ' ' : c;
|
||||
if (out.size() >= maxLen) { cut = true; break; }
|
||||
}
|
||||
if (cut) out.resize(Utf8Boundary(out));
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string FormatTimeStamp(std::time_t t)
|
||||
{
|
||||
std::tm tm{};
|
||||
localtime_r(&t, &tm);
|
||||
char buf[64];
|
||||
snprintf(buf, sizeof(buf), "%04d-%02d-%02d %02d:%02d:%02d",
|
||||
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
|
||||
tm.tm_hour, tm.tm_min, tm.tm_sec);
|
||||
return buf;
|
||||
}
|
||||
|
||||
// 时长格式化:Ns / Nm / NmNs / NhNm(与 Windows/Linux 端一致)
|
||||
std::string FormatDuration(int sec)
|
||||
{
|
||||
if (sec < 0) sec = 0;
|
||||
if (sec < 60) return std::to_string(sec) + "s";
|
||||
if (sec < 3600) {
|
||||
int m = sec / 60, s = sec % 60;
|
||||
return s ? std::to_string(m) + "m" + std::to_string(s) + "s"
|
||||
: std::to_string(m) + "m";
|
||||
}
|
||||
int h = sec / 3600, m = (sec % 3600) / 60;
|
||||
return std::to_string(h) + "h" + std::to_string(m) + "m";
|
||||
}
|
||||
|
||||
std::string FormatWindowRecord(const std::string& startTime, const std::string& title, int dwellSec)
|
||||
{
|
||||
return "[" + startTime + "] [" + CleanLine(title) + "] " + FormatDuration(dwellSec);
|
||||
}
|
||||
|
||||
// 前台窗口探测。CGWindowListCopyWindowInfo 按「从前往后」返回屏幕上的窗口,
|
||||
// 第一个 layer==0 的普通窗口就是当前最前面的那个;窗口标题(kCGWindowName)
|
||||
// 只有录到屏权限时才可见,没有权限时退化为只报应用名。
|
||||
ProbeResult ProbeFrontWindow()
|
||||
{
|
||||
ProbeResult r;
|
||||
|
||||
CFArrayRef list = CGWindowListCopyWindowInfo(
|
||||
kCGWindowListOptionOnScreenOnly | kCGWindowListExcludeDesktopElements,
|
||||
kCGNullWindowID);
|
||||
if (list == nullptr) return r;
|
||||
|
||||
const CFIndex count = CFArrayGetCount(list);
|
||||
for (CFIndex i = 0; i < count; ++i) {
|
||||
CFDictionaryRef window = (CFDictionaryRef)CFArrayGetValueAtIndex(list, i);
|
||||
|
||||
// 菜单栏/停靠栏/悬浮层都不是「用户在用的窗口」
|
||||
int layer = 0;
|
||||
CFNumberRef layerRef = (CFNumberRef)CFDictionaryGetValue(window, kCGWindowLayer);
|
||||
if (layerRef) CFNumberGetValue(layerRef, kCFNumberIntType, &layer);
|
||||
if (layer != 0) continue;
|
||||
|
||||
// 跳过本进程自己的窗口(客户端没有界面,但保险)
|
||||
int ownerPid = 0;
|
||||
CFNumberRef pidRef = (CFNumberRef)CFDictionaryGetValue(window, kCGWindowOwnerPID);
|
||||
if (pidRef) CFNumberGetValue(pidRef, kCFNumberIntType, &ownerPid);
|
||||
if (ownerPid == (int)getpid()) continue;
|
||||
|
||||
std::string owner = CFStrToUtf8((CFStringRef)CFDictionaryGetValue(window, kCGWindowOwnerName));
|
||||
if (owner.empty()) continue; // 无主的系统杂项窗口
|
||||
|
||||
std::string name = CFStrToUtf8((CFStringRef)CFDictionaryGetValue(window, kCGWindowName));
|
||||
|
||||
uint64_t number = 0;
|
||||
CFNumberRef numRef = (CFNumberRef)CFDictionaryGetValue(window, kCGWindowNumber);
|
||||
if (numRef) CFNumberGetValue(numRef, kCFNumberSInt64Type, &number);
|
||||
|
||||
r.id = number ? number : 1;
|
||||
r.title = name.empty() ? owner : owner + " - " + name;
|
||||
break;
|
||||
}
|
||||
|
||||
CFRelease(list);
|
||||
return r;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
MacActivityHistory& MacActivityHistory::Instance()
|
||||
{
|
||||
static MacActivityHistory inst;
|
||||
return inst;
|
||||
}
|
||||
|
||||
std::string MacActivityHistory::EmptyText()
|
||||
{
|
||||
return "[来源] 桌面窗口活动:暂无记录(没有停留超过 5 秒的活动窗口)\n";
|
||||
}
|
||||
|
||||
void MacActivityHistory::Start()
|
||||
{
|
||||
bool expected = false;
|
||||
if (!m_started.compare_exchange_strong(expected, true)) return;
|
||||
m_running = true;
|
||||
try {
|
||||
m_thread = std::thread(&MacActivityHistory::Loop, this);
|
||||
} catch (const std::exception& e) {
|
||||
// 采样是附加功能:线程起不来就降级成「没有历史活动」,别让异常穿过 main
|
||||
// (main.mm 里是裸调用,逃出去就是 std::terminate)。复位后允许再次 Start。
|
||||
m_running = false;
|
||||
m_started.store(false);
|
||||
Mprintf("*** ActivityHistory: failed to start sampler: %s ***\n", e.what());
|
||||
}
|
||||
}
|
||||
|
||||
void MacActivityHistory::Stop()
|
||||
{
|
||||
m_running = false;
|
||||
if (m_thread.joinable()) m_thread.join();
|
||||
m_started.store(false);
|
||||
}
|
||||
|
||||
std::string MacActivityHistory::Dump() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
std::string out;
|
||||
if (!m_curTitle.empty() && m_curDwellSec >= ACTIVITY_MIN_DWELL_SEC)
|
||||
out += FormatWindowRecord(m_curStartTime, m_curTitle, m_curDwellSec) + "\n";
|
||||
for (const auto& rec : m_records)
|
||||
out += rec + "\n";
|
||||
return out;
|
||||
}
|
||||
|
||||
void MacActivityHistory::Loop()
|
||||
{
|
||||
uint64_t lastId = 0;
|
||||
std::string lastTitle, startTime;
|
||||
int dwellSec = 0;
|
||||
|
||||
while (m_running) {
|
||||
ProbeResult p = ProbeFrontWindow();
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
if (p.id == 0 || p.title.empty()) {
|
||||
// 空闲/锁屏/无窗口:结账上一个窗口
|
||||
if (lastId != 0 && dwellSec >= ACTIVITY_MIN_DWELL_SEC)
|
||||
m_records.push_front(FormatWindowRecord(startTime, lastTitle, dwellSec));
|
||||
lastId = 0;
|
||||
lastTitle.clear();
|
||||
dwellSec = 0;
|
||||
} else if (p.id == lastId) {
|
||||
// 同一窗口:标题变了也连续累计(浏览器标签切换标题常变)
|
||||
++dwellSec;
|
||||
lastTitle = p.title;
|
||||
} else {
|
||||
if (lastId != 0 && dwellSec >= ACTIVITY_MIN_DWELL_SEC)
|
||||
m_records.push_front(FormatWindowRecord(startTime, lastTitle, dwellSec));
|
||||
lastId = p.id;
|
||||
lastTitle = p.title;
|
||||
startTime = FormatTimeStamp(std::time(nullptr));
|
||||
dwellSec = 1;
|
||||
}
|
||||
|
||||
while (m_records.size() > ACTIVITY_HISTORY_MAX)
|
||||
m_records.pop_back();
|
||||
|
||||
m_curTitle = lastTitle;
|
||||
m_curStartTime = startTime;
|
||||
m_curDwellSec = dwellSec;
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::seconds(1));
|
||||
}
|
||||
}
|
||||
+51
-4
@@ -4,11 +4,16 @@ project(ghost_macos)
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
|
||||
# macOS deployment target
|
||||
set(CMAKE_OSX_DEPLOYMENT_TARGET "10.13" CACHE STRING "Minimum macOS version")
|
||||
# macOS deployment target。arm64 的底线就是 11.0(Apple Silicon 首发系统),
|
||||
# 与 Homebrew openssl@3 自身的最低版本一致,避免链接时出现 "built for newer" 告警。
|
||||
set(CMAKE_OSX_DEPLOYMENT_TARGET "11.0" CACHE STRING "Minimum macOS version")
|
||||
|
||||
# Universal Binary (Intel + Apple Silicon)
|
||||
set(CMAKE_OSX_ARCHITECTURES "x86_64;arm64" CACHE STRING "Build architectures")
|
||||
# 只构建 Apple Silicon。仓库里发布过的 macos/ghost 一直是 arm64-only(universal 设置从未
|
||||
# 真正落地),且 Homebrew 的 OpenSSL 是单架构——保留 x86_64 slice 会让链接直接失败。
|
||||
# 将来真要支持 Intel Mac,应单独用 x86_64 的 OpenSSL 构建一份,而不是把这里改回 universal。
|
||||
# 注意 CMAKE_OSX_ARCHITECTURES 是 cache 变量:旧 build 目录里存的值不会因这里改字面量而
|
||||
# 更新,build.sh 因此显式传 -DCMAKE_OSX_ARCHITECTURES=arm64。
|
||||
set(CMAKE_OSX_ARCHITECTURES "arm64" CACHE STRING "Build architectures (arm64 only)")
|
||||
|
||||
include_directories(../)
|
||||
include_directories(../client)
|
||||
@@ -19,8 +24,13 @@ set(SOURCES
|
||||
main.mm
|
||||
../client/Buffer.cpp
|
||||
../client/IOCPClient.cpp
|
||||
# TLS 传输(OpenSSL 实现,与 Linux/Android 共用)。文件名叫 Linux 是历史原因,
|
||||
# 平台守卫为 __linux__ || __APPLE__;macOS 的差异只有 ExeDir() 用 _NSGetExecutablePath。
|
||||
../client/TlsChannelLinux.cpp
|
||||
../client/sign_shim_unix.cpp
|
||||
ScreenHandler.mm
|
||||
ScreenPreview.mm
|
||||
ActivityHistory.mm
|
||||
InputHandler.mm
|
||||
SystemManager.mm
|
||||
Permissions.mm
|
||||
@@ -49,6 +59,41 @@ find_library(COREVIDEO_FRAMEWORK CoreVideo REQUIRED)
|
||||
find_library(ACCELERATE_FRAMEWORK Accelerate REQUIRED)
|
||||
find_library(ICONV_LIBRARY iconv REQUIRED)
|
||||
|
||||
# ---- OpenSSL(TLS 传输,见 client/TlsChannelLinux.cpp)----
|
||||
# macOS 不自带 OpenSSL。优先用 Homebrew 的 openssl@3;也可显式指定
|
||||
# cmake .. -DOPENSSL_ROOT_DIR=/path/to/openssl
|
||||
# Apple Silicon 的 Homebrew 前缀是 /opt/homebrew,Intel 是 /usr/local。
|
||||
if(NOT OPENSSL_ROOT_DIR)
|
||||
foreach(_openssl_candidate
|
||||
/opt/homebrew/opt/openssl@3
|
||||
/usr/local/opt/openssl@3
|
||||
/opt/homebrew/opt/openssl
|
||||
/usr/local/opt/openssl)
|
||||
if(EXISTS "${_openssl_candidate}/include/openssl/ssl.h")
|
||||
set(OPENSSL_ROOT_DIR "${_openssl_candidate}")
|
||||
break()
|
||||
endif()
|
||||
endforeach()
|
||||
endif()
|
||||
if(NOT OPENSSL_ROOT_DIR)
|
||||
message(FATAL_ERROR
|
||||
"找不到 OpenSSL。先执行: brew install openssl@3\n"
|
||||
"或显式指定: cmake .. -DOPENSSL_ROOT_DIR=/opt/homebrew/opt/openssl@3")
|
||||
endif()
|
||||
|
||||
# 有静态库就静态链接:产物保持单文件,install.sh 不需要打包 dylib 或修 @rpath。
|
||||
# Homebrew 的 openssl@3 同时装 .a 和 .dylib;只有动态库时这里退化为动态链接并告警,
|
||||
# 那种情况下发布前必须把 libssl/libcrypto dylib 一并放进 .app 的 Contents/Frameworks。
|
||||
if(EXISTS "${OPENSSL_ROOT_DIR}/lib/libssl.a" AND EXISTS "${OPENSSL_ROOT_DIR}/lib/libcrypto.a")
|
||||
set(OPENSSL_USE_STATIC_LIBS TRUE)
|
||||
else()
|
||||
message(WARNING
|
||||
"OpenSSL 静态库不存在(${OPENSSL_ROOT_DIR}/lib/libssl.a),将动态链接;"
|
||||
"发布前请确认目标 Mac 装有同一份 OpenSSL,或把 dylib 放进 Contents/Frameworks。")
|
||||
endif()
|
||||
find_package(OpenSSL REQUIRED)
|
||||
message(STATUS "OpenSSL: ${OPENSSL_VERSION} (${OPENSSL_INCLUDE_DIR})")
|
||||
|
||||
target_link_libraries(ghost PRIVATE
|
||||
${COCOA_FRAMEWORK}
|
||||
${COREGRAPHICS_FRAMEWORK}
|
||||
@@ -68,6 +113,8 @@ target_link_libraries(ghost PRIVATE
|
||||
# libsign.a 内部使用 macOS CommonCrypto(HMAC-SHA256),CCHmac 在 libSystem
|
||||
# 中已被 Cocoa/CoreFoundation 等链接自动引入,故此处无需额外 framework
|
||||
"${CMAKE_SOURCE_DIR}/lib/libsign.a"
|
||||
OpenSSL::SSL
|
||||
OpenSSL::Crypto
|
||||
)
|
||||
|
||||
# Compiler flags
|
||||
|
||||
@@ -10,6 +10,12 @@ public:
|
||||
// Returns true if granted, false otherwise
|
||||
static bool checkScreenCapture();
|
||||
|
||||
// 只查授权状态、不真的抓屏(macOS 10.15+,更早的版本恒为 true)。
|
||||
// 授权看守线程用它轮询:checkScreenCapture() 每调一次就抓一整帧(视网膜屏
|
||||
// 20+ MB),而这里只需要「用户刚在设置里勾上了」这个状态位。它在二进制重签名
|
||||
// 后可能报假阴性 —— 正因如此,启动时的那次检查仍用 checkScreenCapture()。
|
||||
static bool checkScreenCapturePreflight();
|
||||
|
||||
// Request screen recording permission (shows system dialog, macOS 10.15+)
|
||||
static void requestScreenCapture();
|
||||
|
||||
|
||||
@@ -34,6 +34,13 @@ bool Permissions::checkScreenCapture() {
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Permissions::checkScreenCapturePreflight() {
|
||||
if (@available(macOS 10.15, *)) {
|
||||
return CGPreflightScreenCaptureAccess();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void Permissions::requestScreenCapture() {
|
||||
if (@available(macOS 10.15, *)) {
|
||||
// Trigger system permission dialog
|
||||
|
||||
+76
-1
@@ -4,6 +4,12 @@ macOS Remote Desktop Client
|
||||
Prerequisites:
|
||||
1. Xcode Command Line Tools: xcode-select --install
|
||||
2. CMake: brew install cmake
|
||||
3. OpenSSL (TLS transport): brew install openssl@3
|
||||
CMake 自动探测 /opt/homebrew/opt/openssl@3,也可用
|
||||
cmake .. -DOPENSSL_ROOT_DIR=/path/to/openssl 指定。
|
||||
|
||||
构建目标是 Apple Silicon (arm64) 单架构:Homebrew 的 OpenSSL 只有本机架构,
|
||||
保留 x86_64 slice 会链接失败。Intel Mac 需另建 x86_64 的 OpenSSL 单独构建。
|
||||
|
||||
Build:
|
||||
chmod +x build.sh
|
||||
@@ -11,7 +17,7 @@ Build:
|
||||
|
||||
Or manually:
|
||||
mkdir build && cd build
|
||||
cmake ..
|
||||
cmake .. -DCMAKE_OSX_ARCHITECTURES=arm64 -DCMAKE_OSX_DEPLOYMENT_TARGET=11.0
|
||||
make
|
||||
|
||||
Run:
|
||||
@@ -21,10 +27,79 @@ Configuration:
|
||||
Server address is configured in main.mm (g_SETTINGS variable).
|
||||
Modify before building if needed.
|
||||
|
||||
TLS Transport:
|
||||
Default is plaintext on first connect. The controller's host right-click menu
|
||||
("TLS 传输") sends the trust anchor; the client stores it at
|
||||
~/.config/ghost/yama-ca.pem, hot-reloads and reconnects over TLS 1.2
|
||||
(fail-closed, pinned to that anchor). "取消TLS" deletes the file and
|
||||
reconnects in plaintext. Existing sessions survive only if the transport does
|
||||
not change (replacing the certificate keeps TLS).
|
||||
|
||||
Verify after building:
|
||||
otool -L build/bin/ghost | grep -i ssl # 期望无输出:OpenSSL 已静态链接
|
||||
tail -f /tmp/ghost.log
|
||||
Startup prints one of:
|
||||
[TLS] transport on first connect: plaintext (no trust anchor)
|
||||
[TLS] transport on first connect: TLS (trust anchor present)
|
||||
Clicking "TLS 传输" should log "TLS transport switched to TLS, reconnecting";
|
||||
the host's TLS column in the online list then shows Y. "取消TLS" logs
|
||||
"switched to plaintext" and the column flips back to N.
|
||||
If the log says "trust anchor exists but failed to load", the client refuses
|
||||
to connect (fail-closed) until the anchor is fixed or removed.
|
||||
|
||||
Client Log:
|
||||
The controller's host right-click menu ("运行日志") sends COMMAND_QUERY_LOG;
|
||||
the client opens a sub-connection and reports its in-memory log ring
|
||||
(Logger, last 1000 lines) as TOKEN_REPORT_LOG. On macOS Mprintf (as defined
|
||||
by common/logger.h) writes that ring, and Logger mirrors the same line to
|
||||
stderr, so one Mprintf line reads identically in the dialog and in
|
||||
/tmp/ghost.log (same prefix and timestamp); content older than the
|
||||
1000-entry ring exists only in the file. main.mm logs startup, config,
|
||||
permissions, TLS, WS, connection and exit through Mprintf, so those lines
|
||||
are all visible in the dialog. The ObjC helper modules (ScreenHandler /
|
||||
H264Encoder / InputHandler / Permissions) still use NSLog, and the two
|
||||
"=== ghost ... started ===" banners are raw write(2) calls; all of those
|
||||
appear only in /tmp/ghost.log. Mprintf lines also no longer go to Apple's
|
||||
Unified Logging (NSLog in the helpers still does). The MCP tool
|
||||
get_client_log reads that same ring.
|
||||
|
||||
Verify: open "运行日志" for the Mac host; the dialog should show startup
|
||||
lines such as "=== macOS Ghost Client ===", "Config loaded from ...",
|
||||
the permission results, "[TLS] transport on first connect: ...", plus
|
||||
command and heartbeat entries.
|
||||
|
||||
Note: the POSIX client reports a snapshot once per connection (the Windows
|
||||
client keeps pushing increments every 3s). Closing and reopening "运行日志"
|
||||
takes a fresh snapshot.
|
||||
|
||||
Permissions Required:
|
||||
1. Screen Recording - System Settings > Privacy & Security > Screen Recording
|
||||
2. Accessibility - System Settings > Privacy & Security > Accessibility
|
||||
|
||||
Both are TCC grants, and macOS applies them per process: a grant made while
|
||||
the app is running only takes effect after it restarts. install.sh also resets
|
||||
both (tccutil reset) and re-signs the bundle ad-hoc on every install, and a
|
||||
rebuilt binary has a new cdhash, so the old records would not match anyway --
|
||||
expect to re-grant after each update.
|
||||
|
||||
When a permission is missing at startup the client requests both, and starts
|
||||
a watcher that polls CGPreflightScreenCaptureAccess / AXIsProcessTrusted --
|
||||
only for the permission that was actually missing; one that already passed
|
||||
the real capture check is not re-judged by preflight (it can report false
|
||||
negatives after re-signing). Once everything reads granted, the main loop
|
||||
disconnects and launches a fresh process ("Auto-restart: launching a fresh
|
||||
process ..."), so the new process starts with the grants in place: the old
|
||||
"grant one, kill, reopen" round trip twice becomes "tick both boxes and let
|
||||
it restart". The new process logs "(started by the auto-restart after
|
||||
permissions were granted)" at startup, and that line is what the 运行日志
|
||||
dialog shows, because the in-memory ring dies with the old process; the
|
||||
Auto-restart line itself stays in /tmp/ghost.log only. The watcher gives up
|
||||
after 15 minutes, and the auto-restart happens at most once per launch
|
||||
(guarded by GHOST_AUTO_RELAUNCHED), so if something still reports missing,
|
||||
restart manually as before. The restart disconnects first, so the controller
|
||||
sees a clean disconnect and reconnect, but any remote session in progress
|
||||
(screen, terminal, file transfer) is dropped when it happens.
|
||||
|
||||
Features:
|
||||
[x] Screen capture (CGDisplayCreateImage)
|
||||
[x] H264 video encoding (VideoToolbox)
|
||||
|
||||
@@ -128,6 +128,9 @@ private:
|
||||
std::atomic<uint8_t> m_algorithm;
|
||||
std::atomic<int> m_maxFPS;
|
||||
int8_t m_qualityLevel;
|
||||
// Web 端请求下一帧强制 IDR(COMMAND_SCREEN_KEYFRAME_REQ)。只由接收线程置位、
|
||||
// 采集线程消费:编码器实例只在采集线程里创建/销毁,接收线程不能直接碰。
|
||||
std::atomic<bool> m_keyframeRequested{false};
|
||||
|
||||
// Pending resolution change (set by applyQualityLevel, consumed by captureLoop)
|
||||
std::atomic<bool> m_dimensionsChanged{false};
|
||||
|
||||
+52
-3
@@ -17,6 +17,22 @@
|
||||
// Global client ID (calculated in main.mm)
|
||||
extern uint64_t g_myClientID;
|
||||
|
||||
// 质量等级持久化:服务端下发 CMD_QUALITY_LEVEL 时带 persist 位,就是「下次开机还这样」。
|
||||
// 存 NSUserDefaults 而不是 ~/.config/ghost/config.conf——后者由 main.mm 用内存 map 整体
|
||||
// 重写(分组变更会触发),单独往同一个文件写键会被下一次写盘冲掉。
|
||||
static NSString* const kQualityLevelKey = @"GhostQualityLevel";
|
||||
|
||||
// 读上次保存的等级。范围外的值(-2 关闭 / -1 自适应 / 越界)保留原值返回,
|
||||
// 由 applyQualityLevel 决定怎么处理:只有 [0, QUALITY_COUNT) 才会套用配置表。
|
||||
static int8_t loadPersistedQualityLevel()
|
||||
{
|
||||
NSNumber* saved = [[NSUserDefaults standardUserDefaults] objectForKey:kQualityLevelKey];
|
||||
if (!saved) return (int8_t)QUALITY_GOOD;
|
||||
int level = [saved intValue];
|
||||
if (level < QUALITY_DISABLED || level >= QUALITY_COUNT) return (int8_t)QUALITY_GOOD;
|
||||
return (int8_t)level;
|
||||
}
|
||||
|
||||
ScreenHandler::ScreenHandler(IOCPClient* client)
|
||||
: m_client(client)
|
||||
, m_clientID(0)
|
||||
@@ -45,6 +61,10 @@ ScreenHandler::ScreenHandler(IOCPClient* client)
|
||||
// Cache color space (avoid per-frame creation)
|
||||
m_colorSpace = CGColorSpaceCreateDeviceRGB();
|
||||
|
||||
// 上次保存的质量等级(服务端下发的 CMD_QUALITY_LEVEL 带 persist 位时写入)。
|
||||
// 放在构造末尾按普通调用应用一次:此时 m_width==0,尺寸相关分支天然不触发。
|
||||
applyQualityLevel(loadPersistedQualityLevel(), false);
|
||||
|
||||
// Initialize input handler for mouse/keyboard control
|
||||
m_inputHandler = std::make_unique<InputHandler>();
|
||||
if (m_inputHandler->init()) {
|
||||
@@ -498,6 +518,12 @@ void ScreenHandler::OnReceive(uint8_t* data, ULONG size)
|
||||
}
|
||||
break;
|
||||
|
||||
case COMMAND_SCREEN_KEYFRAME_REQ:
|
||||
// Web 屏幕墙恢复/新加入者请求:下一帧强制 IDR,立即重建参考链。
|
||||
// 这里只置标志,由采集线程在下一帧消费(见 sendH264Frame 的调用点)。
|
||||
m_keyframeRequested.store(true);
|
||||
break;
|
||||
|
||||
case COMMAND_SCREEN_SET_CLIPBOARD:
|
||||
// 服务端设置剪贴板: [cmd:1][text:N]
|
||||
if (size > 1) {
|
||||
@@ -626,8 +652,13 @@ void ScreenHandler::applyQualityLevel(int8_t level, bool persist)
|
||||
{
|
||||
m_qualityLevel = level;
|
||||
|
||||
// TODO: persist to config file if needed
|
||||
(void)persist;
|
||||
// 持久化(服务端 CMD_QUALITY_LEVEL 的第 3 字节)。下次启动构造时读回并应用,
|
||||
// 与 Linux 端把 QualityLevel 写进 config 的语义一致。
|
||||
if (persist) {
|
||||
[[NSUserDefaults standardUserDefaults] setInteger:(NSInteger)level forKey:kQualityLevelKey];
|
||||
[[NSUserDefaults standardUserDefaults] synchronize];
|
||||
NSLog(@">>> Quality saved: level=%d", (int)level);
|
||||
}
|
||||
|
||||
if (level == QUALITY_DISABLED) {
|
||||
// Disabled mode: keep current settings
|
||||
@@ -834,6 +865,18 @@ void ScreenHandler::sendDiffFrame()
|
||||
|
||||
void ScreenHandler::sendH264Frame(bool keyframe)
|
||||
{
|
||||
// 强制 IDR 请求在调用点已经 exchange 掉,只有真的把这一帧编出来才算消费成功。
|
||||
// 中途任何提前返回(抓屏失败 / 没连接 / 编码器开不起来 / 编码失败)都把它还回去,
|
||||
// 否则 Web 端要等编码器下一次自然 IDR(最长一个 GOP)才能解出画面。
|
||||
struct RearmOnFailure {
|
||||
std::atomic<bool>& flag;
|
||||
bool force;
|
||||
bool consumed;
|
||||
RearmOnFailure(std::atomic<bool>& f, bool force_)
|
||||
: flag(f), force(force_), consumed(false) {}
|
||||
~RearmOnFailure() { if (force && !consumed) flag.store(true); }
|
||||
} rearm(m_keyframeRequested, keyframe);
|
||||
|
||||
if (!captureScreen(m_currFrame)) return;
|
||||
if (!m_client) return;
|
||||
|
||||
@@ -900,6 +943,7 @@ void ScreenHandler::sendH264Frame(bool keyframe)
|
||||
memcpy(&packet[headerSize], encodedData, encodedSize);
|
||||
|
||||
m_client->Send2Server((char*)packet.data(), packet.size());
|
||||
rearm.consumed = true;
|
||||
}
|
||||
|
||||
uint32_t ScreenHandler::compareBitmap(const uint8_t* curr, const uint8_t* prev,
|
||||
@@ -1214,8 +1258,12 @@ void ScreenHandler::captureLoop()
|
||||
currentAlgo = algo;
|
||||
|
||||
if (algo == ALGORITHM_H264) {
|
||||
// 这一帧本身就是关键帧:挂起的强制 IDR 请求顺手清掉,别下一帧再打一次
|
||||
m_keyframeRequested.store(false);
|
||||
sendH264Frame(true); // First H264 frame is keyframe
|
||||
} else {
|
||||
// 非 H264 时关键帧请求没有意义,顺手清掉,免得切回 H264 时白打一次 IDR
|
||||
m_keyframeRequested.store(false);
|
||||
if (m_h264Encoder) {
|
||||
m_h264Encoder->close();
|
||||
m_h264Encoder.reset();
|
||||
@@ -1224,7 +1272,8 @@ void ScreenHandler::captureLoop()
|
||||
}
|
||||
} else {
|
||||
if (algo == ALGORITHM_H264) {
|
||||
sendH264Frame(false);
|
||||
// 服务端的强制 IDR 请求在这里消费:下一帧就是关键帧。
|
||||
sendH264Frame(m_keyframeRequested.exchange(false));
|
||||
} else {
|
||||
sendDiffFrame();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
#pragma once
|
||||
// 屏幕预览(COMMAND_SCREEN_PREVIEW_REQ)—— macOS 端一次性抓屏
|
||||
//
|
||||
// 与 linux/ScreenPreview.h、Windows 端 client/ScreenPreview.h 对应:服务端双击在线主机
|
||||
// 时索取一张缩略图。macOS 没有可依赖的 JPEG 编码库(ImageIO 能编,但走的是另一套
|
||||
// 颜色/尺寸语义,与 Windows 的 GDI+ 输出不一致),所以这里只做 抓屏 → 等比缩放 →
|
||||
// BGRA 原始像素,由服务端在 IO 线程统一编码成 JPEG(下游只认 JPEG 一种格式)。
|
||||
#include <vector>
|
||||
|
||||
class ScreenPreview
|
||||
{
|
||||
public:
|
||||
// 本机当前能否截图:有主显示器且已授予录屏权限。
|
||||
// 服务端按 CLIENT_CAP_SCREEN_PREVIEW 决定要不要下发预览请求,能力位就取自它。
|
||||
static bool IsAvailable();
|
||||
|
||||
// 抓主屏并等比缩放到 maxWidth 以内(不放大、高不超过 1080),返回 ScreenPreviewStatus。
|
||||
// out 为自上而下逐行、每像素 B,G,R,X 四字节(X=0xFF),无行首填充。
|
||||
static int Capture(int maxWidth, std::vector<unsigned char>& out, int& outW, int& outH);
|
||||
};
|
||||
@@ -0,0 +1,101 @@
|
||||
#import "ScreenPreview.h"
|
||||
#import "Permissions.h"
|
||||
#import <CoreGraphics/CoreGraphics.h>
|
||||
|
||||
#include "../common/commands.h" // ScreenPreviewStatus / SCREEN_PREVIEW_FMT_BGRX
|
||||
|
||||
#include <cstddef>
|
||||
|
||||
namespace {
|
||||
|
||||
// 目标尺寸:与 Linux/Windows 端同一套规则——等比缩到 maxWidth 以内(不放大),
|
||||
// 高度再压到 1080(竖屏/超宽屏的原始像素包会大到没意义),宽高取偶数。
|
||||
bool ComputeTargetSize(int sw, int sh, int maxWidth, int& tw, int& th)
|
||||
{
|
||||
if (sw <= 0 || sh <= 0) return false;
|
||||
tw = sw;
|
||||
th = sh;
|
||||
if (tw > maxWidth) {
|
||||
th = (int)((long long)sh * maxWidth / sw);
|
||||
tw = maxWidth;
|
||||
}
|
||||
if (th > 1080) {
|
||||
tw = (int)((long long)tw * 1080 / th);
|
||||
th = 1080;
|
||||
}
|
||||
tw &= ~1;
|
||||
th &= ~1;
|
||||
if (tw < 2) tw = 2;
|
||||
if (th < 2) th = 2;
|
||||
if (tw > sw) tw = sw;
|
||||
if (th > sh) th = sh;
|
||||
return tw > 0 && th > 0;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool ScreenPreview::IsAvailable()
|
||||
{
|
||||
// 没有录屏授权时 CGDisplayCreateImage 仍然会返回一张图(macOS 15 起是壁纸 +
|
||||
// 窗口占位),看起来"成功"却什么都看不到,所以不能只靠试抓一次。
|
||||
if (CGMainDisplayID() == 0) return false;
|
||||
// 预检只读 TCC 状态位,ad-hoc 重签之后可能假阴性;启动时的授权判定因此用的是
|
||||
// 真抓一帧(Permissions::checkScreenCapture)。这里两者取或:宁可多发几次注定
|
||||
// 失败的预览请求,也不要出现「远程能看屏、get_screenshot 却一直 -32005」。
|
||||
return Permissions::checkScreenCapturePreflight() || Permissions::checkScreenCapture();
|
||||
}
|
||||
|
||||
int ScreenPreview::Capture(int maxWidth, std::vector<unsigned char>& out, int& outW, int& outH)
|
||||
{
|
||||
outW = 0;
|
||||
outH = 0;
|
||||
out.clear();
|
||||
|
||||
// 与 Linux 端一致:上限防滥用,下限防止 1 像素宽的退化请求
|
||||
if (maxWidth < 64) maxWidth = 64;
|
||||
if (maxWidth > 1920) maxWidth = 1920;
|
||||
|
||||
const CGDirectDisplayID display = CGMainDisplayID();
|
||||
if (display == 0) return SCREEN_PREVIEW_NOT_SUPPORTED;
|
||||
|
||||
const int sw = (int)CGDisplayPixelsWide(display);
|
||||
const int sh = (int)CGDisplayPixelsHigh(display);
|
||||
int tw = 0, th = 0;
|
||||
if (!ComputeTargetSize(sw, sh, maxWidth, tw, th)) return SCREEN_PREVIEW_CAPTURE_FAILED;
|
||||
|
||||
// CGDisplayCreateImage 从 macOS 14 起标记废弃(官方推荐 ScreenCaptureKit 的异步
|
||||
// SCScreenshotManager),但没有删除;一次几十毫秒的抓图用异步 API 要额外起 run loop,
|
||||
// 不划算。这里显式压掉废弃告警,并在构建机升级到真正移除该 API 时再换实现。
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
|
||||
CGImageRef image = CGDisplayCreateImage(display);
|
||||
#pragma clang diagnostic pop
|
||||
if (image == nullptr) return SCREEN_PREVIEW_CAPTURE_FAILED;
|
||||
|
||||
// kCGImageAlphaNoneSkipFirst + 32Little 在内存里就是 B,G,R,X 的字节序,与协议里
|
||||
// SCREEN_PREVIEW_FMT_BGRX 的定义一致;缩放交给 CoreGraphics 在绘制时完成。
|
||||
const size_t stride = (size_t)tw * 4;
|
||||
out.resize(stride * (size_t)th);
|
||||
CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB();
|
||||
CGContextRef ctx = CGBitmapContextCreate(out.data(), (size_t)tw, (size_t)th, 8, stride, cs,
|
||||
kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Little);
|
||||
CGColorSpaceRelease(cs);
|
||||
if (ctx == nullptr) {
|
||||
CGImageRelease(image);
|
||||
out.clear();
|
||||
return SCREEN_PREVIEW_CAPTURE_FAILED;
|
||||
}
|
||||
|
||||
CGContextSetInterpolationQuality(ctx, kCGInterpolationMedium);
|
||||
CGContextSetShouldAntialias(ctx, false);
|
||||
CGContextDrawImage(ctx, CGRectMake(0, 0, tw, th), image);
|
||||
CGContextRelease(ctx);
|
||||
CGImageRelease(image);
|
||||
|
||||
// Alpha 字节协议要求 0xFF;kCGImageAlphaNoneSkipFirst 不会写它
|
||||
for (size_t i = 3; i < out.size(); i += 4) out[i] = 0xFF;
|
||||
|
||||
outW = tw;
|
||||
outH = th;
|
||||
return SCREEN_PREVIEW_OK;
|
||||
}
|
||||
+28
-21
@@ -1,40 +1,47 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <sys/types.h>
|
||||
|
||||
// Forward declaration
|
||||
class IOCPClient;
|
||||
// IOCPManager / IOCPClient / PBYTE / ULONG 来自这里;本类必须派生 IOCPManager,
|
||||
// 见下方注释。Mprintf 由 common/logger.h 提供(本类的日志要进「运行日志」的 ring)。
|
||||
#include "../client/IOCPClient.h"
|
||||
#include "../common/logger.h"
|
||||
|
||||
class SystemManager {
|
||||
// ============== macOS 进程管理 ==============
|
||||
// 与 Linux 端(linux/SystemManager.h)同一套 wire 格式:主连接收到 COMMAND_SYSTEM 后,
|
||||
// 客户端另起一条「系统子连接」,本类只在这条子连接上收发:
|
||||
// COMMAND_PSLIST → TOKEN_PSLIST
|
||||
// COMMAND_KILLPROCESS → kill(2) 后补发一次 TOKEN_PSLIST
|
||||
// COMMAND_WSLIST → TOKEN_WSLIST
|
||||
//
|
||||
// 两个约束都是子连接骨架(common/sub_conn_thread.h)定死的:
|
||||
// 1. 必须派生 IOCPManager —— 骨架装的回调是 IOCPManager::DataProcess,它把 user
|
||||
// 强转成 IOCPManager* 再调虚函数 OnReceive;普通类装上去会直接崩。
|
||||
// 2. 构造函数必须只收 IOCPClient* —— 骨架的 createHandler 契约是
|
||||
// std::unique_ptr<T>(IOCPClient*)。
|
||||
// 这也解释了它以前为什么是死代码:签名对不上骨架,一直没被实例化,
|
||||
// main.mm 的 COMMAND_SYSTEM 只打了一行日志。
|
||||
class SystemManager : public IOCPManager
|
||||
{
|
||||
public:
|
||||
SystemManager(IOCPClient* client, uint64_t clientID);
|
||||
~SystemManager();
|
||||
explicit SystemManager(IOCPClient* client);
|
||||
~SystemManager() override {}
|
||||
|
||||
// Handle commands from server
|
||||
void onReceive(const uint8_t* data, size_t size);
|
||||
virtual VOID OnReceive(PBYTE szBuffer, ULONG ulLength) override;
|
||||
|
||||
private:
|
||||
// Send process list to server
|
||||
// 发送完整进程列表(构造时立即发一次,服务端据此判定子连接就绪)
|
||||
void sendProcessList();
|
||||
|
||||
// Kill processes by PID
|
||||
// 终止进程:载荷是若干个 4 字节 PID(与 Windows/Linux 一致)
|
||||
void killProcesses(const uint8_t* data, size_t size);
|
||||
|
||||
// Send window list (limited on macOS without accessibility)
|
||||
// 窗口列表:macOS 只能给「有可见窗口的应用」的伪句柄(PID)+ 应用名
|
||||
void sendWindowsList();
|
||||
|
||||
// Get process name by PID
|
||||
static std::string getProcessName(pid_t pid);
|
||||
|
||||
// Get process executable path by PID
|
||||
static std::string getProcessPath(pid_t pid);
|
||||
|
||||
// Get all running PIDs
|
||||
static std::vector<pid_t> getAllPids();
|
||||
|
||||
private:
|
||||
IOCPClient* m_client;
|
||||
uint64_t m_clientID;
|
||||
};
|
||||
+30
-32
@@ -4,34 +4,30 @@
|
||||
#import <sys/sysctl.h>
|
||||
#import <libproc.h>
|
||||
#import <signal.h>
|
||||
#import <unistd.h>
|
||||
#include <cstring> // memcpy / strlen / memset
|
||||
#include <unistd.h>
|
||||
|
||||
SystemManager::SystemManager(IOCPClient* client, uint64_t clientID)
|
||||
SystemManager::SystemManager(IOCPClient* client)
|
||||
: m_client(client)
|
||||
, m_clientID(clientID)
|
||||
{
|
||||
// Send initial process list on connection
|
||||
// 与 Windows/Linux 端一致:构造时立即发送进程列表。服务端把这条首包当作
|
||||
// 「系统子连接已就绪」,kill_process / list_processes 都在等它。
|
||||
sendProcessList();
|
||||
}
|
||||
|
||||
SystemManager::~SystemManager()
|
||||
void SystemManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
{
|
||||
}
|
||||
if (!szBuffer || ulLength == 0) return;
|
||||
|
||||
void SystemManager::onReceive(const uint8_t* data, size_t size)
|
||||
{
|
||||
if (!data || size == 0) return;
|
||||
|
||||
switch (data[0]) {
|
||||
switch (szBuffer[0]) {
|
||||
case COMMAND_PSLIST:
|
||||
sendProcessList();
|
||||
break;
|
||||
|
||||
case COMMAND_KILLPROCESS:
|
||||
if (size > 1) {
|
||||
killProcesses(data + 1, size - 1);
|
||||
if (ulLength > 1) {
|
||||
killProcesses(szBuffer + 1, ulLength - 1);
|
||||
// Refresh list after kill
|
||||
usleep(100000); // 100ms wait
|
||||
sendProcessList();
|
||||
}
|
||||
break;
|
||||
@@ -41,12 +37,12 @@ void SystemManager::onReceive(const uint8_t* data, size_t size)
|
||||
break;
|
||||
|
||||
default:
|
||||
NSLog(@"SystemManager: Unknown command: %d", (int)data[0]);
|
||||
Mprintf("[SystemManager] Unknown sub-command: %d\n", (int)szBuffer[0]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<pid_t> SystemManager::getAllPids()
|
||||
static std::vector<pid_t> getAllPids()
|
||||
{
|
||||
std::vector<pid_t> pids;
|
||||
|
||||
@@ -54,8 +50,8 @@ std::vector<pid_t> SystemManager::getAllPids()
|
||||
int count = proc_listpids(PROC_ALL_PIDS, 0, NULL, 0);
|
||||
if (count <= 0) return pids;
|
||||
|
||||
// Allocate buffer for PIDs
|
||||
std::vector<pid_t> buffer(count * 2); // Extra space for new processes
|
||||
// Allocate buffer for PIDs (double the size: processes may spawn in between)
|
||||
std::vector<pid_t> buffer(count * 2);
|
||||
count = proc_listpids(PROC_ALL_PIDS, 0, buffer.data(), (int)(buffer.size() * sizeof(pid_t)));
|
||||
if (count <= 0) return pids;
|
||||
|
||||
@@ -69,7 +65,7 @@ std::vector<pid_t> SystemManager::getAllPids()
|
||||
return pids;
|
||||
}
|
||||
|
||||
std::string SystemManager::getProcessName(pid_t pid)
|
||||
static std::string getProcessName(pid_t pid)
|
||||
{
|
||||
char name[PROC_PIDPATHINFO_MAXSIZE];
|
||||
memset(name, 0, sizeof(name));
|
||||
@@ -82,7 +78,7 @@ std::string SystemManager::getProcessName(pid_t pid)
|
||||
return "";
|
||||
}
|
||||
|
||||
std::string SystemManager::getProcessPath(pid_t pid)
|
||||
static std::string getProcessPath(pid_t pid)
|
||||
{
|
||||
char path[PROC_PIDPATHINFO_MAXSIZE];
|
||||
memset(path, 0, sizeof(path));
|
||||
@@ -112,6 +108,7 @@ void SystemManager::sendProcessList()
|
||||
#endif
|
||||
|
||||
std::vector<pid_t> pids = getAllPids();
|
||||
size_t sent = 0;
|
||||
|
||||
for (pid_t pid : pids) {
|
||||
if (pid <= 0) continue;
|
||||
@@ -139,29 +136,31 @@ void SystemManager::sendProcessList()
|
||||
// Write fullPath (null-terminated)
|
||||
buf.insert(buf.end(), path.begin(), path.end());
|
||||
buf.push_back(0);
|
||||
++sent;
|
||||
}
|
||||
|
||||
m_client->Send2Server((char*)buf.data(), buf.size());
|
||||
NSLog(@"SystemManager SendProcessList: %zu bytes, %zu processes",
|
||||
buf.size(), pids.size());
|
||||
m_client->Send2Server((char*)buf.data(), (ULONG)buf.size());
|
||||
Mprintf("[SystemManager] SendProcessList: %zu bytes, %zu processes\n", buf.size(), sent);
|
||||
}
|
||||
|
||||
void SystemManager::killProcesses(const uint8_t* data, size_t size)
|
||||
{
|
||||
// Each PID is 4 bytes (DWORD)
|
||||
// Each PID is 4 bytes (DWORD),与 Windows/Linux 端一致
|
||||
for (size_t i = 0; i + sizeof(uint32_t) <= size; i += sizeof(uint32_t)) {
|
||||
uint32_t dwPid = *(uint32_t*)(data + i);
|
||||
uint32_t dwPid;
|
||||
memcpy(&dwPid, data + i, sizeof(dwPid));
|
||||
pid_t pid = (pid_t)dwPid;
|
||||
|
||||
// Don't allow killing kernel/launchd
|
||||
// Don't allow killing kernel/launchd(launchd 的 pid 是 1)
|
||||
if (pid <= 1) continue;
|
||||
|
||||
// Don't allow killing ourselves
|
||||
if (pid == getpid()) continue;
|
||||
|
||||
int ret = kill(pid, SIGKILL);
|
||||
NSLog(@"SystemManager kill(%d, SIGKILL) = %d", (int)pid, ret);
|
||||
Mprintf("[SystemManager] kill(%d, SIGKILL) = %d\n", (int)pid, ret);
|
||||
}
|
||||
usleep(100000); // 100ms 等待进程退出,之后的列表才不会还把死进程列出来
|
||||
}
|
||||
|
||||
void SystemManager::sendWindowsList()
|
||||
@@ -171,7 +170,8 @@ void SystemManager::sendWindowsList()
|
||||
std::vector<uint8_t> buf;
|
||||
buf.push_back(TOKEN_WSLIST);
|
||||
|
||||
// Get list of running applications
|
||||
// macOS 没有 HWND。这里列「有可见窗口的应用」,句柄位置放 PID 充当伪句柄,
|
||||
// 与 Windows 的 TOKEN_WSLIST 同构(uint64 句柄 + NUL 结尾标题)。
|
||||
NSArray<NSRunningApplication*>* apps = [[NSWorkspace sharedWorkspace] runningApplications];
|
||||
|
||||
for (NSRunningApplication* app in apps) {
|
||||
@@ -185,17 +185,15 @@ void SystemManager::sendWindowsList()
|
||||
|
||||
pid_t pid = app.processIdentifier;
|
||||
|
||||
// Write window handle (use PID as pseudo-handle)
|
||||
uint64_t hwnd = (uint64_t)pid;
|
||||
const uint8_t* p = (const uint8_t*)&hwnd;
|
||||
buf.insert(buf.end(), p, p + sizeof(uint64_t));
|
||||
|
||||
// Write window title (null-terminated)
|
||||
const char* utf8Name = [name UTF8String];
|
||||
buf.insert(buf.end(), utf8Name, utf8Name + strlen(utf8Name));
|
||||
buf.push_back(0);
|
||||
}
|
||||
|
||||
m_client->Send2Server((char*)buf.data(), buf.size());
|
||||
NSLog(@"SystemManager SendWindowsList: %zu bytes", buf.size());
|
||||
m_client->Send2Server((char*)buf.data(), (ULONG)buf.size());
|
||||
Mprintf("[SystemManager] SendWindowsList: %zu bytes\n", buf.size());
|
||||
}
|
||||
+6
-1
@@ -27,8 +27,13 @@ mkdir -p build
|
||||
cd build
|
||||
|
||||
# Configure
|
||||
# 架构与最低系统版本显式传:两者都是 CMake 的 cache 变量,旧 build 目录里可能还存着
|
||||
# universal / 10.13 的旧值,只改 CMakeLists.txt 不会生效(arm64 + Homebrew OpenSSL
|
||||
# 是单架构组合,留着 x86_64 slice 会链接失败)。
|
||||
echo "Configuring..."
|
||||
cmake .. -DCMAKE_BUILD_TYPE=Release
|
||||
cmake .. -DCMAKE_BUILD_TYPE=Release \
|
||||
-DCMAKE_OSX_ARCHITECTURES=arm64 \
|
||||
-DCMAKE_OSX_DEPLOYMENT_TARGET=11.0
|
||||
|
||||
# Build
|
||||
echo ""
|
||||
|
||||
+2
-1
@@ -110,7 +110,8 @@ echo "2. 授权以下权限 (在系统设置中勾选 GhostClient):"
|
||||
echo " - 屏幕录制: 允许捕获屏幕画面"
|
||||
echo " - 辅助功能: 允许控制鼠标键盘"
|
||||
echo ""
|
||||
echo "3. 授权后重启应用:"
|
||||
echo "3. 两个都授权后应用会自己重启一次(日志里是 Auto-restart: launching ...),"
|
||||
echo " 一般不用手动操作。若 15 分钟内没等到,手动重启:"
|
||||
echo ""
|
||||
echo " pkill -f GhostClient && open /Applications/GhostClient.app"
|
||||
echo ""
|
||||
|
||||
+546
-40
@@ -7,6 +7,10 @@
|
||||
#import <signal.h>
|
||||
#import <unistd.h>
|
||||
#import <fcntl.h>
|
||||
#import <errno.h>
|
||||
#import <limits.h>
|
||||
#import <pthread.h>
|
||||
#import <sys/wait.h>
|
||||
#import <IOKit/IOKitLib.h>
|
||||
#import <IOKit/pwr_mgt/IOPMLib.h>
|
||||
#import <fstream>
|
||||
@@ -15,8 +19,12 @@
|
||||
#import <memory>
|
||||
#import <string>
|
||||
#import <map>
|
||||
#import <vector>
|
||||
#import <cstring> // strncpy(RefreshLoginTls 改写 szReserved)
|
||||
#import <system_error>
|
||||
|
||||
#import "../client/IOCPClient.h"
|
||||
#include "../client/TlsChannel.h" // TLS 传输(信任锚保存/热重载),随 IOCPClient 一起定义 YAMA_TLS_CHANNEL
|
||||
#define XXH_INLINE_ALL
|
||||
#include "../common/xxhash.h"
|
||||
#include "../common/rtt_estimator.h"
|
||||
@@ -28,19 +36,38 @@
|
||||
#import "ScreenHandler.h"
|
||||
#import "InputHandler.h"
|
||||
#import "SystemManager.h"
|
||||
#import "ScreenPreview.h"
|
||||
#import "ActivityHistory.h"
|
||||
#import "../common/PTYHandler.h"
|
||||
#import "../common/FileManager.h"
|
||||
#import "../common/FileTransferV2.h"
|
||||
#import "../common/logger.h"
|
||||
#import "ClipboardHandler.h"
|
||||
|
||||
// 本文件的运行期日志一律用 Mprintf:它既进内存 ring —— 服务端「运行日志」菜单与
|
||||
// MCP 的 get_client_log 就取这一份 —— 又由 Logger 镜像到 stderr(/tmp/ghost.log)。
|
||||
// NSLog 只会落在文件里、不进 ring,所以启动/配置/权限这些现场最常翻的行不要用
|
||||
// NSLog。(ScreenHandler/H264/InputHandler 等 ObjC 模块里的 NSLog 保持原样。)
|
||||
|
||||
// Global state
|
||||
static std::atomic<bool> g_running(true);
|
||||
static std::atomic<bool> g_needResendLogin(false); // 分组变更后需要重发登录信息
|
||||
// 传输方式热切换(服务端 COMMAND_TLS_ENABLE/DISABLE 改了信任锚)后需要重建连接。
|
||||
// DataProcess 跑在接收线程上,直接关 socket 会和主线程的发送竞争,所以只置标志,
|
||||
// 由主心跳循环择机 Disconnect 并重连(与 linux/main.cpp 的 g_needReconnect 同语义)。
|
||||
static std::atomic<bool> g_needReconnect(false);
|
||||
// 权限补齐后要求重启进程(见文件下方的「授权后自动重启」)。只看守线程置位,主循环
|
||||
// 见到它先断开主连接再重启,避免新进程起来时旧连接还挂在服务端。
|
||||
static std::atomic<bool> g_autoRestartPending(false);
|
||||
|
||||
// Client ID (calculated from system info, used by ScreenHandler)
|
||||
uint64_t g_myClientID = 0;
|
||||
|
||||
// 主连接句柄。DataProcess 的 user 参数恒为 NULL,而 V2 C2C 落盘回执
|
||||
// (TOKEN_C2C_RECV_RESULT)要发在主连接上,所以留一个全局指针(同 linux/main.cpp)。
|
||||
// Send2Server 内部持锁,可在工作线程调用;用之前一律先判 IsConnected()。
|
||||
static IOCPClient* g_pMainClient = nullptr;
|
||||
|
||||
// 服务端身份校验全局状态已抽到 common/client_auth_state.h(namespace ClientAuth)
|
||||
|
||||
// 远程地址:当前为写死状态,如需调试,请按实际情况修改
|
||||
@@ -108,14 +135,14 @@ static void saveConfig()
|
||||
|
||||
std::ofstream file(g_configPath, std::ios::trunc);
|
||||
if (!file.is_open()) {
|
||||
NSLog(@"Failed to save config to %s", g_configPath.c_str());
|
||||
Mprintf("Failed to save config to %s\n", g_configPath.c_str());
|
||||
return;
|
||||
}
|
||||
|
||||
for (const auto& kv : g_configData) {
|
||||
file << kv.first << "=" << kv.second << "\n";
|
||||
}
|
||||
NSLog(@"Config saved to %s", g_configPath.c_str());
|
||||
Mprintf("Config saved to %s\n", g_configPath.c_str());
|
||||
}
|
||||
|
||||
// Get config string value
|
||||
@@ -136,7 +163,7 @@ static void setConfigStr(const std::string& key, const std::string& value)
|
||||
static void saveGroupName(const std::string& groupName)
|
||||
{
|
||||
setConfigStr("group_name", groupName);
|
||||
NSLog(@"Group name saved: %s", groupName.c_str());
|
||||
Mprintf("Group name saved: %s\n", groupName.c_str());
|
||||
}
|
||||
|
||||
// Load group name from config file
|
||||
@@ -481,7 +508,7 @@ static std::string getInstallTime()
|
||||
installTime = [NSString stringWithUTF8String:currentTime.c_str()];
|
||||
[defaults setObject:installTime forKey:@"ghost_install_time"];
|
||||
[defaults synchronize];
|
||||
NSLog(@"First run - recorded install time: %@", installTime);
|
||||
Mprintf("First run - recorded install time: %s\n", [installTime UTF8String]);
|
||||
}
|
||||
|
||||
return std::string([installTime UTF8String]);
|
||||
@@ -495,6 +522,11 @@ static void fillLoginInfo(LOGIN_INFOR& info)
|
||||
// Token is set in constructor
|
||||
info.bToken = TOKEN_LOGIN;
|
||||
|
||||
// 分组变更后会带着同一个 logInfo 再调一次本函数。AddReserved 是「追加」,不清空
|
||||
// 就会把整套保留字段再拼一遍,服务端按 LOGIN_RES 下标取值,看到的是重复/错位的
|
||||
// 字段。这里先把保留区清空,让本函数可重入。
|
||||
info.szReserved[0] = '\0';
|
||||
|
||||
// OS Version
|
||||
std::string osVer = getMacOSVersion();
|
||||
strncpy(info.OsVerInfoEx, osVer.c_str(), sizeof(info.OsVerInfoEx) - 1);
|
||||
@@ -595,8 +627,8 @@ static void fillLoginInfo(LOGIN_INFOR& info)
|
||||
std::string normPath = normalizeExePathLower(exePath);
|
||||
std::string idInput = machineId + "|" + normPath;
|
||||
g_myClientID = XXH64(idInput.c_str(), idInput.length(), 0);
|
||||
NSLog(@"ClientID(v2): %llu (machineId=%s, path=%s)",
|
||||
g_myClientID, machineId.c_str(), normPath.c_str());
|
||||
Mprintf("ClientID(v2): %llu (machineId=%s, path=%s)\n",
|
||||
g_myClientID, machineId.c_str(), normPath.c_str());
|
||||
} else {
|
||||
// 老算法兜底
|
||||
char cpuStr[32];
|
||||
@@ -607,23 +639,70 @@ static void fillLoginInfo(LOGIN_INFOR& info)
|
||||
cpuStr + "|" +
|
||||
exePath;
|
||||
g_myClientID = XXH64(idInput.c_str(), idInput.length(), 0);
|
||||
NSLog(@"ClientID(v1 fallback): %llu (IOPlatformUUID 读取失败)", g_myClientID);
|
||||
Mprintf("ClientID(v1 fallback): %llu (IOPlatformUUID 读取失败)\n", g_myClientID);
|
||||
}
|
||||
info.AddReserved(std::to_string(g_myClientID).c_str());
|
||||
|
||||
// PID / 文件大小 / TLS:macOS 暂不上报,占位保持位置(服务端按 LOGIN_RES 下标取值,
|
||||
// PID / 文件大小:macOS 暂不上报,占位保持位置(服务端按 LOGIN_RES 下标取值,
|
||||
// 少发一项会让后面所有字段前移)。
|
||||
info.AddReserved("");
|
||||
info.AddReserved("");
|
||||
info.AddReserved("");
|
||||
// [19] RES_TLS:与 Linux 一致,有信任锚即 1。服务端在线列表的 TLS 列取这个值;
|
||||
// 热切换后重连重发登录,务必用 RefreshLoginTls 刷新成当前状态。
|
||||
info.AddReserved(TlsEnabled() ? 1 : 0);
|
||||
// [20] RES_UPTIME:登录时刻的进程已运行秒数,服务端据此算「启动信息」里的时长
|
||||
info.AddReserved((int)getProcessUptimeSeconds());
|
||||
|
||||
// 服务端签名输入:与服务端 AddList 处签名格式一致(startTime + "|" + clientID)
|
||||
ClientAuth::g_loginMsg = std::string(info.szStartTime) + "|" + std::to_string(g_myClientID);
|
||||
|
||||
NSLog(@"LOGIN_INFOR filled: OS=%s, Host=%s, CPU=%dMHz, PubIP=%s, ClientID=%llu",
|
||||
osVer.c_str(), hostname.c_str(), info.dwCPUMHz, pubIP.c_str(), g_myClientID);
|
||||
Mprintf("LOGIN_INFOR filled: OS=%s, Host=%s, CPU=%dMHz, PubIP=%s, ClientID=%llu\n",
|
||||
osVer.c_str(), hostname.c_str(), info.dwCPUMHz, pubIP.c_str(), g_myClientID);
|
||||
}
|
||||
|
||||
// [[19] RES_TLS] 是「当前」传输状态的快照,服务端在线列表的 TLS 列就取这个值。
|
||||
// logInfo 只在启动时填一次、之后每条连接复用,因此热切换后重连时必须刷新它,
|
||||
// 否则列里会一直显示切换前的状态。szReserved 是按 '|' 位置解析的,这里逐字段
|
||||
// 拆开、只改第 [19] 项再拼回去(不能用 AddReserved,它只会往后追加)。
|
||||
// 只在主线程调用(与 SendLoginInfo 同一线程),避免和接收线程抢同一个结构体。
|
||||
static void RefreshLoginTls(LOGIN_INFOR& info)
|
||||
{
|
||||
std::vector<std::string> fields;
|
||||
std::string s(info.szReserved);
|
||||
size_t pos = 0;
|
||||
for (;;) {
|
||||
size_t bar = s.find('|', pos);
|
||||
if (bar == std::string::npos) {
|
||||
fields.push_back(s.substr(pos));
|
||||
break;
|
||||
}
|
||||
fields.push_back(s.substr(pos, bar - pos));
|
||||
pos = bar + 1;
|
||||
}
|
||||
while (fields.size() <= (size_t)RES_TLS)
|
||||
fields.push_back("");
|
||||
fields[RES_TLS] = TlsEnabled() ? "1" : "0";
|
||||
|
||||
std::string joined;
|
||||
for (size_t i = 0; i < fields.size(); ++i) {
|
||||
if (i)
|
||||
joined += '|';
|
||||
joined += fields[i];
|
||||
}
|
||||
strncpy(info.szReserved, joined.c_str(), sizeof(info.szReserved) - 1);
|
||||
info.szReserved[sizeof(info.szReserved) - 1] = '\0';
|
||||
}
|
||||
|
||||
// 能力位(moduleVersion 的 "-%04X" 后缀)里唯一依赖运行环境的是屏幕预览:
|
||||
// 只有本机已授予录屏权限时才声明,否则服务端会一直要缩略图、每次都要等超时降级。
|
||||
// 与 RefreshLoginTls 一样只在主线程登录前调用,每次重连都会重新判断。
|
||||
static void RefreshLoginCaps(LOGIN_INFOR& info)
|
||||
{
|
||||
unsigned int caps = LOGIN_INFOR::DefaultCaps();
|
||||
if (ScreenPreview::IsAvailable()) {
|
||||
caps |= CLIENT_CAP_SCREEN_PREVIEW;
|
||||
}
|
||||
info.SetCaps(caps);
|
||||
}
|
||||
|
||||
// ============== Signal Handling ==============
|
||||
@@ -648,6 +727,10 @@ static void setupSignals()
|
||||
}
|
||||
|
||||
// 经典 Unix 双 fork 守护进程
|
||||
//
|
||||
// 必须早于任何 Mprintf:Logger 单例在首次 Mprintf 时创建并启动刷盘线程,fork 之后
|
||||
// 子进程里那条线程并不存在(这里 enable=false 不刷盘,ring 与 stderr 镜像照常,
|
||||
// 但别把第一条 Mprintf 挪到本函数之前)。
|
||||
static void daemonize()
|
||||
{
|
||||
// macOS 10.12+ NSLog 默认只写 os_log(Unified Logging),非 TTY 时不写 stderr。
|
||||
@@ -693,6 +776,163 @@ static void daemonize()
|
||||
}
|
||||
}
|
||||
|
||||
// ============== 授权后自动重启 ==============
|
||||
//
|
||||
// macOS 的 TCC 授权对每个进程只算一次:屏幕录制由 WindowServer 按进程缓存,无障碍
|
||||
// 的输入注入也是按进程判定的。用户在「系统设置」里勾上之后,当前进程仍然拿不到,
|
||||
// 必须重新启动;install.sh 每次安装又会 tccutil reset 并重新 ad-hoc 签名(binary
|
||||
// 一变 cdhash 就变,旧记录本来也对不上),所以每次更新都要重新授权。
|
||||
//
|
||||
// 这里把「勾选 → 手动杀掉 → 重新打开」压成「勾两下,应用自己重启一次」:启动时只要
|
||||
// 缺任一权限,就起一个看守线程轮询;补齐后置 g_autoRestartPending,由主循环断开主连接
|
||||
// 再拉起一个**新进程**(RelaunchSelf,不是原地 execv),新进程就是带着授权起来的。
|
||||
//
|
||||
// 为什么用新进程而不是原地 execv:
|
||||
// · TCC 按进程判定,新 pid / 新 audit token 一定重新评估,不赌 exec 会不会刷新缓存;
|
||||
// · 子进程在 exec 前关掉 3 以上的所有 fd,旧的主连接/子连接 socket 不会被带进新
|
||||
// 镜像 —— 否则服务端会一直把一条已经没人读的连接当成在线主机,新登录被排进
|
||||
// standby,要等心跳超时才顶上来。
|
||||
//
|
||||
// 轮询用 CGPreflightScreenCaptureAccess(Permissions::checkScreenCapturePreflight),
|
||||
// 不用 checkScreenCapture():后者每次真的抓一整帧(视网膜屏 20+ MB),而这里要的只是
|
||||
// 「用户刚勾上」这个状态位。而且只对启动时**确实缺**的那一项轮询:启动时已经用真抓一帧
|
||||
// 证明可用的录屏权限不再看 preflight —— 它重签名后会假阴性(见 Permissions.mm),
|
||||
// 真拿它当门槛会让「录屏本来就好、只差无障碍」的场景永远等不到重启。
|
||||
//
|
||||
// 防重启循环:exec 前置 GHOST_AUTO_RELAUNCHED=1,新进程看到它就不再起看守线程,
|
||||
// 每次启动最多自动重启一次。
|
||||
static char** g_relaunchArgv = nullptr;
|
||||
static bool g_permNeedScreen = false; // 启动时确实缺录屏权限(起线程前置好)
|
||||
static bool g_permNeedAx = false;
|
||||
|
||||
static bool RelaunchSelf()
|
||||
{
|
||||
std::string selfPath = getExecutablePath();
|
||||
if (selfPath.empty()) {
|
||||
Mprintf("Auto-restart skipped: cannot resolve the executable path\n");
|
||||
return false;
|
||||
}
|
||||
char resolved[PATH_MAX] = {};
|
||||
const char* exe = realpath(selfPath.c_str(), resolved) ? resolved : selfPath.c_str();
|
||||
|
||||
setenv("GHOST_AUTO_RELAUNCHED", "1", 1);
|
||||
Mprintf("Auto-restart: launching a fresh process (%s)\n", exe);
|
||||
fflush(NULL);
|
||||
|
||||
pid_t pid = fork();
|
||||
if (pid < 0) {
|
||||
Mprintf("Auto-restart failed: fork() errno=%d\n", errno);
|
||||
unsetenv("GHOST_AUTO_RELAUNCHED");
|
||||
return false;
|
||||
}
|
||||
if (pid == 0) {
|
||||
// 子进程:多线程进程 fork 之后只能调用 async-signal-safe 的函数。
|
||||
// 关掉父进程除 0/1/2 外的所有 fd(旧连接 socket 都在其中),新镜像会自己
|
||||
// 重新打开 /tmp/ghost.log。exec 失败以 127 退出,让父进程知道要留下来。
|
||||
long maxfd = sysconf(_SC_OPEN_MAX);
|
||||
if (maxfd < 0 || maxfd > 65536) maxfd = 65536;
|
||||
for (long fd = 3; fd < maxfd; ++fd) close((int)fd);
|
||||
execv(exe, g_relaunchArgv);
|
||||
_exit(127);
|
||||
}
|
||||
|
||||
// 父进程:等子进程交出结果。成功的子进程不会退出;daemon 模式下 exec 后的镜像会
|
||||
// 以 0 退出、把守护进程交给它再 fork 出来的孙进程。失败的样子有好几种,一律当失败
|
||||
// 并保留当前进程 —— 不能因为换进程失败把客户端弄丢:
|
||||
// · execv 失败(127);
|
||||
// · AMFI 因签名不符 SIGKILL(install.sh 的注释里就写了这个场景:服务端 patch 过
|
||||
// 地址的 binary 必须先重签,没签的那份一 exec 就被内核杀掉);
|
||||
// · dyld 装载失败 / 静态初始化期崩溃(SIGABRT 等);
|
||||
// · daemonize() 的 fork 失败(exit(1))。
|
||||
// 交接 1 秒之后才发生的崩溃看不到,这是换进程本身的上限。
|
||||
int status = 0;
|
||||
bool handoffFailed = false;
|
||||
for (int i = 0; i < 200; ++i) {
|
||||
pid_t r = waitpid(pid, &status, WNOHANG);
|
||||
if (r == pid) {
|
||||
handoffFailed = WIFSIGNALED(status) || (WIFEXITED(status) && WEXITSTATUS(status) != 0);
|
||||
break;
|
||||
}
|
||||
Sleep(5);
|
||||
}
|
||||
|
||||
// 交接的这 1 秒里如果收到了停止请求(信号、Activity Monitor 里退出、服务端
|
||||
// COMMAND_BYE),新进程并不知道这件事,会把刚退出的客户端又拉起来。收掉子进程,
|
||||
// 让退出照常完成。
|
||||
if (!g_running) {
|
||||
Mprintf("Auto-restart cancelled: shutdown was requested while starting the new process\n");
|
||||
if (kill(pid, SIGTERM) == 0) {
|
||||
bool reaped = false;
|
||||
for (int i = 0; i < 200 && !reaped; ++i) {
|
||||
int st = 0;
|
||||
if (waitpid(pid, &st, WNOHANG) == pid) reaped = true;
|
||||
else Sleep(5);
|
||||
}
|
||||
if (!reaped) {
|
||||
kill(pid, SIGKILL);
|
||||
waitpid(pid, NULL, 0);
|
||||
}
|
||||
}
|
||||
unsetenv("GHOST_AUTO_RELAUNCHED");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (handoffFailed) {
|
||||
if (WIFEXITED(status) && WEXITSTATUS(status) == 127) {
|
||||
Mprintf("Auto-restart failed: the new process could not exec %s\n", exe);
|
||||
} else if (WIFSIGNALED(status)) {
|
||||
Mprintf("Auto-restart failed: the new process was killed by signal %d during startup\n",
|
||||
WTERMSIG(status));
|
||||
} else {
|
||||
Mprintf("Auto-restart failed: the new process exited with %d during startup\n",
|
||||
WEXITSTATUS(status));
|
||||
}
|
||||
unsetenv("GHOST_AUTO_RELAUNCHED");
|
||||
return false;
|
||||
}
|
||||
|
||||
Mprintf("Auto-restart: handing over to the new process\n");
|
||||
_exit(0);
|
||||
return false; // 不可达
|
||||
}
|
||||
|
||||
// 看守线程:等启动时缺的权限补齐,然后请主循环重启(重启本身在主线程里做)。
|
||||
static void* PermissionWatcherThread(void* /*param*/)
|
||||
{
|
||||
const bool needScreen = g_permNeedScreen;
|
||||
const bool needAx = g_permNeedAx;
|
||||
|
||||
if (needScreen && needAx) {
|
||||
Mprintf("Permission watcher: waiting for screen recording and accessibility...\n");
|
||||
} else if (needScreen) {
|
||||
Mprintf("Permission watcher: waiting for screen recording...\n");
|
||||
} else {
|
||||
Mprintf("Permission watcher: waiting for accessibility...\n");
|
||||
}
|
||||
|
||||
const int kMaxWaitSec = 15 * 60;
|
||||
for (int waited = 0; g_running && !g_autoRestartPending && waited < kMaxWaitSec; ++waited) {
|
||||
const bool screenOk = !needScreen || Permissions::checkScreenCapturePreflight();
|
||||
const bool axOk = !needAx || Permissions::checkAccessibility();
|
||||
if (screenOk && axOk) {
|
||||
Mprintf("Permissions are granted; asking the main loop to restart\n");
|
||||
g_autoRestartPending = true;
|
||||
return NULL;
|
||||
}
|
||||
if (waited % 30 == 0) {
|
||||
Mprintf("Permission watcher: still waiting (%ds): screen=%s, accessibility=%s\n",
|
||||
waited, screenOk ? "granted" : "missing", axOk ? "granted" : "missing");
|
||||
}
|
||||
Sleep(1000);
|
||||
}
|
||||
|
||||
if (g_running && !g_autoRestartPending) {
|
||||
Mprintf("Permission watcher: gave up after %ds; restart the app once permissions are granted\n",
|
||||
kMaxWaitSec);
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// ============== Main Entry Point ==============
|
||||
// RttEstimator + g_rttEstimator + g_heartbeatInterval 已抽到 common/rtt_estimator.h
|
||||
|
||||
@@ -742,6 +982,19 @@ void* FileManagerworkingThread(void* /*param*/)
|
||||
return NULL;
|
||||
}
|
||||
|
||||
void* SystemManagerworkingThread(void* /*param*/)
|
||||
{
|
||||
// 进程/窗口子连接。SystemManager 的构造函数会把首包 TOKEN_PSLIST 发出去,
|
||||
// 服务端据此判定「系统子连接就绪」(kill_process 的确认包也靠它)。
|
||||
RunSubConnThread<SystemManager>(
|
||||
"SystemManagerworkingThread",
|
||||
[](IOCPClient* c) { return std::unique_ptr<SystemManager>(new SystemManager(c)); },
|
||||
[](IOCPClient* c, SystemManager*) {
|
||||
Mprintf(">>> SystemManagerworkingThread [%p] initialized\n", c);
|
||||
});
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// 日志上报(对应 Windows 端 CClientLogManager):子连接建立即发首包全量。
|
||||
// 服务端取走首包后会关掉这条子连接,发完等连接断开即可。
|
||||
void* ClientLogworkingThread(void* /*param*/)
|
||||
@@ -755,6 +1008,122 @@ void* ClientLogworkingThread(void* /*param*/)
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// 子连接 worker 线程的唯一启动点。
|
||||
//
|
||||
// 顺序是有意为之:先把「收到命令」打出来,再 spawn。原先 Mprintf 写在
|
||||
// std::thread(...).detach() 之后,一旦线程创建失败(pthread_create 返回
|
||||
// EAGAIN/EPERM,进程线程数到顶、或受宿主环境限制),std::thread 构造函数抛
|
||||
// std::system_error,异常会穿过 DataProcess 落到 OnServerReceiving 的 catch(...),
|
||||
// 客户端日志里只剩一行笼统的 "[ERROR] OnServerReceiving catch an error":
|
||||
// 「点了终端/桌面/文件毫无反应,而且连一条收到命令的日志都没有」正是这样产生的
|
||||
// ——坏的三个功能恰好全都 spawn 线程,好的 SYSTEM(当时只打日志)/WSLIST 恰好都不 spawn。
|
||||
// 后来 COMMAND_SYSTEM 也接上了子连接(SystemManagerworkingThread),这条历史注释保留
|
||||
// 是为了说明「线程创建失败会让功能看起来毫无反应」这个坑。
|
||||
static void SpawnSubConnWorker(const char* name, void* (*entry)(void*))
|
||||
{
|
||||
Mprintf("** Received '%s' command, spawning worker ***\n", name);
|
||||
try {
|
||||
std::thread(entry, nullptr).detach();
|
||||
} catch (const std::system_error& e) {
|
||||
// 线程创建失败只会抛 system_error,code() 里就是 pthread_create 的返回值
|
||||
// (EAGAIN=35 / EPERM=1)。这里不能读 errno:libc++ 是把 pthread_create 的
|
||||
// 返回值直接包成 error_code 抛出,并不设置 errno,读到的会是无关的旧值。
|
||||
Mprintf("*** spawn '%s' worker FAILED: %s (code=%d) ***\n",
|
||||
name, e.what(), e.code().value());
|
||||
} catch (const std::exception& e) {
|
||||
Mprintf("*** spawn '%s' worker FAILED: %s ***\n", name, e.what());
|
||||
}
|
||||
}
|
||||
|
||||
// 信任锚已落盘/已删除:热重载 TLS 状态,必要时请求主循环重建连接。
|
||||
// 只在传输方式真正变化(明文↔TLS)时重连;仅换证书(仍是 TLS)不打断现有会话,
|
||||
// 新锚从下一条新连接开始生效。与 linux/main.cpp 的 ApplyTlsAnchorChange 同语义。
|
||||
static void ApplyTlsAnchorChange(void* user)
|
||||
{
|
||||
bool before = TlsEnabled();
|
||||
std::string err;
|
||||
if (!TlsReload(err)) {
|
||||
Mprintf("** [%p] TLS reload failed: %s (keeping current transport) ***\n", user, err.c_str());
|
||||
return;
|
||||
}
|
||||
bool after = TlsEnabled();
|
||||
if (before == after) {
|
||||
Mprintf("** [%p] TLS trust anchor updated, transport unchanged (%s) ***\n",
|
||||
user, after ? "TLS" : "plaintext");
|
||||
return;
|
||||
}
|
||||
g_needReconnect.store(true);
|
||||
Mprintf("** [%p] TLS transport switched to %s, reconnecting ***\n",
|
||||
user, after ? "TLS" : "plaintext");
|
||||
}
|
||||
|
||||
// ============== 屏幕预览(COMMAND_SCREEN_PREVIEW_REQ) ==============
|
||||
// 同一时刻只跑一个抓屏任务:列表缩略图是周期性刷新,服务端还可能重发/并发请求,
|
||||
// 多余的直接丢弃,让服务端超时后按「预览不可用」降级(与 Linux 端限流一致)。
|
||||
static std::atomic<int> g_previewInFlight(0);
|
||||
|
||||
static void ScreenPreviewThread(ScreenPreviewReq req)
|
||||
{
|
||||
// 抓屏/缩放全程可能在几十毫秒量级,跑在独立线程里,不阻塞接收线程
|
||||
struct InFlightGuard {
|
||||
~InFlightGuard() { g_previewInFlight.fetch_sub(1); }
|
||||
} guard;
|
||||
|
||||
std::vector<unsigned char> pixels;
|
||||
int w = 0, h = 0;
|
||||
int st = ScreenPreview::Capture(req.maxWidth, pixels, w, h);
|
||||
bool ok = (st == SCREEN_PREVIEW_OK) && !pixels.empty();
|
||||
if (!ok) pixels.clear();
|
||||
|
||||
uint32_t bytes = ok ? (uint32_t)pixels.size() : 0;
|
||||
std::vector<char> pkt(sizeof(ScreenPreviewRspHeader) + bytes);
|
||||
ScreenPreviewRspHeader* hdr = (ScreenPreviewRspHeader*)pkt.data();
|
||||
memset(hdr, 0, sizeof(*hdr));
|
||||
hdr->token = TOKEN_SCREEN_PREVIEW_RSP;
|
||||
hdr->reqId = req.reqId;
|
||||
hdr->status = (uint8_t)st;
|
||||
// 成功时发原始 BGRA,由服务端统一编码成 JPEG(macOS 没有与 Windows GDI+ 输出
|
||||
// 一致的 JPEG 路径);失败时 format 无意义,填 JPEG 保持包头合法
|
||||
hdr->format = ok ? SCREEN_PREVIEW_FMT_BGRX : SCREEN_PREVIEW_FMT_JPEG;
|
||||
hdr->width = (uint16_t)w;
|
||||
hdr->height = (uint16_t)h;
|
||||
hdr->bytes = bytes;
|
||||
if (ok) {
|
||||
memcpy(pkt.data() + sizeof(*hdr), pixels.data(), pixels.size());
|
||||
}
|
||||
|
||||
// Send2Server 内部持锁,可在工作线程调用;进程退出/断线时不再回包
|
||||
if (g_bExit == S_CLIENT_NORMAL && g_pMainClient && g_pMainClient->IsConnected()) {
|
||||
g_pMainClient->Send2Server(pkt.data(), (int)pkt.size());
|
||||
}
|
||||
if (!ok) {
|
||||
Mprintf("** Screen preview capture failed: status=%d ***\n", st);
|
||||
}
|
||||
}
|
||||
|
||||
// ============== 历史活动(COMMAND_QUERY_ACTIVITY → TOKEN_REPORT_ACTIVITY) ==============
|
||||
// 与 Windows/Linux 一致:主连接一次性快照,不开子连接(服务端 TOKEN_REPORT_ACTIVITY
|
||||
// 分支不 CancelIO)。快照要拿锁、拼字符串,放线程里,别堵接收线程。
|
||||
// 同时在飞的报表最多一份:连点/多个 MCP 调用把同一份快照叠起来没有任何意义。
|
||||
static std::atomic<int> g_activityReportsInFlight(0);
|
||||
|
||||
static void ActivityReportThread()
|
||||
{
|
||||
std::string text = MacActivityHistory::Instance().Dump();
|
||||
if (text.empty())
|
||||
text = MacActivityHistory::EmptyText();
|
||||
|
||||
std::vector<BYTE> pkt(1 + text.size());
|
||||
pkt[0] = TOKEN_REPORT_ACTIVITY;
|
||||
if (!text.empty())
|
||||
memcpy(pkt.data() + 1, text.data(), text.size());
|
||||
bool sent = false;
|
||||
if (g_bExit == S_CLIENT_NORMAL && g_pMainClient && g_pMainClient->IsConnected())
|
||||
sent = g_pMainClient->Send2Server((char*)pkt.data(), (ULONG)pkt.size()) != FALSE;
|
||||
Mprintf("[Activity] report %zu bytes%s\n", text.size(), sent ? "" : " FAILED");
|
||||
g_activityReportsInFlight.fetch_sub(1, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
|
||||
{
|
||||
if (szBuffer == nullptr || ulLength == 0)
|
||||
@@ -771,21 +1140,49 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
|
||||
g_bExit = S_CLIENT_EXIT;
|
||||
g_running = false; // Stop main loop to prevent reconnection
|
||||
} else if (szBuffer[0] == COMMAND_SHELL) {
|
||||
std::thread(ShellworkingThread, nullptr).detach();
|
||||
Mprintf("** [%p] Received 'SHELL' command ***\n", user);
|
||||
SpawnSubConnWorker("SHELL", ShellworkingThread);
|
||||
} else if (szBuffer[0] == COMMAND_SCREEN_SPY) {
|
||||
std::thread(ScreenworkingThread, nullptr).detach();
|
||||
Mprintf("** [%p] Received 'SCREEN_SPY' command ***\n", user);
|
||||
SpawnSubConnWorker("SCREEN_SPY", ScreenworkingThread);
|
||||
} else if (szBuffer[0] == COMMAND_SYSTEM) {
|
||||
Mprintf("** [%p] Received 'SYSTEM' command ***\n", user);
|
||||
// 系统子连接:进程列表、杀进程、窗口列表都在子连接上收发(同 Windows/Linux)
|
||||
SpawnSubConnWorker("SYSTEM", SystemManagerworkingThread);
|
||||
} else if (szBuffer[0] == COMMAND_LIST_DRIVE) {
|
||||
std::thread(FileManagerworkingThread, nullptr).detach();
|
||||
Mprintf("** [%p] Received 'LIST_DRIVE' command ***\n", user);
|
||||
SpawnSubConnWorker("LIST_DRIVE", FileManagerworkingThread);
|
||||
} else if (szBuffer[0] == COMMAND_QUERY_LOG) {
|
||||
// 与 Windows 端一致:回日志必须开子连接(服务端取走首包后 CancelIO 关的是
|
||||
// 子连接;若回在主连接上,被关掉的就是主连接本身)。
|
||||
std::thread(ClientLogworkingThread, nullptr).detach();
|
||||
Mprintf("** [%p] Received 'QUERY_LOG' command ***\n", user);
|
||||
SpawnSubConnWorker("QUERY_LOG", ClientLogworkingThread);
|
||||
} else if (szBuffer[0] == COMMAND_QUERY_ACTIVITY) {
|
||||
// 历史活动:主连接一次性快照。已经有报表在飞就丢掉这一次
|
||||
// (服务端每主机单飞行,连点也只是重复请求)
|
||||
if (g_activityReportsInFlight.fetch_add(1) >= 1) {
|
||||
g_activityReportsInFlight.fetch_sub(1);
|
||||
return TRUE;
|
||||
}
|
||||
Mprintf("** [%p] Received 'QUERY_ACTIVITY' command ***\n", user);
|
||||
try {
|
||||
std::thread(ActivityReportThread).detach();
|
||||
} catch (const std::exception& e) {
|
||||
// 线程起不来要把在途计数还回去,否则之后的历史活动请求全被当成「忙」丢掉
|
||||
g_activityReportsInFlight.fetch_sub(1);
|
||||
Mprintf("** Activity report thread failed: %s ***\n", e.what());
|
||||
}
|
||||
} else if (szBuffer[0] == COMMAND_SCREEN_PREVIEW_REQ) {
|
||||
if (ulLength < sizeof(ScreenPreviewReq)) return TRUE;
|
||||
ScreenPreviewReq req;
|
||||
memcpy(&req, szBuffer, sizeof(req));
|
||||
// 抓屏可能耗几十毫秒,必须离开接收线程;超额请求直接丢弃(服务端会超时降级)
|
||||
if (g_previewInFlight.fetch_add(1) >= 1) {
|
||||
g_previewInFlight.fetch_sub(1);
|
||||
return TRUE;
|
||||
}
|
||||
try {
|
||||
std::thread(ScreenPreviewThread, req).detach();
|
||||
} catch (const std::exception& e) {
|
||||
// 线程起不来时必须把在途计数还回去,否则后面所有预览请求都会被当成「忙」丢掉
|
||||
g_previewInFlight.fetch_sub(1);
|
||||
Mprintf("** Screen preview thread failed: %s ***\n", e.what());
|
||||
}
|
||||
} else if (szBuffer[0] == COMMAND_C2C_PREPARE) {
|
||||
// C2C 准备接收通知
|
||||
FileTransferV2::HandleC2CPrepare(szBuffer, ulLength, nullptr);
|
||||
@@ -807,8 +1204,8 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
|
||||
}
|
||||
}
|
||||
} else if (szBuffer[0] == COMMAND_SEND_FILE_V2 || szBuffer[0] == COMMAND_FILE_COMPLETE_V2) {
|
||||
// V2 文件接收
|
||||
int result = FileTransferV2::RecvFileChunkV2(szBuffer, ulLength, g_myClientID);
|
||||
// V2 文件接收;g_pMainClient 用于 C2C 落盘回执(DataProcess 的 user 恒为 NULL)
|
||||
int result = FileTransferV2::RecvFileChunkV2(szBuffer, ulLength, g_myClientID, g_pMainClient);
|
||||
if (result != 0) {
|
||||
Mprintf("** [%p] V2 File recv error: %d ***\n", user, result);
|
||||
}
|
||||
@@ -866,6 +1263,31 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
|
||||
// 标记需要重发登录信息(让服务端更新分组显示)
|
||||
g_needResendLogin.store(true);
|
||||
Mprintf("** [%p] Group changed to: %s ***\n", user, groupName.c_str());
|
||||
} else if (szBuffer[0] == COMMAND_TLS_ENABLE) {
|
||||
// 服务端下发信任锚证书(载荷与 Windows/Linux 一致:szBuffer+1 起为 PEM 正文)。
|
||||
// 落盘到 ~/.config/ghost/yama-ca.pem 后热重载,传输方式真正变化时由主循环重连。
|
||||
if (ulLength > 1) {
|
||||
std::string pem((char*)szBuffer + 1, ulLength - 1);
|
||||
std::string err;
|
||||
if (TlsTrustAnchorSave(pem, err)) {
|
||||
Mprintf("** [%p] TLS trust anchor received and saved ***\n", user);
|
||||
ApplyTlsAnchorChange(user);
|
||||
} else {
|
||||
Mprintf("** [%p] TLS trust anchor save failed: %s ***\n", user, err.c_str());
|
||||
}
|
||||
} else {
|
||||
// 没有证书正文就等于「启用但没有锚」——不该悄悄忽略,留一行便于排查。
|
||||
Mprintf("** [%p] COMMAND_TLS_ENABLE without a certificate payload, ignored\n", user);
|
||||
}
|
||||
} else if (szBuffer[0] == COMMAND_TLS_DISABLE) {
|
||||
// 撤销信任锚:删除配置文件并热重载,当前连接若是 TLS 就重连回明文。
|
||||
std::string err;
|
||||
if (TlsTrustAnchorRemove(err)) {
|
||||
Mprintf("** [%p] TLS trust anchor removed ***\n", user);
|
||||
ApplyTlsAnchorChange(user);
|
||||
} else {
|
||||
Mprintf("** [%p] TLS trust anchor removal: %s ***\n", user, err.c_str());
|
||||
}
|
||||
} else {
|
||||
Mprintf("** [%p] Received unimplemented command: %d ***\n", user, int(szBuffer[0]));
|
||||
}
|
||||
@@ -876,6 +1298,9 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
|
||||
// -d 后台守护进程模式
|
||||
int main(int argc, const char* argv[])
|
||||
{
|
||||
// 自动重启要按原样重放命令行(比如带 -d),argv 在进程生命周期内一直有效
|
||||
g_relaunchArgv = const_cast<char**>(argv);
|
||||
|
||||
// 解析 -d 参数
|
||||
bool daemon_mode = (argc > 1 && strcmp(argv[1], "-d") == 0);
|
||||
|
||||
@@ -898,14 +1323,20 @@ int main(int argc, const char* argv[])
|
||||
}
|
||||
|
||||
@autoreleasepool {
|
||||
NSLog(@"=== macOS Ghost Client%s ===", daemon_mode ? " (daemon)" : "");
|
||||
Mprintf("=== macOS Ghost Client%s ===\n", daemon_mode ? " (daemon)" : "");
|
||||
// 上一代进程补齐权限后把我们拉起来的。这行进内存 ring,主控端「运行日志」能
|
||||
// 看到;触发重启的那行 "Auto-restart: ..." 只留在 /tmp/ghost.log 里(ring 随
|
||||
// 旧进程一起没了)。
|
||||
if (getenv("GHOST_AUTO_RELAUNCHED")) {
|
||||
Mprintf("(started by the auto-restart after permissions were granted)\n");
|
||||
}
|
||||
|
||||
// ============== Power Management: Keep System Awake ==============
|
||||
// 1. Disable App Nap - prevent macOS from suspending this process
|
||||
id<NSObject> powerActivity = [[NSProcessInfo processInfo]
|
||||
beginActivityWithOptions:(NSActivityUserInitiated | NSActivityIdleSystemSleepDisabled)
|
||||
reason:@"Remote control client must maintain persistent connection"];
|
||||
NSLog(@"App Nap disabled, activity token acquired");
|
||||
Mprintf("App Nap disabled, activity token acquired\n");
|
||||
|
||||
// 2. Prevent system idle sleep using IOKit power assertion
|
||||
IOPMAssertionID sleepAssertionID = 0;
|
||||
@@ -916,9 +1347,9 @@ int main(int argc, const char* argv[])
|
||||
&sleepAssertionID
|
||||
);
|
||||
if (result == kIOReturnSuccess) {
|
||||
NSLog(@"Power assertion created: system idle sleep disabled (ID: %u)", sleepAssertionID);
|
||||
Mprintf("Power assertion created: system idle sleep disabled (ID: %u)\n", sleepAssertionID);
|
||||
} else {
|
||||
NSLog(@"Warning: Failed to create power assertion (error: 0x%x)", result);
|
||||
Mprintf("Warning: Failed to create power assertion (error: 0x%x)\n", result);
|
||||
}
|
||||
|
||||
// 3. Display sleep: managed by ScreenHandler - only prevents display sleep
|
||||
@@ -929,17 +1360,30 @@ int main(int argc, const char* argv[])
|
||||
|
||||
// Load configuration file (~/.config/ghost/config.conf)
|
||||
loadConfig();
|
||||
NSLog(@"Config loaded from %s", g_configPath.c_str());
|
||||
Mprintf("Config loaded from %s\n", g_configPath.c_str());
|
||||
|
||||
// 历史活动采样:进程一启动就开始攒(服务端随时可能来查),
|
||||
// 与 Linux 端在登录前 Start 的时机一致。
|
||||
MacActivityHistory::Instance().Start();
|
||||
|
||||
// 传输方式由信任锚文件决定(服务端右键「TLS 传输」才会写入 ~/.config/ghost/yama-ca.pem)。
|
||||
// 启动时打一行,排查「首次连接为什么/为什么不加密」不用去猜。
|
||||
if (TlsLoadError()) {
|
||||
Mprintf("[TLS] trust anchor exists but failed to load; connections will be refused (fail-closed)\n");
|
||||
} else {
|
||||
Mprintf("[TLS] transport on first connect: %s\n",
|
||||
TlsEnabled() ? "TLS (trust anchor present)" : "plaintext (no trust anchor)");
|
||||
}
|
||||
|
||||
// Check permissions
|
||||
NSLog(@"Checking permissions...");
|
||||
Mprintf("Checking permissions...\n");
|
||||
|
||||
bool hasScreenCapture = Permissions::checkScreenCapture();
|
||||
if (hasScreenCapture) {
|
||||
NSLog(@"Screen capture permission: OK");
|
||||
Mprintf("Screen capture permission: OK\n");
|
||||
} else {
|
||||
NSLog(@"Screen capture permission not granted.");
|
||||
NSLog(@"Please grant permission in System Preferences > Privacy & Security > Screen Recording");
|
||||
Mprintf("Screen capture permission not granted.\n");
|
||||
Mprintf("Please grant permission in System Preferences > Privacy & Security > Screen Recording\n");
|
||||
// Request permission (triggers system dialog on first run)
|
||||
Permissions::requestScreenCapture();
|
||||
// Only open settings if this appears to be a re-run without permission
|
||||
@@ -951,25 +1395,45 @@ int main(int argc, const char* argv[])
|
||||
|
||||
bool hasAccessibility = Permissions::checkAccessibility();
|
||||
if (hasAccessibility) {
|
||||
NSLog(@"Accessibility permission: OK");
|
||||
Mprintf("Accessibility permission: OK\n");
|
||||
} else {
|
||||
NSLog(@"Accessibility permission not granted.");
|
||||
NSLog(@"Please grant permission in System Preferences > Privacy & Security > Accessibility");
|
||||
Mprintf("Accessibility permission not granted.\n");
|
||||
Mprintf("Please grant permission in System Preferences > Privacy & Security > Accessibility\n");
|
||||
Permissions::requestAccessibility();
|
||||
}
|
||||
|
||||
// 缺权限时起看守线程:用户在系统设置里勾选后自动重启一次,省掉手动杀掉重开。
|
||||
// 上面的 request* 已经把两个系统提示都弹了,这里只负责「授权完成 → 应用重启」。
|
||||
if (!hasScreenCapture || !hasAccessibility) {
|
||||
if (getenv("GHOST_AUTO_RELAUNCHED")) {
|
||||
Mprintf("Auto-restart already used once this launch; restart manually after granting permissions\n");
|
||||
} else {
|
||||
g_permNeedScreen = !hasScreenCapture;
|
||||
g_permNeedAx = !hasAccessibility;
|
||||
pthread_t tid;
|
||||
if (pthread_create(&tid, nullptr, PermissionWatcherThread, nullptr) == 0) {
|
||||
pthread_detach(tid);
|
||||
} else {
|
||||
Mprintf("Warning: failed to start the permission watcher\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// FDA check is unreliable (no official API), just log a warning
|
||||
if (!Permissions::checkFullDiskAccess()) {
|
||||
NSLog(@"Full Disk Access: not detected (may be false negative).");
|
||||
NSLog(@"If file access issues occur, grant FDA in System Preferences > Privacy & Security > Full Disk Access");
|
||||
Mprintf("Full Disk Access: not detected (may be false negative).\n");
|
||||
Mprintf("If file access issues occur, grant FDA in System Preferences > Privacy & Security > Full Disk Access\n");
|
||||
// Don't auto-open settings since detection is unreliable
|
||||
} else {
|
||||
NSLog(@"Full Disk Access: OK");
|
||||
Mprintf("Full Disk Access: OK\n");
|
||||
}
|
||||
|
||||
// Create client
|
||||
auto ClientObject = std::make_unique<IOCPClient>(g_bExit, false);
|
||||
ClientObject->setManagerCallBack(NULL, DataProcess, NULL);
|
||||
// C2C 落盘回执要在主连接上回包,但 DataProcess 拿到的 user 恒为 NULL,
|
||||
// 只能靠全局句柄(同 linux/main.cpp)。重连复用同一个对象,因此只在这里赋一次。
|
||||
g_pMainClient = ClientObject.get();
|
||||
// 同 Linux:不传 conn 就取不到注入的 CONNECT_ADDRESS,协议必须显式喂进去,
|
||||
// 否则配成 WS/WSS 也只会静默按明文 TCP 直连。
|
||||
ClientObject->SetDefaultProto((int)(unsigned char)g_SETTINGS.protoType);
|
||||
@@ -979,19 +1443,34 @@ int main(int argc, const char* argv[])
|
||||
}
|
||||
|
||||
// Main event loop
|
||||
NSLog(@"Starting main loop...");
|
||||
Mprintf("Starting main loop...\n");
|
||||
LOGIN_INFOR logInfo;
|
||||
fillLoginInfo(logInfo);
|
||||
|
||||
while (g_running) {
|
||||
// 权限补齐后重启:放在循环最前面,连着的和没连上的都只走这一个出口。
|
||||
if (g_autoRestartPending) {
|
||||
Mprintf("Restarting to apply newly granted permissions\n");
|
||||
if (RelaunchSelf()) break; // 成功则不返回(父进程直接退出)
|
||||
Mprintf("Auto-restart failed; continuing with the current process\n");
|
||||
g_autoRestartPending = false;
|
||||
}
|
||||
clock_t c = clock();
|
||||
if (!ClientObject->ConnectServer(g_SETTINGS.ServerIP(), g_SETTINGS.ServerPort())) {
|
||||
Sleep(5000);
|
||||
continue;
|
||||
}
|
||||
// 上一条连接断掉时若还挂着「切换传输」的请求,这条连接已经是按新信任锚
|
||||
// 建立的了(ConnectServer 现读 TlsEnabled),标志已过时——不清掉会让心跳
|
||||
// 循环刚进去就再断一次,白白抖动一轮。
|
||||
g_needReconnect.store(false);
|
||||
|
||||
// 进入新连接,重置服务端身份校验状态
|
||||
ClientAuth::OnNewConnection();
|
||||
// 本条连接可能是热切换信任锚后重建的:TLS 标志按当前状态重算,再发登录。
|
||||
RefreshLoginTls(logInfo);
|
||||
// 录屏授权可能刚补齐(看守线程会重启进程,但这一次登录也要报对能力位)
|
||||
RefreshLoginCaps(logInfo);
|
||||
ClientObject->SendLoginInfo(logInfo.Speed(clock() - c));
|
||||
|
||||
// 心跳保活循环:定时发送心跳包,服务端回复后动态更新 RTT
|
||||
@@ -999,6 +1478,7 @@ int main(int argc, const char* argv[])
|
||||
// 检查是否需要重发登录信息(分组变更后)
|
||||
if (g_needResendLogin.exchange(false)) {
|
||||
fillLoginInfo(logInfo);
|
||||
RefreshLoginCaps(logInfo);
|
||||
ClientObject->SendLoginInfo(logInfo);
|
||||
Mprintf(">> Resent login info after group change\n");
|
||||
}
|
||||
@@ -1006,10 +1486,27 @@ int main(int argc, const char* argv[])
|
||||
// 等待心跳间隔(每秒检查一次退出条件,保证及时响应)
|
||||
int interval = g_heartbeatInterval > 0 ? g_heartbeatInterval : 30;
|
||||
for (int i = 0; i < interval; ++i) {
|
||||
if (g_needReconnect.load(std::memory_order_relaxed))
|
||||
break;
|
||||
if (g_autoRestartPending)
|
||||
break;
|
||||
if (!ClientObject->IsRunning() || !ClientObject->IsConnected() || g_bExit != S_CLIENT_NORMAL)
|
||||
break;
|
||||
Sleep(1000);
|
||||
}
|
||||
// 权限补齐:先正常断开主连接,再回外层重启 —— 服务端立刻看到断开,
|
||||
// 新进程登录时不会和一条「还挂着」的旧连接撞车。
|
||||
if (g_autoRestartPending) {
|
||||
ClientObject->Disconnect();
|
||||
break;
|
||||
}
|
||||
// 信任锚热切换(COMMAND_TLS_ENABLE/DISABLE)会置这个标志:
|
||||
// 断开后由外层循环按新的传输方式重连。
|
||||
if (g_needReconnect.exchange(false)) {
|
||||
Mprintf(">>> Reconnecting to apply the transport change\n");
|
||||
ClientObject->Disconnect();
|
||||
break;
|
||||
}
|
||||
if (!ClientObject->IsRunning() || !ClientObject->IsConnected() || g_bExit != S_CLIENT_NORMAL)
|
||||
break;
|
||||
|
||||
@@ -1043,12 +1540,21 @@ int main(int argc, const char* argv[])
|
||||
Mprintf(">>> Exit normally (g_bExit=%d)\n", (int)g_bExit);
|
||||
}
|
||||
|
||||
NSLog(@"Shutting down...");
|
||||
Mprintf("Shutting down...\n");
|
||||
|
||||
// 先断开在飞线程对主连接的引用:抓屏/历史活动线程是 detach 出来的,
|
||||
// ClientObject 出作用域时它们可能还在跑。g_bExit 已置位能挡住绝大多数,
|
||||
// 清空指针是最后一道保险(先判 g_bExit 再解引用)。
|
||||
g_pMainClient = nullptr;
|
||||
|
||||
// 先收采样线程再关日志:采样循环本身不写日志,但停在静态析构里
|
||||
// 会撞上正在拆除的 CoreFoundation 对象,不如走正常退出路径收干净。
|
||||
MacActivityHistory::Instance().Stop();
|
||||
|
||||
// Release power assertions
|
||||
if (sleepAssertionID) {
|
||||
IOPMAssertionRelease(sleepAssertionID);
|
||||
NSLog(@"Released sleep assertion");
|
||||
Mprintf("Released sleep assertion\n");
|
||||
}
|
||||
// Display assertion is managed by ScreenHandler (released in stop())
|
||||
// powerActivity is automatically released when exiting @autoreleasepool
|
||||
|
||||
+204
-15
@@ -363,11 +363,12 @@
|
||||
},
|
||||
{
|
||||
"name": "get_activity_history",
|
||||
"description": "获取指定在线主机的历史活动记录。Windows 与有桌面的 Linux 客户端返回前台窗口驻留记录,每行一条「[时间] [标题] 时长」;Android 客户端返回前台应用驻留记录(标题为「应用名 (包名)」,需开启无障碍服务);无桌面的 Linux 客户端返回登录记录与 shell 命令历史,每行带「[登录]」或「[命令]」标签(首行为「[来源]」说明)。主连接 RPC。结果按 limit/offset 分页(默认 100 条、上限 1000),新在前:offset=0 就是最近 limit 条,想看更早的再往后翻。total 为本机现有记录总数,hasMore 表示还有更早的记录;窗口后端只保留最近 500 条,所以 total 最多约 501(含进行中的当前窗口)。",
|
||||
"description": "获取指定在线主机的历史活动记录。Windows、有桌面的 Linux 与 macOS 客户端返回前台窗口驻留记录,每行一条「[时间] [标题] 时长」(macOS 无录屏授权时标题退化为应用名);Android 客户端返回前台应用驻留记录(标题为「应用名 (包名)」,需开启无障碍服务);无桌面的 Linux 客户端返回登录记录与 shell 命令历史,每行带「[登录]」或「[命令]」标签(首行为「[来源]」说明)。主连接 RPC。结果按 limit/offset 分页(默认 100 条、上限 1000),新在前:offset=0 就是最近 limit 条,想看更早的再往后翻。total 为本机现有记录总数,hasMore 表示还有更早的记录;窗口后端只保留最近 500 条,所以 total 最多约 501(含进行中的当前窗口)。",
|
||||
"gate": null,
|
||||
"platforms": [
|
||||
"win",
|
||||
"lnx",
|
||||
"mac",
|
||||
"apk"
|
||||
],
|
||||
"impl": "mfc",
|
||||
@@ -506,15 +507,57 @@
|
||||
},
|
||||
{
|
||||
"name": "get_screenshot",
|
||||
"description": "截取指定在线主机的一帧画面,返回 base64 编码的 JPEG 图片(image 对象含 mimeType/data/width/height)。支持 Windows 与带 X11 桌面的 Linux 客户端(能力位 CLIENT_CAP_SCREEN_PREVIEW),主连接 RPC、一次性返回。Android 客户端用无障碍服务 takeScreenshot 抓屏(Android 11+ 且开启无障碍服务,此时登录会声明该能力位;只支持 mode=screen)。mode 可选 screen(默认,整虚拟桌面)/region(指定矩形)/window(指定 hwnd)/monitor(指定显示器);后三种默认按源尺寸 1:1 原生分辨率抓取(适合 OCR/视觉读字),需要较新的 Windows 客户端(CLIENT_CAP_SCREEN_REGION,否则 -32005),结果在 structuredContent.capture 里回报实际源矩形与缩放比例。",
|
||||
"description": "截取指定在线主机的一帧画面,返回 base64 编码的 JPEG 图片:图片在 content 的 image 块(data 为 base64,mimeType=image/jpeg);structuredContent.image 只有 mimeType/width/height/bytes 元数据,不含图片数据。支持 Windows、带 X11 桌面的 Linux 与 macOS(登录时已授予录屏权限)客户端(能力位 CLIENT_CAP_SCREEN_PREVIEW),主连接 RPC、一次性返回。Android 客户端用无障碍服务 takeScreenshot 抓屏(Android 11+ 且开启无障碍服务,此时登录会声明该能力位;只支持 mode=screen)。mode 可选 screen(默认,整虚拟桌面)/region(指定矩形)/window(指定 hwnd)/monitor(指定显示器);后三种默认按源尺寸 1:1 原生分辨率抓取(适合 OCR/视觉读字),需要较新的 Windows 客户端(CLIENT_CAP_SCREEN_REGION,否则 -32005),结果在 structuredContent.capture 里回报实际源矩形与缩放比例。",
|
||||
"gate": null,
|
||||
"platforms": [
|
||||
"win",
|
||||
"lnx",
|
||||
"mac",
|
||||
"apk"
|
||||
],
|
||||
"impl": "mfc",
|
||||
"inputSchema": {
|
||||
"allOf": [
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"mode": {
|
||||
"enum": [
|
||||
"region"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"mode"
|
||||
]
|
||||
},
|
||||
"then": {
|
||||
"required": [
|
||||
"width",
|
||||
"height"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"mode": {
|
||||
"enum": [
|
||||
"window"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"mode"
|
||||
]
|
||||
},
|
||||
"then": {
|
||||
"required": [
|
||||
"hwnd"
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"properties": {
|
||||
"height": {
|
||||
"description": "region 模式必填:矩形高度(像素,1~8192)。超出虚拟桌面的部分会被裁剪。",
|
||||
@@ -704,7 +747,7 @@
|
||||
},
|
||||
{
|
||||
"name": "list_files",
|
||||
"description": "列举指定在线主机的目录。省略或空 path 返回驱动器列表(drives);给定 path 返回该目录一层内的文件/子目录(files,最多 500 条,含 name/isDir/size/mtime)。只读。",
|
||||
"description": "列举指定在线主机的目录。省略或空 path 返回驱动器列表(drives);给定 path 返回该目录一层内的文件/子目录(files,含 name/isDir/size/mtime),整目录解析后按 limit/offset 分页(默认 100 条、上限 1000 条,total/hasMore 是真实的目录条目数;目录超过 10 万条时按上限截断并返回 truncated=true)。Windows 上 \".\"/\"/\"/\"\\\\\" 视同省略 path;Linux/macOS 上 \"/\" 是根目录。只读。",
|
||||
"gate": null,
|
||||
"platforms": [
|
||||
"win",
|
||||
@@ -746,7 +789,7 @@
|
||||
"type": "integer"
|
||||
},
|
||||
"path": {
|
||||
"description": "要列举的目录路径(如 C:\\Windows);省略或传空则返回驱动器列表",
|
||||
"description": "要列举的目录路径(如 C:\\Windows 或 /etc)。省略或传空返回驱动器列表;Windows 上 \".\"、\"/\"、\"\\\\\" 视同省略;Linux/macOS 上 \"/\" 是根目录,按真实目录列举。",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
@@ -816,6 +859,10 @@
|
||||
},
|
||||
"totalAll": {
|
||||
"type": "integer"
|
||||
},
|
||||
"truncated": {
|
||||
"description": "目录条目超过服务端解析上限(100000 条)时为 true;仅在返回 files 时可能出现,此时 total 不是真实总数。",
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
@@ -1255,7 +1302,7 @@
|
||||
},
|
||||
{
|
||||
"name": "mcp_cancel_session",
|
||||
"description": "取消在飞请求并尽快释放主机占用。给 request_id(tools/call 的 JSON-RPC id,类型要与调用时一致)精确取消一次调用,或按 id(主机)与 session_id 取消匹配的调用(两个都给则必须同时匹配)。工具层的等待在 ≤500ms 内退出并走既有清理路径;本工具最多等 2s,返回 cancelled(取消个数)、released(是否已释放占用)、waited_ms 与 matched(匹配到的会话)。被取消的请求以 -32800 结束。等价于对 SSE 流发 notifications/cancelled。",
|
||||
"description": "取消在飞请求并尽快释放主机占用。只能取消 kind=call 的在飞调用:给 request_id(tools/call 的 JSON-RPC id,类型要与调用时一致)精确取消一次,或按 id(主机,必须非 0)/ session_id 取消匹配的调用(两个都给则必须同时匹配)。取消一次卡住的调用会连带释放它持有的 pending / file_transfer 等待;持久会话本身不会被关闭,terminal / remote_control / chat 分别用 terminal_close / remote_close / chat_close(两者都要同时给 id 与 session_id)。工具层的等待在 ≤500ms 内退出并走既有清理路径;本工具最多等 2s,返回 cancelled(真正取消的调用个数,不含本工具自身)、released(这些调用是否已释放占用)、waited_ms 与 matched(匹配到的所有会话,每项带 cancellable)。被取消的请求以 -32800 结束。等价于对 SSE 流发 notifications/cancelled。",
|
||||
"gate": null,
|
||||
"platforms": [
|
||||
"win",
|
||||
@@ -1265,6 +1312,23 @@
|
||||
],
|
||||
"impl": "mfc",
|
||||
"inputSchema": {
|
||||
"anyOf": [
|
||||
{
|
||||
"required": [
|
||||
"request_id"
|
||||
]
|
||||
},
|
||||
{
|
||||
"required": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
{
|
||||
"required": [
|
||||
"session_id"
|
||||
]
|
||||
}
|
||||
],
|
||||
"properties": {
|
||||
"id": {
|
||||
"description": "主机 id:取消该主机上所有在飞请求",
|
||||
@@ -1296,7 +1360,7 @@
|
||||
"type": "array"
|
||||
},
|
||||
"released": {
|
||||
"description": "2s 内匹配的会话是否已从服务端表中消失(主机已松开)",
|
||||
"description": "2s 内被取消的在飞调用(kind=call,不含本工具自身)是否已从服务端表中消失(主机已松开)",
|
||||
"type": "boolean"
|
||||
},
|
||||
"waited_ms": {
|
||||
@@ -1451,6 +1515,7 @@
|
||||
"platforms": [
|
||||
"win",
|
||||
"lnx",
|
||||
"mac",
|
||||
"apk"
|
||||
],
|
||||
"impl": "mfc",
|
||||
@@ -1501,6 +1566,7 @@
|
||||
"platforms": [
|
||||
"win",
|
||||
"lnx",
|
||||
"mac",
|
||||
"apk"
|
||||
],
|
||||
"impl": "mfc",
|
||||
@@ -1550,10 +1616,23 @@
|
||||
"platforms": [
|
||||
"win",
|
||||
"lnx",
|
||||
"mac",
|
||||
"apk"
|
||||
],
|
||||
"impl": "mfc",
|
||||
"inputSchema": {
|
||||
"anyOf": [
|
||||
{
|
||||
"required": [
|
||||
"command"
|
||||
]
|
||||
},
|
||||
{
|
||||
"required": [
|
||||
"session_id"
|
||||
]
|
||||
}
|
||||
],
|
||||
"properties": {
|
||||
"command": {
|
||||
"description": "要执行的命令(完整 shell,不受白名单约束)。省略时进入轮询模式:不执行新命令,只等待并取回当前会话的增量输出(上一条命令超时后用这个方式继续取)。PTY 会话(Windows ConPTY / Linux PTY)下可用管道 | 与 && / || 串联,退出码取整条管道/串联;不要用后台执行符 &(POSIX)或换行。老非 PTY 客户端仍不支持 & 与 |,请拆成多条调用。Linux 下通过 POSIX shell 执行,可用 ; 串联且退出码取最后一条命令",
|
||||
@@ -1636,6 +1715,7 @@
|
||||
"platforms": [
|
||||
"win",
|
||||
"lnx",
|
||||
"mac",
|
||||
"apk"
|
||||
],
|
||||
"impl": "mfc",
|
||||
@@ -1671,7 +1751,7 @@
|
||||
},
|
||||
{
|
||||
"name": "remote_open",
|
||||
"description": "在指定在线 Windows、Linux 或 Android 主机上建立远程控制会话(隐藏屏幕子连接)并返回 session_id、抓屏帧尺寸(screen_w/screen_h)与目标(target)。默认推整屏/整虚拟桌面(可能等比缩放);可用 window_hwnd 只推一个窗口,或用 region 只推一个矩形区域,带宽、延迟和点击精度都更好,此时归一化坐标 0..1 相对该目标帧。后续 remote_mouse/remote_keyboard 用归一化坐标(0..1)注入输入,用毕须 remote_close。Linux 需要 X11/Xorg(或 XWayland)桌面,纯 Wayland 会话无法抓屏/注入;window_hwnd/region 仅支持声明 CLIENT_CAP_WINDOW_INFO 的新 Windows 客户端。Windows 多显示器下整屏目标需要新版客户端(整虚拟桌面抓屏),老客户端会被拒绝;window 目标不依赖虚拟桌面抓屏,不受此限。Android 主机只支持整屏目标,输入被翻译成触摸手势与全局动作(见 remote_mouse / remote_keyboard);抓屏依赖客户端已授权录屏(MediaProjection),未授权时 remote_open 会一直等不到屏幕子连接,注入还依赖无障碍服务在跑(未开启时命令照样下发但不生效,且没有回执)。",
|
||||
"description": "在指定在线 Windows、Linux 或 Android 主机上建立远程控制会话(隐藏屏幕子连接)并返回 session_id、抓屏帧尺寸(screen_w/screen_h)与目标(target)。默认推整屏/整虚拟桌面(可能等比缩放);可用 window_hwnd 只推一个窗口,或用 region 只推一个矩形区域,带宽、延迟和点击精度都更好,此时归一化坐标 0..1 相对该目标帧。后续 remote_mouse/remote_keyboard 用归一化坐标(0..1)注入输入,用毕须 remote_close。Linux 需要 X11/Xorg(或 XWayland)桌面,纯 Wayland 会话无法抓屏/注入(这类主机直接返回 -32005);window_hwnd/region 仅支持声明 CLIENT_CAP_WINDOW_INFO 的新 Windows 客户端。Windows 多显示器下整屏目标需要新版客户端(整虚拟桌面抓屏),老客户端会被拒绝;window 目标不依赖虚拟桌面抓屏,不受此限。Android 主机只支持整屏目标,输入被翻译成触摸手势与全局动作(见 remote_mouse / remote_keyboard);抓屏依赖客户端已授权录屏(MediaProjection),未授权时 remote_open 会一直等不到屏幕子连接,注入还依赖无障碍服务在跑(未开启时命令照样下发但不生效,且没有回执)。",
|
||||
"gate": "remote_control",
|
||||
"write": true,
|
||||
"platforms": [
|
||||
@@ -1832,6 +1912,48 @@
|
||||
],
|
||||
"impl": "mfc",
|
||||
"inputSchema": {
|
||||
"allOf": [
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"action": {
|
||||
"enum": [
|
||||
"type"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"action"
|
||||
]
|
||||
},
|
||||
"then": {
|
||||
"required": [
|
||||
"text"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"action": {
|
||||
"enum": [
|
||||
"key_down",
|
||||
"key_up",
|
||||
"key_press"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"action"
|
||||
]
|
||||
},
|
||||
"then": {
|
||||
"required": [
|
||||
"key"
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"properties": {
|
||||
"action": {
|
||||
"description": "动作:key_down / key_up / key_press / type",
|
||||
@@ -1916,6 +2038,28 @@
|
||||
],
|
||||
"impl": "mfc",
|
||||
"inputSchema": {
|
||||
"allOf": [
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"action": {
|
||||
"enum": [
|
||||
"drag"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"action"
|
||||
]
|
||||
},
|
||||
"then": {
|
||||
"required": [
|
||||
"x2",
|
||||
"y2"
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"properties": {
|
||||
"action": {
|
||||
"description": "动作:move / down / up / click / right_click / middle_click / drag / scroll",
|
||||
@@ -2450,7 +2594,7 @@
|
||||
},
|
||||
{
|
||||
"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 复核。",
|
||||
"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/macOS 客户端回执),false 表示目标端没有回执(Windows 目标或老客户端),此时需要确证请用 list_files 复核。",
|
||||
"gate": "file_transfer",
|
||||
"write": true,
|
||||
"platforms": [
|
||||
@@ -2523,7 +2667,7 @@
|
||||
},
|
||||
{
|
||||
"name": "copy_files_c2c",
|
||||
"description": "在两个在线主机之间直接拷贝文件(V2 C2C:源主机自己发、目标主机自己收,服务端只中继,不在主控落盘)。源主机必须是 Windows;目标主机可以是 Windows 或 Linux/macOS。paths 为源主机绝对路径(文件或目录,目录递归、保留相对目录结构);dst_dir 为目标主机保存目录(不存在自动创建),Windows 目标用 D:\\Incoming 这类绝对路径,Linux/macOS 目标用 /home/user/incoming 这类绝对 POSIX 路径。overwrite 默认 false:目标目录已存在同名顶层项时跳过并计入 skipped(目标端是无条件覆盖写,不跳过就会每次全量重发);预检本身失败(目标主机忙/超时/拒绝访问)不报错,退回全发并置 skip_check_failed=true。返回 transfer_id/file_count/total_bytes/skipped/skip_check_failed/receiver_ack:receiver_ack=true 表示目标端已确认写入(Linux 客户端回执),false 表示目标端没有回执(Windows 目标、老客户端或 macOS),此时需要确证请用 list_files 复核。",
|
||||
"description": "在两个在线主机之间直接拷贝文件(V2 C2C:源主机自己发、目标主机自己收,服务端只中继,不在主控落盘)。源主机必须是 Windows;目标主机可以是 Windows 或 Linux/macOS。paths 为源主机绝对路径(文件或目录,目录递归、保留相对目录结构);dst_dir 为目标主机保存目录(不存在自动创建),Windows 目标用 D:\\Incoming 这类绝对路径,Linux/macOS 目标用 /home/user/incoming 这类绝对 POSIX 路径。overwrite 默认 false:目标目录已存在同名顶层项时跳过并计入 skipped(目标端是无条件覆盖写,不跳过就会每次全量重发);预检本身失败(目标主机忙/超时/拒绝访问)不报错,退回全发并置 skip_check_failed=true。返回 transfer_id/file_count/total_bytes/skipped/skip_check_failed/receiver_ack:receiver_ack=true 表示目标端已确认写入(Linux/macOS 客户端回执),false 表示目标端没有回执(Windows 目标或老客户端),此时需要确证请用 list_files 复核。",
|
||||
"gate": "file_transfer",
|
||||
"write": true,
|
||||
"platforms": [
|
||||
@@ -2620,7 +2764,8 @@
|
||||
"write": true,
|
||||
"platforms": [
|
||||
"win",
|
||||
"lnx"
|
||||
"lnx",
|
||||
"mac"
|
||||
],
|
||||
"impl": "mfc",
|
||||
"inputSchema": {
|
||||
@@ -2939,6 +3084,23 @@
|
||||
"properties": {
|
||||
"files": {
|
||||
"items": {
|
||||
"properties": {
|
||||
"dir": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"modified": {
|
||||
"type": "string"
|
||||
},
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"path": {
|
||||
"type": "string"
|
||||
},
|
||||
"size": {
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"type": "array"
|
||||
@@ -2946,6 +3108,21 @@
|
||||
"finished": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"hasMore": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"limit": {
|
||||
"type": "integer"
|
||||
},
|
||||
"offset": {
|
||||
"type": "integer"
|
||||
},
|
||||
"total": {
|
||||
"type": "integer"
|
||||
},
|
||||
"totalAll": {
|
||||
"type": "integer"
|
||||
},
|
||||
"truncated": {
|
||||
"type": "boolean"
|
||||
}
|
||||
@@ -3415,7 +3592,7 @@
|
||||
},
|
||||
{
|
||||
"name": "host_inspect",
|
||||
"description": "一次取回在线 Windows 主机的多类主机管理信息(原 10 个 host_list_* 工具合并)。aspects 必填、可多选:processes(进程:PID/架构/窗口标题/路径/优先级/线程数/用户/工作集与文件大小)| windows(当前可见顶层窗口;只含可见窗口,单次最多 96 条,超出时 truncated=true 且列表不完整,不能据此断定某窗口不存在;hwnd 可交给 host_control_window / operate_window)| network(网络连接,进程视角、含 UDP;与 list_network_connections 的「连接管理」数据源不同)| software(已安装软件,来自注册表 Uninstall 项;不提供卸载)| browser_history(IE 浏览历史,隐私数据)| favorites(IE 收藏夹,隐私数据)| win32_services(Win32 服务;服务名可用于 host_control_service)| driver_services(驱动服务;字段同 win32_services)| scheduled_tasks(计划任务;任务名 + folder 可用于 host_control_task)| hosts_file(按行返回并自动识别 UTF-8/GBK)。注意:win32_services / driver_services 要求客户端以管理员权限运行——非提权客户端拿不到 SCM 句柄后直接不回应,调用会在约 12 秒后超时(同等场景 list_services 会明确报 access denied)。过滤参数按 aspect 生效、其余忽略(见各参数说明),在服务端完成且先于分页:total 为命中数、totalAll 为该项全部条目数。单个 aspect 时顶层就是该项的列表结果(与合并前的旧工具一致);多个 aspect 时汇总在 results.<aspect>,某个 aspect 失败只记入 errors.<aspect>、不影响其它 aspect,全部失败才 isError=true。每多选一个 aspect 就多一次子连接,耗时线性增长,不需要的不要选。只读。",
|
||||
"description": "一次取回在线 Windows 主机的多类主机管理信息(原 10 个 host_list_* 工具合并)。aspects 必填、可多选:processes(进程:PID/架构/窗口标题/路径/优先级/线程数/用户/工作集与文件大小)| windows(当前可见顶层窗口;只含可见窗口,单次最多 96 条,超出时 truncated=true 且列表不完整,不能据此断定某窗口不存在;hwnd 可交给 host_control_window / operate_window)| network(网络连接,进程视角、含 UDP;与 list_network_connections 的「连接管理」数据源不同)| software(已安装软件,来自注册表 Uninstall 项;不提供卸载)| browser_history(IE 浏览历史,隐私数据)| favorites(IE 收藏夹,隐私数据)| win32_services(Win32 服务;服务名可用于 host_control_service)| driver_services(驱动服务;字段同 win32_services)| scheduled_tasks(计划任务;任务名 + folder 可用于 host_control_task)| hosts_file(按行返回并自动识别 UTF-8/GBK)。注意:win32_services / driver_services 要求客户端以管理员权限运行——非提权客户端拿不到 SCM 句柄后直接不回应,调用会在约 12 秒后超时(同等场景 list_services 会明确报 access denied)。过滤参数按 aspect 生效、其余忽略(见各参数说明),在服务端完成且先于分页:total 为命中数、totalAll 为该项全部条目数。单个 aspect 时顶层就是该项的列表结果(与合并前的旧工具一致);多个 aspect 时汇总在 results.<aspect>,某个 aspect 失败只记入 errors.<aspect>、不影响其它 aspect,全部失败才 isError=true。每多选一个 aspect 就多一次子连接,耗时线性增长,不需要的不要选;多个 aspect 共用 60 秒预算,用尽后不再下发新的 aspect(正在跑的会跑完),跳过的逐个记入 errors(code=-32001,message 以 skipped 开头),少选几项重试即可。只读。",
|
||||
"gate": "machine",
|
||||
"platforms": [
|
||||
"win"
|
||||
@@ -4410,6 +4587,18 @@
|
||||
],
|
||||
"impl": "mfc",
|
||||
"inputSchema": {
|
||||
"anyOf": [
|
||||
{
|
||||
"required": [
|
||||
"name"
|
||||
]
|
||||
},
|
||||
{
|
||||
"required": [
|
||||
"service_name"
|
||||
]
|
||||
}
|
||||
],
|
||||
"properties": {
|
||||
"action": {
|
||||
"description": "start/stop/pause/continue/restart,以及 set_auto/set_manual(转主连接实现,需 McpManage=1)",
|
||||
@@ -4596,7 +4785,7 @@
|
||||
"inputSchema": {
|
||||
"properties": {
|
||||
"id": {
|
||||
"description": "主机 id,取 list_online_hosts / search_hosts 返回的 id 字段",
|
||||
"description": "主机 id,取 list_hosts 返回的 id 字段",
|
||||
"type": "string"
|
||||
},
|
||||
"timeout_ms": {
|
||||
@@ -4641,7 +4830,7 @@
|
||||
"inputSchema": {
|
||||
"properties": {
|
||||
"id": {
|
||||
"description": "主机 id,取 list_online_hosts / search_hosts 返回的 id 字段",
|
||||
"description": "主机 id,取 list_hosts 返回的 id 字段",
|
||||
"type": "string"
|
||||
},
|
||||
"message": {
|
||||
@@ -4695,7 +4884,7 @@
|
||||
"inputSchema": {
|
||||
"properties": {
|
||||
"id": {
|
||||
"description": "主机 id,取 list_online_hosts / search_hosts 返回的 id 字段",
|
||||
"description": "主机 id,取 list_hosts 返回的 id 字段",
|
||||
"type": "string"
|
||||
},
|
||||
"max_messages": {
|
||||
@@ -4773,7 +4962,7 @@
|
||||
"inputSchema": {
|
||||
"properties": {
|
||||
"id": {
|
||||
"description": "主机 id,取 list_online_hosts / search_hosts 返回的 id 字段",
|
||||
"description": "主机 id,取 list_hosts 返回的 id 字段",
|
||||
"type": "string"
|
||||
},
|
||||
"session_id": {
|
||||
|
||||
Binary file not shown.
@@ -5185,7 +5185,7 @@ void CMy2015RemoteDlg::OnExperimentTlsEnable()
|
||||
return;
|
||||
}
|
||||
// 二次确认:避免误点就切换被控端 TLS。
|
||||
// 两平台都是立即生效:客户端收到命令后落盘信任锚(Windows 注册表 / Linux 配置文件)、
|
||||
// 客户端都是立即生效:收到命令后落盘信任锚(Windows 注册表 / Linux、macOS 配置文件)、
|
||||
// 热重载 TLS 状态(各平台 TlsChannel 的 TlsReload)并断开重连,正在进行的远程会话会中断。
|
||||
if (IDYES != MessageBoxL(_T("确定对选中主机启用 TLS 传输吗?\n"
|
||||
"(客户端立即生效并断线重连,正在进行的远程会话会中断)"),
|
||||
|
||||
@@ -590,6 +590,7 @@
|
||||
<Image Include="res\Bitmap\Refresh.bmp" />
|
||||
<Image Include="res\Bitmap\remove.bmp" />
|
||||
<Image Include="res\Bitmap\RequestAuth.bmp" />
|
||||
<Image Include="res\Bitmap\RunTest.bmp" />
|
||||
<Image Include="res\Bitmap\Settings.bmp" />
|
||||
<Image Include="res\Bitmap\Share.bmp" />
|
||||
<Image Include="res\Bitmap\Show.bmp" />
|
||||
|
||||
@@ -377,5 +377,6 @@
|
||||
<Image Include="res\Bitmap\FileSpeed.bmp" />
|
||||
<Image Include="res\Bitmap\Disclaimer.bmp" />
|
||||
<Image Include="res\Bitmap\CopyName.bmp" />
|
||||
<Image Include="res\Bitmap\RunTest.bmp" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -175,7 +175,7 @@ Json::Value OutputSchema(Json::Value props, std::initializer_list<const char*> r
|
||||
}
|
||||
|
||||
Json::Value HostIdProp() {
|
||||
return PropStr(u8"主机 id,取 list_online_hosts / search_hosts 返回的 id 字段");
|
||||
return PropStr(u8"主机 id,取 list_hosts 返回的 id 字段");
|
||||
}
|
||||
|
||||
Json::Value SessionIdProp() {
|
||||
|
||||
@@ -446,6 +446,39 @@ void MakeIdOrIdsRequired(Json::Value& schema) {
|
||||
schema["anyOf"] = anyOf;
|
||||
}
|
||||
|
||||
void AppendConditionalRequired(Json::Value& schema, const char* prop,
|
||||
std::initializer_list<const char*> values,
|
||||
std::initializer_list<const char*> fields) {
|
||||
Json::Value cond(Json::objectValue);
|
||||
|
||||
Json::Value ifSchema(Json::objectValue);
|
||||
Json::Value reqProp(Json::arrayValue);
|
||||
reqProp.append(prop);
|
||||
ifSchema["required"] = reqProp;
|
||||
if (values.size() > 0) {
|
||||
Json::Value enums(Json::arrayValue);
|
||||
for (const char* v : values)
|
||||
enums.append(v);
|
||||
Json::Value when(Json::objectValue);
|
||||
when["enum"] = enums;
|
||||
Json::Value props(Json::objectValue);
|
||||
props[prop] = when;
|
||||
ifSchema["properties"] = props;
|
||||
}
|
||||
cond["if"] = ifSchema;
|
||||
|
||||
Json::Value thenSchema(Json::objectValue);
|
||||
Json::Value reqFields(Json::arrayValue);
|
||||
for (const char* f : fields)
|
||||
reqFields.append(f);
|
||||
thenSchema["required"] = reqFields;
|
||||
cond["then"] = thenSchema;
|
||||
|
||||
if (!schema.isMember("allOf") || !schema["allOf"].isArray())
|
||||
schema["allOf"] = Json::Value(Json::arrayValue);
|
||||
schema["allOf"].append(cond);
|
||||
}
|
||||
|
||||
std::string PageSummary(const PageWindow& w, const char* unit) {
|
||||
std::string s = std::string(u8"共 ") + std::to_string(w.total) + std::string(u8" ") + unit;
|
||||
if (w.total == 0) return s + std::string(u8"。");
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
|
||||
#include <string>
|
||||
#include <cstdint>
|
||||
#include <initializer_list>
|
||||
#include <vector>
|
||||
|
||||
class CMy2015RemoteDlg;
|
||||
@@ -178,6 +179,14 @@ void AppendBatchIdsProp(Json::Value& props);
|
||||
// 把 inputSchema 的必填约束改成「id 或 ids 二选一」。
|
||||
void MakeIdOrIdsRequired(Json::Value& schema);
|
||||
|
||||
// 往 inputSchema 追加一条条件必填:当 prop 出现且取值在 values 里(values 为空表示
|
||||
// 只要出现就生效)时,fields 里的字段也必须提供。实现形态是 allOf 里的一条
|
||||
// {"if":{"properties":{prop:{"enum":[...]}},"required":[prop]},"then":{"required":fields}},
|
||||
// 从 schema 层面表达只写在描述里的条件约束,模型发参数前就能看到。
|
||||
void AppendConditionalRequired(Json::Value& schema, const char* prop,
|
||||
std::initializer_list<const char*> values,
|
||||
std::initializer_list<const char*> fields);
|
||||
|
||||
// 统一的提示文字,例如「共 283 个进程,本次返回第 1-100 条(还有更多,可用 offset 继续取)。」
|
||||
std::string PageSummary(const PageWindow& w, const char* unit);
|
||||
|
||||
|
||||
@@ -52,6 +52,11 @@ const int kActionTimeoutMs = 12000; // 动作 → 客户端自动回的刷新
|
||||
// 每步最多 12s,故留 60s 余量;单步等待再按剩余时间收敛。
|
||||
const int kSessionDeadlineMs = 60000;
|
||||
|
||||
// host_inspect 多 aspect 的总预算(软截止):每个 aspect 最坏 5s 就绪 + 12s 列表,10 个
|
||||
// 全选要 170s,HTTP 调用方会先超时。60 秒后不再下发新的 aspect,正在跑的那个按自身
|
||||
// 超时跑完;跳过的逐个记入 errors,让调用方看到「没来得及取」而不是一直等。
|
||||
const int kInspectTotalBudgetMs = 60000;
|
||||
|
||||
// 单个包的上限:正常列表远小于此;超过即视为异常,置 clientError 并断开子连接。
|
||||
const size_t kMaxPacketBytes = 8u * 1024u * 1024u;
|
||||
|
||||
@@ -1537,14 +1542,11 @@ std::string BuildKillNetworkConnection(const Json::Value& id, const Json::Value&
|
||||
if (pidFilter < 0) pidFilter = (int)found->pid;
|
||||
|
||||
if (dryRun) {
|
||||
Json::Value sc(Json::objectValue);
|
||||
sc["ok"] = true;
|
||||
sc["dryRun"] = true;
|
||||
sc["target"] = target;
|
||||
sc["connection"] = targetJson;
|
||||
AuditManageAction(parent, ht.dev, toolName, target + " pid=" + std::to_string(pidFilter) +
|
||||
" result=dry_run");
|
||||
return BuildStructuredResult(id, sc, "Dry run: target found, nothing was sent");
|
||||
// 与其它动作工具的 dry_run 同一个形状:ok/dry_run/action/target/state/detail,
|
||||
// 不再自造 dryRun/target/connection 字段(schema 里没有,模型也得猜)。
|
||||
return BuildDryRunResult(id, "kill", target, "present", targetJson);
|
||||
}
|
||||
|
||||
// 会话保持:取列表用的是第一条 255,断开后客户端会自动再回一条 255。
|
||||
@@ -2197,9 +2199,24 @@ std::string BuildHostInspect(const Json::Value& id, const Json::Value& args,
|
||||
Json::Value errors(Json::objectValue);
|
||||
std::string summary;
|
||||
int okCount = 0, failCount = 0;
|
||||
const auto deadline = std::chrono::steady_clock::now() +
|
||||
std::chrono::milliseconds(kInspectTotalBudgetMs);
|
||||
for (const InspectAspect* a : aspects) {
|
||||
InspectRun run;
|
||||
if (!summary.empty()) summary += u8";";
|
||||
// 总预算用尽:剩余的 aspect 不再下发。逐个记入 errors(而不是让整个调用失败),
|
||||
// 调用方据此知道是「没来得及取」,可以少选几项重试。
|
||||
if (std::chrono::steady_clock::now() >= deadline) {
|
||||
Json::Value e(Json::objectValue);
|
||||
e["code"] = -32001;
|
||||
e["message"] = std::string("skipped: host_inspect used up its ") +
|
||||
std::to_string(kInspectTotalBudgetMs / 1000) +
|
||||
"s budget; retry with fewer aspects or a faster host";
|
||||
errors[a->name] = e;
|
||||
failCount++;
|
||||
summary += std::string(a->what) + u8":跳过(总预算用尽)";
|
||||
continue;
|
||||
}
|
||||
InspectRun run;
|
||||
if (RunInspectAspect(*a, id, args, parent, run)) {
|
||||
results[a->name] = run.sc;
|
||||
okCount++;
|
||||
@@ -2581,8 +2598,9 @@ static std::string BuildHostControlService(const Json::Value& id, const Json::Va
|
||||
if (dangerous && !RequireDangerous(id, errJson)) return errJson;
|
||||
|
||||
std::string serviceName = Trim(GetStringArg(args, "name"));
|
||||
if (serviceName.empty()) serviceName = Trim(GetStringArg(args, "service_name"));
|
||||
if (serviceName.empty())
|
||||
return BuildError(id, -32602, "Missing required parameter: name (service name)");
|
||||
return BuildError(id, -32602, "Missing required parameter: name (service name; service_name is an accepted alias)");
|
||||
|
||||
HostTool ht;
|
||||
if (!ResolveHost(id, args, parent, ht, true, errJson)) return errJson;
|
||||
@@ -3190,7 +3208,9 @@ void AppendTools(Json::Value& tools) {
|
||||
u8"total 为命中数、totalAll 为该项全部条目数。"
|
||||
u8"单个 aspect 时顶层就是该项的列表结果(与合并前的旧工具一致);多个 aspect 时汇总在 "
|
||||
u8"results.<aspect>,某个 aspect 失败只记入 errors.<aspect>、不影响其它 aspect,全部失败才 isError=true。"
|
||||
u8"每多选一个 aspect 就多一次子连接,耗时线性增长,不需要的不要选。只读。",
|
||||
u8"每多选一个 aspect 就多一次子连接,耗时线性增长,不需要的不要选;多个 aspect 共用 "
|
||||
u8"60 秒预算,用尽后不再下发新的 aspect(正在跑的会跑完),跳过的逐个记入 errors"
|
||||
u8"(code=-32001,message 以 skipped 开头),少选几项重试即可。只读。",
|
||||
BuildHostInspectInputSchema(), BuildHostInspectOutputSchema());
|
||||
}
|
||||
|
||||
@@ -3238,9 +3258,21 @@ void AppendTools(Json::Value& tools) {
|
||||
props["name"] = PropStr(u8"服务名(ServiceName,不是显示名),取 host_inspect 的 win32_services / driver_services 项的 name;与 service_name 二选一");
|
||||
props["service_name"] = PropStr(u8"name 的旧参数名别名(与 name 等价,二选一)");
|
||||
props["dry_run"] = PropBool(u8"true 时只校验服务存在并返回当前状态,不下发控制命令,默认 false");
|
||||
// name 与 service_name 等价、二选一:只在 required 里写 id/action 会让两者都缺的
|
||||
// 调用也“符合 schema”,到执行期才报错;anyOf 让契约与实现一致。
|
||||
Json::Value schema = MakeSchema(props, { "id", "action" });
|
||||
Json::Value anyOf(Json::arrayValue);
|
||||
for (const char* key : { "name", "service_name" }) {
|
||||
Json::Value alt(Json::objectValue);
|
||||
Json::Value req(Json::arrayValue);
|
||||
req.append(key);
|
||||
alt["required"] = req;
|
||||
anyOf.append(alt);
|
||||
}
|
||||
schema["anyOf"] = anyOf;
|
||||
AddTool(tools, "host_control_service",
|
||||
u8"控制在线 Windows 主机的服务:start/stop/pause/continue/restart/set_auto/set_manual。start 等五个动作走主机管理链路:客户端对每次控制都会自动回一份刷新后的服务列表,工具据此复核状态并如实返回 ok;stop 与 restart 归入危险操作,需要同时开启 McpMachineDangerous;restart 先 stop 再 start。set_auto/set_manual 没有主机管理实现,转由主连接版 control_service 处理(ok 只表示已下发、需另查状态;McpManage=0 时返回 -32006)——它们只在 McpMachine=0 时才以 control_service 之名出现在 tools/list。不提供删除服务。dry_run=true 只核实服务并返回当前状态,不下发命令(是否已是目标状态由你按 state 判断);set_auto/set_manual 不支持 dry_run(返回 -32602)。",
|
||||
MakeSchema(props, { "id", "action" }),
|
||||
schema,
|
||||
ActionOutputSchema());
|
||||
}
|
||||
{
|
||||
|
||||
+329
-70
@@ -283,30 +283,43 @@ const char* kServerInstructions =
|
||||
u8"2) 工具的可见性与开关\n"
|
||||
u8"tools/list 只返回当前服务端开关允许的工具:终端(terminal)、远程控制(remote_control)、"
|
||||
u8"文件传输(file_transfer)、文件写入(file_write)、管理动作(manage)、主机管理(machine)、键盘记录(keylog)、"
|
||||
u8"远程交谈(chat)各有独立开关。工具不在列表里就是不可用,直接调用返回 -32006;"
|
||||
u8"远程交谈(chat)各有独立开关。工具不在列表里通常就不可用,直接调用会被拒(-32006 或 -32005);"
|
||||
u8"例外是下文提到的降级别名(list_processes / list_windows / list_services、operate_window / "
|
||||
u8"control_service,以及 list_online_hosts / search_hosts / list_all_hosts 等旧名)——"
|
||||
u8"它们不在列表里但仍可调用。"
|
||||
u8"当前开关状态可查 get_server_status 的 switches。只读模式(readonly=true)会挡掉大部分写工具,"
|
||||
u8"但只改服务端本地数据的 host_set_remark / host_set_watch_level 仍会列出,调用时才被拒;"
|
||||
u8"get_keylog 也始终可见,只读模式下只是它的 clear / set_offline 参数被拒,读取不受影响。\n"
|
||||
u8"get_keylog 只受 McpKeylog 开关控制(与只读模式无关):开关关闭时它不在列表里;只读模式下"
|
||||
u8"只是它的 clear / set_offline 参数被拒,读取不受影响。\n"
|
||||
u8"同一能力存在两套工具时优先用主机管理族:host_inspect(aspects 选 processes / windows / "
|
||||
u8"win32_services 等,支持 pid/title/status 等服务端过滤,字段更全),list_processes / "
|
||||
u8"list_windows / list_services 是它在 McpMachine=0 时的降级路径。窗口与服务控制同样只有一套"
|
||||
u8"名字(需 McpManage=1):McpMachine=0 时是 operate_window / control_service,开启后是 "
|
||||
u8"host_control_window / host_control_service;后者也接受 close/show 与 set_auto/set_manual"
|
||||
u8"(转给前一套实现)。\n"
|
||||
u8"(转给前一套实现)。危险的主机管理动作目前只有两类——冻结/恢复进程、stop/restart 服务——"
|
||||
u8"另需 McpMachineDangerous=1:工具照常列出,调用时返回 -32006。\n"
|
||||
u8"\n"
|
||||
u8"3) 错误码与动作\n"
|
||||
u8"-32002 主机离线或不存在:先刷新主机列表再选,不要拿旧快照反复重试。\n"
|
||||
u8"-32003 主机忙:同一台主机同一时刻只允许一个请求在飞(列表、截屏、文件、管理动作共用这一道锁,"
|
||||
u8"文件传输会话另有一道互斥),并发重试只会继续被拒;message 末尾会点名占用者与已持续时长,"
|
||||
u8"用 mcp_list_sessions 可看全部会话,确需打断(例如上一条请求已无意义)用 mcp_cancel_session 释放。\n"
|
||||
u8"用 mcp_list_sessions 可看全部会话。确需打断用 mcp_cancel_session,但它只能取消在飞调用(kind=call);"
|
||||
u8"持久会话要按类型关闭(id 与 session_id 都要给):terminal → terminal_close,remote_control → remote_close,"
|
||||
u8"chat → chat_close。pending / file_transfer 是某次在飞调用的等待态,取消那次调用就一并释放。\n"
|
||||
u8"-32004 命令未能送达主机:多半是链路瞬断,可重试一次。\n"
|
||||
u8"-32005 该主机不支持这项能力:换主机或换工具,改参数没有用。\n"
|
||||
u8"-32006 策略拒绝:开关未开或只读模式,重试无效,需要管理员改服务端配置。\n"
|
||||
u8"-32006 策略拒绝:开关未开、只读模式,或目标端能力不足(老客户端不声明 CLIENT_CAP_V2 时,"
|
||||
u8"download_file / upload_file / read_file / copy_files_c2c 会返回 -32006),重试无效:"
|
||||
u8"前者需管理员改服务端配置,后者需升级客户端。\n"
|
||||
u8"-32007 不在命令白名单:换成白名单内的命令,重试无效。\n"
|
||||
u8"-32012 参数被校验拒绝(命令里的 shell 元字符、控制字符等):按 message 修正参数后重试。"
|
||||
u8"历史版本用 -32008 表示同一语义,遇到时按同样方式处理。\n"
|
||||
u8"-32009 目标不存在(文件/目录等):先列一次确认目标,再重试。\n"
|
||||
u8"-32001 超时:可加大 timeout_ms 重试一次;持续超时说明主机卡住。\n"
|
||||
u8"-32001 多为超时,也可能是工具自身失败或已被取消:先看 message。是超时时,工具支持 timeout_ms "
|
||||
u8"就先加大重试一次,不支持就缩小范围(分页、限定目录/单台)再试;子连接/会话没建立、同一主机"
|
||||
u8"反复超时通常重试无效(主机卡住、链路断、老客户端不认命令),先用 mcp_list_sessions 观察;"
|
||||
u8"message 写 Request cancelled 的表示客户端已中止,可直接重试;http_probe 解析失败、"
|
||||
u8"目标端未确认写入等其他 -32001 按 message 处理,加大 timeout_ms 没用。\n"
|
||||
u8"-32800 请求被取消:这是客户端自己取消(notifications/cancelled / mcp_cancel_session / 连接断开)"
|
||||
u8"导致的中止,不是主机故障;主机占用已释放,可以直接重试。\n"
|
||||
u8"-32602 参数错误:按 message 修正后重试。\n"
|
||||
@@ -317,6 +330,7 @@ const char* kServerInstructions =
|
||||
u8"文件:list_files 列盘(省略 path)或列目录 → search_file 按名字查找(递归深度 32、最多 1 万条,"
|
||||
u8"从盘符根扫描很慢且易截断,尽量指定具体目录)→ 看文本内容用 read_file(按字节解码,自动识别 UTF-8/GBK,"
|
||||
u8"offset=-N 看尾部,不要用 type/Get-Content 读配置和日志)→ download_file 取回、upload_file 送到目标。"
|
||||
u8"注意 local_dir / local_path 指 MCP 服务端(主控)所在机器的本地路径,不是模型或用户所在机器的路径。"
|
||||
u8"整理目标机上的东西用 delete_path / move_path / create_folder(需 McpFileWrite 开关),"
|
||||
u8"它们的 ok 同样只代表客户端回了完成包,真实结果看 verified(true=复核确认生效、"
|
||||
u8"false=复核确认未生效、null=复核没做成);删除不可恢复,recursive 必须显式传 true。"
|
||||
@@ -328,7 +342,9 @@ const char* kServerInstructions =
|
||||
u8"remote_mouse / remote_keyboard 用归一化坐标(0..1)操作 → 必须 remote_close 释放会话,闲置会话会被回收。"
|
||||
u8"要防止真人操作打断自动化时用 remote_block_input 锁定对端键鼠(Windows/Android;必须带 max_block_ms,到期自动解除;"
|
||||
u8"客户端无管理员权限时 Windows 会让 BlockInput 静默失败,成功只代表命令已送达)。\n"
|
||||
u8"命令执行:exec_command 一次性取输出(受白名单约束)。terminal_exec 无需先 terminal_open:带 command 时"
|
||||
u8"命令执行:exec_command 一次性取输出(受白名单约束);同一主机已有持久终端会话时它会被 -32003 拒绝"
|
||||
u8"(改用 terminal_exec 复用该会话,或 terminal_close(id, session_id) 立刻关掉;空闲会话 300s 后会在下一次"
|
||||
u8" exec_command / terminal_* 调用时自动回收)。terminal_exec 无需先 terminal_open:带 command 时"
|
||||
u8"自动复用或创建该主机的持久会话(cwd/环境变量跨命令保持,闲置 300 秒回收),结果里带回 session_id,"
|
||||
u8"后续轮询用它;只有需要显式管理会话时才用 terminal_open / terminal_close。\n"
|
||||
u8"HTTP 探测:探主机本机或同网段的接口用 http_probe(只收私网/回环 IP 与 localhost,不给域名,"
|
||||
@@ -344,7 +360,8 @@ const char* kServerInstructions =
|
||||
u8"lnx(LNX):不支持服务、注册表、键日志、文件搜索/删除/移动/建目录、"
|
||||
u8"窗口列表(list_windows)与窗口信息(get_foreground_window)、网络连接列表与断开"
|
||||
u8"(list_network_connections / kill_network_connection)、"
|
||||
u8"块输入、host_* 全族、chat_* 全族、operate_window、power_action、uninstall_host。远程控制与截屏要求目标机"
|
||||
u8"块输入、host_* 全族(host_set_remark / host_set_watch_level 除外,它们只改服务端本地数据,"
|
||||
u8"任何平台都可用)、chat_* 全族、operate_window、power_action、uninstall_host。远程控制与截屏要求目标机"
|
||||
u8"有 X11/Xorg(或 XWayland)桌面,纯 Wayland 或无桌面的服务器不行。\n"
|
||||
u8"mac(MAC):在 lnx 的基础上,还不支持远程控制全族(remote_open / remote_close / "
|
||||
u8"remote_mouse / remote_keyboard / remote_clipboard)、get_screenshot、"
|
||||
@@ -369,7 +386,9 @@ const char* kServerInstructions =
|
||||
u8"(客户端未实现 SYSTEM 等命令)。\n"
|
||||
u8"copy_files_c2c 是唯一有方向性的工具:源端 src_id 必须是 win,目标端 dst_id 可以是 "
|
||||
u8"win / lnx / mac。Linux 和 macOS 只能当接收方,不能当发送方(反向不支持)。\n"
|
||||
u8"这些不支持的组合会立刻返回 -32005,不会白等超时;反之,遇到超时不要当成平台不支持。\n"
|
||||
u8"这些不支持的组合多数会立刻返回 -32005;少数要等子连接才暴露的(老客户端不认命令等)"
|
||||
u8"可能表现为 -32001 超时,平台门禁 McpPlatformGuard=0 关闭时也会这样。反之,遇到超时"
|
||||
u8"也别直接当成平台不支持,先按上面的矩阵确认平台。\n"
|
||||
u8"\n"
|
||||
u8"6) 安全约定\n"
|
||||
u8"写操作前先读一次现状,动作后再用读工具复核;删改类工具的 ok 只表示命令已送达客户端,不代表成功。"
|
||||
@@ -545,17 +564,38 @@ Json::Value ParseDriveList(const std::vector<BYTE>& data, UINT cp) {
|
||||
return arr;
|
||||
}
|
||||
|
||||
// 文件管理通道上的名字解码。协议约定是客户端 ANSI/GBK(Windows 的 FindFirstFileA、
|
||||
// Linux/macOS 的 common/FileManager.h 都按 GBK 收发),但 POSIX 客户端的 utf8ToGbk
|
||||
// 遇到 GBK 无法表示的字符会原样返回 UTF-8。cp=CP_UTF8(POSIX 调用方)时先按 GBK
|
||||
// 严格解码:能解开就当 GBK(线上常态);解不开说明客户端透传了 UTF-8,按 UTF-8 用。
|
||||
// 反过来「先试 UTF-8」不行——约 18% 的常用汉字 GBK 双字节恰好也是合法 UTF-8
|
||||
// (如 目录 = C4 BF C2 BC = "Ŀ¼"),会解成拉丁字母。已知限制:透传的 UTF-8
|
||||
// 字节若恰好也是合法 GBK(例如 emoji)仍会被当 GBK 解,客户端侧编码转换本身不可逆。
|
||||
std::string DecodeListingName(const char* s, UINT cp) {
|
||||
if (cp == CP_UTF8) {
|
||||
if (MultiByteToWideChar(936, MB_ERR_INVALID_CHARS, s, -1, NULL, 0) > 0)
|
||||
return ToUtf8(s, 936);
|
||||
return std::string(s);
|
||||
}
|
||||
return ToUtf8(s, cp);
|
||||
}
|
||||
|
||||
// 解析 TOKEN_FILE_LIST 缓冲(data[0]=token,其后为
|
||||
// [attr:1][filename\0][sizeHigh:4][sizeLow:4][ftLastWriteTime:8] 记录)。
|
||||
// 文件名为客户端 ANSI(编码由 cp 指定);attr 非 0 表示目录(FILE_ATTRIBUTE_DIRECTORY)。
|
||||
Json::Value ParseFileList(const std::vector<BYTE>& data, int maxEntries, UINT cp) {
|
||||
// 文件名为客户端 ANSI(编码由 cp 指定,见 DecodeListingName);attr 非 0 表示目录
|
||||
// (FILE_ATTRIBUTE_DIRECTORY)。
|
||||
// maxEntries 只限制构建出的条目数:超出时提前返回,并通过 truncated 告知数据里还有
|
||||
// 更多记录(调用方据此区分「目录就这么大」和「服务端解析上限到了」)。
|
||||
Json::Value ParseFileList(const std::vector<BYTE>& data, int maxEntries, UINT cp,
|
||||
bool* truncated = nullptr) {
|
||||
Json::Value arr(Json::arrayValue);
|
||||
if (truncated) *truncated = false;
|
||||
if (data.size() < 2) return arr;
|
||||
const char* p = (const char*)data.data();
|
||||
size_t len = data.size();
|
||||
size_t off = 1;
|
||||
int count = 0;
|
||||
while (off + 1 <= len && count < maxEntries) {
|
||||
while (off + 1 <= len) {
|
||||
bool isDir = (p[off] & FILE_ATTRIBUTE_DIRECTORY) != 0;
|
||||
off += 1;
|
||||
|
||||
@@ -563,6 +603,10 @@ Json::Value ParseFileList(const std::vector<BYTE>& data, int maxEntries, UINT cp
|
||||
size_t nlen = BoundedStrlen(name, len - off);
|
||||
if (nlen >= len - off) break;
|
||||
if (nlen == 0) break; // 空记录 = 尾部零填充(LocalAlloc 对齐),停止解析
|
||||
if (count >= maxEntries) { // 还有记录但已达上限:数据不完整
|
||||
if (truncated) *truncated = true;
|
||||
break;
|
||||
}
|
||||
off += nlen + 1;
|
||||
|
||||
if (off + 16 > len) break;
|
||||
@@ -580,7 +624,7 @@ Json::Value ParseFileList(const std::vector<BYTE>& data, int maxEntries, UINT cp
|
||||
Json::Int64 mtime = (Json::Int64)(ft / 10000000ULL) - 11644473600LL;
|
||||
|
||||
Json::Value item(Json::objectValue);
|
||||
item["name"] = ToUtf8(name, cp);
|
||||
item["name"] = DecodeListingName(name, cp);
|
||||
item["isDir"] = isDir;
|
||||
item["size"] = (Json::UInt64)size;
|
||||
item["mtime"] = mtime;
|
||||
@@ -1927,6 +1971,10 @@ Json::Value BuildGetScreenshotInputSchema() {
|
||||
Json::Value required(Json::arrayValue);
|
||||
required.append("id");
|
||||
schema["required"] = required;
|
||||
// region 需 width/height、window 需 hwnd(handler 会以 -32602 拒);monitor 有默认 0,
|
||||
// 无需条件。x/y 在 region 下可省略(按 0),故不进 then。
|
||||
AppendConditionalRequired(schema, "mode", { "region" }, { "width", "height" });
|
||||
AppendConditionalRequired(schema, "mode", { "window" }, { "hwnd" });
|
||||
return schema;
|
||||
}
|
||||
|
||||
@@ -1959,7 +2007,9 @@ Json::Value BuildListFilesInputSchema() {
|
||||
|
||||
Json::Value pathProp(Json::objectValue);
|
||||
pathProp["type"] = "string";
|
||||
pathProp["description"] = u8"要列举的目录路径(如 C:\\Windows);省略或传空则返回驱动器列表";
|
||||
pathProp["description"] = u8"要列举的目录路径(如 C:\\Windows 或 /etc)。省略或传空返回驱动器列表;"
|
||||
u8"Windows 上 \".\"、\"/\"、\"\\\\\" 视同省略;Linux/macOS 上 \"/\" 是根目录,"
|
||||
u8"按真实目录列举。";
|
||||
props["path"] = pathProp;
|
||||
|
||||
AppendBatchIdsProp(props);
|
||||
@@ -2017,6 +2067,13 @@ Json::Value BuildListFilesOutputSchema() {
|
||||
fileItems["properties"] = fileProps;
|
||||
filesProp["items"] = fileItems;
|
||||
props["files"] = filesProp;
|
||||
|
||||
// 目录条目超过解析上限(10 万条)时为 true,此时 total 只是上限内的数量。
|
||||
Json::Value truncatedProp(Json::objectValue);
|
||||
truncatedProp["type"] = "boolean";
|
||||
truncatedProp["description"] = u8"目录条目超过服务端解析上限(100000 条)时为 true;"
|
||||
u8"仅在返回 files 时可能出现,此时 total 不是真实总数。";
|
||||
props["truncated"] = truncatedProp;
|
||||
AppendPageOutputProps(props);
|
||||
|
||||
Json::Value schema(Json::objectValue);
|
||||
@@ -2185,7 +2242,7 @@ std::string BuildToolsListResult(const Json::Value& id) {
|
||||
{
|
||||
Json::Value tool(Json::objectValue);
|
||||
tool["name"] = "get_activity_history";
|
||||
tool["description"] = u8"获取指定在线主机的历史活动记录。Windows 与有桌面的 Linux 客户端返回前台窗口驻留记录,每行一条「[时间] [标题] 时长」;Android 客户端返回前台应用驻留记录(标题为「应用名 (包名)」,需开启无障碍服务);无桌面的 Linux 客户端返回登录记录与 shell 命令历史,每行带「[登录]」或「[命令]」标签(首行为「[来源]」说明)。主连接 RPC。结果按 limit/offset 分页(默认 100 条、上限 1000),新在前:offset=0 就是最近 limit 条,想看更早的再往后翻。total 为本机现有记录总数,hasMore 表示还有更早的记录;窗口后端只保留最近 500 条,所以 total 最多约 501(含进行中的当前窗口)。";
|
||||
tool["description"] = u8"获取指定在线主机的历史活动记录。Windows、有桌面的 Linux 与 macOS 客户端返回前台窗口驻留记录,每行一条「[时间] [标题] 时长」(macOS 无录屏授权时标题退化为应用名);Android 客户端返回前台应用驻留记录(标题为「应用名 (包名)」,需开启无障碍服务);无桌面的 Linux 客户端返回登录记录与 shell 命令历史,每行带「[登录]」或「[命令]」标签(首行为「[来源]」说明)。主连接 RPC。结果按 limit/offset 分页(默认 100 条、上限 1000),新在前:offset=0 就是最近 limit 条,想看更早的再往后翻。total 为本机现有记录总数,hasMore 表示还有更早的记录;窗口后端只保留最近 500 条,所以 total 最多约 501(含进行中的当前窗口)。";
|
||||
|
||||
tool["inputSchema"] = BuildPagedHostListInputSchema(); // { id | ids } + limit/offset
|
||||
tool["outputSchema"] = BuildActivityHistoryOutputSchema();
|
||||
@@ -2197,7 +2254,7 @@ std::string BuildToolsListResult(const Json::Value& id) {
|
||||
{
|
||||
Json::Value tool(Json::objectValue);
|
||||
tool["name"] = "get_screenshot";
|
||||
tool["description"] = u8"截取指定在线主机的一帧画面,返回 base64 编码的 JPEG 图片(image 对象含 mimeType/data/width/height)。支持 Windows 与带 X11 桌面的 Linux 客户端(能力位 CLIENT_CAP_SCREEN_PREVIEW),主连接 RPC、一次性返回。Android 客户端用无障碍服务 takeScreenshot 抓屏(Android 11+ 且开启无障碍服务,此时登录会声明该能力位;只支持 mode=screen)。mode 可选 screen(默认,整虚拟桌面)/region(指定矩形)/window(指定 hwnd)/monitor(指定显示器);后三种默认按源尺寸 1:1 原生分辨率抓取(适合 OCR/视觉读字),需要较新的 Windows 客户端(CLIENT_CAP_SCREEN_REGION,否则 -32005),结果在 structuredContent.capture 里回报实际源矩形与缩放比例。";
|
||||
tool["description"] = u8"截取指定在线主机的一帧画面,返回 base64 编码的 JPEG 图片:图片在 content 的 image 块(data 为 base64,mimeType=image/jpeg);structuredContent.image 只有 mimeType/width/height/bytes 元数据,不含图片数据。支持 Windows、带 X11 桌面的 Linux 与 macOS(登录时已授予录屏权限)客户端(能力位 CLIENT_CAP_SCREEN_PREVIEW),主连接 RPC、一次性返回。Android 客户端用无障碍服务 takeScreenshot 抓屏(Android 11+ 且开启无障碍服务,此时登录会声明该能力位;只支持 mode=screen)。mode 可选 screen(默认,整虚拟桌面)/region(指定矩形)/window(指定 hwnd)/monitor(指定显示器);后三种默认按源尺寸 1:1 原生分辨率抓取(适合 OCR/视觉读字),需要较新的 Windows 客户端(CLIENT_CAP_SCREEN_REGION,否则 -32005),结果在 structuredContent.capture 里回报实际源矩形与缩放比例。";
|
||||
|
||||
tool["inputSchema"] = BuildGetScreenshotInputSchema(); // { id } 必填 + max_width 可选
|
||||
tool["outputSchema"] = BuildScreenshotOutputSchema();
|
||||
@@ -2221,7 +2278,7 @@ std::string BuildToolsListResult(const Json::Value& id) {
|
||||
{
|
||||
Json::Value tool(Json::objectValue);
|
||||
tool["name"] = "list_files";
|
||||
tool["description"] = u8"列举指定在线主机的目录。省略或空 path 返回驱动器列表(drives);给定 path 返回该目录一层内的文件/子目录(files,最多 500 条,含 name/isDir/size/mtime)。只读。";
|
||||
tool["description"] = u8"列举指定在线主机的目录。省略或空 path 返回驱动器列表(drives);给定 path 返回该目录一层内的文件/子目录(files,含 name/isDir/size/mtime),整目录解析后按 limit/offset 分页(默认 100 条、上限 1000 条,total/hasMore 是真实的目录条目数;目录超过 10 万条时按上限截断并返回 truncated=true)。Windows 上 \".\"/\"/\"/\"\\\\\" 视同省略 path;Linux/macOS 上 \"/\" 是根目录。只读。";
|
||||
|
||||
tool["inputSchema"] = BuildListFilesInputSchema();
|
||||
tool["outputSchema"] = BuildListFilesOutputSchema();
|
||||
@@ -2405,7 +2462,7 @@ std::string BuildToolsListResult(const Json::Value& id) {
|
||||
{
|
||||
Json::Value tool(Json::objectValue);
|
||||
tool["name"] = "mcp_cancel_session";
|
||||
tool["description"] = u8"取消在飞请求并尽快释放主机占用。给 request_id(tools/call 的 JSON-RPC id,类型要与调用时一致)精确取消一次调用,或按 id(主机)与 session_id 取消匹配的调用(两个都给则必须同时匹配)。工具层的等待在 ≤500ms 内退出并走既有清理路径;本工具最多等 2s,返回 cancelled(取消个数)、released(是否已释放占用)、waited_ms 与 matched(匹配到的会话)。被取消的请求以 -32800 结束。等价于对 SSE 流发 notifications/cancelled。";
|
||||
tool["description"] = u8"取消在飞请求并尽快释放主机占用。只能取消 kind=call 的在飞调用:给 request_id(tools/call 的 JSON-RPC id,类型要与调用时一致)精确取消一次,或按 id(主机,必须非 0)/ session_id 取消匹配的调用(两个都给则必须同时匹配)。取消一次卡住的调用会连带释放它持有的 pending / file_transfer 等待;持久会话本身不会被关闭,terminal / remote_control / chat 分别用 terminal_close / remote_close / chat_close(两者都要同时给 id 与 session_id)。工具层的等待在 ≤500ms 内退出并走既有清理路径;本工具最多等 2s,返回 cancelled(真正取消的调用个数,不含本工具自身)、released(这些调用是否已释放占用)、waited_ms 与 matched(匹配到的所有会话,每项带 cancellable)。被取消的请求以 -32800 结束。等价于对 SSE 流发 notifications/cancelled。";
|
||||
|
||||
Json::Value inputSchema(Json::objectValue);
|
||||
inputSchema["type"] = "object";
|
||||
@@ -2426,6 +2483,17 @@ std::string BuildToolsListResult(const Json::Value& id) {
|
||||
sidProp["description"] = u8"会话 id(terminal/remote_control/chat 的 session_id):只取消该会话上的在飞请求";
|
||||
props["session_id"] = sidProp;
|
||||
inputSchema["properties"] = props;
|
||||
// 三个选择器至少给一个:原 schema 是 required:[],模型发 {} 才会在 handler 里被 -32602 打回。
|
||||
Json::Value anyOf(Json::arrayValue);
|
||||
const char* selectors[] = { "request_id", "id", "session_id" };
|
||||
for (const char* sel : selectors) {
|
||||
Json::Value alt(Json::objectValue);
|
||||
Json::Value req(Json::arrayValue);
|
||||
req.append(sel);
|
||||
alt["required"] = req;
|
||||
anyOf.append(alt);
|
||||
}
|
||||
inputSchema["anyOf"] = anyOf;
|
||||
inputSchema["required"] = Json::Value(Json::arrayValue);
|
||||
tool["inputSchema"] = inputSchema;
|
||||
|
||||
@@ -2436,7 +2504,7 @@ std::string BuildToolsListResult(const Json::Value& id) {
|
||||
outProps["cancelled"] = cancelledProp;
|
||||
Json::Value releasedProp(Json::objectValue);
|
||||
releasedProp["type"] = "boolean";
|
||||
releasedProp["description"] = u8"2s 内匹配的会话是否已从服务端表中消失(主机已松开)";
|
||||
releasedProp["description"] = u8"2s 内被取消的在飞调用(kind=call,不含本工具自身)是否已从服务端表中消失(主机已松开)";
|
||||
outProps["released"] = releasedProp;
|
||||
Json::Value waitedProp(Json::objectValue);
|
||||
waitedProp["type"] = "integer";
|
||||
@@ -2515,7 +2583,7 @@ std::string BuildToolsListResult(const Json::Value& id) {
|
||||
{
|
||||
Json::Value tool(Json::objectValue);
|
||||
tool["name"] = "remote_open";
|
||||
tool["description"] = u8"在指定在线 Windows、Linux 或 Android 主机上建立远程控制会话(隐藏屏幕子连接)并返回 session_id、抓屏帧尺寸(screen_w/screen_h)与目标(target)。默认推整屏/整虚拟桌面(可能等比缩放);可用 window_hwnd 只推一个窗口,或用 region 只推一个矩形区域,带宽、延迟和点击精度都更好,此时归一化坐标 0..1 相对该目标帧。后续 remote_mouse/remote_keyboard 用归一化坐标(0..1)注入输入,用毕须 remote_close。Linux 需要 X11/Xorg(或 XWayland)桌面,纯 Wayland 会话无法抓屏/注入;window_hwnd/region 仅支持声明 CLIENT_CAP_WINDOW_INFO 的新 Windows 客户端。Windows 多显示器下整屏目标需要新版客户端(整虚拟桌面抓屏),老客户端会被拒绝;window 目标不依赖虚拟桌面抓屏,不受此限。Android 主机只支持整屏目标,输入被翻译成触摸手势与全局动作(见 remote_mouse / remote_keyboard);抓屏依赖客户端已授权录屏(MediaProjection),未授权时 remote_open 会一直等不到屏幕子连接,注入还依赖无障碍服务在跑(未开启时命令照样下发但不生效,且没有回执)。";
|
||||
tool["description"] = u8"在指定在线 Windows、Linux 或 Android 主机上建立远程控制会话(隐藏屏幕子连接)并返回 session_id、抓屏帧尺寸(screen_w/screen_h)与目标(target)。默认推整屏/整虚拟桌面(可能等比缩放);可用 window_hwnd 只推一个窗口,或用 region 只推一个矩形区域,带宽、延迟和点击精度都更好,此时归一化坐标 0..1 相对该目标帧。后续 remote_mouse/remote_keyboard 用归一化坐标(0..1)注入输入,用毕须 remote_close。Linux 需要 X11/Xorg(或 XWayland)桌面,纯 Wayland 会话无法抓屏/注入(这类主机直接返回 -32005);window_hwnd/region 仅支持声明 CLIENT_CAP_WINDOW_INFO 的新 Windows 客户端。Windows 多显示器下整屏目标需要新版客户端(整虚拟桌面抓屏),老客户端会被拒绝;window 目标不依赖虚拟桌面抓屏,不受此限。Android 主机只支持整屏目标,输入被翻译成触摸手势与全局动作(见 remote_mouse / remote_keyboard);抓屏依赖客户端已授权录屏(MediaProjection),未授权时 remote_open 会一直等不到屏幕子连接,注入还依赖无障碍服务在跑(未开启时命令照样下发但不生效,且没有回执)。";
|
||||
tool["inputSchema"] = BuildRemoteOpenInputSchema();
|
||||
tool["outputSchema"] = BuildRemoteOpenOutputSchema();
|
||||
tools.append(tool);
|
||||
@@ -2608,7 +2676,7 @@ std::string BuildToolsListResult(const Json::Value& id) {
|
||||
if (CMcpServer::Instance().IsFileTransferEnabled() && !CMcpServer::Instance().IsReadonly()) {
|
||||
Json::Value tool(Json::objectValue);
|
||||
tool["name"] = "upload_file";
|
||||
tool["description"] = u8"把主控本机文件或目录上传到指定在线主机的目录(V2 协议,主连接发送)。支持 Windows 与 Linux/macOS 主机;local_path 为主控本机绝对路径(文件或目录,目录递归上传);remote_dir 为远程保存目录(不存在自动创建),Windows 用 C:\\uploads 这类盘符路径,Linux/macOS 用 /home/user/uploads 这类绝对 POSIX 路径;overwrite=false 时跳过 remote_dir 下已存在的同名顶层项。返回 files[{path,size,sha256}] 与 total_bytes/skipped/receiver_ack;sha256 恒为空(发送端不计算)。receiver_ack=true 表示目标端已确认写入(Linux 客户端回执),false 表示目标端没有回执(Windows 目标、老客户端或 macOS),此时需要确证请用 list_files 复核。";
|
||||
tool["description"] = u8"把主控本机文件或目录上传到指定在线主机的目录(V2 协议,主连接发送)。支持 Windows 与 Linux/macOS 主机;local_path 为主控本机绝对路径(文件或目录,目录递归上传);remote_dir 为远程保存目录(不存在自动创建),Windows 用 C:\\uploads 这类盘符路径,Linux/macOS 用 /home/user/uploads 这类绝对 POSIX 路径;overwrite=false 时跳过 remote_dir 下已存在的同名顶层项。返回 files[{path,size,sha256}] 与 total_bytes/skipped/receiver_ack;sha256 恒为空(发送端不计算)。receiver_ack=true 表示目标端已确认写入(Linux/macOS 客户端回执),false 表示目标端没有回执(Windows 目标或老客户端),此时需要确证请用 list_files 复核。";
|
||||
tool["inputSchema"] = BuildUploadFileInputSchema();
|
||||
tool["outputSchema"] = BuildUploadFileOutputSchema();
|
||||
tools.append(tool);
|
||||
@@ -2620,7 +2688,7 @@ std::string BuildToolsListResult(const Json::Value& id) {
|
||||
if (CMcpServer::Instance().IsFileTransferEnabled() && !CMcpServer::Instance().IsReadonly()) {
|
||||
Json::Value tool(Json::objectValue);
|
||||
tool["name"] = "copy_files_c2c";
|
||||
tool["description"] = u8"在两个在线主机之间直接拷贝文件(V2 C2C:源主机自己发、目标主机自己收,服务端只中继,不在主控落盘)。源主机必须是 Windows;目标主机可以是 Windows 或 Linux/macOS。paths 为源主机绝对路径(文件或目录,目录递归、保留相对目录结构);dst_dir 为目标主机保存目录(不存在自动创建),Windows 目标用 D:\\Incoming 这类绝对路径,Linux/macOS 目标用 /home/user/incoming 这类绝对 POSIX 路径。overwrite 默认 false:目标目录已存在同名顶层项时跳过并计入 skipped(目标端是无条件覆盖写,不跳过就会每次全量重发);预检本身失败(目标主机忙/超时/拒绝访问)不报错,退回全发并置 skip_check_failed=true。返回 transfer_id/file_count/total_bytes/skipped/skip_check_failed/receiver_ack:receiver_ack=true 表示目标端已确认写入(Linux 客户端回执),false 表示目标端没有回执(Windows 目标、老客户端或 macOS),此时需要确证请用 list_files 复核。";
|
||||
tool["description"] = u8"在两个在线主机之间直接拷贝文件(V2 C2C:源主机自己发、目标主机自己收,服务端只中继,不在主控落盘)。源主机必须是 Windows;目标主机可以是 Windows 或 Linux/macOS。paths 为源主机绝对路径(文件或目录,目录递归、保留相对目录结构);dst_dir 为目标主机保存目录(不存在自动创建),Windows 目标用 D:\\Incoming 这类绝对路径,Linux/macOS 目标用 /home/user/incoming 这类绝对 POSIX 路径。overwrite 默认 false:目标目录已存在同名顶层项时跳过并计入 skipped(目标端是无条件覆盖写,不跳过就会每次全量重发);预检本身失败(目标主机忙/超时/拒绝访问)不报错,退回全发并置 skip_check_failed=true。返回 transfer_id/file_count/total_bytes/skipped/skip_check_failed/receiver_ack:receiver_ack=true 表示目标端已确认写入(Linux/macOS 客户端回执),false 表示目标端没有回执(Windows 目标或老客户端),此时需要确证请用 list_files 复核。";
|
||||
tool["inputSchema"] = BuildCopyFilesC2CInputSchema();
|
||||
tool["outputSchema"] = BuildCopyFilesC2COutputSchema();
|
||||
tools.append(tool);
|
||||
@@ -3589,6 +3657,7 @@ static std::string BuildRemoteWin32Error(const Json::Value& id, DWORD win32err,
|
||||
|
||||
// tools/call:list_files(列盘走 COMMAND_LIST_DRIVE→TOKEN_DRIVE_LIST;
|
||||
// 列目录走 COMMAND_LIST_DRIVE 开子链接后,再下发 COMMAND_LIST_FILES→TOKEN_FILE_LIST)
|
||||
static const int kListFilesMaxEntries = 100000; // 解析上限,仅为兜住病态目录
|
||||
std::string BuildListFiles(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
|
||||
uint64_t devId = 0;
|
||||
std::string err;
|
||||
@@ -3600,16 +3669,32 @@ std::string BuildListFiles(const Json::Value& id, const Json::Value& args, CMy20
|
||||
return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId));
|
||||
|
||||
std::string path = GetStringArg(args, "path");
|
||||
bool listDrives = path.empty() || path == "." || path == "/" || path == "\\";
|
||||
|
||||
// 目录路径/文件名编码按 clientType 判定:Windows 走 A 接口(FindFirstFileA 等)= 客户端
|
||||
// ANSI(GBK/936),不随 CLIENT_CAP_UTF8 转 UTF-8;LNX/MAC 文件系统天然 UTF-8。不能用
|
||||
// GetClientEncoding——它按能力位返回 CP_UTF8,会误解 Windows 客户端的 GBK 文件名。
|
||||
// 编码:文件管理通道在线上是客户端 ANSI/GBK —— Windows 客户端走 A 接口
|
||||
// (FindFirstFileA);Linux/macOS 客户端在 common/FileManager.h 里对收到的路径做
|
||||
// gbkToUtf8、对发出的名字做 utf8ToGbk,与 download_file/upload_file 的 936 约定
|
||||
// 一致。不能用 GetClientEncoding——它按能力位返回 CP_UTF8,会误解线上的 GBK 字节。
|
||||
// 名字解析对 POSIX 用 CP_UTF8 作「先按 GBK 严格解、解不开再当 UTF-8」的开关
|
||||
// (客户端 utf8ToGbk 遇到 GBK 无法表示的字符会原样透传 UTF-8),见 DecodeListingName。
|
||||
CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
|
||||
UINT cp = (clientType == "LNX" || clientType == "MAC") ? CP_UTF8 : 936;
|
||||
const bool posixFs = (clientType == "LNX" || clientType == "MAC");
|
||||
const UINT nameCp = posixFs ? CP_UTF8 : 936;
|
||||
|
||||
// 下发前把 UTF-8 path 转成客户端 ANSI(空/./\/\\ 为 ASCII,转换后不变),OnDriveList 直接用。
|
||||
std::string ansiPath = ToAnsi(path, cp);
|
||||
// Windows 上 "."、"/"、"\\" 是「列盘」的历史写法;POSIX 上 "/" 是真实目录
|
||||
// (根目录),不能当列盘。列盘统一用空 path 下发给 OnDriveList。
|
||||
const bool listDrives = path.empty() ||
|
||||
(!posixFs && (path == "." || path == "/" || path == "\\"));
|
||||
std::string ansiPath;
|
||||
if (!listDrives) {
|
||||
if (posixFs) {
|
||||
// 客户端对收到的路径先做 gbkToUtf8:能转 GBK 就发 GBK;含 GBK 表示不了的
|
||||
// 字符(韩文等)时客户端 iconv 会失败并原样使用输入,所以这里直接发 UTF-8,
|
||||
// 两边才能对上(ToAnsi 在这里会静默替换成 '?')。
|
||||
if (!Utf8ToCpExact(path, 936, ansiPath)) ansiPath = path;
|
||||
} else {
|
||||
ansiPath = ToAnsi(path, 936);
|
||||
}
|
||||
}
|
||||
|
||||
CMcpServer& mcp = CMcpServer::Instance();
|
||||
if (!mcp.BeginPending(devId, "list_files", ansiPath))
|
||||
@@ -3632,11 +3717,13 @@ std::string BuildListFiles(const Json::Value& id, const Json::Value& args, CMy20
|
||||
|
||||
Json::Value drives(Json::arrayValue);
|
||||
Json::Value files(Json::arrayValue);
|
||||
bool truncated = false;
|
||||
if (listDrives) {
|
||||
drives = ParseDriveList(data, cp);
|
||||
drives = ParseDriveList(data, nameCp);
|
||||
} else {
|
||||
// 服务端按 500 条截断(避免子连接/JSON 过大),再按 limit/offset 取窗口。
|
||||
files = ParseFileList(data, 500, cp);
|
||||
// 整目录解析后再分页:先按 500 条截断会让 total/hasMore 说谎(超过 500 条的
|
||||
// 目录永远翻不到后面的条目)。上限 100000 条只为兜住病态目录。
|
||||
files = ParseFileList(data, kListFilesMaxEntries, nameCp, &truncated);
|
||||
}
|
||||
|
||||
PageWindow page = ResolvePageWindow(args);
|
||||
@@ -3645,8 +3732,12 @@ std::string BuildListFiles(const Json::Value& id, const Json::Value& args, CMy20
|
||||
|
||||
Json::Value result(Json::objectValue);
|
||||
Json::Value structuredContent(Json::objectValue);
|
||||
if (listDrives) structuredContent["drives"] = pageItems;
|
||||
else structuredContent["files"] = pageItems;
|
||||
if (listDrives) {
|
||||
structuredContent["drives"] = pageItems;
|
||||
} else {
|
||||
structuredContent["files"] = pageItems;
|
||||
structuredContent["truncated"] = truncated; // 一律带出,便于按 schema 校验
|
||||
}
|
||||
WritePageFields(structuredContent, page);
|
||||
result["structuredContent"] = structuredContent;
|
||||
|
||||
@@ -3654,6 +3745,13 @@ std::string BuildListFiles(const Json::Value& id, const Json::Value& args, CMy20
|
||||
Json::Value item(Json::objectValue);
|
||||
item["type"] = "text";
|
||||
item["text"] = listDrives ? PageSummary(page, u8"个驱动器") : PageSummary(page, u8"个条目");
|
||||
if (truncated)
|
||||
item["text"] = item["text"].asString() +
|
||||
std::string(u8"目录条目超过服务端解析上限 ") +
|
||||
std::to_string(kListFilesMaxEntries) +
|
||||
std::string(u8" 条,total 只是上限内的数量;请缩小目录范围") +
|
||||
(posixFs ? std::string(u8"。")
|
||||
: std::string(u8"或改用 search_file。"));
|
||||
content.append(item);
|
||||
result["content"] = content;
|
||||
result["isError"] = false;
|
||||
@@ -4059,6 +4157,34 @@ static bool HasPosixBackgroundAmpersand(const std::string& s) {
|
||||
return false;
|
||||
}
|
||||
|
||||
static const int kTermIdleTimeoutSec = 300; // 持久终端 idle 回收超时(秒)
|
||||
|
||||
// 终端会话的简短标签(-32003 与 mcp_list_sessions 共用同一写法,避免两处漂移)。
|
||||
static std::string TerminalLabel(const std::string& sessionId) {
|
||||
return sessionId.empty() ? std::string("exec_command")
|
||||
: std::string("terminal session_id=") + sessionId;
|
||||
}
|
||||
|
||||
// exec_command 被终端挡住时的完整报错:带会话名/session_id 与闲置/已跑时长,并给出正确出路。
|
||||
// 不复用 BusyMessage:那边的描述顺序会优先报 pending/文件传输,可能把别的占用者算到终端头上。
|
||||
static std::string TerminalBusyMessage(uint64_t devId) {
|
||||
for (const auto& s : CMcpServer::Instance().ListSessions()) {
|
||||
if (s.kind != "terminal" || s.device != devId) continue;
|
||||
std::string detail = " (" + TerminalLabel(s.sessionId);
|
||||
if (s.idleMs >= 0) detail += ", idle=" + std::to_string(s.idleMs / 1000) + "s";
|
||||
if (s.elapsedMs >= 0) detail += ", elapsed=" + std::to_string(s.elapsedMs / 1000) + "s";
|
||||
detail += ")";
|
||||
if (s.tool == "exec_command") {
|
||||
return "Device busy: another exec_command is still running for this host" + detail +
|
||||
"; wait for it to finish, or cancel that call with mcp_cancel_session(request_id)";
|
||||
}
|
||||
return "Device busy: a persistent terminal session is already open for this host" + detail +
|
||||
"; reuse it with terminal_exec, or close it with terminal_close(id, session_id); "
|
||||
"idle sessions are reclaimed after 300s";
|
||||
}
|
||||
return "Device busy: a terminal session is already active for this host";
|
||||
}
|
||||
|
||||
// tools/call:exec_command(Windows/Linux 一次性远程命令:主连接 COMMAND_SHELL → 子连接终端 →
|
||||
// 哨兵命令行 → 收集 stdout + exit_code → 关子链接)。安全门:只读默认 + 白名单 + 审计。
|
||||
std::string BuildExecCommand(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
|
||||
@@ -4071,11 +4197,15 @@ std::string BuildExecCommand(const Json::Value& id, const Json::Value& args, CMy
|
||||
if (!ctx)
|
||||
return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId));
|
||||
|
||||
// Linux/Android 客户端同样走 PTY + POSIX 哨兵;macOS 本轮不开放。
|
||||
// Linux/Android 客户端同样走 PTY + POSIX 哨兵;macOS 客户端也有完整 PTY
|
||||
// (common/PTYHandler.h,zsh/bash 交互),是否可用改由 CLIENT_CAP_TERMINAL 判定:
|
||||
// 老 macOS 构建收到 COMMAND_SHELL 只打一行 unimplemented,发下去只会拖到超时。
|
||||
CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
|
||||
const bool posix = (clientType == "LNX" || clientType == "APK");
|
||||
if (clientType == "MAC")
|
||||
return BuildError(id, -32005, "exec_command is only supported on Windows, Linux and Android hosts");
|
||||
const bool posix = (clientType == "LNX" || clientType == "APK" || clientType == "MAC");
|
||||
if (clientType == "MAC" && !ctx->SupportsTerminal())
|
||||
return BuildError(id, -32005,
|
||||
"macOS client is too old for exec_command: "
|
||||
"it does not declare CLIENT_CAP_TERMINAL; upgrade the client first");
|
||||
// 老 APK 的 COMMAND_SHELL 是空实现,发下去只会拖到超时;按能力位提前拒绝。
|
||||
if (clientType == "APK" && !ctx->SupportsTerminal())
|
||||
return BuildError(id, -32005,
|
||||
@@ -4112,8 +4242,12 @@ std::string BuildExecCommand(const Json::Value& id, const Json::Value& args, CMy
|
||||
|
||||
std::string nonce = GenerateRandomToken().substr(0, 8);
|
||||
|
||||
// 持久终端闲置回收原先只在 terminal_open/exec/close/http_probe 入口触发;exec_command
|
||||
// 不走这些入口,于是「开过一次 terminal_exec → 之后 exec_command 永远 -32003」。
|
||||
// 这里补一次 sweep,并让报错带上 session_id 与替代路径。
|
||||
mcp.SweepIdleTerminals(kTermIdleTimeoutSec);
|
||||
if (!mcp.BeginTermPending(devId, command, nonce))
|
||||
return BuildError(id, -32003, "Device busy: a terminal session is already active for this host");
|
||||
return BuildError(id, -32003, TerminalBusyMessage(devId));
|
||||
|
||||
// 主连接下发 COMMAND_SHELL,客户端建立 shell 子连接并回 TOKEN_*_START。
|
||||
BYTE cmd = COMMAND_SHELL;
|
||||
@@ -4474,9 +4608,9 @@ std::string BuildGetServerStatus(const Json::Value& id, CMy2015RemoteDlg* parent
|
||||
status["blocked_auth_ips"] = blockedIps;
|
||||
|
||||
Json::Value result(Json::objectValue);
|
||||
Json::Value structuredContent(Json::objectValue);
|
||||
structuredContent["status"] = status;
|
||||
result["structuredContent"] = structuredContent;
|
||||
// outputSchema 声明的就是顶层字段;不要再套一层 "status",否则按 schema 取字段
|
||||
// (structuredContent.version 等)的客户端拿不到任何东西。
|
||||
result["structuredContent"] = status;
|
||||
|
||||
std::string text = std::string(BRAND_APP_NAME) + " v" + VERSION_STR +
|
||||
std::string(u8",已运行 ") + std::to_string((long long)status["uptime_sec"].asInt64()) +
|
||||
@@ -4587,6 +4721,10 @@ static std::string BuildMcpCancelSession(const Json::Value& id, const Json::Valu
|
||||
const bool hasDev = args.isObject() && args.isMember("id");
|
||||
if (hasDev && !ReadUInt64Arg(args, "id", devId))
|
||||
return BuildError(id, -32602, "id must be a decimal host id string");
|
||||
// "0" 能通过整数校验,但会让设备过滤失效(matches 里 devId!=0 才比),
|
||||
// 变成「取消全服所有在飞调用」——宁可拒绝。
|
||||
if (hasDev && devId == 0)
|
||||
return BuildError(id, -32602, "id must be a non-zero host id string");
|
||||
const std::string sessionId = GetStringArg(args, "session_id");
|
||||
|
||||
if (reqIdKey.empty() && !hasDev && sessionId.empty())
|
||||
@@ -4603,8 +4741,10 @@ static std::string BuildMcpCancelSession(const Json::Value& id, const Json::Valu
|
||||
};
|
||||
|
||||
CMcpServer& srv = CMcpServer::Instance();
|
||||
const auto self = CurrentMcpCall(); // 取消工具自身也在这张表里,不算「匹配到」也不取消
|
||||
Json::Value matched(Json::arrayValue);
|
||||
for (const auto& s : srv.ListSessions()) {
|
||||
if (self && s.kind == "call" && s.idKey == self->idKey) continue;
|
||||
if (!matches(s)) continue;
|
||||
Json::Value o(Json::objectValue);
|
||||
if (s.device != 0) o["host_id"] = std::to_string(s.device);
|
||||
@@ -4612,6 +4752,7 @@ static std::string BuildMcpCancelSession(const Json::Value& id, const Json::Valu
|
||||
o["tool"] = s.tool;
|
||||
if (!s.sessionId.empty()) o["session_id"] = s.sessionId;
|
||||
if (!s.requestId.empty()) o["request_id"] = s.requestId;
|
||||
o["cancellable"] = (s.kind == "call"); // 本工具只能打断在飞调用
|
||||
matched.append(o);
|
||||
}
|
||||
|
||||
@@ -4626,6 +4767,10 @@ static std::string BuildMcpCancelSession(const Json::Value& id, const Json::Valu
|
||||
while (waitedMs < kCancelWaitMs) {
|
||||
bool stillThere = false;
|
||||
for (const auto& s : srv.ListSessions()) {
|
||||
// 只轮询 kind=call:取消动不到持久会话,它们赖在表里不代表「在收尾」。
|
||||
// 也要跳过取消工具自身——它一直在表里,否则 released 永远等不到 true。
|
||||
if (s.kind != "call") continue;
|
||||
if (self && s.idKey == self->idKey) continue;
|
||||
if (matches(s)) { stillThere = true; break; }
|
||||
}
|
||||
if (!stillThere) { released = true; break; }
|
||||
@@ -4642,7 +4787,23 @@ static std::string BuildMcpCancelSession(const Json::Value& id, const Json::Valu
|
||||
|
||||
std::string text;
|
||||
if (cancelled == 0) {
|
||||
text = u8"没有匹配的在飞请求:可能已经结束,或 request_id 与列表里的值不一致。";
|
||||
if (matched.empty()) {
|
||||
text = u8"没有匹配的在飞请求:可能已经结束,或 request_id 与列表里的值不一致。";
|
||||
} else {
|
||||
// 只匹配到持久会话/挂起表项:本工具只能取消 kind=call,说清楚下一步该用哪个工具。
|
||||
std::string kinds;
|
||||
for (const auto& m : matched) {
|
||||
const std::string k = m["kind"].asString();
|
||||
if (kinds.find(k) == std::string::npos) {
|
||||
if (!kinds.empty()) kinds += "/";
|
||||
kinds += k;
|
||||
}
|
||||
}
|
||||
text = u8"匹配到 " + std::to_string((int)matched.size()) + u8" 个会话(kind=" + kinds +
|
||||
u8"),但都不是可取消的在飞调用(kind=call)。持久会话请按类型关闭(id 与 session_id 都要给):"
|
||||
u8"terminal → terminal_close,remote_control → remote_close,chat → chat_close;"
|
||||
u8"pending / file_transfer 是所属在飞调用的等待态,取消那次调用即可一并释放。";
|
||||
}
|
||||
} else if (released) {
|
||||
text = std::string(u8"已取消 ") + std::to_string(cancelled) + u8" 个在飞请求," +
|
||||
std::to_string(waitedMs) + u8" ms 内已释放占用;被取消的请求会收到 -32800。";
|
||||
@@ -4666,7 +4827,6 @@ static std::string BuildMcpCancelSession(const Json::Value& id, const Json::Valu
|
||||
|
||||
// ===== P4:持久远程终端(terminal_open / terminal_exec / terminal_close)=====
|
||||
|
||||
static const int kTermIdleTimeoutSec = 300; // 持久终端 idle 回收超时(秒)
|
||||
static const int kTermTombstoneSec = 600; // 「终端被销毁」墓碑保留时长(秒),供后续报错文案用
|
||||
// 超时轮询(P0-2):超时不再销毁会话,改为返回部分输出 + 可继续轮询,因此需要三个上限。
|
||||
static const int kTermMaxDataBytes = 8 * 1024 * 1024; // 单条命令原始输出硬上限(超出丢最旧字节)
|
||||
@@ -4698,8 +4858,10 @@ static bool ResolveTerminalSessionHost(const Json::Value& id, const Json::Value&
|
||||
}
|
||||
|
||||
CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
|
||||
if (clientType == "MAC") {
|
||||
errJson = BuildError(id, -32005, "Persistent terminal is only supported on Windows, Linux and Android hosts");
|
||||
if (clientType == "MAC" && !ctx->SupportsTerminal()) {
|
||||
errJson = BuildError(id, -32005,
|
||||
"macOS client is too old for the persistent terminal: "
|
||||
"it does not declare CLIENT_CAP_TERMINAL; upgrade the client first");
|
||||
return false;
|
||||
}
|
||||
if (clientType == "APK" && !ctx->SupportsTerminal()) {
|
||||
@@ -4811,6 +4973,17 @@ Json::Value BuildTerminalExecInputSchema() {
|
||||
Json::Value required(Json::arrayValue);
|
||||
required.append("id");
|
||||
schema["required"] = required;
|
||||
// 执行(带 command)可省略 session_id,轮询(不带 command)必须带 session_id;
|
||||
// 两者都没有时 handler 直接 -32602。用 anyOf 把这条只写在描述里的约束落到 schema。
|
||||
Json::Value anyOf(Json::arrayValue);
|
||||
for (const char* key : { "command", "session_id" }) {
|
||||
Json::Value alt(Json::objectValue);
|
||||
Json::Value req(Json::arrayValue);
|
||||
req.append(key);
|
||||
alt["required"] = req;
|
||||
anyOf.append(alt);
|
||||
}
|
||||
schema["anyOf"] = anyOf;
|
||||
return schema;
|
||||
}
|
||||
|
||||
@@ -5029,7 +5202,8 @@ std::string BuildTerminalExec(const Json::Value& id, const Json::Value& args, CM
|
||||
if (!ResolveTerminalSessionHost(id, args, parent, devId, ctx, errJson))
|
||||
return errJson;
|
||||
const bool posix = (ctx->GetAdditionalData(RES_CLIENT_TYPE) == "LNX" ||
|
||||
ctx->GetAdditionalData(RES_CLIENT_TYPE) == "APK");
|
||||
ctx->GetAdditionalData(RES_CLIENT_TYPE) == "APK" ||
|
||||
ctx->GetAdditionalData(RES_CLIENT_TYPE) == "MAC");
|
||||
|
||||
// command 省略 = 轮询模式(P0-2);session_id 可省略(P0-1:带 command 时自动建/复用默认会话)。
|
||||
std::string command = Trim(GetStringArg(args, "command"));
|
||||
@@ -5426,6 +5600,21 @@ std::string BuildRemoteOpen(const Json::Value& id, const Json::Value& args, CMy2
|
||||
if (!ResolveScreenCtrlSessionHost(id, args, parent, devId, ctx, errJson))
|
||||
return errJson;
|
||||
|
||||
// 能力位前置:Linux 的抓屏与注入都走 X11(Xorg/XWayland),客户端只在 DISPLAY 可用时
|
||||
// 才在登录里声明 CLIENT_CAP_SCREEN_PREVIEW;声明了能力位(非空 caps)却没有这一位,
|
||||
// 说明是纯 Wayland/无 X11 的会话,抓不到帧也注入不了——提前返回 -32005,免得白等
|
||||
// timeout_ms 再报「子连接超时」,还留下一次 web-triggered 标记的清理。老客户端
|
||||
// (caps 为空)无从判定,与多显示器门一样按放行处理(老的 COMMAND_SCREEN_SPY 链路仍可用)。
|
||||
// Android 不能套这个门:APK 的 SCREEN_PREVIEW 位只代表 API 30+ 且无障碍在运行(用于
|
||||
// get_screenshot 的 takeScreenshot),而远程控制抓屏走 MediaProjection、注入走
|
||||
// dispatchGesture——没有这一位的主机远程控制仍可能可用。
|
||||
CString hostClientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
|
||||
const bool declaresCaps = !ctx->GetClientData(ONLINELIST_CAPABILITIES).IsEmpty();
|
||||
if (declaresCaps && hostClientType == "LNX" && !ctx->SupportsScreenPreview())
|
||||
return BuildError(id, -32005,
|
||||
"Remote control requires screen preview capability (X11/Xorg desktop on Linux); "
|
||||
"this host does not declare it");
|
||||
|
||||
// ---- 帧目标(可选):window_hwnd 只推窗口,region 只推矩形;缺省推整屏/整虚拟桌面 ----
|
||||
uint32_t windowHwnd = 0;
|
||||
bool hasWindow = false;
|
||||
@@ -5523,7 +5712,8 @@ std::string BuildRemoteOpen(const Json::Value& id, const Json::Value& args, CMy2
|
||||
|
||||
// 与人类远程桌面观看互斥:已有屏幕子连接(web 观看)→ 拒绝,避免向人类正在看的画面注入。
|
||||
if (WebService().HasActiveSession(devId))
|
||||
return BuildError(id, -32003, "Device busy: a remote desktop session is already active for this host");
|
||||
return BuildError(id, -32003, BusyMessage(
|
||||
"Device busy: a remote desktop session is already active for this host", devId));
|
||||
|
||||
int timeoutMs = CMcpServer::Instance().ToolTimeoutMs();
|
||||
int v = 0;
|
||||
@@ -5531,7 +5721,8 @@ std::string BuildRemoteOpen(const Json::Value& id, const Json::Value& args, CMy2
|
||||
|
||||
std::string sessionId = GenerateRandomToken();
|
||||
if (!mcp.BeginScreenCtrlOpen(devId, sessionId))
|
||||
return BuildError(id, -32003, "Device busy: a remote control session is already active for this host");
|
||||
return BuildError(id, -32003, BusyMessage(
|
||||
"Device busy: a remote control session is already active for this host", devId));
|
||||
|
||||
// 失败清理:会话 + 隐藏对话框 + web-triggered 标记(StartRemoteDesktop 先置标记再发送)。
|
||||
auto abortOpen = [&]() {
|
||||
@@ -5898,6 +6089,10 @@ Json::Value BuildRemoteKeyboardInputSchema() {
|
||||
required.append("session_id");
|
||||
required.append("action");
|
||||
schema["required"] = required;
|
||||
// 描述里写明「type 用 text、按键动作用 key」,但 schema 只要求 id/session_id/action,
|
||||
// 漏字段要到 handler 才报错。条件必填让模型在发参数前就看到。
|
||||
AppendConditionalRequired(schema, "action", { "type" }, { "text" });
|
||||
AppendConditionalRequired(schema, "action", { "key_down", "key_up", "key_press" }, { "key" });
|
||||
return schema;
|
||||
}
|
||||
|
||||
@@ -6372,6 +6567,8 @@ Json::Value BuildRemoteMouseInputSchema() {
|
||||
required.append("x");
|
||||
required.append("y");
|
||||
schema["required"] = required;
|
||||
// drag 的终点坐标 x2/y2 在描述里标了「仅 drag」,schema 里补成条件必填。
|
||||
AppendConditionalRequired(schema, "action", { "drag" }, { "x2", "y2" });
|
||||
return schema;
|
||||
}
|
||||
|
||||
@@ -8710,9 +8907,32 @@ std::string BuildHttpProbe(const Json::Value& id, const Json::Value& args, CMy20
|
||||
+ " | " + std::to_string(rawBody.size()) + " bytes"
|
||||
+ (p.truncated ? " (truncated)" : "")
|
||||
+ " | " + std::to_string(p.elapsedMs) + " ms";
|
||||
// 响应头也写进 text:只读 content 文本的客户端看不到 structuredContent.headers,
|
||||
// 而 Location/Set-Cookie/Content-Type 正是判断重定向与鉴权状态要用的。整体限长
|
||||
// (单个值也限长),完整响应头仍在 structuredContent.headers 里。
|
||||
const size_t kMaxHeaderTextBytes = 4096;
|
||||
const size_t kMaxHeaderLineBytes = 1200;
|
||||
std::string headerText;
|
||||
for (const std::string& key : hdrs.getMemberNames()) {
|
||||
if (headerText.size() >= kMaxHeaderTextBytes) {
|
||||
headerText += "(truncated; full response headers are in structuredContent.headers)\n";
|
||||
break;
|
||||
}
|
||||
std::string line = key + ": " + hdrs[key].asString();
|
||||
if (line.size() > kMaxHeaderLineBytes) {
|
||||
// 按字节截断可能切在多字节 UTF-8 字符中间:回退到该字符的首字节。
|
||||
size_t cut = kMaxHeaderLineBytes;
|
||||
while (cut > 0 && ((unsigned char)line[cut] & 0xC0) == 0x80)
|
||||
--cut;
|
||||
line = line.substr(0, cut) + "...";
|
||||
}
|
||||
headerText += line + "\n";
|
||||
}
|
||||
std::string text = head;
|
||||
if (!headerText.empty())
|
||||
text += "\nheaders:\n" + headerText;
|
||||
if (!rawBody.empty())
|
||||
text += "\n" + (bodyUtf8 ? rawBody : std::string("(base64) ") + sc["body_base64"].asString());
|
||||
text += "\nbody:\n" + (bodyUtf8 ? rawBody : std::string("(base64) ") + sc["body_base64"].asString());
|
||||
|
||||
Json::Value content(Json::arrayValue);
|
||||
Json::Value item(Json::objectValue);
|
||||
@@ -9590,8 +9810,14 @@ std::string BuildKillProcess(const Json::Value& id, const Json::Value& args, CMy
|
||||
return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId));
|
||||
|
||||
CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
|
||||
if (clientType == "MAC" || clientType == "APK")
|
||||
return BuildError(id, -32005, "kill_process is only supported on Windows and Linux hosts");
|
||||
// macOS 客户端有 COMMAND_SYSTEM → SystemManager(proc_listpids + SIGKILL)分支,
|
||||
// 但没有对应能力位的老构建收到 COMMAND_SYSTEM 只打一行日志 → 刷新永远等不到,故按位拒绝。
|
||||
if (clientType == "MAC" && !ctx->SupportsProcess())
|
||||
return BuildError(id, -32005,
|
||||
"macOS client is too old for kill_process: "
|
||||
"it does not declare CLIENT_CAP_PROCESS; upgrade the client first");
|
||||
if (clientType == "APK")
|
||||
return BuildError(id, -32005, "kill_process is only supported on Windows, Linux and macOS hosts");
|
||||
|
||||
CMcpServer& mcp = CMcpServer::Instance();
|
||||
if (mcp.IsReadonly())
|
||||
@@ -10801,6 +11027,19 @@ Json::Value BuildSearchFileOutputSchema() {
|
||||
filesProp["type"] = "array";
|
||||
Json::Value items(Json::objectValue);
|
||||
items["type"] = "object";
|
||||
Json::Value itemProps(Json::objectValue);
|
||||
for (const char* f : { "path", "name", "modified" }) {
|
||||
Json::Value s(Json::objectValue);
|
||||
s["type"] = "string";
|
||||
itemProps[f] = s;
|
||||
}
|
||||
Json::Value dirProp(Json::objectValue);
|
||||
dirProp["type"] = "boolean";
|
||||
itemProps["dir"] = dirProp;
|
||||
Json::Value sizeProp(Json::objectValue);
|
||||
sizeProp["type"] = "integer";
|
||||
itemProps["size"] = sizeProp;
|
||||
items["properties"] = itemProps;
|
||||
filesProp["items"] = items;
|
||||
props["files"] = filesProp;
|
||||
Json::Value finProp(Json::objectValue);
|
||||
@@ -10809,6 +11048,9 @@ Json::Value BuildSearchFileOutputSchema() {
|
||||
Json::Value truncProp(Json::objectValue);
|
||||
truncProp["type"] = "boolean";
|
||||
props["truncated"] = truncProp;
|
||||
// 分页字段:BuildSearchFile 一直会带 total/totalAll/offset/limit/hasMore,
|
||||
// schema 补齐后客户端按输出契约取值才不会扑空。
|
||||
AppendPageOutputProps(props);
|
||||
Json::Value schema(Json::objectValue);
|
||||
schema["type"] = "object";
|
||||
schema["properties"] = props;
|
||||
@@ -11238,7 +11480,7 @@ ListingLookup LookupInListing(const std::vector<BYTE>& data, const std::string&
|
||||
return ListingLookup::Unknown;
|
||||
}
|
||||
if (data[0] != TOKEN_FILE_LIST) return ListingLookup::Unknown;
|
||||
// 不在服务端截断:默认那 500 条是给界面用的窗口,这里要扫全(大小仍由客户端单包上限约束)。
|
||||
// 复核要扫全整个列表(list_files 自己也已整目录解析;这里上限只为兜底)。
|
||||
const Json::Value items = ParseFileList(data, 1000000, 936);
|
||||
for (unsigned int i = 0; i < items.size(); ++i) {
|
||||
const std::string name = JsonStrField(items[i], "name");
|
||||
@@ -11759,7 +12001,9 @@ const ToolPlatform kToolPlatforms[] = {
|
||||
{ "upload_file", kPlatWin|kPlatLnx|kPlatMac },
|
||||
// ---- win+lnx(+apk) ---- 远程控制全族 + 需 SCREEN_PREVIEW 的截屏 + macOS 未开放项
|
||||
// Android 用无障碍 takeScreenshot(API 30+,需开无障碍服务),只支持 mode=screen
|
||||
{ "get_screenshot", kPlatWin|kPlatLnx|kPlatApk },
|
||||
// macOS 走 macos/ScreenPreview.mm(CGDisplayCreateImage,声明 CLIENT_CAP_SCREEN_PREVIEW
|
||||
// 的前提是登录时已授予录屏权限),与 Linux 一样回 BGRX 由服务端编码
|
||||
{ "get_screenshot", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
|
||||
// 窗口信息 RPC 只在 Windows 客户端实现(CLIENT_CAP_WINDOW_INFO)
|
||||
{ "get_foreground_window", kPlatWin },
|
||||
// Android 客户端把注入翻译成触摸手势 / 全局动作(android/.../ControlService.kt),
|
||||
@@ -11771,17 +12015,21 @@ const ToolPlatform kToolPlatforms[] = {
|
||||
{ "remote_clipboard", kPlatWin|kPlatLnx|kPlatApk },
|
||||
// COMMAND_SCREEN_CTRL_ALT_DEL:只有 Android 客户端实现(映射为系统锁屏)
|
||||
{ "remote_lock_screen", kPlatApk },
|
||||
// macOS 客户端有 PTY 实现(macos/main.mm:753),但服务端刻意不开放
|
||||
// (McpServer.cpp:3652「macOS 本轮不开放」),故实际不可用;
|
||||
// Android 新版复用 common/PTYHandler.h(/system/bin/sh),声明 CLIENT_CAP_TERMINAL
|
||||
{ "exec_command", kPlatWin|kPlatLnx|kPlatApk },
|
||||
{ "terminal_open", kPlatWin|kPlatLnx|kPlatApk },
|
||||
{ "terminal_exec", kPlatWin|kPlatLnx|kPlatApk },
|
||||
{ "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)。
|
||||
// macOS 客户端同样是完整 PTY(common/PTYHandler.h,zsh/bash),新版声明
|
||||
// CLIENT_CAP_TERMINAL;老 macOS 构建收到 COMMAND_SHELL 只打一行 unimplemented,
|
||||
// 工具内部按能力位提前拒绝(McpServer.cpp 的 SupportsTerminal 判定)。
|
||||
// Android 新版复用 common/PTYHandler.h(/system/bin/sh),同样声明 CLIENT_CAP_TERMINAL
|
||||
{ "exec_command", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
|
||||
{ "terminal_open", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
|
||||
{ "terminal_exec", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
|
||||
{ "terminal_close", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
|
||||
// macOS 客户端有 COMMAND_SYSTEM → SystemManager(proc_listpids + SIGKILL),
|
||||
// 新版声明 CLIENT_CAP_PROCESS;老构建按能力位提前拒绝。
|
||||
{ "kill_process", kPlatWin|kPlatLnx|kPlatMac },
|
||||
// http_probe 要走终端通道(Windows 用 PowerShell、Linux 用 curl)。
|
||||
// macOS 终端已开放,但这里的 POSIX 命令用了 `base64 -w`(GNU 专有),BSD base64
|
||||
// 没有这个开关,头和体都会解不出来——等换成两平台通用的折行写法再放行。
|
||||
// Android 的 toybox 不保证有 curl/base64,故仍只标 win/lnx。
|
||||
{ "http_probe", kPlatWin|kPlatLnx },
|
||||
// ---- win ---- 服务 / 注册表 / 键日志 / 文件写 / host_* / chat_* / power_action
|
||||
// list_windows 单列:BuildListWindows 把 COMMAND_WSLIST 发在**主连接**上
|
||||
@@ -11794,7 +12042,8 @@ const ToolPlatform kToolPlatforms[] = {
|
||||
// Linux 客户端已实现 COMMAND_QUERY_ACTIVITY → TOKEN_REPORT_ACTIVITY(linux/LinuxActivityHistory.h,
|
||||
// 有桌面走 X11 窗口采样,无桌面走 last + shell 历史),Android 复用同一套采样机、
|
||||
// 前台应用由无障碍服务提供,与 Windows 同为主连接 RPC
|
||||
{ "get_activity_history", kPlatWin|kPlatLnx|kPlatApk },
|
||||
// macOS 是 macos/ActivityHistory.mm(CGWindowList 前台窗口采样,同样主连接一次性快照)
|
||||
{ "get_activity_history", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
|
||||
{ "list_services", kPlatWin },
|
||||
{ "get_keylog", kPlatWin },
|
||||
{ "list_registry", kPlatWin },
|
||||
@@ -12715,7 +12964,9 @@ int CMcpServer::SweepIdleTerminals(time_t idleTimeoutSec) {
|
||||
const auto steadyNow = std::chrono::steady_clock::now();
|
||||
for (auto it = m_TermSessions.begin(); it != m_TermSessions.end(); ) {
|
||||
TermSession& s = it->second;
|
||||
const bool idle = s.persistent && !s.busy &&
|
||||
// started 条件不能省:尚未 START 的会话可能正被 WaitTerminalReady 等着,
|
||||
// 回收它会把自己的新会话暴露给等待线程(抢到/被误删),等它自己的超时分支清理。
|
||||
const bool idle = s.persistent && s.started && !s.busy &&
|
||||
difftime(now, s.lastActiveAt) > (double)idleTimeoutSec;
|
||||
// busy 兜底(P0-2):超时轮询下会话一直 busy,调用方若再也不回来,该主机的终端槽
|
||||
// 会永远返回 -32003。跑满 1 小时强制回收(等待函数会重新查表,不会悬空)。
|
||||
@@ -13169,14 +13420,18 @@ void CMcpServer::EndCall(const std::shared_ptr<McpCallContext>& call) {
|
||||
|
||||
bool CMcpServer::CancelCallById(const std::string& idKey, const std::string& idText) {
|
||||
std::lock_guard<std::mutex> lk(m_CallMutex);
|
||||
// 取消工具自己也是一次在飞调用;request_id 指到自己时不能把自己算成「被取消」。
|
||||
const McpCallContext* self = CurrentMcpCall().get();
|
||||
// 先按精确写法找:"41"(字符串)与 41(数字)是两个不同的 id,不能混。
|
||||
for (const auto& c : m_Calls) {
|
||||
if (c.get() == self) continue;
|
||||
if (c->idKey == idKey) { c->cancelled.store(true); return true; }
|
||||
}
|
||||
// 再退回展示文本:调用方常把列表里的 request_id 当字符串原样传回来,
|
||||
// 而原调用用的是数字 id —— 这是同一意图,容忍。
|
||||
if (!idText.empty()) {
|
||||
for (const auto& c : m_Calls) {
|
||||
if (c.get() == self) continue;
|
||||
if (c->idText == idText) { c->cancelled.store(true); return true; }
|
||||
}
|
||||
}
|
||||
@@ -13186,7 +13441,9 @@ bool CMcpServer::CancelCallById(const std::string& idKey, const std::string& idT
|
||||
int CMcpServer::CancelCalls(uint64_t device, const std::string& sessionId) {
|
||||
int n = 0;
|
||||
std::lock_guard<std::mutex> lk(m_CallMutex);
|
||||
const McpCallContext* self = CurrentMcpCall().get();
|
||||
for (const auto& c : m_Calls) {
|
||||
if (c.get() == self) continue; // 不把取消工具自身计入 cancelled
|
||||
if (device != 0 && c->device != device) continue;
|
||||
if (!sessionId.empty() && c->sessionId != sessionId) continue;
|
||||
c->cancelled.store(true);
|
||||
@@ -13318,8 +13575,7 @@ std::string CMcpServer::DescribeBusy(uint64_t device_id) {
|
||||
std::lock_guard<std::mutex> lk(m_TermMutex);
|
||||
auto it = m_TermSessions.find(device_id);
|
||||
if (it != m_TermSessions.end() && it->second.busy)
|
||||
return describe(it->second.sessionId.empty() ? "exec_command" : "terminal",
|
||||
ElapsedMsSince(it->second.startedAt));
|
||||
return describe(TerminalLabel(it->second.sessionId), ElapsedMsSince(it->second.startedAt));
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(m_ScreenCtrlMutex);
|
||||
@@ -13926,7 +14182,10 @@ bool CMcpServer::OnDriveList(uint64_t device_id, context* subCtx, const BYTE* bu
|
||||
searchFile = true;
|
||||
it->second.subCtx = subCtx; // 超时停搜 / 收尾要用
|
||||
} else {
|
||||
listDrives = path.empty() || path == "." || path == "/" || path == "\\";
|
||||
// 列盘一律用空 path 表示:Windows 的 "."、"/"、"\\" 已在 BuildListFiles 归一化成
|
||||
// 空串;POSIX 上 "/" 与 "." 是真实目录,必须按目录下发。这里不再自行判魔法路径,
|
||||
// 免得两个地方口径不一致。
|
||||
listDrives = path.empty();
|
||||
if (listDrives) {
|
||||
it->second.data.assign(buf, buf + len);
|
||||
it->second.done = true;
|
||||
|
||||
@@ -46,7 +46,7 @@
|
||||
|
||||
// 程序版本号 [建议格式: X.Y.Z]
|
||||
// 影响:关于对话框、标题栏
|
||||
#define BRAND_VERSION "1.4.2"
|
||||
#define BRAND_VERSION "1.4.3"
|
||||
|
||||
// 启动画面名称 [建议大写,更有 Logo 感]
|
||||
// 影响:启动画面 Logo 文字(大号艺术字体渲染)
|
||||
|
||||
@@ -171,6 +171,16 @@ public:
|
||||
return (strtoul(caps.GetString(), nullptr, 16) & CLIENT_CAP_TERMINAL) != 0;
|
||||
}
|
||||
|
||||
// 检查客户端是否处理 COMMAND_SYSTEM(系统子连接:COMMAND_PSLIST / COMMAND_KILLPROCESS)。
|
||||
// Linux/macOS 声明;Windows 客户端一直有这条分支但不声明,调用方按平台区分。
|
||||
// 没有这一位的主机(如老 macOS 构建)收到 COMMAND_SYSTEM 只打一行日志,
|
||||
// 服务端据此提前拒绝 kill_process,而不是发下去后等刷新超时、再报一个假的 ok。
|
||||
bool SupportsProcess() const {
|
||||
CString caps = GetClientData(ONLINELIST_CAPABILITIES);
|
||||
if (caps.IsEmpty()) return false;
|
||||
return (strtoul(caps.GetString(), nullptr, 16) & CLIENT_CAP_PROCESS) != 0;
|
||||
}
|
||||
|
||||
// 检查客户端是否处理 COMMAND_SCREEN_BLOCK_INPUT / COMMAND_SCREEN_BLANK(Android 用
|
||||
// 无障碍全屏 overlay 实现:输入锁 = 透明 overlay 吃掉触摸,黑屏 = 黑色 overlay)。
|
||||
// Windows 客户端一直支持键鼠锁定但不声明这个位,调用方按平台区分;老 APK 收到两个
|
||||
|
||||
+9
-2
@@ -10,8 +10,15 @@ BUILD_DIR=build
|
||||
# Main package path
|
||||
MAIN_PACKAGE=./cmd
|
||||
|
||||
# Go build flags (strip debug info for smaller binary)
|
||||
LDFLAGS=-ldflags "-s -w"
|
||||
# Version metadata injected at link time (see buildinfo package). Both are
|
||||
# empty outside a git checkout; the server then reports no version rather than
|
||||
# a fabricated one.
|
||||
VERSION := $(shell git describe --tags --always --dirty 2>nul)
|
||||
COMMIT := $(shell git rev-parse --short HEAD 2>nul)
|
||||
BUILDINFO_PKG = github.com/yuanyuanxiang/SimpleRemoter/server/go/buildinfo
|
||||
|
||||
# Go build flags (strip debug info for smaller binary; version always injected)
|
||||
LDFLAGS=-ldflags "-s -w -X $(BUILDINFO_PKG).Version=$(VERSION) -X $(BUILDINFO_PKG).Commit=$(COMMIT)"
|
||||
|
||||
# Windows commands
|
||||
MKDIR=if not exist $(BUILD_DIR) mkdir $(BUILD_DIR)
|
||||
|
||||
@@ -0,0 +1,287 @@
|
||||
// Package auditquery scans the server's JSON-lines audit file.
|
||||
//
|
||||
// The server writes its own audit records to logs/audit.log (see
|
||||
// logger.AuditAt); records are already redacted at write time, so returning
|
||||
// raw fields to an authenticated viewer is safe as long as we never widen what
|
||||
// is written.
|
||||
//
|
||||
// Only the CURRENT audit file is searched. Rotated files (audit-*.log[.gz])
|
||||
// are deliberately out of scope: they need gzip support and a separate index,
|
||||
// and both the web UI and the MCP tool exist for recent-window triage ("what
|
||||
// happened just now").
|
||||
//
|
||||
// The package is shared by web/audit_query.go (admin audit page) and the MCP
|
||||
// get_audit_log tool, which is why it has no dependency on either.
|
||||
package auditquery
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
// DefaultLimit is used when the caller asks for no limit (0 or negative).
|
||||
DefaultLimit = 100
|
||||
// MaxLimit caps how many records one query may return.
|
||||
MaxLimit = 1000
|
||||
// MaxOffset caps how far a query may page into the result set.
|
||||
MaxOffset = 10000
|
||||
|
||||
// scanBudget bounds how much of the audit file a single query reads. The
|
||||
// tail is read when the file is larger, so the newest records (what
|
||||
// operators actually triage) are always covered and a multi-GB log cannot
|
||||
// stall the query goroutine.
|
||||
scanBudget = 32 << 20 // 32 MB
|
||||
)
|
||||
|
||||
// Query is one audit-log search. All filters are optional and combined with
|
||||
// AND. Limit/Offset are clamped by Scan; callers that report the effective
|
||||
// values back should clamp first with ClampLimit/ClampOffset.
|
||||
type Query struct {
|
||||
From string `json:"from"` // RFC3339 ("2026-10-18T10:00:00Z"), optional
|
||||
To string `json:"to"` // RFC3339, optional
|
||||
Event string `json:"event"` // exact ("web.login.failure"), prefix ("web." / "web.*"), or ""
|
||||
Actor string `json:"actor"` // exact, case-insensitive
|
||||
IP string `json:"ip"` // exact
|
||||
DeviceID string `json:"device_id"`
|
||||
Keyword string `json:"keyword"` // case-insensitive substring of the raw record
|
||||
WarnOnly bool `json:"warn_only"` // only level=warn records
|
||||
|
||||
// EventContains is a case-insensitive substring match on the event column.
|
||||
// The web UI uses Event's exact/prefix forms; the MCP get_audit_log tool
|
||||
// exposes a "type contains" filter, which maps here.
|
||||
EventContains string `json:"event_contains"`
|
||||
|
||||
Limit int `json:"limit"`
|
||||
Offset int `json:"offset"` // skip the newest N matching records
|
||||
}
|
||||
|
||||
// Result is the outcome of scanning the audit file.
|
||||
type Result struct {
|
||||
Events []map[string]any // newest-first
|
||||
Total int // matching records in the scanned window
|
||||
TotalAll int // audit records in the scanned window before filters
|
||||
FileExists bool
|
||||
FileSize int64
|
||||
ScannedBytes int64
|
||||
Truncated bool // the file was larger than the scan budget
|
||||
}
|
||||
|
||||
// ClampLimit bounds n to [1, max]. A non-positive n means DefaultLimit; a
|
||||
// non-positive max means MaxLimit. Callers with a tighter UI cap (the web
|
||||
// audit page uses 500) pass it as max.
|
||||
func ClampLimit(n, max int) int {
|
||||
if max <= 0 {
|
||||
max = MaxLimit
|
||||
}
|
||||
if n <= 0 {
|
||||
return DefaultLimit
|
||||
}
|
||||
if n > max {
|
||||
return max
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// ClampOffset bounds n to [0, MaxOffset].
|
||||
func ClampOffset(n int) int {
|
||||
if n < 0 {
|
||||
return 0
|
||||
}
|
||||
if n > MaxOffset {
|
||||
return MaxOffset
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// Scan scans path for audit records matching q. The returned events are the
|
||||
// newest Limit records after skipping Offset, in newest-first order. A missing
|
||||
// file is not an error: no audit record has been written yet (the logger
|
||||
// creates the file lazily), so the result is empty with FileExists=false.
|
||||
func Scan(path string, q Query) (Result, error) {
|
||||
q.Limit = ClampLimit(q.Limit, MaxLimit)
|
||||
q.Offset = ClampOffset(q.Offset)
|
||||
|
||||
res := Result{Events: []map[string]any{}}
|
||||
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return res, nil
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
info, err := f.Stat()
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
res.FileExists = true
|
||||
res.FileSize = info.Size()
|
||||
|
||||
// For very large files, scan only the tail; the newest matches live there.
|
||||
start := int64(0)
|
||||
if info.Size() > scanBudget {
|
||||
start = info.Size() - scanBudget
|
||||
if _, err := f.Seek(start, 0); err != nil {
|
||||
return res, err
|
||||
}
|
||||
res.Truncated = true
|
||||
}
|
||||
|
||||
from, hasFrom := parseTime(q.From)
|
||||
to, hasTo := parseTime(q.To)
|
||||
|
||||
keep := q.Offset + q.Limit
|
||||
ring := make([]map[string]any, keep)
|
||||
filled := 0
|
||||
|
||||
sc := bufio.NewScanner(f)
|
||||
// Sanitized values are capped at 4096 bytes each; a record with many
|
||||
// fields stays well under 1 MB. Allow headroom rather than aborting the
|
||||
// whole query on one long line.
|
||||
sc.Buffer(make([]byte, 64*1024), 4*1024*1024)
|
||||
|
||||
first := true
|
||||
for sc.Scan() {
|
||||
line := sc.Text()
|
||||
if start > 0 && first {
|
||||
// Seeking into the middle of the file lands mid-line. Drop that
|
||||
// partial record.
|
||||
first = false
|
||||
continue
|
||||
}
|
||||
first = false
|
||||
res.ScannedBytes += int64(len(line)) + 1
|
||||
|
||||
line = strings.TrimSpace(line)
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
var rec map[string]any
|
||||
if err := json.Unmarshal([]byte(line), &rec); err != nil {
|
||||
continue // tolerate a torn line instead of failing the page
|
||||
}
|
||||
if _, ok := rec["event"].(string); !ok {
|
||||
continue
|
||||
}
|
||||
// Only audit records belong in the result. The dedicated file contains
|
||||
// nothing else, but a hand-edited or mixed file must not surface
|
||||
// ordinary operational lines here.
|
||||
if rec["audit"] != true {
|
||||
continue
|
||||
}
|
||||
res.TotalAll++
|
||||
if !recordMatches(rec, line, q, from, hasFrom, to, hasTo) {
|
||||
continue
|
||||
}
|
||||
// Ring buffer of the last `keep` matches (file order is chronological).
|
||||
ring[res.Total%keep] = rec
|
||||
if filled < keep {
|
||||
filled++
|
||||
}
|
||||
res.Total++
|
||||
}
|
||||
if err := sc.Err(); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
// Newest first, skipping Offset. The match with 0-based index i lives at
|
||||
// ring[i%keep] as long as i >= Total-filled.
|
||||
for i := res.Total - 1 - q.Offset; i >= 0 && i >= res.Total-filled; i-- {
|
||||
res.Events = append(res.Events, ring[i%keep])
|
||||
if len(res.Events) >= q.Limit {
|
||||
break
|
||||
}
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// recordMatches applies the non-time and time filters to one record. line is
|
||||
// the raw JSON line, used for the keyword substring search.
|
||||
func recordMatches(rec map[string]any, line string, q Query, from time.Time, hasFrom bool, to time.Time, hasTo bool) bool {
|
||||
if q.Event != "" && !eventFilterMatches(q.Event, StringField(rec, "event")) {
|
||||
return false
|
||||
}
|
||||
if q.EventContains != "" && !strings.Contains(strings.ToLower(StringField(rec, "event")), strings.ToLower(q.EventContains)) {
|
||||
return false
|
||||
}
|
||||
if q.Actor != "" && !strings.EqualFold(StringField(rec, "actor"), q.Actor) {
|
||||
return false
|
||||
}
|
||||
if q.IP != "" && StringField(rec, "ip") != q.IP {
|
||||
return false
|
||||
}
|
||||
if q.DeviceID != "" && StringField(rec, "device_id") != q.DeviceID {
|
||||
return false
|
||||
}
|
||||
if q.WarnOnly && StringField(rec, "level") != "warn" {
|
||||
return false
|
||||
}
|
||||
if q.Keyword != "" && !strings.Contains(strings.ToLower(line), strings.ToLower(q.Keyword)) {
|
||||
return false
|
||||
}
|
||||
if hasFrom || hasTo {
|
||||
t, ok := parseTime(StringField(rec, "time"))
|
||||
if !ok {
|
||||
return false // cannot prove it is in range
|
||||
}
|
||||
if hasFrom && t.Before(from) {
|
||||
return false
|
||||
}
|
||||
if hasTo && t.After(to) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// eventFilterMatches supports three forms so the UI stays simple:
|
||||
//
|
||||
// "web.login.failure" exact
|
||||
// "web.*" prefix (trailing "*")
|
||||
// "web." prefix (trailing ".")
|
||||
func eventFilterMatches(filter, event string) bool {
|
||||
switch {
|
||||
case strings.HasSuffix(filter, "*"):
|
||||
return strings.HasPrefix(event, strings.TrimSuffix(filter, "*"))
|
||||
case strings.HasSuffix(filter, "."):
|
||||
return strings.HasPrefix(event, filter)
|
||||
default:
|
||||
return event == filter
|
||||
}
|
||||
}
|
||||
|
||||
// StringField returns rec[key] when it is a string, else "".
|
||||
func StringField(rec map[string]any, key string) string {
|
||||
s, _ := rec[key].(string)
|
||||
return s
|
||||
}
|
||||
|
||||
// parseTime accepts the formats operators and browsers realistically send.
|
||||
// Layouts without an explicit zone are parsed as UTC; the frontend always sends
|
||||
// Date.toISOString(), so the RFC3339 path is what production uses.
|
||||
func parseTime(s string) (time.Time, bool) {
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" {
|
||||
return time.Time{}, false
|
||||
}
|
||||
layouts := []string{
|
||||
time.RFC3339Nano,
|
||||
time.RFC3339,
|
||||
"2006-01-02T15:04:05",
|
||||
"2006-01-02T15:04",
|
||||
"2006-01-02 15:04:05",
|
||||
"2006-01-02",
|
||||
}
|
||||
for _, layout := range layouts {
|
||||
if t, err := time.Parse(layout, s); err == nil {
|
||||
return t, true
|
||||
}
|
||||
}
|
||||
return time.Time{}, false
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
package auditquery
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// writeAuditFixture writes JSON-lines audit records (oldest first) and returns
|
||||
// the file path. Times are UTC RFC3339 so the tests are timezone-independent.
|
||||
func writeAuditFixture(t *testing.T, records []map[string]any) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "audit.log")
|
||||
var b strings.Builder
|
||||
for _, rec := range records {
|
||||
line, err := json.Marshal(rec)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal fixture: %v", err)
|
||||
}
|
||||
b.Write(line)
|
||||
b.WriteByte('\n')
|
||||
}
|
||||
if err := os.WriteFile(path, []byte(b.String()), 0o644); err != nil {
|
||||
t.Fatalf("write fixture: %v", err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func auditFixtureRecords() []map[string]any {
|
||||
at := func(hhmm string) string {
|
||||
tm, err := time.Parse("2006-01-02T15:04", "2026-10-18T"+hhmm)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return tm.Format(time.RFC3339)
|
||||
}
|
||||
return []map[string]any{
|
||||
{"level": "info", "time": at("10:00"), "audit": true, "event": "web.login.success", "actor": "admin", "ip": "203.0.113.1"},
|
||||
{"level": "warn", "time": at("10:01"), "audit": true, "event": "web.login.failure", "actor": "alice", "ip": "203.0.113.2", "reason": "invalid_credentials"},
|
||||
{"level": "info", "time": at("10:02"), "audit": true, "event": "remote.screen.start", "actor": "admin", "role": "admin", "ip": "203.0.113.1", "device_id": "dev1"},
|
||||
{"level": "info", "time": at("10:03"), "audit": true, "event": "admin.user.delete", "actor": "admin", "ip": "203.0.113.1", "target": "bob"},
|
||||
}
|
||||
}
|
||||
|
||||
func runAuditQuery(t *testing.T, path string, q Query) Result {
|
||||
t.Helper()
|
||||
q.Limit = ClampLimit(q.Limit, MaxLimit)
|
||||
q.Offset = ClampOffset(q.Offset)
|
||||
res, err := Scan(path, q)
|
||||
if err != nil {
|
||||
t.Fatalf("Scan: %v", err)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func eventNames(res Result) []string {
|
||||
out := make([]string, 0, len(res.Events))
|
||||
for _, e := range res.Events {
|
||||
out = append(out, StringField(e, "event"))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestNoFilterNewestFirst(t *testing.T) {
|
||||
path := writeAuditFixture(t, auditFixtureRecords())
|
||||
res := runAuditQuery(t, path, Query{Limit: 100})
|
||||
if res.Total != 4 || len(res.Events) != 4 {
|
||||
t.Fatalf("total=%d events=%d, want 4/4", res.Total, len(res.Events))
|
||||
}
|
||||
if res.TotalAll != 4 {
|
||||
t.Fatalf("totalAll=%d, want 4", res.TotalAll)
|
||||
}
|
||||
got := eventNames(res)
|
||||
want := []string{"admin.user.delete", "remote.screen.start", "web.login.failure", "web.login.success"}
|
||||
if strings.Join(got, ",") != strings.Join(want, ",") {
|
||||
t.Fatalf("events = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEventFilters(t *testing.T) {
|
||||
path := writeAuditFixture(t, auditFixtureRecords())
|
||||
cases := []struct {
|
||||
filter string
|
||||
want []string
|
||||
}{
|
||||
{"web.", []string{"web.login.failure", "web.login.success"}},
|
||||
{"web.*", []string{"web.login.failure", "web.login.success"}},
|
||||
{"web.login.failure", []string{"web.login.failure"}},
|
||||
{"remote.*", []string{"remote.screen.start"}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
res := runAuditQuery(t, path, Query{Event: tc.filter, Limit: 100})
|
||||
got := eventNames(res)
|
||||
if strings.Join(got, ",") != strings.Join(tc.want, ",") {
|
||||
t.Errorf("filter %q → %v, want %v", tc.filter, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEventContainsFilter(t *testing.T) {
|
||||
path := writeAuditFixture(t, auditFixtureRecords())
|
||||
res := runAuditQuery(t, path, Query{EventContains: "LOGIN", Limit: 100})
|
||||
got := eventNames(res)
|
||||
want := []string{"web.login.failure", "web.login.success"}
|
||||
if strings.Join(got, ",") != strings.Join(want, ",") {
|
||||
t.Fatalf("events = %v, want %v", got, want)
|
||||
}
|
||||
// Filters run before paging: total reflects matches, totalAll the window.
|
||||
if res.Total != 2 || res.TotalAll != 4 {
|
||||
t.Fatalf("total=%d totalAll=%d, want 2/4", res.Total, res.TotalAll)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFieldFilters(t *testing.T) {
|
||||
path := writeAuditFixture(t, auditFixtureRecords())
|
||||
from, _ := time.Parse(time.RFC3339, "2026-10-18T10:01:00Z")
|
||||
to, _ := time.Parse(time.RFC3339, "2026-10-18T10:02:00Z")
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
q Query
|
||||
want []string
|
||||
}{
|
||||
{"actor case-insensitive", Query{Actor: "ALICE", Limit: 100}, []string{"web.login.failure"}},
|
||||
{"ip", Query{IP: "203.0.113.2", Limit: 100}, []string{"web.login.failure"}},
|
||||
{"device", Query{DeviceID: "dev1", Limit: 100}, []string{"remote.screen.start"}},
|
||||
{"warn only", Query{WarnOnly: true, Limit: 100}, []string{"web.login.failure"}},
|
||||
{"keyword target", Query{Keyword: "BOB", Limit: 100}, []string{"admin.user.delete"}},
|
||||
{"time range", Query{
|
||||
From: from.Format(time.RFC3339), To: to.Format(time.RFC3339), Limit: 100,
|
||||
}, []string{"remote.screen.start", "web.login.failure"}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
res := runAuditQuery(t, path, tc.q)
|
||||
got := eventNames(res)
|
||||
if strings.Join(got, ",") != strings.Join(tc.want, ",") {
|
||||
t.Errorf("%s → %v, want %v", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestOffsetAndLimit(t *testing.T) {
|
||||
path := writeAuditFixture(t, auditFixtureRecords())
|
||||
res := runAuditQuery(t, path, Query{Limit: 2, Offset: 1})
|
||||
if res.Total != 4 {
|
||||
t.Fatalf("total = %d, want 4", res.Total)
|
||||
}
|
||||
got := eventNames(res)
|
||||
want := []string{"remote.screen.start", "web.login.failure"}
|
||||
if strings.Join(got, ",") != strings.Join(want, ",") {
|
||||
t.Fatalf("events = %v, want %v", got, want)
|
||||
}
|
||||
|
||||
// Offsetting past the end yields no events but keeps the total.
|
||||
res = runAuditQuery(t, path, Query{Limit: 2, Offset: 4})
|
||||
if res.Total != 4 || len(res.Events) != 0 {
|
||||
t.Fatalf("offset past end: total=%d events=%v", res.Total, eventNames(res))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSkipsNonAuditAndTornLines(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "audit.log")
|
||||
content := `{"event":"device.online","actor":"x"}
|
||||
not json at all
|
||||
{"level":"info","time":"2026-10-18T10:00:00Z","audit":true,"event":"web.login.success","actor":"admin"}`
|
||||
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
res := runAuditQuery(t, path, Query{Limit: 100})
|
||||
if res.Total != 1 || len(res.Events) != 1 {
|
||||
t.Fatalf("total=%d events=%v, want the single valid record", res.Total, eventNames(res))
|
||||
}
|
||||
// Non-audit and torn lines do not count toward totalAll either.
|
||||
if res.TotalAll != 1 {
|
||||
t.Fatalf("totalAll=%d, want 1", res.TotalAll)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMissingFile(t *testing.T) {
|
||||
res := runAuditQuery(t, filepath.Join(t.TempDir(), "does-not-exist.log"), Query{Limit: 10})
|
||||
if res.FileExists {
|
||||
t.Error("FileExists = true for a missing file")
|
||||
}
|
||||
if res.Total != 0 || len(res.Events) != 0 {
|
||||
t.Errorf("total=%d events=%v, want empty", res.Total, eventNames(res))
|
||||
}
|
||||
if res.Events == nil {
|
||||
t.Error("Events is nil; JSON would encode null instead of []")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClampsPaging(t *testing.T) {
|
||||
if got := ClampLimit(0, MaxLimit); got != DefaultLimit {
|
||||
t.Errorf("limit(0) = %d, want default %d", got, DefaultLimit)
|
||||
}
|
||||
if got := ClampLimit(-3, MaxLimit); got != DefaultLimit {
|
||||
t.Errorf("limit(-3) = %d, want default %d", got, DefaultLimit)
|
||||
}
|
||||
if got := ClampLimit(9999, MaxLimit); got != MaxLimit {
|
||||
t.Errorf("limit(9999) = %d, want max %d", got, MaxLimit)
|
||||
}
|
||||
if got := ClampLimit(9999, 500); got != 500 {
|
||||
t.Errorf("limit(9999, max 500) = %d, want 500", got)
|
||||
}
|
||||
if got := ClampLimit(50, MaxLimit); got != 50 {
|
||||
t.Errorf("limit(50) = %d, want 50", got)
|
||||
}
|
||||
if got := ClampLimit(0, 0); got != DefaultLimit {
|
||||
t.Errorf("limit(0, max 0) = %d, want default %d", got, DefaultLimit)
|
||||
}
|
||||
if got := ClampOffset(-5); got != 0 {
|
||||
t.Errorf("offset(-5) = %d, want 0", got)
|
||||
}
|
||||
if got := ClampOffset(1 << 30); got != MaxOffset {
|
||||
t.Errorf("offset(huge) = %d, want max %d", got, MaxOffset)
|
||||
}
|
||||
}
|
||||
|
||||
// The web audit page sends snake_case keys. Query is decoded from that wire
|
||||
// format in web/audit_query.go, so the tags must keep those names — otherwise
|
||||
// device_id / warn_only silently stop filtering.
|
||||
func TestQueryDecodesWebWireFormat(t *testing.T) {
|
||||
body := `{"from":"2026-11-01T00:00:00Z","to":"2026-11-12T00:00:00Z",` +
|
||||
`"event":"web.","actor":"admin","ip":"1.2.3.4","device_id":"1001",` +
|
||||
`"keyword":"k","warn_only":true,"limit":5,"offset":2}`
|
||||
var q Query
|
||||
if err := json.Unmarshal([]byte(body), &q); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if q.From != "2026-11-01T00:00:00Z" || q.To != "2026-11-12T00:00:00Z" {
|
||||
t.Fatalf("time range = %q..%q", q.From, q.To)
|
||||
}
|
||||
if q.Event != "web." || q.Actor != "admin" || q.IP != "1.2.3.4" {
|
||||
t.Fatalf("filters = %+v", q)
|
||||
}
|
||||
if q.DeviceID != "1001" {
|
||||
t.Fatalf("device_id = %q, want 1001", q.DeviceID)
|
||||
}
|
||||
if q.Keyword != "k" || !q.WarnOnly {
|
||||
t.Fatalf("keyword/warn_only = %q/%v", q.Keyword, q.WarnOnly)
|
||||
}
|
||||
if q.Limit != 5 || q.Offset != 2 {
|
||||
t.Fatalf("limit/offset = %d/%d", q.Limit, q.Offset)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
// Package buildinfo exposes the version metadata injected at link time.
|
||||
//
|
||||
// Version and Commit are set by the build scripts with
|
||||
//
|
||||
// go build -ldflags "-X github.com/yuanyuanxiang/SimpleRemoter/server/go/buildinfo.Version=... \
|
||||
// -X github.com/yuanyuanxiang/SimpleRemoter/server/go/buildinfo.Commit=..."
|
||||
//
|
||||
// They stay empty when the binary is built without git (source tarball, IDE
|
||||
// run). Callers must report the empty string rather than inventing a value;
|
||||
// only the MCP initialize response substitutes a literal "dev" marker.
|
||||
package buildinfo
|
||||
|
||||
var (
|
||||
// Version is the full `git describe --tags --always --dirty` string, e.g.
|
||||
// "v1.4.2-72-g425d737-dirty".
|
||||
Version = ""
|
||||
// Commit is the short commit hash, e.g. "425d737".
|
||||
Commit = ""
|
||||
)
|
||||
|
||||
// Info is a JSON-friendly snapshot of the injected metadata.
|
||||
type Info struct {
|
||||
Version string `json:"version"`
|
||||
Commit string `json:"commit"`
|
||||
}
|
||||
|
||||
// Snapshot returns the current build metadata. It is safe to call before the
|
||||
// values are injected (both fields are empty).
|
||||
func Snapshot() Info {
|
||||
return Info{Version: Version, Commit: Commit}
|
||||
}
|
||||
+90
-3
@@ -17,11 +17,13 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/auth"
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/buildinfo"
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/connection"
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/devicehistory"
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/licensing"
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/logger"
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/mcp"
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/protocol"
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/server"
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/web"
|
||||
@@ -37,6 +39,7 @@ type MyHandler struct {
|
||||
signer licensing.Signer // CMD_MASTERSETTING signer (local / remote / noop)
|
||||
loginLimit *wsauth.RateLimiter // per-IP TOKEN_AUTH throttle
|
||||
connAuthKey []byte // nil = ConnAuth HMAC verification disabled (legacy always-OK)
|
||||
mcp *mcp.Server // routes main-connection RPC replies (screen preview, file lists)
|
||||
}
|
||||
|
||||
// OnConnect is called when a client connects
|
||||
@@ -129,8 +132,11 @@ func (h *MyHandler) OnReceive(ctx *connection.Context, data []byte) {
|
||||
h.handleTerminalStart(ctx, false)
|
||||
case protocol.TokenTerminalClose:
|
||||
// Pre-bind close (rare — device gives up before the server
|
||||
// finished its half of the handshake). Best-effort cleanup.
|
||||
if devID := h.deviceIDOfSubConn(ctx); devID != "" {
|
||||
// finished its half of the handshake). Best-effort cleanup, but only
|
||||
// of a pending lease: an unbound sub-conn carries no lease identity,
|
||||
// and after a re-login it may be a stale orphan whose close would
|
||||
// otherwise tear down a shell someone else has since opened.
|
||||
if devID := h.deviceIDOfSubConn(ctx); devID != "" && h.hub.IsTerminalPending(devID) {
|
||||
h.log.Info("pre-bind terminal close: device=%s conn=%d", devID, ctx.ID)
|
||||
h.hub.CloseTerminalSession(devID)
|
||||
}
|
||||
@@ -160,6 +166,32 @@ func (h *MyHandler) OnReceive(ctx *connection.Context, data []byte) {
|
||||
// overlay learns to render arbitrary BGRA images. Drop silently for
|
||||
// now; the standard IDC_* index (data[10] of every frame header) is
|
||||
// what we actually use right now.
|
||||
case protocol.TokenScreenPreviewRsp:
|
||||
// get_screenshot is a main-connection RPC: the reply carries only a
|
||||
// reqId, so MCP matches it against the pending request for this device
|
||||
// and drops a late or foreign one. No other component reads this token.
|
||||
if h.mcp != nil && h.mcp.OnPacket(ctx, data) {
|
||||
return
|
||||
}
|
||||
h.log.Info("Unhandled command %d from client %d", cmd, ctx.ID)
|
||||
case protocol.TokenDriveList, protocol.TokenFileList, protocol.TokenFileListError:
|
||||
// list_files replies arrive on the file-manager sub-connection, whose
|
||||
// ClientID is pinned by its ConnAuth handshake. MCP matches them against
|
||||
// the pending request for that device and retires the sub-conn when the
|
||||
// request finishes or an orphan announces itself.
|
||||
if h.mcp != nil && h.mcp.OnFilePacket(ctx, data) {
|
||||
return
|
||||
}
|
||||
h.log.Info("Unhandled command %d from client %d", cmd, ctx.ID)
|
||||
case protocol.CommandSendFileV2, protocol.CommandFileCompleteV2, protocol.TokenDownloadError:
|
||||
// read_file's V2 transfer: chunks and the completion packet arrive on an
|
||||
// authenticated sub-conn (a fresh one on Windows, the file-manager one on
|
||||
// POSIX), the download error on the file-manager sub-conn. MCP routes
|
||||
// them to the pending session for the device and writes the bytes itself.
|
||||
if h.mcp != nil && h.mcp.OnTransferPacket(ctx, data) {
|
||||
return
|
||||
}
|
||||
h.log.Info("Unhandled command %d from client %d", cmd, ctx.ID)
|
||||
case protocol.CmdSockDllLoader:
|
||||
// SOCKET_DLLLOADER (210): the shellcode / memory-DLL loader asks for the
|
||||
// full DLL payload before it can load the client. Serving it is the MFC
|
||||
@@ -880,6 +912,16 @@ func envInt(name string, def int) int {
|
||||
return n
|
||||
}
|
||||
|
||||
// envBool parses a boolean env var; accepts 1/true/yes/on (case-insensitive)
|
||||
// as true and everything else — including unset — as false.
|
||||
func envBool(name string) bool {
|
||||
switch strings.ToLower(strings.TrimSpace(os.Getenv(name))) {
|
||||
case "1", "true", "yes", "on":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// runIssueToken handles the "issue-token" subcommand. It mints a customer JWT
|
||||
// signed with the operator's RSA private key and prints it to stdout.
|
||||
//
|
||||
@@ -1189,6 +1231,43 @@ func main() {
|
||||
log.Info("Trusting forwarded client IPs from: %s", strings.Join(trustedProxies, ", "))
|
||||
}
|
||||
|
||||
// MCP endpoint: a static bearer token independent of the web login. An
|
||||
// empty YAMA_MCP_TOKEN leaves /mcp unregistered (404) — there is no
|
||||
// auto-generated token, because a secret that only appears in a log is not
|
||||
// a secret. Version/commit come from the link-time buildinfo injection.
|
||||
//
|
||||
// Built before the TCP servers so each handler can hand main-connection
|
||||
// RPC replies (screen preview, file lists) to it. Starting its reaper a
|
||||
// few statements early is harmless; the HTTP route is mounted later.
|
||||
mcpReadonly := envBool("YAMA_MCP_READONLY")
|
||||
var mcpUnsubscribe func()
|
||||
bindAddr := ""
|
||||
if *httpPort != 0 {
|
||||
bindAddr = "0.0.0.0" // web server listens on :port (all interfaces)
|
||||
}
|
||||
mcpSrv := mcp.New(mcp.Config{
|
||||
Token: strings.TrimSpace(os.Getenv("YAMA_MCP_TOKEN")),
|
||||
Readonly: mcpReadonly,
|
||||
TermIdle: time.Duration(envInt("YAMA_MCP_TERM_IDLE", 180)) * time.Second,
|
||||
MaxConcurrency: envInt("YAMA_MCP_MAX_CONCURRENCY", 16),
|
||||
ReadMax: int64(envInt("YAMA_MCP_READ_MAX", 2<<20)),
|
||||
Version: buildinfo.Version,
|
||||
StartedAt: time.Now(),
|
||||
Log: log.WithPrefix("MCP"),
|
||||
Hub: deviceHub,
|
||||
History: deviceHistory,
|
||||
AuditPath: auditFile,
|
||||
Port: *httpPort,
|
||||
Bind: bindAddr,
|
||||
})
|
||||
if mcpSrv.Enabled() {
|
||||
// Terminal tools need the hub's shell events (ready/data/closed).
|
||||
// Unsubscribed again at shutdown, before the TCP servers stop.
|
||||
mcpUnsubscribe = deviceHub.Subscribe(mcpSrv)
|
||||
log.Info("MCP endpoint enabled on /mcp (readonly=%v, commit=%s)",
|
||||
mcpReadonly, buildinfo.Commit)
|
||||
}
|
||||
|
||||
// Create servers for each port
|
||||
var servers []*server.Server
|
||||
for _, port := range ports {
|
||||
@@ -1214,6 +1293,7 @@ func main() {
|
||||
signer: signer,
|
||||
loginLimit: authLoginLimit,
|
||||
connAuthKey: connAuthKey,
|
||||
mcp: mcpSrv,
|
||||
}
|
||||
srv.SetHandler(handler)
|
||||
|
||||
@@ -1292,7 +1372,8 @@ func main() {
|
||||
// device registry; the authenticator owns user accounts and session tokens.
|
||||
httpSrv := web.New(*httpPort, log.WithPrefix("Web"), deviceHub, webAuth).
|
||||
WithDeviceHistory(deviceHistory).
|
||||
WithConfig(webCfg)
|
||||
WithConfig(webCfg).
|
||||
WithMCP(mcpSrv)
|
||||
if err := httpSrv.Start(); err != nil {
|
||||
log.Fatal("Failed to start HTTP server: %v", err)
|
||||
}
|
||||
@@ -1362,6 +1443,12 @@ func main() {
|
||||
log.Warn("signer Close: %v", err)
|
||||
}
|
||||
httpSrv.Stop()
|
||||
// Detach from hub events first, then tear down the shells MCP opened while
|
||||
// the TCP sender is still alive so the client gets a clean BYE.
|
||||
if mcpUnsubscribe != nil {
|
||||
mcpUnsubscribe()
|
||||
}
|
||||
mcpSrv.Close()
|
||||
for _, srv := range servers {
|
||||
srv.Stop()
|
||||
}
|
||||
|
||||
@@ -33,6 +33,25 @@ YAMA_WEB_TRUST_PROXY=1
|
||||
# WebSocket Origin 白名单(逗号分隔)。空 = 仅允许同源
|
||||
#YAMA_WEB_ALLOWED_ORIGINS=https://你的域名
|
||||
|
||||
# ---------- MCP 端点(可选)----------
|
||||
# 设计见 docs/Mcp_Go_Minimal_Design.md;启用后挂在同一个 Web 端口的 /mcp。
|
||||
|
||||
# 静态 Bearer Token(客户端填同一个值)。空 = 不注册 /mcp(404)。
|
||||
# 不会自动生成:只出现在日志里的秘密不算秘密
|
||||
#YAMA_MCP_TOKEN=
|
||||
|
||||
# "1" = 只读模式:隐藏并拒收 terminal_exec / terminal_close(会创建/关闭会话)
|
||||
#YAMA_MCP_READONLY=1
|
||||
|
||||
# 终端会话空闲回收(秒,默认 180)
|
||||
#YAMA_MCP_TERM_IDLE=180
|
||||
|
||||
# 全球在途 tools/call 上限(默认 16,超出返回 -32003)
|
||||
#YAMA_MCP_MAX_CONCURRENCY=16
|
||||
|
||||
# read_file 单文件上限(字节,默认 2 MiB;超限提示改用 download_file)
|
||||
#YAMA_MCP_READ_MAX=2097152
|
||||
|
||||
# ---------- SSO(单点登录,可选)----------
|
||||
|
||||
# 共享的 HS256 签名密钥。设置后启用 SSO:YAMA 校验父域名(如 FMS 网关)下发的
|
||||
|
||||
+69
-11
@@ -94,9 +94,13 @@ type Device struct {
|
||||
// and after teardown.
|
||||
// terminalIsPTY: distinguishes Linux/macOS/ConPTY (true) from the legacy
|
||||
// Windows cmd-pipe path. PTY mode supports resize; cmd-pipe ignores it.
|
||||
// terminalGen: identifies one lease. Every successful open bumps it, so a
|
||||
// viewer that lost the lease (a re-login drops a pending request, then
|
||||
// someone else opens) cannot close the new owner's shell.
|
||||
terminalPending bool
|
||||
terminalConn *connection.Context
|
||||
terminalIsPTY bool
|
||||
terminalGen uint64
|
||||
}
|
||||
|
||||
// ScreenCache is a read-only snapshot of a device's last-seen screen state,
|
||||
@@ -275,6 +279,20 @@ func (h *Hub) SendToDevice(id string, data []byte) error {
|
||||
return h.sender(d.conn, data)
|
||||
}
|
||||
|
||||
// SendToConn forwards a payload to an arbitrary connection (typically a
|
||||
// sub-conn the caller learned about from an inbound packet) through the same
|
||||
// framing/compression path as SendToDevice. Raw conn.Write would bypass the
|
||||
// per-connection encoder and the client could not parse it.
|
||||
func (h *Hub) SendToConn(ctx *connection.Context, data []byte) error {
|
||||
if ctx == nil || ctx.IsClosed() {
|
||||
return ErrDeviceOffline
|
||||
}
|
||||
if h.sender == nil {
|
||||
return ErrNoSender
|
||||
}
|
||||
return h.sender(ctx, data)
|
||||
}
|
||||
|
||||
// SendToScreen routes a payload to the device's currently-bound screen
|
||||
// sub-connection. Input events (COMMAND_SCREEN_CONTROL) MUST go through the
|
||||
// screen sub-conn rather than the main conn — the C++ client only dispatches
|
||||
@@ -496,6 +514,7 @@ func (h *Hub) Register(d *Device, conn *connection.Context) {
|
||||
d.cursorSeen, d.lastCursorIndex = prev.cursorSeen, prev.lastCursorIndex
|
||||
d.lastCursorX, d.lastCursorY, d.cursorPubAt = prev.lastCursorX, prev.lastCursorY, prev.cursorPubAt
|
||||
d.terminalConn, d.terminalIsPTY = prev.terminalConn, prev.terminalIsPTY
|
||||
d.terminalGen = prev.terminalGen
|
||||
}
|
||||
h.devices[d.ID] = d
|
||||
info := deviceToInfo(d)
|
||||
@@ -754,37 +773,57 @@ var ErrTerminalBusy = errors.New("terminal already open by another viewer")
|
||||
// returns ErrTerminalBusy. Mirrors C++ CWebService::HandleTermOpen
|
||||
// (server/2015Remote/WebService.cpp:1838).
|
||||
func (h *Hub) OpenTerminalSession(deviceID string) error {
|
||||
_, err := h.openTerminalSession(deviceID)
|
||||
return err
|
||||
}
|
||||
|
||||
// OpenTerminalSessionLease is OpenTerminalSession that also returns the lease
|
||||
// generation. A caller that later closes via CloseTerminalSessionLease can
|
||||
// only tear down the lease it opened: if the session was dropped (device
|
||||
// re-login) and taken over by another viewer, the generation no longer matches
|
||||
// and the close is a no-op.
|
||||
func (h *Hub) OpenTerminalSessionLease(deviceID string) (uint64, error) {
|
||||
return h.openTerminalSession(deviceID)
|
||||
}
|
||||
|
||||
func (h *Hub) openTerminalSession(deviceID string) (uint64, error) {
|
||||
if deviceID == "" {
|
||||
return ErrDeviceOffline
|
||||
return 0, ErrDeviceOffline
|
||||
}
|
||||
h.mu.Lock()
|
||||
d, ok := h.devices[deviceID]
|
||||
if !ok || d.conn == nil {
|
||||
h.mu.Unlock()
|
||||
return ErrDeviceOffline
|
||||
return 0, ErrDeviceOffline
|
||||
}
|
||||
if d.terminalPending || d.terminalConn != nil {
|
||||
h.mu.Unlock()
|
||||
return ErrTerminalBusy
|
||||
return 0, ErrTerminalBusy
|
||||
}
|
||||
d.terminalPending = true
|
||||
// The generation is bumped with the pending flag, under the same lock: a
|
||||
// later open can only start once this lease is gone, and it bumps again, so
|
||||
// an older generation can never match a newer owner's lease.
|
||||
d.terminalGen++
|
||||
gen := d.terminalGen
|
||||
mainConn := d.conn
|
||||
h.mu.Unlock()
|
||||
|
||||
if h.sender == nil {
|
||||
// Roll back so a retry isn't permanently blocked.
|
||||
// Roll back so a retry isn't permanently blocked. The generation stays
|
||||
// bumped; it is only an identity, not a resource.
|
||||
h.mu.Lock()
|
||||
d.terminalPending = false
|
||||
h.mu.Unlock()
|
||||
return ErrNoSender
|
||||
return 0, ErrNoSender
|
||||
}
|
||||
if err := h.sender(mainConn, []byte{protocol.CommandShell}); err != nil {
|
||||
h.mu.Lock()
|
||||
d.terminalPending = false
|
||||
h.mu.Unlock()
|
||||
return err
|
||||
return 0, err
|
||||
}
|
||||
return nil
|
||||
return gen, nil
|
||||
}
|
||||
|
||||
// IsTerminalPending tells the TCP layer whether the next-arriving shell
|
||||
@@ -798,6 +837,16 @@ func (h *Hub) IsTerminalPending(deviceID string) bool {
|
||||
return ok && d.terminalPending
|
||||
}
|
||||
|
||||
// HasTerminalSession reports whether the device currently has a pending or
|
||||
// active shell lease. MCP uses it to tell a genuine terminal close from a
|
||||
// stale one that raced a fresh open (see mcp.sessionTable.closed).
|
||||
func (h *Hub) HasTerminalSession(deviceID string) bool {
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
d, ok := h.devices[deviceID]
|
||||
return ok && (d.terminalConn != nil || d.terminalPending)
|
||||
}
|
||||
|
||||
// BindTerminalConn promotes the pending session to an active one by
|
||||
// associating the device's freshly-arrived shell sub-conn. Returns false
|
||||
// if no pending session exists — callers should drop the orphan ctx.
|
||||
@@ -909,20 +958,29 @@ func (h *Hub) TerminalIsPTY(id string) bool {
|
||||
// send COMMAND_BYE, then close after a short grace period so the client's
|
||||
// IOCPClient reconnect logic doesn't fire.
|
||||
func (h *Hub) CloseTerminalSession(deviceID string) {
|
||||
h.closeTerminalPinned(deviceID, nil)
|
||||
h.closeTerminalPinned(deviceID, nil, 0)
|
||||
}
|
||||
|
||||
// CloseTerminalSessionLease tears down the session only if its lease
|
||||
// generation still matches gen. False means the lease was already gone (or was
|
||||
// renewed by another open) and nothing was touched.
|
||||
func (h *Hub) CloseTerminalSessionLease(deviceID string, gen uint64) bool {
|
||||
return h.closeTerminalPinned(deviceID, nil, gen)
|
||||
}
|
||||
|
||||
// CloseTerminalSessionPinned is CloseTerminalSession restricted to a device
|
||||
// still pinned to main; see CloseScreenPinned for why the disconnect path
|
||||
// needs the ownership check.
|
||||
func (h *Hub) CloseTerminalSessionPinned(deviceID string, main *connection.Context) bool {
|
||||
return h.closeTerminalPinned(deviceID, main)
|
||||
return h.closeTerminalPinned(deviceID, main, 0)
|
||||
}
|
||||
|
||||
func (h *Hub) closeTerminalPinned(deviceID string, main *connection.Context) bool {
|
||||
// closeTerminalPinned tears down the session. gen==0 closes whatever lease the
|
||||
// device holds; a non-zero gen closes only that lease.
|
||||
func (h *Hub) closeTerminalPinned(deviceID string, main *connection.Context, gen uint64) bool {
|
||||
h.mu.Lock()
|
||||
d, ok := h.devices[deviceID]
|
||||
if !ok || (main != nil && d.conn != main) {
|
||||
if !ok || (main != nil && d.conn != main) || (gen != 0 && d.terminalGen != gen) {
|
||||
h.mu.Unlock()
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -188,3 +188,38 @@ func TestRegisterDoesNotCarryPendingTerminal(t *testing.T) {
|
||||
t.Fatalf("retry after re-register: %v, want nil", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A lease generation is an ownership proof: a stale opener whose pending
|
||||
// request a re-login dropped cannot close the lease someone else acquired
|
||||
// afterwards, while the current owner can still close its own.
|
||||
func TestCloseTerminalSessionLeaseIgnoresRenewedLease(t *testing.T) {
|
||||
h := New()
|
||||
h.SetSender(func(ctx *connection.Context, data []byte) error { return nil })
|
||||
h.Register(&Device{ID: "dev", PeerIP: "10.0.0.1"},
|
||||
&connection.Context{RemoteAddr: "10.0.0.1:1000"})
|
||||
|
||||
stale, err := h.OpenTerminalSessionLease("dev")
|
||||
if err != nil {
|
||||
t.Fatalf("first open: %v", err)
|
||||
}
|
||||
// Re-login drops the pending request without an OnTerminalClosed event.
|
||||
h.Register(&Device{ID: "dev", PeerIP: "10.0.0.1"},
|
||||
&connection.Context{RemoteAddr: "10.0.0.1:1002"})
|
||||
|
||||
current, err := h.OpenTerminalSessionLease("dev")
|
||||
if err != nil {
|
||||
t.Fatalf("second open: %v", err)
|
||||
}
|
||||
if h.CloseTerminalSessionLease("dev", stale) {
|
||||
t.Fatal("a stale generation closed the renewed lease")
|
||||
}
|
||||
if !h.HasTerminalSession("dev") {
|
||||
t.Fatal("renewed lease was torn down by the stale close")
|
||||
}
|
||||
if !h.CloseTerminalSessionLease("dev", current) {
|
||||
t.Fatal("the owning generation could not close its lease")
|
||||
}
|
||||
if h.HasTerminalSession("dev") {
|
||||
t.Fatal("lease still held after the owner closed it")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// auditArgsMaxBytes bounds the argument digest written to the audit file. The
|
||||
// full payload never goes there: commands can contain passwords and request
|
||||
// bodies can be large.
|
||||
const auditArgsMaxBytes = 512
|
||||
|
||||
// auditCall writes one mcp.tool.call record per tools/call, matching the Win32
|
||||
// server's fields (design §4.4). actor/role/source distinguish it from browser
|
||||
// sessions, which audit as the logged-in username.
|
||||
func (s *Server) auditCall(tool, deviceID string, args json.RawMessage, result any, rerr *rpcError, elapsed time.Duration) {
|
||||
fields := map[string]any{
|
||||
"actor": "mcp",
|
||||
"role": "admin",
|
||||
"source": "mcp",
|
||||
"tool": tool,
|
||||
"device": "-",
|
||||
"ok": rerr == nil,
|
||||
"code": 0,
|
||||
"ms": elapsed.Milliseconds(),
|
||||
"args": summarizeArgs(args),
|
||||
}
|
||||
if deviceID != "" {
|
||||
fields["device"] = deviceID
|
||||
}
|
||||
if rerr != nil {
|
||||
fields["code"] = rerr.Code
|
||||
fields["result"] = rerr.Message
|
||||
} else {
|
||||
fields["result"] = resultSize(result)
|
||||
}
|
||||
s.log.Audit("mcp.tool.call", fields)
|
||||
}
|
||||
|
||||
// redactedArgKeys name top-level arguments whose value is user content or a
|
||||
// credential. They are replaced by their size so the audit trail records that
|
||||
// something was sent, without copying it: terminal commands, chat text, HTTP
|
||||
// bodies and headers routinely carry passwords.
|
||||
var redactedArgKeys = map[string]bool{
|
||||
"text": true,
|
||||
"message": true,
|
||||
"body": true,
|
||||
"headers": true,
|
||||
"password": true,
|
||||
"token": true,
|
||||
}
|
||||
|
||||
// summarizeArgs renders a compact, truncated argument digest. A "command"
|
||||
// value is reduced to its first word and length so terminal passwords never
|
||||
// reach the audit file; other sensitive values are replaced by their size. The
|
||||
// full payload stays out of the audit file entirely.
|
||||
func summarizeArgs(raw json.RawMessage) string {
|
||||
if len(raw) == 0 || string(raw) == "null" {
|
||||
return "{}"
|
||||
}
|
||||
var obj map[string]any
|
||||
if err := json.Unmarshal(raw, &obj); err != nil {
|
||||
return fmt.Sprintf("<unparsed %d bytes>", len(raw))
|
||||
}
|
||||
for key, value := range obj {
|
||||
if key == "command" {
|
||||
if command, ok := value.(string); ok {
|
||||
obj[key] = commandDigest(command)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if redactedArgKeys[key] {
|
||||
obj[key] = redactedDigest(value)
|
||||
}
|
||||
}
|
||||
b, err := json.Marshal(obj)
|
||||
if err != nil {
|
||||
return "{}"
|
||||
}
|
||||
return truncateUTF8(string(b), auditArgsMaxBytes)
|
||||
}
|
||||
|
||||
// redactedDigest replaces a sensitive value with its serialized size. The
|
||||
// marker avoids angle brackets so encoding/json does not escape it.
|
||||
func redactedDigest(value any) string {
|
||||
b, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return "redacted"
|
||||
}
|
||||
return fmt.Sprintf("redacted(%d bytes)", len(b))
|
||||
}
|
||||
|
||||
func commandDigest(command string) string {
|
||||
first := command
|
||||
if i := strings.IndexAny(command, " \t"); i >= 0 {
|
||||
first = command[:i]
|
||||
}
|
||||
return fmt.Sprintf("%s (len=%d)", first, len(command))
|
||||
}
|
||||
|
||||
func resultSize(result any) string {
|
||||
b, err := json.Marshal(result)
|
||||
if err != nil {
|
||||
return "?"
|
||||
}
|
||||
return fmt.Sprintf("%d bytes", len(b))
|
||||
}
|
||||
|
||||
// truncateUTF8 cuts s to at most max bytes, including the ellipsis, without
|
||||
// splitting a rune.
|
||||
func truncateUTF8(s string, max int) string {
|
||||
if len(s) <= max {
|
||||
return s
|
||||
}
|
||||
cut := max - len("…")
|
||||
for cut > 0 && !utf8.RuneStart(s[cut]) {
|
||||
cut--
|
||||
}
|
||||
return s[:cut] + "…"
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
package mcp
|
||||
|
||||
import "strings"
|
||||
|
||||
// Terminal output cleaning, ported byte-for-byte from the Win32 server
|
||||
// (server/2015Remote/McpServer.cpp:3875-4060). The stage order is load-bearing
|
||||
// — ConPTY is a screen-rendering stream, not a byte stream, so echoed input,
|
||||
// ANSI repaints and sentinel remnants all interact. clean_test.go locks the
|
||||
// behaviour against samples captured from the MFC implementation; do not
|
||||
// "simplify" the matchers.
|
||||
//
|
||||
// MFC's CleanTerminalOutput runs: StripAnsi → CRLF normalize → StripEchoedInput
|
||||
// (which itself ends with StripSentinelText) → TrimRight. We keep that order.
|
||||
|
||||
// stripAnsi drops CSI/OSC and other single-byte ESC sequences so terminal
|
||||
// colour codes never reach the model.
|
||||
func stripAnsi(s string) string {
|
||||
var b strings.Builder
|
||||
b.Grow(len(s))
|
||||
for i := 0; i < len(s); i++ {
|
||||
if s[i] != 0x1b {
|
||||
b.WriteByte(s[i])
|
||||
continue
|
||||
}
|
||||
i++ // swallow ESC
|
||||
if i < len(s) && s[i] == '[' { // CSI ... ends at @..~
|
||||
i++
|
||||
for i < len(s) && !(s[i] >= '@' && s[i] <= '~') {
|
||||
i++
|
||||
}
|
||||
} else if i < len(s) && s[i] == ']' { // OSC ... ends at BEL or ST
|
||||
i++
|
||||
for i < len(s) && s[i] != 0x07 && s[i] != 0x1b {
|
||||
i++
|
||||
}
|
||||
// ST is the two-byte sequence ESC '\'; consume both.
|
||||
if i+1 < len(s) && s[i] == 0x1b && s[i+1] == '\\' {
|
||||
i++
|
||||
}
|
||||
}
|
||||
// Any other one-byte ESC sequence: the byte after ESC is swallowed by
|
||||
// the loop increment.
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// stripEchoedLine removes the first occurrence of line, ignoring CR/LF inside
|
||||
// the match because ConPTY wraps a long echo at 80 columns. The echoed line's
|
||||
// trailing newlines are removed with it.
|
||||
func stripEchoedLine(s, line string) string {
|
||||
if line == "" || s == "" {
|
||||
return s
|
||||
}
|
||||
for i := 0; i < len(s); i++ {
|
||||
j, k := 0, i
|
||||
for j < len(line) && k < len(s) {
|
||||
c := s[k]
|
||||
if c == '\r' || c == '\n' {
|
||||
k++
|
||||
continue
|
||||
}
|
||||
if c != line[j] {
|
||||
break
|
||||
}
|
||||
j++
|
||||
k++
|
||||
}
|
||||
if j != len(line) {
|
||||
continue
|
||||
}
|
||||
for k < len(s) && (s[k] == '\r' || s[k] == '\n') {
|
||||
k++
|
||||
}
|
||||
return s[:i] + s[k:]
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// cutThroughEchoedLine deletes everything up to and including the echoed input
|
||||
// line. ConPTY replays the boot screen and prompt just before our input echo,
|
||||
// so the echo marks where real output starts. ok=false means the client did
|
||||
// not echo; the caller then falls back to stripEchoedLine.
|
||||
func cutThroughEchoedLine(s, line string) (string, bool) {
|
||||
if line == "" || s == "" {
|
||||
return s, false
|
||||
}
|
||||
for i := 0; i < len(s); i++ {
|
||||
j, k := 0, i
|
||||
for j < len(line) && k < len(s) {
|
||||
c := s[k]
|
||||
if c == '\r' || c == '\n' {
|
||||
k++
|
||||
continue
|
||||
}
|
||||
if c != line[j] {
|
||||
break
|
||||
}
|
||||
j++
|
||||
k++
|
||||
}
|
||||
if j != len(line) {
|
||||
continue
|
||||
}
|
||||
for k < len(s) && (s[k] == '\r' || s[k] == '\n') {
|
||||
k++
|
||||
}
|
||||
return s[k:], true
|
||||
}
|
||||
return s, false
|
||||
}
|
||||
|
||||
// trimLeadingNewlines drops the blank lines left by the boot screen or the
|
||||
// previous command's trailing newline.
|
||||
func trimLeadingNewlines(s string) string {
|
||||
i := 0
|
||||
for i < len(s) && (s[i] == '\r' || s[i] == '\n') {
|
||||
i++
|
||||
}
|
||||
return s[i:]
|
||||
}
|
||||
|
||||
// stripSentinelText erases sentinel remnants that a ConPTY repaint duplicated
|
||||
// into the output (e.g. `cmd /c echo abc` renders as "abc__MCP_DONE_x__0").
|
||||
// The nonce is random per command, so real output cannot contain the marker;
|
||||
// matching skips CR/LF (wrapped echoes) and also eats a trailing
|
||||
// "%errorlevel%" echo template. A preceding "echo " is removed with it.
|
||||
func stripSentinelText(s, nonce string) string {
|
||||
if nonce == "" || s == "" {
|
||||
return s
|
||||
}
|
||||
marker := "__MCP_DONE_" + nonce + "__"
|
||||
i := 0
|
||||
for i < len(s) {
|
||||
j, k := 0, i
|
||||
for j < len(marker) && k < len(s) {
|
||||
c := s[k]
|
||||
if c == '\r' || c == '\n' {
|
||||
k++
|
||||
continue
|
||||
}
|
||||
if c != marker[j] {
|
||||
break
|
||||
}
|
||||
j++
|
||||
k++
|
||||
}
|
||||
if j != len(marker) {
|
||||
i++
|
||||
continue
|
||||
}
|
||||
end := k
|
||||
if end < len(s) && s[end] == '-' {
|
||||
end++
|
||||
}
|
||||
for end < len(s) && s[end] >= '0' && s[end] <= '9' {
|
||||
end++
|
||||
}
|
||||
if end < len(s) && s[end] == '%' { // echoed template ...__%errorlevel%
|
||||
for end < len(s) && s[end] != '\r' && s[end] != '\n' {
|
||||
end++
|
||||
}
|
||||
}
|
||||
begin := i // also remove a stray "echo " left in front of it
|
||||
if begin >= 5 && strings.EqualFold(s[begin-5:begin], "echo ") {
|
||||
begin -= 5
|
||||
}
|
||||
s = s[:begin] + s[end:]
|
||||
i = begin
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// stripEchoedInput removes the PTY's echo of the command line and sentinel
|
||||
// line. Non-PTY sessions only remove the sentinel line: the legacy shell
|
||||
// manager skips the echo by written length, so deleting the command echo could
|
||||
// eat real output (e.g. `echo echo hello`).
|
||||
func stripEchoedInput(s string, isPTY bool, cmdLine, sentLine, nonce string) string {
|
||||
out := s
|
||||
cut := false
|
||||
if isPTY {
|
||||
out, cut = cutThroughEchoedLine(out, cmdLine)
|
||||
}
|
||||
if isPTY && !cut {
|
||||
out = stripEchoedLine(out, cmdLine)
|
||||
}
|
||||
out = stripEchoedLine(out, sentLine)
|
||||
out = stripSentinelText(out, nonce)
|
||||
return trimLeadingNewlines(out)
|
||||
}
|
||||
|
||||
// buildSentinelLines builds the command line and sentinel line for one
|
||||
// platform. PTY platforms send them as two lines so line-swallowing commands
|
||||
// (rem / cmd / exit / if / for) cannot eat the sentinel; the legacy non-PTY
|
||||
// path keeps the single-line &&/|| form.
|
||||
func buildSentinelLines(isPTY, posix bool, command, nonce string) (cmdLine, sentLine string) {
|
||||
if posix {
|
||||
return command, "echo __MCP_DONE_" + nonce + "__$?"
|
||||
}
|
||||
if !isPTY {
|
||||
return command + " 2>&1 && echo __MCP_DONE_" + nonce + "__0 || echo __MCP_DONE_" + nonce + "__1", ""
|
||||
}
|
||||
return "@echo off & " + command, "echo __MCP_DONE_" + nonce + "__%errorlevel%"
|
||||
}
|
||||
|
||||
// buildTerminalWire assembles what goes to the shell. POSIX shells print PS1
|
||||
// on every read, which would pollute stdout, so it is cleared first; that
|
||||
// line's echo is cut together with the boot noise.
|
||||
func buildTerminalWire(posix bool, cmdLine, sentLine string) []byte {
|
||||
var b strings.Builder
|
||||
if posix {
|
||||
b.WriteString("PS1=\r\n")
|
||||
}
|
||||
b.WriteString(cmdLine)
|
||||
b.WriteString("\r\n")
|
||||
if sentLine != "" {
|
||||
b.WriteString(sentLine)
|
||||
b.WriteString("\r\n")
|
||||
}
|
||||
return []byte(b.String())
|
||||
}
|
||||
|
||||
// containsControlChar reports a byte < 0x20, including CR/LF. A newline would
|
||||
// split the command into extra lines, only the last of which carries the
|
||||
// sentinel, so the exit code would be wrong.
|
||||
func containsControlChar(s string) bool {
|
||||
for i := 0; i < len(s); i++ {
|
||||
if s[i] < 0x20 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// hasPosixBackgroundAmpersand reports an unquoted, unescaped '&' that is not
|
||||
// part of &&, &> or >&. A background command's output and exit code cannot be
|
||||
// attributed to the sentinel, so it is refused.
|
||||
func hasPosixBackgroundAmpersand(s string) bool {
|
||||
var inSingle, inDouble, esc bool
|
||||
for i := 0; i < len(s); i++ {
|
||||
c := s[i]
|
||||
if esc {
|
||||
esc = false
|
||||
continue
|
||||
}
|
||||
if c == '\\' && !inSingle {
|
||||
esc = true
|
||||
continue
|
||||
}
|
||||
if inSingle {
|
||||
if c == '\'' {
|
||||
inSingle = false
|
||||
}
|
||||
continue
|
||||
}
|
||||
if inDouble {
|
||||
if c == '"' {
|
||||
inDouble = false
|
||||
}
|
||||
continue
|
||||
}
|
||||
if c == '\'' {
|
||||
inSingle = true
|
||||
continue
|
||||
}
|
||||
if c == '"' {
|
||||
inDouble = true
|
||||
continue
|
||||
}
|
||||
if c != '&' {
|
||||
continue
|
||||
}
|
||||
if i+1 < len(s) && (s[i+1] == '&' || s[i+1] == '>') {
|
||||
i++
|
||||
continue
|
||||
}
|
||||
if i > 0 && s[i-1] == '>' { // 2>&1 / >&2
|
||||
continue
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// normalizeCRLF drops the '\r' of every CRLF pair, as MFC does.
|
||||
func normalizeCRLF(s string) string {
|
||||
if !strings.Contains(s, "\r\n") {
|
||||
return s
|
||||
}
|
||||
var b strings.Builder
|
||||
b.Grow(len(s))
|
||||
for i := 0; i < len(s); i++ {
|
||||
if s[i] == '\r' && i+1 < len(s) && s[i+1] == '\n' {
|
||||
continue
|
||||
}
|
||||
b.WriteByte(s[i])
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// cleanTerminalOutput is one delivery window's worth of cleaning. first is
|
||||
// true only for the command-issuing call's first window (echo exists only
|
||||
// there); trimTrailing stays false for a partial window so the next window's
|
||||
// first line does not get glued onto this one.
|
||||
func cleanTerminalOutput(raw []byte, isPTY, first bool, cmdLine, sentLine, nonce string, trimTrailing bool) string {
|
||||
if len(raw) == 0 {
|
||||
return ""
|
||||
}
|
||||
s := stripAnsi(string(raw))
|
||||
s = normalizeCRLF(s)
|
||||
if first {
|
||||
s = stripEchoedInput(s, isPTY, cmdLine, sentLine, nonce)
|
||||
} else {
|
||||
s = stripSentinelText(s, nonce)
|
||||
s = trimLeadingNewlines(s)
|
||||
}
|
||||
if trimTrailing {
|
||||
s = strings.TrimRight(s, " \t\r\n")
|
||||
}
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestStripAnsi(t *testing.T) {
|
||||
cases := []struct{ in, want string }{
|
||||
{"plain", "plain"},
|
||||
{"\x1b[31mred\x1b[0m text", "red text"},
|
||||
{"a\x1b[?25hb", "ab"},
|
||||
{"\x1b]0;title\x07after", "after"},
|
||||
{"\x1b]0;title\x1b\\after", "after"},
|
||||
{"\x1b]8;;http://x\x07link\x1b]8;;\x07", "link"},
|
||||
{"\x1b(Bcharset", "Bcharset"}, // ESC ( is a two-byte sequence; only '(' is swallowed
|
||||
{"\x1b", ""},
|
||||
{"tail\x1b[", "tail"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := stripAnsi(tc.in); got != tc.want {
|
||||
t.Errorf("stripAnsi(%q) = %q, want %q", tc.in, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildSentinelLines(t *testing.T) {
|
||||
const cmd, nonce = "echo hi", "ab12cd34"
|
||||
var cmdLine, sentLine string
|
||||
|
||||
cmdLine, sentLine = buildSentinelLines(true, true, cmd, nonce)
|
||||
if cmdLine != cmd || sentLine != "echo __MCP_DONE_ab12cd34__$?" {
|
||||
t.Fatalf("posix: %q / %q", cmdLine, sentLine)
|
||||
}
|
||||
wire := string(buildTerminalWire(true, cmdLine, sentLine))
|
||||
if want := "PS1=\r\necho hi\r\necho __MCP_DONE_ab12cd34__$?\r\n"; wire != want {
|
||||
t.Fatalf("posix wire = %q, want %q", wire, want)
|
||||
}
|
||||
|
||||
cmdLine, sentLine = buildSentinelLines(true, false, cmd, nonce)
|
||||
if cmdLine != "@echo off & echo hi" || sentLine != "echo __MCP_DONE_ab12cd34__%errorlevel%" {
|
||||
t.Fatalf("conpty: %q / %q", cmdLine, sentLine)
|
||||
}
|
||||
if wire := string(buildTerminalWire(false, cmdLine, sentLine)); !strings.HasPrefix(wire, "@echo off & echo hi\r\necho ") {
|
||||
t.Fatalf("conpty wire = %q", wire)
|
||||
}
|
||||
|
||||
cmdLine, sentLine = buildSentinelLines(false, false, cmd, nonce)
|
||||
if cmdLine != "echo hi 2>&1 && echo __MCP_DONE_ab12cd34__0 || echo __MCP_DONE_ab12cd34__1" || sentLine != "" {
|
||||
t.Fatalf("legacy: %q / %q", cmdLine, sentLine)
|
||||
}
|
||||
}
|
||||
|
||||
// Samples follow the ConPTY repaint behaviour documented in
|
||||
// McpServer.cpp:3946-3989: the boot prompt and echoed input precede the real
|
||||
// output, and a repaint can glue the sentinel onto the last output line.
|
||||
func TestStripEchoedInputWindows(t *testing.T) {
|
||||
const nonce = "ab12cd34"
|
||||
cmdLine, sentLine := buildSentinelLines(true, false, "rem hello", nonce)
|
||||
got := cleanTerminalOutput([]byte(
|
||||
"\x1b[?25l@echo off & rem hello\r\n\r\n__MCP_DONE_ab12cd34__%errorlevel%\r\n__MCP_DONE_ab12cd34__0\r\n"),
|
||||
true, true, cmdLine, sentLine, nonce, true)
|
||||
if got != "" {
|
||||
t.Fatalf("rem hello output = %q, want empty", got)
|
||||
}
|
||||
|
||||
cmdLine, sentLine = buildSentinelLines(true, false, "cmd /c echo abc", nonce)
|
||||
got = cleanTerminalOutput([]byte(
|
||||
"@echo off & cmd /c echo abc\r\nabc__MCP_DONE_ab12cd34__0\r\n"),
|
||||
true, true, cmdLine, sentLine, nonce, true)
|
||||
if got != "abc" {
|
||||
t.Fatalf("cmd /c echo abc output = %q, want %q", got, "abc")
|
||||
}
|
||||
|
||||
cmdLine, sentLine = buildSentinelLines(true, false, "type .env", nonce)
|
||||
got = cleanTerminalOutput([]byte(
|
||||
"@echo off & type .env\r\nKEY=value\r\nSECOND=line\r\n__MCP_DONE_ab12cd34__1\r\n"),
|
||||
true, true, cmdLine, sentLine, nonce, true)
|
||||
if got != "KEY=value\nSECOND=line" {
|
||||
t.Fatalf("type .env output = %q", got)
|
||||
}
|
||||
|
||||
// A long command line is wrapped at 80 columns by ConPTY; the echo matcher
|
||||
// skips the inserted newlines. "cmd /\c" is a literal path, not an escape.
|
||||
long := "cmd /c " + strings.Repeat("x", 100)
|
||||
cmdLine, sentLine = buildSentinelLines(true, false, long, nonce)
|
||||
wrapped := "@echo off & cmd /c " + strings.Repeat("x", 60) + "\r\n" + strings.Repeat("x", 40) +
|
||||
"\r\nwrapped-ok\r\n__MCP_DONE_ab12cd34__0\r\n"
|
||||
got = cleanTerminalOutput([]byte(wrapped), true, true, cmdLine, sentLine, nonce, true)
|
||||
if got != "wrapped-ok" {
|
||||
t.Fatalf("wrapped echo output = %q, want %q", got, "wrapped-ok")
|
||||
}
|
||||
}
|
||||
|
||||
// The legacy non-PTY shell skips the echo by written length, so the command
|
||||
// echo must not be removed (it could be real output, e.g. `echo echo hello`).
|
||||
func TestCleanNonPTYKeepsCommandEcho(t *testing.T) {
|
||||
const nonce = "ab12cd34"
|
||||
cmdLine, sentLine := buildSentinelLines(false, false, "echo echo hello", nonce)
|
||||
raw := []byte("echo echo hello\r\nhello\r\n__MCP_DONE_ab12cd34__0\r\n")
|
||||
got := cleanTerminalOutput(raw, false, true, cmdLine, sentLine, nonce, true)
|
||||
if got != "echo echo hello\nhello" {
|
||||
t.Fatalf("non-PTY output = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanTerminalOutputTrimOnlyOnFinalChunk(t *testing.T) {
|
||||
const nonce = "ab12cd34"
|
||||
if got := cleanTerminalOutput([]byte("LINE-17\r\n"), true, false, "", "", nonce, false); got != "LINE-17\n" {
|
||||
t.Fatalf("partial window = %q, want trailing newline kept", got)
|
||||
}
|
||||
if got := cleanTerminalOutput([]byte("LINE-17\r\n"), true, false, "", "", nonce, true); got != "LINE-17" {
|
||||
t.Fatalf("final window = %q, want trimmed", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStripSentinelTextEchoTemplate(t *testing.T) {
|
||||
got := stripSentinelText("before\necho __MCP_DONE_ab12cd34__%errorlevel%\nafter\n", "ab12cd34")
|
||||
// The template line's own newline stays: stripEchoedLine removes the
|
||||
// echoed sentinel line first in the real pipeline; this is the fallback.
|
||||
if got != "before\n\nafter\n" {
|
||||
t.Fatalf("template removal = %q", got)
|
||||
}
|
||||
// A negative exit code (%errorlevel% of a crashed process) is removed too.
|
||||
got = stripSentinelText("out\n__MCP_DONE_ab12cd34__-1073741510\n", "ab12cd34")
|
||||
if got != "out\n" {
|
||||
t.Fatalf("negative removal = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestContainsControlChar(t *testing.T) {
|
||||
for _, s := range []string{"a\nb", "a\rb", "a\tb", "\x01"} {
|
||||
if !containsControlChar(s) {
|
||||
t.Errorf("containsControlChar(%q) = false", s)
|
||||
}
|
||||
}
|
||||
for _, s := range []string{"", "echo ok", "中文", "a|b&&c"} {
|
||||
if containsControlChar(s) {
|
||||
t.Errorf("containsControlChar(%q) = true", s)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHasPosixBackgroundAmpersand(t *testing.T) {
|
||||
cases := []struct {
|
||||
in string
|
||||
want bool
|
||||
}{
|
||||
{"sleep 1 &", true},
|
||||
{"echo a & echo b", true},
|
||||
{"a && b", false},
|
||||
{"a &> /dev/null", false},
|
||||
{"a 2>&1", false},
|
||||
{"echo 'a & b'", false},
|
||||
{`echo a\&b`, false},
|
||||
{`echo "a & b"`, false},
|
||||
{"grep -v '^#' /etc/hosts", false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := hasPosixBackgroundAmpersand(tc.in); got != tc.want {
|
||||
t.Errorf("hasPosixBackgroundAmpersand(%q) = %v, want %v", tc.in, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeCRLF(t *testing.T) {
|
||||
if got := normalizeCRLF("a\r\nb\rc"); got != "a\nb\rc" {
|
||||
t.Fatalf("normalizeCRLF = %q", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package mcp
|
||||
|
||||
import "fmt"
|
||||
|
||||
// JSON-RPC 2.0 error codes used by the MCP endpoint. The -320xx range mirrors
|
||||
// the Win32 server (McpServer.cpp:296-312) so a model sees the same numbers
|
||||
// regardless of which backend it talks to; reusing them matters more than
|
||||
// inventing Go-specific ones.
|
||||
const (
|
||||
CodeInternal = -32000 // unexpected server-side failure
|
||||
CodeTimeout = -32001 // sub-connection or device reply did not arrive
|
||||
CodeOffline = -32002 // host unknown or offline
|
||||
CodeBusy = -32003 // per-device lock / terminal slot occupied
|
||||
CodeSendFailed = -32004 // command could not be delivered to the host
|
||||
CodeUnsupported = -32005 // host lacks the required capability
|
||||
CodeDenied = -32006 // policy refusal (readonly mode, disabled tool)
|
||||
CodeNotFound = -32009 // target file/directory does not exist
|
||||
CodePermission = -32010 // target rejected the operation (access denied)
|
||||
CodeParseError = -32700 // invalid JSON
|
||||
CodeInvalidRequest = -32600 // not a valid JSON-RPC request
|
||||
CodeMethodNotFound = -32601 // unknown method or tool name
|
||||
CodeInvalidParams = -32602 // schema/argument validation failed
|
||||
)
|
||||
|
||||
// rpcError is the JSON-RPC "error" object. It is returned as a Go error from
|
||||
// tool handlers, which lets call sites use plain returns instead of carrying
|
||||
// a response object through every layer.
|
||||
type rpcError struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
Data any `json:"data,omitempty"`
|
||||
}
|
||||
|
||||
func (e *rpcError) Error() string {
|
||||
return fmt.Sprintf("mcp error %d: %s", e.Code, e.Message)
|
||||
}
|
||||
|
||||
// errf builds an rpcError with a formatted message.
|
||||
func errf(code int, format string, args ...any) *rpcError {
|
||||
return &rpcError{Code: code, Message: fmt.Sprintf(format, args...)}
|
||||
}
|
||||
@@ -0,0 +1,768 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/connection"
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/protocol"
|
||||
)
|
||||
|
||||
// list_files drives the client's file-manager sub-connection (design §5.3).
|
||||
// With ids it fans out one call per host under a shared deadline, matching the
|
||||
// Win32 batch contract (see listFilesBatch):
|
||||
//
|
||||
// main conn : COMMAND_LIST_DRIVE(1)
|
||||
// └─ client opens a sub-conn, sends TOKEN_CONN_AUTH then
|
||||
// TOKEN_DRIVE_LIST(103) — the sub-conn stays open
|
||||
// that sub : COMMAND_LIST_FILES(2) [path\0]
|
||||
// └─ TOKEN_FILE_LIST(104) or TOKEN_FILE_LIST_ERROR(171)
|
||||
// then the server closes the sub-conn (COMMAND_BYE + 500 ms)
|
||||
//
|
||||
// The sub-conn carries ConnAuth, so handleConnAuth has already pinned the
|
||||
// device's ClientID on its ctx and no pending-connection bookkeeping is needed
|
||||
// (design §5.3); the pending request is keyed by device and remembers which
|
||||
// ctx answered, which is also how late packets from a previous sub-conn are
|
||||
// told apart from the current one.
|
||||
const (
|
||||
// fileListMaxEntries is the parse cap shared with the Win32 server: the
|
||||
// directory is parsed in full and paged afterwards, so total/hasMore stay
|
||||
// true; only a pathological directory is cut here, and structuredContent
|
||||
// then carries truncated=true and the summary says so.
|
||||
fileListMaxEntries = 100000
|
||||
|
||||
// fileRecordFixedLen is attr(1) + size(8) + FILETIME(8).
|
||||
fileRecordFixedLen = 17
|
||||
// driveRecordFixedLen is letter(1) + type(1) + totalMB(4) + freeMB(4).
|
||||
driveRecordFixedLen = 10
|
||||
|
||||
// filetimeEpochDiff converts FILETIME (100 ns ticks since 1601-01-01) to
|
||||
// Unix seconds once divided by filetimeTicksPerSec.
|
||||
filetimeTicksPerSec = 10000000
|
||||
filetimeEpochDiffSec = 11644473600
|
||||
errorAccessDenied = 5
|
||||
errorFileNotFound = 2
|
||||
errorPathNotFound = 3
|
||||
|
||||
// listFilesBatchMaxIDs is the ids[] cap, matching the Win32 batch wrapper.
|
||||
listFilesBatchMaxIDs = 50
|
||||
)
|
||||
|
||||
// listFilesBatchDeadline bounds one ids[] call: every host must be answered
|
||||
// before it, and hosts not attempted afterwards are reported as skipped. A
|
||||
// variable only so tests can shorten it.
|
||||
var listFilesBatchDeadline = 50 * time.Second
|
||||
|
||||
// fileListTimeout bounds one list_files round trip, including the sub-conn
|
||||
// handshake. A variable only so tests can shorten it.
|
||||
var fileListTimeout = 10 * time.Second
|
||||
|
||||
// fileRetireDelay is how long the sub-conn stays open after COMMAND_BYE, so the
|
||||
// client's read loop sees the goodbye before FIN (the hub uses the same 500 ms
|
||||
// for screen sub-conns).
|
||||
var fileRetireDelay = 500 * time.Millisecond
|
||||
|
||||
// fileEventKind distinguishes the three packets a list_files call can receive.
|
||||
type fileEventKind byte
|
||||
|
||||
const (
|
||||
fileEventDriveList fileEventKind = iota + 1 // TOKEN_DRIVE_LIST
|
||||
fileEventFileList // TOKEN_FILE_LIST
|
||||
fileEventError // TOKEN_FILE_LIST_ERROR
|
||||
)
|
||||
|
||||
// fileEvent is one packet handed from the TCP read loop to the waiting call.
|
||||
// ctx identifies the sub-conn it arrived on; payload bytes are copied because
|
||||
// the read buffer is not ours to keep.
|
||||
type fileEvent struct {
|
||||
kind fileEventKind
|
||||
ctx *connection.Context
|
||||
payload []byte // drive records or file records (token byte removed)
|
||||
win32err uint32 // fileEventError only
|
||||
}
|
||||
|
||||
// fileRequest is one in-flight list_files call. ch is buffered so the read loop
|
||||
// never blocks; sub records which sub-conn answered the drive-list phase and
|
||||
// rejects packets from any other connection for the same device. abandoned is
|
||||
// set by cancel so a packet that loses the race with the call's own return is
|
||||
// not queued into a channel nobody reads.
|
||||
type fileRequest struct {
|
||||
ch chan fileEvent
|
||||
|
||||
mu sync.Mutex
|
||||
sub *connection.Context
|
||||
abandoned bool
|
||||
}
|
||||
|
||||
func (r *fileRequest) subConn() *connection.Context {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
return r.sub
|
||||
}
|
||||
|
||||
// fileTable holds the single pending list_files per device. The per-device
|
||||
// call lock already serialises tools, so more than one entry cannot normally
|
||||
// exist; the table rejects it anyway rather than mis-routing replies.
|
||||
type fileTable struct {
|
||||
mu sync.Mutex
|
||||
byDevice map[string]*fileRequest
|
||||
}
|
||||
|
||||
func newFileTable() *fileTable {
|
||||
return &fileTable{byDevice: make(map[string]*fileRequest)}
|
||||
}
|
||||
|
||||
func (t *fileTable) begin(deviceID string) (*fileRequest, bool) {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
if _, ok := t.byDevice[deviceID]; ok {
|
||||
return nil, false
|
||||
}
|
||||
r := &fileRequest{ch: make(chan fileEvent, 2)}
|
||||
t.byDevice[deviceID] = r
|
||||
return r, true
|
||||
}
|
||||
|
||||
// cancel ends the request and returns the sub-conn it learned about, if any.
|
||||
// The caller retires that sub-conn: this is the single retirement point, so a
|
||||
// call that gives up while its drive-list packet is already queued (the timer
|
||||
// and the channel being ready at the same time, or the MCP request cancelled)
|
||||
// still closes the client's file-manager thread instead of leaking it.
|
||||
func (t *fileTable) cancel(deviceID string, r *fileRequest) *connection.Context {
|
||||
t.mu.Lock()
|
||||
if t.byDevice[deviceID] == r {
|
||||
delete(t.byDevice, deviceID)
|
||||
}
|
||||
t.mu.Unlock()
|
||||
|
||||
r.mu.Lock()
|
||||
r.abandoned = true
|
||||
sub := r.sub
|
||||
r.mu.Unlock()
|
||||
return sub
|
||||
}
|
||||
|
||||
// deliver routes one event to the pending call. It reports whether the event
|
||||
// was accepted; a packet from a connection other than the one that answered
|
||||
// the drive-list phase is a late packet from an earlier sub-conn and must be
|
||||
// ignored (the client sends a legacy one-byte TOKEN_FILE_LIST right after
|
||||
// TOKEN_FILE_LIST_ERROR, and back-to-back calls can overlap with it).
|
||||
func (t *fileTable) deliver(deviceID string, ev fileEvent) bool {
|
||||
t.mu.Lock()
|
||||
r := t.byDevice[deviceID]
|
||||
t.mu.Unlock()
|
||||
if r == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
r.mu.Lock()
|
||||
if r.abandoned {
|
||||
// The call already returned; let OnFilePacket treat the packet as an
|
||||
// orphan (a drive list) instead of queueing it for nobody.
|
||||
r.mu.Unlock()
|
||||
return false
|
||||
}
|
||||
switch ev.kind {
|
||||
case fileEventDriveList:
|
||||
if r.sub != nil && r.sub != ev.ctx {
|
||||
r.mu.Unlock()
|
||||
return false
|
||||
}
|
||||
if r.sub == nil {
|
||||
r.sub = ev.ctx
|
||||
}
|
||||
case fileEventError:
|
||||
// No client answers COMMAND_LIST_DRIVE with an error, but if one ever
|
||||
// does, adopt the connection and let the call translate the code
|
||||
// instead of dropping the packet and timing out.
|
||||
if r.sub == nil {
|
||||
r.sub = ev.ctx
|
||||
}
|
||||
if r.sub != ev.ctx {
|
||||
r.mu.Unlock()
|
||||
return false
|
||||
}
|
||||
default:
|
||||
if r.sub != ev.ctx {
|
||||
r.mu.Unlock()
|
||||
return false
|
||||
}
|
||||
}
|
||||
r.mu.Unlock()
|
||||
|
||||
select {
|
||||
case r.ch <- ev:
|
||||
default:
|
||||
// The current phase already has an event queued; a duplicate is only
|
||||
// noise (the legacy empty TOKEN_FILE_LIST after an error packet).
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Server) registerFileTools() {
|
||||
s.handlers["list_files"] = s.callListFiles
|
||||
s.handlers["read_file"] = s.callReadFile
|
||||
}
|
||||
|
||||
// OnFilePacket feeds one file-manager packet from a sub-connection to the
|
||||
// pending list_files call. It reports whether the packet belongs to this
|
||||
// protocol at all; cmd/main.go forwards only the three file-manager tokens.
|
||||
func (s *Server) OnFilePacket(ctx *connection.Context, data []byte) bool {
|
||||
if s == nil || len(data) == 0 {
|
||||
return false
|
||||
}
|
||||
switch data[0] {
|
||||
case protocol.TokenDriveList, protocol.TokenFileList, protocol.TokenFileListError:
|
||||
default:
|
||||
return false
|
||||
}
|
||||
deviceID := ctx.GetInfo().ClientID
|
||||
if deviceID == "" {
|
||||
return true
|
||||
}
|
||||
if s.cfg.Hub != nil {
|
||||
if main := s.cfg.Hub.MainConn(deviceID); main == ctx {
|
||||
// File-manager packets only ever arrive on the dedicated sub-conn;
|
||||
// a token that looks like one on the main connection is not ours.
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
ev := fileEvent{ctx: ctx}
|
||||
switch data[0] {
|
||||
case protocol.TokenDriveList:
|
||||
ev.kind = fileEventDriveList
|
||||
ev.payload = append([]byte(nil), data[1:]...)
|
||||
case protocol.TokenFileList:
|
||||
ev.kind = fileEventFileList
|
||||
ev.payload = append([]byte(nil), data[1:]...)
|
||||
case protocol.TokenFileListError:
|
||||
ev.kind = fileEventError
|
||||
if len(data) >= 5 {
|
||||
ev.win32err = binary.LittleEndian.Uint32(data[1:5])
|
||||
}
|
||||
}
|
||||
|
||||
if s.files.deliver(deviceID, ev) {
|
||||
return true
|
||||
}
|
||||
// Nothing is waiting for this sub-conn: the call it belonged to already
|
||||
// timed out or finished. Retire it so the client does not leak its
|
||||
// file-manager thread, but only once the sub-conn has announced itself.
|
||||
// A live read_file keeps its file-manager sub-conn registered in the
|
||||
// transfer table (POSIX clients stream on it), so never close that one.
|
||||
if ev.kind == fileEventDriveList && !s.transfers.owns(ctx) {
|
||||
s.retireFileConn(ctx)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// retireFileConn closes a file-manager sub-conn the way the hub retires screen
|
||||
// sub-conns: COMMAND_BYE so the client's IOCP loop exits through its clean
|
||||
// path, then a delayed Close so the goodbye is not overtaken by FIN.
|
||||
func (s *Server) retireFileConn(ctx *connection.Context) {
|
||||
if ctx == nil {
|
||||
return
|
||||
}
|
||||
if s.cfg.Hub != nil {
|
||||
_ = s.cfg.Hub.SendToConn(ctx, []byte{protocol.CommandBye})
|
||||
}
|
||||
// Read the delay before spawning: tests shorten it between calls.
|
||||
delay := fileRetireDelay
|
||||
go func(c *connection.Context) {
|
||||
time.Sleep(delay)
|
||||
_ = c.Close()
|
||||
}(ctx)
|
||||
}
|
||||
|
||||
// ----- get_screenshot-style argument / result shapes -------------------------
|
||||
|
||||
// listFilesArgs is the published inputSchema as Go. ids selects the batch path;
|
||||
// path/limit/offset then apply to every host.
|
||||
type listFilesArgs struct {
|
||||
ID string `json:"id"`
|
||||
IDs []string `json:"ids"`
|
||||
Path string `json:"path"`
|
||||
Limit int `json:"limit"`
|
||||
Offset int `json:"offset"`
|
||||
}
|
||||
|
||||
type driveEntry struct {
|
||||
Drive string `json:"drive"`
|
||||
Type uint64 `json:"type"`
|
||||
TypeName string `json:"typeName"`
|
||||
FileSystem string `json:"fileSystem"`
|
||||
TotalMB uint64 `json:"totalMB"`
|
||||
FreeMB uint64 `json:"freeMB"`
|
||||
}
|
||||
|
||||
type fileEntry struct {
|
||||
Name string `json:"name"`
|
||||
IsDir bool `json:"isDir"`
|
||||
Size uint64 `json:"size"`
|
||||
Mtime int64 `json:"mtime"`
|
||||
}
|
||||
|
||||
// openFileManagerConn asks the device for its file-manager sub-connection
|
||||
// (COMMAND_LIST_DRIVE on the main connection) and waits for the drive list.
|
||||
// On success it returns the sub-connection, the still-pending request (later
|
||||
// packets are matched against it) and the parsed drives; the caller owns both
|
||||
// and must call closeFileManagerConn when done. Every failure path retires the
|
||||
// sub-connection here, so a timed-out or rejected handshake leaves no orphan
|
||||
// file-manager thread on the client.
|
||||
func (s *Server) openFileManagerConn(ctx context.Context, deviceID string) (*connection.Context, *fileRequest, []driveEntry, *rpcError) {
|
||||
req, ok := s.files.begin(deviceID)
|
||||
if !ok {
|
||||
return nil, nil, nil, errf(CodeBusy, "Device busy: another file request is already pending for host %s", deviceID)
|
||||
}
|
||||
keep := false
|
||||
defer func() {
|
||||
if !keep {
|
||||
if sub := s.files.cancel(deviceID, req); sub != nil {
|
||||
s.retireFileConn(sub)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
if err := s.cfg.Hub.SendToDevice(deviceID, []byte{protocol.CommandListDrive}); err != nil {
|
||||
if errors.Is(err, hub.ErrDeviceOffline) {
|
||||
return nil, nil, nil, errf(CodeOffline, "Host not found or offline: %s", deviceID)
|
||||
}
|
||||
return nil, nil, nil, errf(CodeSendFailed, "Failed to ask the host for its file-manager channel: %v", err)
|
||||
}
|
||||
|
||||
timer := time.NewTimer(fileListTimeout)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case ev := <-req.ch:
|
||||
switch ev.kind {
|
||||
case fileEventDriveList:
|
||||
keep = true
|
||||
return ev.ctx, req, parseDriveList(ev.payload), nil
|
||||
case fileEventError:
|
||||
return nil, nil, nil, errf(win32ErrorCode(ev.win32err),
|
||||
"Failed to open the file-manager channel on host %s (win32=%d)", deviceID, ev.win32err)
|
||||
default:
|
||||
return nil, nil, nil, errf(CodeInternal, "Unexpected file-manager reply while listing drives")
|
||||
}
|
||||
case <-timer.C:
|
||||
return nil, nil, nil, errf(CodeTimeout,
|
||||
"Timeout waiting for the host to open a file-manager channel (%s). Older clients that do not implement file browsing stay silent; retrying will not help.",
|
||||
fileListTimeout)
|
||||
case <-ctx.Done():
|
||||
return nil, nil, nil, errf(CodeTimeout, "Request cancelled while waiting for the host's file-manager channel")
|
||||
}
|
||||
}
|
||||
|
||||
// closeFileManagerConn ends the request and retires the sub-connection it
|
||||
// learned about. It is the single retirement point for that sub-conn: the
|
||||
// cancel below also covers a call that gave up while its drive-list packet was
|
||||
// already queued (the select taking the timer branch with both ready).
|
||||
func (s *Server) closeFileManagerConn(deviceID string, req *fileRequest) {
|
||||
if sub := s.files.cancel(deviceID, req); sub != nil {
|
||||
s.retireFileConn(sub)
|
||||
}
|
||||
}
|
||||
|
||||
// callListFiles lists drives (no path) or one directory level. With ids it
|
||||
// answers the batch before any per-host work.
|
||||
func (s *Server) callListFiles(ctx context.Context, raw json.RawMessage) (any, *rpcError) {
|
||||
if s.cfg.Hub == nil {
|
||||
return nil, errf(CodeInternal, "server device registry is not configured")
|
||||
}
|
||||
var args listFilesArgs
|
||||
if rerr := decodeArgs(raw, &args); rerr != nil {
|
||||
return nil, rerr
|
||||
}
|
||||
// ids 出现即走批量,空数组也算:Win32 的 isMember("ids") && isArray 同样接受,
|
||||
// 返回 total=0;只看 len>0 会把一个 schema 合法的空批量误报成缺少 id。
|
||||
if batchIDsPresent(raw) {
|
||||
if args.ID != "" {
|
||||
return nil, errf(CodeInvalidParams, "Pass either id or ids, not both")
|
||||
}
|
||||
return s.listFilesBatch(ctx, args)
|
||||
}
|
||||
if args.ID == "" {
|
||||
return nil, errf(CodeInvalidParams, "Missing required parameter: id")
|
||||
}
|
||||
res, rerr := s.listFilesOne(ctx, args)
|
||||
if rerr != nil {
|
||||
return nil, rerr
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// batchIDsPresent reports whether the call spelled ids[] at all. It looks at
|
||||
// the raw JSON because an empty array decodes to the same empty slice as a
|
||||
// missing one, yet the two mean different things (empty batch vs. no target).
|
||||
func batchIDsPresent(raw json.RawMessage) bool {
|
||||
var probe struct {
|
||||
IDs json.RawMessage `json:"ids"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &probe); err != nil || len(probe.IDs) == 0 {
|
||||
return false
|
||||
}
|
||||
return string(probe.IDs) != "null"
|
||||
}
|
||||
|
||||
// listFilesBatch answers list_files with ids[] by calling listFilesOne once per
|
||||
// host, matching the Win32 batch contract: at most 50 hosts, and ids not
|
||||
// attempted after the 50 s deadline are reported as skipped (not as failures).
|
||||
// The deadline only gates starting a host: one already running gets its own
|
||||
// per-host timeout and its result is recorded normally, exactly like Win32.
|
||||
// Results keep the input order.
|
||||
func (s *Server) listFilesBatch(ctx context.Context, args listFilesArgs) (any, *rpcError) {
|
||||
if len(args.IDs) > listFilesBatchMaxIDs {
|
||||
return nil, errf(CodeInvalidParams,
|
||||
"Too many ids: %d (max %d per batch)", len(args.IDs), listFilesBatchMaxIDs)
|
||||
}
|
||||
deadline := time.Now().Add(listFilesBatchDeadline)
|
||||
results := make([]map[string]any, 0, len(args.IDs))
|
||||
failLines := make([]string, 0, len(args.IDs))
|
||||
succeeded, failed, skipped := 0, 0, 0
|
||||
for _, id := range args.IDs {
|
||||
if !isDecimalID(id) {
|
||||
msg := "Invalid id: expected a decimal host id string"
|
||||
results = append(results, batchListError(id, CodeInvalidParams, msg))
|
||||
failLines = append(failLines, id+": "+msg)
|
||||
failed++
|
||||
continue
|
||||
}
|
||||
if !time.Now().Before(deadline) {
|
||||
entry := batchListError(id, CodeTimeout,
|
||||
fmt.Sprintf("Batch deadline exceeded (%s): not attempted", listFilesBatchDeadline))
|
||||
entry["skipped"] = true
|
||||
results = append(results, entry)
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
one := args
|
||||
one.ID = id
|
||||
one.IDs = nil
|
||||
// Win32's batch calls the same per-host entry as a single-host call, so
|
||||
// an entry loses to an operation already in flight on that host
|
||||
// (-32003) instead of running beside it. listFilesOne cannot take the
|
||||
// lock itself: the single-host path already holds it (callTool).
|
||||
if held, acquired := s.locks.tryAcquire(id, "list_files"); !acquired {
|
||||
msg := busyMessage(held)
|
||||
results = append(results, batchListError(id, CodeBusy, msg))
|
||||
failLines = append(failLines, id+": "+msg)
|
||||
failed++
|
||||
continue
|
||||
}
|
||||
res, rerr := func() (toolResult, *rpcError) {
|
||||
defer s.locks.release(id)
|
||||
return s.listFilesOne(ctx, one)
|
||||
}()
|
||||
if rerr != nil {
|
||||
results = append(results, batchListError(id, rerr.Code, rerr.Message))
|
||||
failLines = append(failLines, id+": "+rerr.Message)
|
||||
failed++
|
||||
continue
|
||||
}
|
||||
entry := map[string]any{"id": id, "ok": true, "data": res.StructuredContent}
|
||||
if len(res.Content) > 0 {
|
||||
entry["text"] = res.Content[0].Text
|
||||
}
|
||||
results = append(results, entry)
|
||||
succeeded++
|
||||
}
|
||||
|
||||
structured := map[string]any{
|
||||
"tool": "list_files",
|
||||
"total": len(args.IDs),
|
||||
"succeeded": succeeded,
|
||||
"failed": failed,
|
||||
"skipped": skipped,
|
||||
"results": results,
|
||||
}
|
||||
text := fmt.Sprintf("批量调用 list_files:共 %d 台,成功 %d 台,失败 %d 台", len(args.IDs), succeeded, failed)
|
||||
if skipped > 0 {
|
||||
text += fmt.Sprintf(",超时跳过 %d 台", skipped)
|
||||
}
|
||||
text += "。"
|
||||
for _, line := range failLines {
|
||||
text += "\n - " + line
|
||||
}
|
||||
return newToolResult(text, structured), nil
|
||||
}
|
||||
|
||||
// batchListError is one failed batch entry in the shape the outputSchema
|
||||
// declares: id, ok=false, error{code,message} and the message as text.
|
||||
func batchListError(id string, code int, msg string) map[string]any {
|
||||
return map[string]any{
|
||||
"id": id,
|
||||
"ok": false,
|
||||
"text": msg,
|
||||
"error": map[string]any{"code": code, "message": msg},
|
||||
}
|
||||
}
|
||||
|
||||
// listFilesOne lists drives or one directory of a single host.
|
||||
func (s *Server) listFilesOne(ctx context.Context, args listFilesArgs) (toolResult, *rpcError) {
|
||||
if !isDecimalID(args.ID) {
|
||||
return toolResult{}, errf(CodeInvalidParams, "Invalid id: expected a decimal host id string")
|
||||
}
|
||||
// NUL and newlines would truncate or split the client's C string field.
|
||||
if strings.ContainsAny(args.Path, "\x00\r\n") {
|
||||
return toolResult{}, errf(CodeInvalidParams, "Invalid path: NUL and line breaks are not allowed")
|
||||
}
|
||||
if s.cfg.Hub.MainConn(args.ID) == nil {
|
||||
return toolResult{}, errf(CodeOffline, "Host not found or offline: %s", args.ID)
|
||||
}
|
||||
|
||||
path := args.Path
|
||||
// The published contract (tools.json) is: no path lists drives, any path
|
||||
// lists that directory. MFC also folds "." and "/" into the drive list,
|
||||
// but that makes a POSIX root listing unreachable, so this server follows
|
||||
// the documented rule instead.
|
||||
listDrives := path == ""
|
||||
pathGBK := protocol.UTF8ToGBK(path)
|
||||
if len(pathGBK) >= 250 {
|
||||
// The client copies the path into a MAX_PATH buffer and appends "\\*.*".
|
||||
return toolResult{}, errf(CodeInvalidParams,
|
||||
"Path too long: %d bytes after conversion to the client's GBK encoding (limit 249)", len(pathGBK))
|
||||
}
|
||||
|
||||
sub, req, drives, rerr := s.openFileManagerConn(ctx, args.ID)
|
||||
if rerr != nil {
|
||||
return toolResult{}, rerr
|
||||
}
|
||||
defer s.closeFileManagerConn(args.ID, req)
|
||||
|
||||
if listDrives {
|
||||
return listFilesResult(args, drives, nil, false), nil
|
||||
}
|
||||
|
||||
// Phase 2: reuse the same sub-conn for the directory itself.
|
||||
pkt := make([]byte, 0, 2+len(pathGBK))
|
||||
pkt = append(pkt, protocol.CommandListFiles)
|
||||
pkt = append(pkt, pathGBK...)
|
||||
pkt = append(pkt, 0)
|
||||
if err := s.cfg.Hub.SendToConn(sub, pkt); err != nil {
|
||||
return toolResult{}, errf(CodeSendFailed, "Failed to send the directory request on the file-manager channel: %v", err)
|
||||
}
|
||||
|
||||
timer := time.NewTimer(fileListTimeout)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case ev := <-req.ch:
|
||||
switch ev.kind {
|
||||
case fileEventFileList:
|
||||
files, truncated := parseFileList(ev.payload)
|
||||
return listFilesResult(args, nil, files, truncated), nil
|
||||
case fileEventError:
|
||||
return toolResult{}, fileWin32Error(ev.win32err, path)
|
||||
default:
|
||||
return toolResult{}, errf(CodeInternal, "Unexpected file-manager reply while listing a directory")
|
||||
}
|
||||
case <-timer.C:
|
||||
return toolResult{}, errf(CodeTimeout,
|
||||
"Timeout waiting for the directory listing of %q (%s). If the path does not exist, an older client stays silent instead of reporting an error — list the parent directory first.",
|
||||
path, fileListTimeout)
|
||||
case <-ctx.Done():
|
||||
return toolResult{}, errf(CodeTimeout, "Request cancelled while waiting for the directory listing")
|
||||
}
|
||||
}
|
||||
|
||||
// win32ErrorCode maps a client-reported Win32 error onto an MCP code the same
|
||||
// way the Win32 server does: 5 is a permission problem, 2/3 mean "no such
|
||||
// target", everything else is an internal failure carrying the raw code.
|
||||
func win32ErrorCode(win32err uint32) int {
|
||||
switch win32err {
|
||||
case errorAccessDenied:
|
||||
return CodePermission
|
||||
case errorFileNotFound, errorPathNotFound:
|
||||
return CodeNotFound
|
||||
default:
|
||||
return CodeInternal
|
||||
}
|
||||
}
|
||||
|
||||
// fileWin32Error maps the client's win32 error onto MCP codes the same way the
|
||||
// Win32 server does: 5 is a permission problem, 2/3 mean "no such target",
|
||||
// everything else is an internal failure carrying the raw code.
|
||||
func fileWin32Error(win32err uint32, path string) *rpcError {
|
||||
subject := fmt.Sprintf("Failed to list %q", path)
|
||||
switch win32err {
|
||||
case errorAccessDenied:
|
||||
return errf(CodePermission, "%s: access denied (win32=%d)", subject, win32err)
|
||||
case errorFileNotFound, errorPathNotFound:
|
||||
return errf(CodeNotFound, "%s: target not found (win32=%d)", subject, win32err)
|
||||
default:
|
||||
return errf(CodeInternal, "%s: the host reported a failure (win32=%d)", subject, win32err)
|
||||
}
|
||||
}
|
||||
|
||||
// parseDriveList decodes [letter][type][totalMB:4 LE][freeMB:4 LE][typeName\0][fs\0]
|
||||
// records until a zero letter (the client's end marker) or a truncated record.
|
||||
// Names are GBK on the wire for every platform.
|
||||
func parseDriveList(p []byte) []driveEntry {
|
||||
out := make([]driveEntry, 0, 8)
|
||||
off := 0
|
||||
for off+driveRecordFixedLen <= len(p) && p[off] != 0 {
|
||||
letter := p[off]
|
||||
dtype := uint64(p[off+1])
|
||||
total := uint64(binary.LittleEndian.Uint32(p[off+2:]))
|
||||
free := uint64(binary.LittleEndian.Uint32(p[off+6:]))
|
||||
off += driveRecordFixedLen
|
||||
|
||||
typeName, n, ok := cString(p[off:])
|
||||
if !ok {
|
||||
break
|
||||
}
|
||||
off += n + 1
|
||||
fs, n, ok := cString(p[off:])
|
||||
if !ok {
|
||||
break
|
||||
}
|
||||
off += n + 1
|
||||
|
||||
// Windows letters become "C:\". The POSIX clients report '/' as their
|
||||
// single root "drive"; return it as "/" so it can be passed straight
|
||||
// back as a path (MFC renders "/:\", which also works after the
|
||||
// client's path conversion, but "/" is the friendlier form).
|
||||
drive := string(letter) + ":\\"
|
||||
if letter == '/' {
|
||||
drive = "/"
|
||||
}
|
||||
out = append(out, driveEntry{
|
||||
Drive: drive,
|
||||
Type: dtype,
|
||||
TypeName: protocol.GbkToUTF8(typeName),
|
||||
FileSystem: protocol.GbkToUTF8(fs),
|
||||
TotalMB: total,
|
||||
FreeMB: free,
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// parseFileList decodes [attr][name\0][sizeHi:4][sizeLo:4][ftLo:4][ftHi:4]
|
||||
// records. An empty name is the client's trailing zero padding; reaching the
|
||||
// entry cap stops the parse and reports truncation.
|
||||
func parseFileList(p []byte) ([]fileEntry, bool) {
|
||||
out := make([]fileEntry, 0, 64)
|
||||
off := 0
|
||||
for off < len(p) {
|
||||
attr := p[off]
|
||||
off++
|
||||
name, n, ok := cString(p[off:])
|
||||
if !ok || n == 0 {
|
||||
break
|
||||
}
|
||||
// Cap check after a real record is seen: trailing zero padding (an empty
|
||||
// name) must not report truncation when the listing is exactly at the cap.
|
||||
if len(out) >= fileListMaxEntries {
|
||||
return out, true
|
||||
}
|
||||
off += n + 1
|
||||
if off+fileRecordFixedLen-1 > len(p) {
|
||||
break
|
||||
}
|
||||
sizeHigh := uint64(binary.LittleEndian.Uint32(p[off:]))
|
||||
sizeLow := uint64(binary.LittleEndian.Uint32(p[off+4:]))
|
||||
ftLow := uint64(binary.LittleEndian.Uint32(p[off+8:]))
|
||||
ftHigh := uint64(binary.LittleEndian.Uint32(p[off+12:]))
|
||||
off += 16
|
||||
|
||||
ft := ftHigh<<32 | ftLow
|
||||
var mtime int64
|
||||
if ft != 0 {
|
||||
mtime = int64(ft/filetimeTicksPerSec) - filetimeEpochDiffSec
|
||||
if mtime < 0 {
|
||||
mtime = 0
|
||||
}
|
||||
}
|
||||
out = append(out, fileEntry{
|
||||
Name: protocol.GbkToUTF8(name),
|
||||
IsDir: attr&0x10 != 0,
|
||||
Size: sizeHigh<<32 | sizeLow,
|
||||
Mtime: mtime,
|
||||
})
|
||||
}
|
||||
return out, false
|
||||
}
|
||||
|
||||
// cString returns the NUL-terminated field at the start of p. ok is false when
|
||||
// p runs out before the terminator (a truncated packet).
|
||||
func cString(p []byte) (name []byte, n int, ok bool) {
|
||||
for i, b := range p {
|
||||
if b == 0 {
|
||||
return p[:i], i, true
|
||||
}
|
||||
}
|
||||
return nil, 0, false
|
||||
}
|
||||
|
||||
// listFilesResult applies the limit/offset window and builds the MCP envelope.
|
||||
// Only one of drives/files is non-nil; total/totalAll/hasMore describe the
|
||||
// full listing, not the returned page. truncated reports that the directory
|
||||
// held more entries than the parse cap, so the model is not told "that is all
|
||||
// there is".
|
||||
func listFilesResult(args listFilesArgs, drives []driveEntry, files []fileEntry, truncated bool) toolResult {
|
||||
limit := clampPageLimit(args.Limit)
|
||||
offset := max(args.Offset, 0)
|
||||
|
||||
var structured map[string]any
|
||||
var text string
|
||||
var header []string
|
||||
var rows [][]string
|
||||
if drives != nil {
|
||||
total := len(drives)
|
||||
begin := min(offset, total)
|
||||
end := min(begin+limit, total)
|
||||
structured = map[string]any{
|
||||
"drives": drives[begin:end],
|
||||
"total": total,
|
||||
"totalAll": total,
|
||||
"limit": limit,
|
||||
"offset": offset,
|
||||
"hasMore": end < total,
|
||||
}
|
||||
text = pageSummary(total, limit, offset, "个驱动器")
|
||||
header = []string{"drive", "typeName", "fileSystem", "totalMB", "freeMB"}
|
||||
rows = make([][]string, 0, end-begin)
|
||||
for _, d := range drives[begin:end] {
|
||||
rows = append(rows, []string{
|
||||
d.Drive, d.TypeName, d.FileSystem,
|
||||
strconv.FormatUint(d.TotalMB, 10), strconv.FormatUint(d.FreeMB, 10),
|
||||
})
|
||||
}
|
||||
} else {
|
||||
total := len(files)
|
||||
begin := min(offset, total)
|
||||
end := min(begin+limit, total)
|
||||
structured = map[string]any{
|
||||
"files": files[begin:end],
|
||||
"total": total,
|
||||
"totalAll": total,
|
||||
"limit": limit,
|
||||
"offset": offset,
|
||||
"hasMore": end < total,
|
||||
"truncated": truncated,
|
||||
}
|
||||
text = pageSummary(total, limit, offset, "个条目")
|
||||
header = []string{"name", "isDir", "size", "mtime"}
|
||||
rows = make([][]string, 0, end-begin)
|
||||
for _, f := range files[begin:end] {
|
||||
rows = append(rows, []string{
|
||||
f.Name, strconv.FormatBool(f.IsDir),
|
||||
strconv.FormatUint(f.Size, 10), strconv.FormatInt(f.Mtime, 10),
|
||||
})
|
||||
}
|
||||
}
|
||||
if truncated {
|
||||
text += fmt.Sprintf("目录条目超过 %d 条,total 只是上限内的数量,请缩小目录范围。", fileListMaxEntries)
|
||||
}
|
||||
text = appendRows(text, header, rows)
|
||||
return newToolResult(text, structured)
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,628 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/connection"
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/protocol"
|
||||
)
|
||||
|
||||
// shortenTransferTimeouts makes the read_file watchdogs test-sized. The poll
|
||||
// interval stays well under the stall window so the stalled check is reached
|
||||
// deterministically.
|
||||
func shortenTransferTimeouts(t *testing.T, stall, total, poll time.Duration) {
|
||||
t.Helper()
|
||||
oldStall, oldTotal, oldPoll := fileTransferStallTimeout, fileTransferTotalTimeout, fileTransferPollInterval
|
||||
fileTransferStallTimeout, fileTransferTotalTimeout, fileTransferPollInterval = stall, total, poll
|
||||
t.Cleanup(func() {
|
||||
fileTransferStallTimeout, fileTransferTotalTimeout, fileTransferPollInterval = oldStall, oldTotal, oldPoll
|
||||
})
|
||||
}
|
||||
|
||||
// ----- wire builders ---------------------------------------------------------
|
||||
|
||||
func chunkPacket(transferID uint64, fileIndex, totalFiles uint32, fileSize, offset uint64,
|
||||
flags uint16, name string, payload []byte) []byte {
|
||||
nameGBK := protocol.UTF8ToGBK(name)
|
||||
buf := make([]byte, fileChunkHeaderLen+len(nameGBK)+len(payload))
|
||||
buf[0] = protocol.CommandSendFileV2
|
||||
binary.LittleEndian.PutUint64(buf[fileChunkOffTransferID:], transferID)
|
||||
binary.LittleEndian.PutUint32(buf[fileChunkOffFileIndex:], fileIndex)
|
||||
binary.LittleEndian.PutUint32(buf[fileChunkOffTotalFiles:], totalFiles)
|
||||
binary.LittleEndian.PutUint64(buf[fileChunkOffFileSize:], fileSize)
|
||||
binary.LittleEndian.PutUint64(buf[fileChunkOffOffset:], offset)
|
||||
binary.LittleEndian.PutUint64(buf[fileChunkOffDataLength:], uint64(len(payload)))
|
||||
binary.LittleEndian.PutUint64(buf[fileChunkOffNameLength:], uint64(len(nameGBK)))
|
||||
binary.LittleEndian.PutUint16(buf[fileChunkOffFlags:], flags)
|
||||
copy(buf[fileChunkHeaderLen:], nameGBK)
|
||||
copy(buf[fileChunkHeaderLen+len(nameGBK):], payload)
|
||||
return buf
|
||||
}
|
||||
|
||||
func completePacket(transferID uint64, fileIndex uint32, fileSize uint64, sum []byte) []byte {
|
||||
buf := make([]byte, fileCompleteHeaderLen)
|
||||
buf[0] = protocol.CommandFileCompleteV2
|
||||
binary.LittleEndian.PutUint64(buf[fileCompleteOffTransferID:], transferID)
|
||||
binary.LittleEndian.PutUint32(buf[fileCompleteOffFileIndex:], fileIndex)
|
||||
binary.LittleEndian.PutUint64(buf[fileCompleteOffFileSize:], fileSize)
|
||||
copy(buf[fileCompleteOffSHA256:], sum)
|
||||
return buf
|
||||
}
|
||||
|
||||
func downloadErrorPacket(win32err uint32) []byte {
|
||||
buf := make([]byte, 5)
|
||||
buf[0] = protocol.TokenDownloadError
|
||||
binary.LittleEndian.PutUint32(buf[1:], win32err)
|
||||
return buf
|
||||
}
|
||||
|
||||
// ----- harness ---------------------------------------------------------------
|
||||
|
||||
func (r *fileRig) callRead(args string) <-chan fileCall {
|
||||
ch := make(chan fileCall, 1)
|
||||
go func() {
|
||||
res, rerr := r.s.callReadFile(context.Background(), []byte(args))
|
||||
if rerr != nil {
|
||||
ch <- fileCall{err: rerr}
|
||||
return
|
||||
}
|
||||
tr, ok := res.(toolResult)
|
||||
if !ok {
|
||||
ch <- fileCall{err: errf(CodeInternal, "unexpected result type %T", res)}
|
||||
return
|
||||
}
|
||||
ch <- fileCall{res: tr}
|
||||
}()
|
||||
return ch
|
||||
}
|
||||
|
||||
// startReadCall runs one read_file call through the drive-list handshake and
|
||||
// returns the waiting call, the file-manager sub-conn, and the target directory
|
||||
// the server asked the client to write under (which is what real clients echo
|
||||
// back as the packet name prefix).
|
||||
func (r *fileRig) startReadCall(args string, drives ...driveRec) (<-chan fileCall, *connection.Context, string) {
|
||||
r.t.Helper()
|
||||
ch := r.callRead(args)
|
||||
if got := r.next(r.main); len(got) != 1 || got[0] != protocol.CommandListDrive {
|
||||
r.t.Fatalf("drive request wire = %v, want [%d]", got, protocol.CommandListDrive)
|
||||
}
|
||||
sub := r.newSub()
|
||||
if drives == nil {
|
||||
drives = []driveRec{{'C', 3, 500000, 123456, "本地磁盘", "NTFS"}}
|
||||
}
|
||||
if !r.s.OnFilePacket(sub, driveListPacket(drives...)) {
|
||||
r.t.Fatal("drive-list packet was not consumed")
|
||||
}
|
||||
got := r.next(sub)
|
||||
if got[0] != protocol.CmdDownFilesV2 {
|
||||
r.t.Fatalf("download request wire = %v, want token %d first", got, protocol.CmdDownFilesV2)
|
||||
}
|
||||
rest := got[1:]
|
||||
i := strings.IndexByte(string(rest), 0)
|
||||
if i < 0 {
|
||||
r.t.Fatal("download request has no NUL after targetDir")
|
||||
}
|
||||
targetDir := string(rest[:i])
|
||||
if !strings.HasSuffix(targetDir, string(os.PathSeparator)) {
|
||||
r.t.Fatalf("targetDir %q does not end with a path separator", targetDir)
|
||||
}
|
||||
return ch, sub, targetDir
|
||||
}
|
||||
|
||||
// readOutput pulls the structured output out of a successful call.
|
||||
func readOutput(t *testing.T, c fileCall) readFileOutput {
|
||||
t.Helper()
|
||||
if c.err != nil {
|
||||
t.Fatalf("read_file failed: %d %s", c.err.Code, c.err.Message)
|
||||
}
|
||||
out, ok := c.res.StructuredContent.(readFileOutput)
|
||||
if !ok {
|
||||
t.Fatalf("structured content type = %T", c.res.StructuredContent)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ----- name validation -------------------------------------------------------
|
||||
|
||||
func TestTransferNameWithinDir(t *testing.T) {
|
||||
const sep = `\`
|
||||
target := "C:" + sep + "Users" + sep + "tmp" + sep + "yama-mcp-read-1" + sep
|
||||
cases := []struct {
|
||||
name string
|
||||
want string // "" means rejected
|
||||
}{
|
||||
{target + "file.txt", "file.txt"},
|
||||
{target + `sub\file.txt`, "sub/file.txt"},
|
||||
{target + "a//b.txt", "a/b.txt"},
|
||||
{"../x", ""},
|
||||
{`..\..\x`, ""},
|
||||
{`C:\Windows\x`, ""},
|
||||
{"/etc/passwd", ""},
|
||||
{`\\server\share\x`, ""},
|
||||
{`a/../../b`, ""},
|
||||
{target + `sub\..\..\..\x`, ""},
|
||||
{target, ""},
|
||||
{"", ""},
|
||||
{"x\x00y", ""},
|
||||
{"x\ny", ""},
|
||||
}
|
||||
for _, c := range cases {
|
||||
got, ok := transferNameWithinDir(target, c.name)
|
||||
if c.want == "" {
|
||||
if ok {
|
||||
t.Errorf("transferNameWithinDir(%q) = %q, want rejection", c.name, got)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if !ok || got != c.want {
|
||||
t.Errorf("transferNameWithinDir(%q) = %q,%v, want %q", c.name, got, ok, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ----- end-to-end transfers --------------------------------------------------
|
||||
|
||||
func TestReadFileWindowsStreamSubConn(t *testing.T) {
|
||||
shortenTransferTimeouts(t, time.Second, 5*time.Second, 5*time.Millisecond)
|
||||
rig := newFileRig(t)
|
||||
ch, fm, targetDir := rig.startReadCall(`{"id":"1001","path":"C:\\cfg\\app.ini"}`)
|
||||
|
||||
content := []byte("line1\r\nline2\r\nline3\r\n")
|
||||
split := 8
|
||||
stream := rig.newSub() // Windows clients open a fresh authenticated sub-conn
|
||||
name := targetDir + "app.ini"
|
||||
rig.s.OnTransferPacket(stream, chunkPacket(42, 0, 1, uint64(len(content)), 0, 0, name, content[:split]))
|
||||
rig.s.OnTransferPacket(stream, chunkPacket(42, 0, 1, uint64(len(content)), uint64(split), ffV2LastChunk, name, content[split:]))
|
||||
sum := sha256.Sum256(content)
|
||||
rig.s.OnTransferPacket(stream, completePacket(42, 0, uint64(len(content)), sum[:]))
|
||||
|
||||
out := readOutput(t, rig.wait(ch))
|
||||
if out.Size != len(content) || out.Text != "line1\nline2\nline3" {
|
||||
t.Fatalf("text = %q size=%d", out.Text, out.Size)
|
||||
}
|
||||
if out.Encoding != "utf-8" || out.EOL != "crlf" {
|
||||
t.Fatalf("encoding=%q eol=%q", out.Encoding, out.EOL)
|
||||
}
|
||||
if out.LinesTotal != 3 || out.LinesReturned != 3 || out.Truncated {
|
||||
t.Fatalf("lines_total=%d lines_returned=%d truncated=%v", out.LinesTotal, out.LinesReturned, out.Truncated)
|
||||
}
|
||||
if want := hex.EncodeToString(sum[:]); out.SHA256 != want {
|
||||
t.Fatalf("sha256 = %q, want %q", out.SHA256, want)
|
||||
}
|
||||
if !strings.Contains(out.Path, "app.ini") {
|
||||
t.Fatalf("path = %q", out.Path)
|
||||
}
|
||||
// The file-manager sub-conn is retired once the call returns.
|
||||
waitClosed(t, fm)
|
||||
}
|
||||
|
||||
func TestReadFilePosixChunksOnFileManagerConn(t *testing.T) {
|
||||
shortenTransferTimeouts(t, time.Second, 5*time.Second, 5*time.Millisecond)
|
||||
rig := newFileRig(t)
|
||||
ch, fm, targetDir := rig.startReadCall(`{"id":"1001","path":"/etc/app.conf"}`,
|
||||
driveRec{'/', 4, 100000, 1000, "Linux", "ext4"})
|
||||
|
||||
content := []byte("a=1\nb=2\n")
|
||||
name := targetDir + "app.conf"
|
||||
rig.s.OnTransferPacket(fm, chunkPacket(7, 0, 1, uint64(len(content)), 0, ffV2LastChunk, name, content))
|
||||
sum := sha256.Sum256(content)
|
||||
rig.s.OnTransferPacket(fm, completePacket(7, 0, uint64(len(content)), sum[:]))
|
||||
|
||||
out := readOutput(t, rig.wait(ch))
|
||||
if out.Text != "a=1\nb=2" || out.EOL != "lf" {
|
||||
t.Fatalf("text=%q eol=%q", out.Text, out.EOL)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadFilePosixRejectsWindowsPath(t *testing.T) {
|
||||
rig := newFileRig(t)
|
||||
ch := rig.callRead(`{"id":"1001","path":"C:\\cfg\\app.ini"}`)
|
||||
if got := rig.next(rig.main); len(got) != 1 || got[0] != protocol.CommandListDrive {
|
||||
t.Fatalf("drive request wire = %v", got)
|
||||
}
|
||||
fm := rig.newSub()
|
||||
if !rig.s.OnFilePacket(fm, driveListPacket(driveRec{'/', 4, 100000, 1000, "Linux", "ext4"})) {
|
||||
t.Fatal("drive-list packet was not consumed")
|
||||
}
|
||||
// The path is checked before anything goes out on the file-manager conn.
|
||||
c := rig.wait(ch)
|
||||
if c.err == nil || c.err.Code != CodeInvalidParams {
|
||||
t.Fatalf("error = %+v, want -32602", c.err)
|
||||
}
|
||||
if !strings.Contains(c.err.Message, "absolute POSIX path") {
|
||||
t.Fatalf("message = %q", c.err.Message)
|
||||
}
|
||||
waitClosed(t, fm)
|
||||
}
|
||||
|
||||
func TestReadFileSizeGate(t *testing.T) {
|
||||
shortenTransferTimeouts(t, time.Second, 5*time.Second, 5*time.Millisecond)
|
||||
rig := newFileRig(t)
|
||||
rig.s.cfg.ReadMax = 4096
|
||||
ch, _, targetDir := rig.startReadCall(`{"id":"1001","path":"C:\\big.bin"}`)
|
||||
|
||||
stream := rig.newSub()
|
||||
rig.s.OnTransferPacket(stream, chunkPacket(1, 0, 1, 5000, 0, 0, targetDir+"big.bin", make([]byte, 100)))
|
||||
c := rig.wait(ch)
|
||||
if c.err == nil || c.err.Code != CodeInvalidParams {
|
||||
t.Fatalf("error = %+v, want -32602", c.err)
|
||||
}
|
||||
if !strings.Contains(c.err.Message, "no download_file") ||
|
||||
!strings.Contains(c.err.Message, "terminal_exec") {
|
||||
t.Fatalf("message = %q", c.err.Message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadFileDirectoryRejected(t *testing.T) {
|
||||
shortenTransferTimeouts(t, time.Second, 5*time.Second, 5*time.Millisecond)
|
||||
rig := newFileRig(t)
|
||||
ch, _, targetDir := rig.startReadCall(`{"id":"1001","path":"C:\\folder"}`)
|
||||
|
||||
stream := rig.newSub()
|
||||
rig.s.OnTransferPacket(stream, chunkPacket(1, 0, 1, 0, 0, ffV2Directory, targetDir+"folder\\", nil))
|
||||
c := rig.wait(ch)
|
||||
if c.err == nil || c.err.Code != CodeInvalidParams {
|
||||
t.Fatalf("error = %+v, want -32602", c.err)
|
||||
}
|
||||
if !strings.Contains(c.err.Message, "Not a single regular file") {
|
||||
t.Fatalf("message = %q", c.err.Message)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReadFileMultiFileBatchRejected pins the expanded-directory case: the
|
||||
// client turns a directory path into a multi-file batch and stamps totalFiles on
|
||||
// every chunk, so the very first chunk must fail the call. Waiting for a second
|
||||
// fileIndex is not enough — file 0's completion packet would end the call and its
|
||||
// content would be returned as if it were the requested path.
|
||||
func TestReadFileMultiFileBatchRejected(t *testing.T) {
|
||||
shortenTransferTimeouts(t, time.Second, 5*time.Second, 5*time.Millisecond)
|
||||
rig := newFileRig(t)
|
||||
ch, _, targetDir := rig.startReadCall(`{"id":"1001","path":"C:\\dir"}`)
|
||||
|
||||
stream := rig.newSub()
|
||||
rig.s.OnTransferPacket(stream, chunkPacket(5, 0, 2, 3, 0, ffV2LastChunk, targetDir+`dir\a.txt`, []byte("aaa")))
|
||||
sum := sha256.Sum256([]byte("aaa"))
|
||||
// Even a matching completion must not rescue a multi-file batch.
|
||||
rig.s.OnTransferPacket(stream, completePacket(5, 0, 3, sum[:]))
|
||||
|
||||
c := rig.wait(ch)
|
||||
if c.err == nil || c.err.Code != CodeInvalidParams {
|
||||
t.Fatalf("error = %+v, want -32602", c.err)
|
||||
}
|
||||
if !strings.Contains(c.err.Message, "single regular file") {
|
||||
t.Fatalf("message = %q", c.err.Message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadFileSecondFileIndexRejected(t *testing.T) {
|
||||
shortenTransferTimeouts(t, time.Second, 5*time.Second, 5*time.Millisecond)
|
||||
rig := newFileRig(t)
|
||||
ch, _, targetDir := rig.startReadCall(`{"id":"1001","path":"C:\\dir"}`)
|
||||
|
||||
stream := rig.newSub()
|
||||
rig.s.OnTransferPacket(stream, chunkPacket(9, 0, 2, 3, 0, 0, targetDir+"a.txt", []byte("abc")))
|
||||
rig.s.OnTransferPacket(stream, chunkPacket(9, 1, 2, 3, 0, 0, targetDir+"b.txt", []byte("xyz")))
|
||||
c := rig.wait(ch)
|
||||
if c.err == nil || c.err.Code != CodeInvalidParams {
|
||||
t.Fatalf("error = %+v, want -32602", c.err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadFileSHA256Mismatch(t *testing.T) {
|
||||
shortenTransferTimeouts(t, time.Second, 5*time.Second, 5*time.Millisecond)
|
||||
rig := newFileRig(t)
|
||||
ch, _, targetDir := rig.startReadCall(`{"id":"1001","path":"C:\\a.txt"}`)
|
||||
|
||||
content := []byte("hello")
|
||||
stream := rig.newSub()
|
||||
rig.s.OnTransferPacket(stream, chunkPacket(3, 0, 1, 5, 0, ffV2LastChunk, targetDir+"a.txt", content))
|
||||
bad := make([]byte, sha256.Size)
|
||||
rig.s.OnTransferPacket(stream, completePacket(3, 0, 5, bad))
|
||||
c := rig.wait(ch)
|
||||
if c.err == nil || c.err.Code != CodeInternal {
|
||||
t.Fatalf("error = %+v, want -32000", c.err)
|
||||
}
|
||||
if !strings.Contains(c.err.Message, "SHA-256") {
|
||||
t.Fatalf("message = %q", c.err.Message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadFileEmptyFile(t *testing.T) {
|
||||
shortenTransferTimeouts(t, time.Second, 5*time.Second, 5*time.Millisecond)
|
||||
rig := newFileRig(t)
|
||||
ch, _, _ := rig.startReadCall(`{"id":"1001","path":"C:\\empty.txt"}`)
|
||||
|
||||
// Windows clients send no chunk for an empty file, only the completion.
|
||||
stream := rig.newSub()
|
||||
sum := sha256.Sum256(nil)
|
||||
rig.s.OnTransferPacket(stream, completePacket(5, 0, 0, sum[:]))
|
||||
|
||||
out := readOutput(t, rig.wait(ch))
|
||||
if out.Size != 0 || out.Text != "" || out.LinesTotal != 0 || out.LinesReturned != 0 || out.Truncated {
|
||||
t.Fatalf("empty file output = %+v", out)
|
||||
}
|
||||
if out.EOL != "none" {
|
||||
t.Fatalf("eol = %q, want none", out.EOL)
|
||||
}
|
||||
if want := hex.EncodeToString(sum[:]); out.SHA256 != want {
|
||||
t.Fatalf("sha256 = %q, want %q", out.SHA256, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadFileDropsForeignTransferIDChunks(t *testing.T) {
|
||||
shortenTransferTimeouts(t, time.Second, 5*time.Second, 5*time.Millisecond)
|
||||
rig := newFileRig(t)
|
||||
ch, _, targetDir := rig.startReadCall(`{"id":"1001","path":"C:\\a.txt"}`)
|
||||
|
||||
content := []byte("payload")
|
||||
name := targetDir + "a.txt"
|
||||
stream := rig.newSub()
|
||||
rig.s.OnTransferPacket(stream, chunkPacket(100, 0, 1, uint64(len(content)), 0, 0, name, content[:3]))
|
||||
// A late chunk from another (older) transfer must not disturb this one.
|
||||
rig.s.OnTransferPacket(stream, chunkPacket(99, 0, 1, 999, 0, 0, `C:\stale`, []byte("zzz")))
|
||||
rig.s.OnTransferPacket(stream, chunkPacket(100, 0, 1, uint64(len(content)), 3, ffV2LastChunk, name, content[3:]))
|
||||
sum := sha256.Sum256(content)
|
||||
rig.s.OnTransferPacket(stream, completePacket(100, 0, uint64(len(content)), sum[:]))
|
||||
|
||||
out := readOutput(t, rig.wait(ch))
|
||||
if out.Text != string(content) {
|
||||
t.Fatalf("text = %q", out.Text)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReadFileIgnoresStaleStreamFromEarlierCall covers the live race that
|
||||
// surfaced as "Path traversal detected": once the server rejects a transfer (the
|
||||
// size gate is the usual reason) the client keeps streaming the rest of its
|
||||
// batch on the sub-connection it opened for that earlier call. Those late bytes
|
||||
// must be dropped, not adopted as the new call's stream — adopting them failed
|
||||
// the fresh call with a traversal error, and the stale connection closing would
|
||||
// have failed it as "connection lost" too.
|
||||
func TestReadFileIgnoresStaleStreamFromEarlierCall(t *testing.T) {
|
||||
shortenTransferTimeouts(t, 500*time.Millisecond, 5*time.Second, 5*time.Millisecond)
|
||||
rig := newFileRig(t)
|
||||
|
||||
stale := rig.newSub() // the rejected earlier call's data sub-conn
|
||||
ch, _, targetDir := rig.startReadCall(`{"id":"1001","path":"C:\\b.txt"}`)
|
||||
|
||||
content := []byte("good")
|
||||
name := targetDir + "b.txt"
|
||||
rig.s.OnTransferPacket(stale, chunkPacket(7, 0, 1, 3<<20, 0, 0,
|
||||
`C:\Users\tmp\yama-mcp-read-old\big.bin`, []byte("zz")))
|
||||
empty := sha256.Sum256(nil)
|
||||
rig.s.OnTransferPacket(stale, completePacket(7, 0, 0, empty[:]))
|
||||
|
||||
stream := rig.newSub() // opened after the download request, as Windows does
|
||||
rig.s.OnTransferPacket(stream, chunkPacket(42, 0, 1, uint64(len(content)), 0, ffV2LastChunk, name, content))
|
||||
sum := sha256.Sum256(content)
|
||||
rig.s.OnTransferPacket(stream, completePacket(42, 0, uint64(len(content)), sum[:]))
|
||||
|
||||
out := readOutput(t, rig.wait(ch))
|
||||
if out.Text != string(content) {
|
||||
t.Fatalf("text = %q, want %q", out.Text, content)
|
||||
}
|
||||
if out.SHA256 != hex.EncodeToString(sum[:]) {
|
||||
t.Fatalf("sha256 = %s, want %s", out.SHA256, hex.EncodeToString(sum[:]))
|
||||
}
|
||||
}
|
||||
|
||||
// TestReadFileClosesStreamSubConn checks that the call hangs up the client's
|
||||
// data sub-connection when it ends, so a batch the server stopped reading does
|
||||
// not keep streaming in the background.
|
||||
func TestReadFileClosesStreamSubConn(t *testing.T) {
|
||||
shortenTransferTimeouts(t, time.Second, 5*time.Second, 5*time.Millisecond)
|
||||
rig := newFileRig(t)
|
||||
ch, _, targetDir := rig.startReadCall(`{"id":"1001","path":"C:\\c.txt"}`)
|
||||
|
||||
content := []byte("bye")
|
||||
stream := rig.newSub()
|
||||
rig.s.OnTransferPacket(stream, chunkPacket(1, 0, 1, uint64(len(content)), 0, ffV2LastChunk,
|
||||
targetDir+"c.txt", content))
|
||||
sum := sha256.Sum256(content)
|
||||
rig.s.OnTransferPacket(stream, completePacket(1, 0, uint64(len(content)), sum[:]))
|
||||
readOutput(t, rig.wait(ch))
|
||||
|
||||
if !stream.IsClosed() {
|
||||
t.Fatal("data sub-conn is still open after the call returned")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadFileDownloadErrorMapping(t *testing.T) {
|
||||
cases := []struct {
|
||||
win32 int
|
||||
code int
|
||||
frag string
|
||||
}{
|
||||
{2, CodeNotFound, "does not exist"},
|
||||
{3, CodeNotFound, "does not exist"},
|
||||
{5, CodePermission, "Access denied"},
|
||||
{87, CodeInternal, "could not queue"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
shortenTransferTimeouts(t, time.Second, 5*time.Second, 5*time.Millisecond)
|
||||
rig := newFileRig(t)
|
||||
ch, fm, _ := rig.startReadCall(`{"id":"1001","path":"C:\\missing.txt"}`)
|
||||
rig.s.OnTransferPacket(fm, downloadErrorPacket(uint32(c.win32)))
|
||||
got := rig.wait(ch)
|
||||
if got.err == nil || got.err.Code != c.code {
|
||||
t.Fatalf("win32=%d error = %+v, want code %d", c.win32, got.err, c.code)
|
||||
}
|
||||
if !strings.Contains(got.err.Message, c.frag) {
|
||||
t.Fatalf("win32=%d message = %q, want %q", c.win32, got.err.Message, c.frag)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadFileOutOfOrderChunkRejected(t *testing.T) {
|
||||
shortenTransferTimeouts(t, time.Second, 5*time.Second, 5*time.Millisecond)
|
||||
rig := newFileRig(t)
|
||||
ch, _, targetDir := rig.startReadCall(`{"id":"1001","path":"C:\\a.txt"}`)
|
||||
|
||||
stream := rig.newSub()
|
||||
rig.s.OnTransferPacket(stream, chunkPacket(1, 0, 1, 10, 4, 0, targetDir+"a.txt", []byte("4567")))
|
||||
c := rig.wait(ch)
|
||||
if c.err == nil || c.err.Code != CodeInternal {
|
||||
t.Fatalf("error = %+v, want -32000", c.err)
|
||||
}
|
||||
if !strings.Contains(c.err.Message, "offset") {
|
||||
t.Fatalf("message = %q", c.err.Message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadFileTraversalChunkRejected(t *testing.T) {
|
||||
shortenTransferTimeouts(t, time.Second, 5*time.Second, 5*time.Millisecond)
|
||||
rig := newFileRig(t)
|
||||
ch, _, _ := rig.startReadCall(`{"id":"1001","path":"C:\\a.txt"}`)
|
||||
|
||||
stream := rig.newSub()
|
||||
rig.s.OnTransferPacket(stream, chunkPacket(1, 0, 1, 5, 0, ffV2LastChunk, `..\..\evil`, []byte("hello")))
|
||||
c := rig.wait(ch)
|
||||
if c.err == nil || c.err.Code != CodeInternal {
|
||||
t.Fatalf("error = %+v, want -32000", c.err)
|
||||
}
|
||||
if !strings.Contains(c.err.Message, "Path traversal") {
|
||||
t.Fatalf("message = %q", c.err.Message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadFileStallTimesOut(t *testing.T) {
|
||||
shortenTransferTimeouts(t, 150*time.Millisecond, 5*time.Second, 10*time.Millisecond)
|
||||
rig := newFileRig(t)
|
||||
ch, _, targetDir := rig.startReadCall(`{"id":"1001","path":"C:\\a.txt"}`)
|
||||
|
||||
stream := rig.newSub()
|
||||
rig.s.OnTransferPacket(stream, chunkPacket(1, 0, 1, 10, 0, 0, targetDir+"a.txt", []byte("12345")))
|
||||
c := rig.wait(ch)
|
||||
if c.err == nil || c.err.Code != CodeTimeout {
|
||||
t.Fatalf("error = %+v, want -32001", c.err)
|
||||
}
|
||||
if !strings.Contains(c.err.Message, "stalled") {
|
||||
t.Fatalf("message = %q", c.err.Message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadFileStreamClosedFailsFast(t *testing.T) {
|
||||
shortenTransferTimeouts(t, 10*time.Second, 20*time.Second, 10*time.Millisecond)
|
||||
rig := newFileRig(t)
|
||||
ch, _, targetDir := rig.startReadCall(`{"id":"1001","path":"C:\\a.txt"}`)
|
||||
|
||||
stream := rig.newSub()
|
||||
rig.s.OnTransferPacket(stream, chunkPacket(1, 0, 1, 10, 0, 0, targetDir+"a.txt", []byte("12345")))
|
||||
_ = stream.Close()
|
||||
c := rig.wait(ch)
|
||||
if c.err == nil || c.err.Code != CodeTimeout {
|
||||
t.Fatalf("error = %+v, want -32001", c.err)
|
||||
}
|
||||
if !strings.Contains(c.err.Message, "Connection lost") {
|
||||
t.Fatalf("message = %q", c.err.Message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadFileRequiresV2Capability(t *testing.T) {
|
||||
rig := newFileRig(t)
|
||||
rig.h.Register(&hub.Device{ID: "1001", PeerIP: "10.0.0.1"}, rig.main) // no capability
|
||||
ch := rig.callRead(`{"id":"1001","path":"C:\\a.txt"}`)
|
||||
c := rig.wait(ch)
|
||||
if c.err == nil || c.err.Code != CodeUnsupported {
|
||||
t.Fatalf("error = %+v, want -32005", c.err)
|
||||
}
|
||||
rig.expectNothing()
|
||||
}
|
||||
|
||||
// ----- text decoding and windowing ------------------------------------------
|
||||
|
||||
func TestBuildReadFileResultGBK(t *testing.T) {
|
||||
rawGBK := protocol.UTF8ToGBK("中文\r\nabc")
|
||||
res := buildReadFileResult("/tmp/x.conf", rawGBK, "abc", "auto", 0, 2000, 262144)
|
||||
out := res.StructuredContent.(readFileOutput)
|
||||
if out.Encoding != "gbk" || out.EOL != "crlf" {
|
||||
t.Fatalf("encoding=%q eol=%q", out.Encoding, out.EOL)
|
||||
}
|
||||
if out.Text != "中文\nabc" || out.LinesTotal != 2 {
|
||||
t.Fatalf("text=%q lines_total=%d", out.Text, out.LinesTotal)
|
||||
}
|
||||
if !strings.Contains(res.Content[0].Text, "[read_file] /tmp/x.conf") {
|
||||
t.Fatalf("head line = %q", res.Content[0].Text)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildReadFileResultNegativeOffset(t *testing.T) {
|
||||
res := buildReadFileResult("x", []byte("a\nb\nc\n"), "s", "auto", -2, 2000, 262144)
|
||||
out := res.StructuredContent.(readFileOutput)
|
||||
if out.Offset != 1 || out.Text != "b\nc" || out.LinesReturned != 2 || out.Truncated {
|
||||
t.Fatalf("output = %+v", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildReadFileResultLimit(t *testing.T) {
|
||||
res := buildReadFileResult("x", []byte("a\nb\nc\n"), "s", "auto", 0, 1, 262144)
|
||||
out := res.StructuredContent.(readFileOutput)
|
||||
if out.Text != "a" || out.LinesReturned != 1 || !out.Truncated {
|
||||
t.Fatalf("output = %+v", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildReadFileResultMaxBytesCutOnCharBoundary(t *testing.T) {
|
||||
line := strings.Repeat("中", 400) // 1200 UTF-8 bytes, one line
|
||||
res := buildReadFileResult("x", []byte(line), "s", "auto", 0, 2000, 1024)
|
||||
out := res.StructuredContent.(readFileOutput)
|
||||
if !out.Truncated || out.LinesReturned != 1 {
|
||||
t.Fatalf("truncated=%v lines_returned=%d", out.Truncated, out.LinesReturned)
|
||||
}
|
||||
if len(out.Text) != 1023 || !utf8.ValidString(out.Text) {
|
||||
t.Fatalf("cut text is %d bytes and valid=%v, want 1023 valid bytes", len(out.Text), utf8.ValidString(out.Text))
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildReadFileResultEncodings(t *testing.T) {
|
||||
// UTF-16LE with BOM.
|
||||
le := []byte{0xFF, 0xFE, 'h', 0, 'i', 0}
|
||||
if out := buildReadFileResult("x", le, "s", "auto", 0, 10, 1024).StructuredContent.(readFileOutput); out.Encoding != "utf-16le" || out.Text != "hi" {
|
||||
t.Fatalf("utf-16le output = %+v", out)
|
||||
}
|
||||
// UTF-8 BOM is stripped.
|
||||
bom := append([]byte{0xEF, 0xBB, 0xBF}, []byte("hi")...)
|
||||
if out := buildReadFileResult("x", bom, "s", "auto", 0, 10, 1024).StructuredContent.(readFileOutput); out.Encoding != "utf-8" || out.Text != "hi" {
|
||||
t.Fatalf("utf-8 bom output = %+v", out)
|
||||
}
|
||||
// Latin-1 is explicit only (byte 0xE9 would otherwise be invalid UTF-8 → GBK).
|
||||
if out := buildReadFileResult("x", []byte{0xE9}, "s", "latin1", 0, 10, 1024).StructuredContent.(readFileOutput); out.Encoding != "latin1" || out.Text != "é" {
|
||||
t.Fatalf("latin1 output = %+v", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDetectEOLVariants(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"": "none",
|
||||
"abc": "none",
|
||||
"a\r\nb": "crlf",
|
||||
"a\nb": "lf",
|
||||
"a\rb": "cr",
|
||||
"a\r\nb\n": "mixed",
|
||||
}
|
||||
for in, want := range cases {
|
||||
if got := detectEOL(in); got != want {
|
||||
t.Errorf("detectEOL(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitTextLines(t *testing.T) {
|
||||
if got := splitTextLines(""); got != nil {
|
||||
t.Fatalf("empty text = %v", got)
|
||||
}
|
||||
if got := splitTextLines("a\nb\n"); len(got) != 2 || got[1] != "b" {
|
||||
t.Fatalf("a\\nb\\n = %v", got)
|
||||
}
|
||||
if got := splitTextLines("\n"); len(got) != 1 || got[0] != "" {
|
||||
t.Fatalf("\\n = %v", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package mcp
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
// request is one JSON-RPC 2.0 call. The MCP endpoint is stateless, so there is
|
||||
// nothing else to track between requests.
|
||||
type request struct {
|
||||
JSONRPC string `json:"jsonrpc"`
|
||||
ID json.RawMessage `json:"id"`
|
||||
Method string `json:"method"`
|
||||
Params json.RawMessage `json:"params"`
|
||||
}
|
||||
|
||||
// isNotification reports whether the caller omitted "id". Such requests get
|
||||
// no JSON-RPC response at all (MCP uses them for notifications/initialized).
|
||||
func (r *request) isNotification() bool { return len(r.ID) == 0 }
|
||||
|
||||
// response is a single JSON-RPC 2.0 reply. Exactly one of Result/Error is set.
|
||||
type response struct {
|
||||
JSONRPC string `json:"jsonrpc"`
|
||||
ID json.RawMessage `json:"id"`
|
||||
Result any `json:"result,omitempty"`
|
||||
Error *rpcError `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// idOrNull keeps the reply valid when the request id is missing or malformed:
|
||||
// JSON-RPC allows "id": null on errors that cannot be correlated.
|
||||
func idOrNull(id json.RawMessage) json.RawMessage {
|
||||
if len(id) == 0 {
|
||||
return json.RawMessage("null")
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
func resultResponse(id json.RawMessage, result any) *response {
|
||||
return &response{JSONRPC: "2.0", ID: idOrNull(id), Result: result}
|
||||
}
|
||||
|
||||
func errorResponse(id json.RawMessage, err *rpcError) *response {
|
||||
return &response{JSONRPC: "2.0", ID: idOrNull(id), Error: err}
|
||||
}
|
||||
|
||||
// toolCallParams is the tools/call payload. Arguments stay raw so each tool
|
||||
// decodes only the fields it understands (and reports -32602 itself).
|
||||
type toolCallParams struct {
|
||||
Name string `json:"name"`
|
||||
Arguments json.RawMessage `json:"arguments"`
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// localReadTools answer from the server's own state (device hub, history,
|
||||
// audit file) and never open a channel to a client. Everything else is assumed
|
||||
// to act on one host, so a call that names an id takes that host's lock.
|
||||
var localReadTools = map[string]bool{
|
||||
"list_hosts": true,
|
||||
"get_host_detail": true,
|
||||
"get_server_status": true,
|
||||
"get_audit_log": true,
|
||||
}
|
||||
|
||||
// deviceLocks enforces one in-flight device operation per host. The lock is
|
||||
// per device, not per channel: the client can share state between the main
|
||||
// connection and its sub-connections, so overlapping commands only make the
|
||||
// situation harder to reason about (design §9).
|
||||
type deviceLocks struct {
|
||||
mu sync.Mutex
|
||||
held map[string]deviceHold
|
||||
}
|
||||
|
||||
// deviceHold describes the call currently owning a device, so a rejection can
|
||||
// tell the caller who is in the way and for how long.
|
||||
type deviceHold struct {
|
||||
tool string
|
||||
since time.Time
|
||||
}
|
||||
|
||||
func newDeviceLocks() *deviceLocks {
|
||||
return &deviceLocks{held: make(map[string]deviceHold)}
|
||||
}
|
||||
|
||||
// tryAcquire takes the device lock without waiting. The second return value is
|
||||
// false when another call holds it; held then describes that call.
|
||||
func (l *deviceLocks) tryAcquire(deviceID, tool string) (held deviceHold, ok bool) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
if h, busy := l.held[deviceID]; busy {
|
||||
return h, false
|
||||
}
|
||||
l.held[deviceID] = deviceHold{tool: tool, since: time.Now()}
|
||||
return deviceHold{}, true
|
||||
}
|
||||
|
||||
func (l *deviceLocks) release(deviceID string) {
|
||||
l.mu.Lock()
|
||||
delete(l.held, deviceID)
|
||||
l.mu.Unlock()
|
||||
}
|
||||
|
||||
// deviceIDFromArgs extracts the one host a tool call targets. Tools with a
|
||||
// batch `ids` array are handled by their handler one id at a time (matching the
|
||||
// Win32 server); this function deliberately looks only at the single-host
|
||||
// spellings.
|
||||
func deviceIDFromArgs(raw json.RawMessage) string {
|
||||
if len(raw) == 0 || string(raw) == "null" {
|
||||
return ""
|
||||
}
|
||||
var args struct {
|
||||
ID string `json:"id"`
|
||||
DeviceID string `json:"device_id"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &args); err != nil {
|
||||
// Malformed arguments are reported by the handler as -32602; there is
|
||||
// no device to lock here.
|
||||
return ""
|
||||
}
|
||||
if args.ID != "" {
|
||||
return args.ID
|
||||
}
|
||||
return args.DeviceID
|
||||
}
|
||||
|
||||
// busyMessage mirrors the Win32 server's -32003 text:
|
||||
// "Device busy: another request is pending for this host (tool=..., elapsed=Ns)".
|
||||
func busyMessage(held deviceHold) string {
|
||||
return fmt.Sprintf(
|
||||
"Device busy: another request is pending for this host (tool=%s, elapsed=%ds)",
|
||||
held.tool, int(time.Since(held.since).Seconds()))
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/logger"
|
||||
)
|
||||
|
||||
// blockingListFiles installs a list_files handler that blocks while id ==
|
||||
// blockID, so a second call for that host can be checked against the lock.
|
||||
func blockingListFiles(t *testing.T, s *Server, blockID string) (entered chan struct{}, release func()) {
|
||||
t.Helper()
|
||||
entered = make(chan struct{})
|
||||
done := make(chan struct{})
|
||||
var once sync.Once
|
||||
s.handlers["list_files"] = func(_ context.Context, args json.RawMessage) (any, *rpcError) {
|
||||
var a struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
_ = json.Unmarshal(args, &a)
|
||||
if a.ID == blockID {
|
||||
once.Do(func() { close(entered) })
|
||||
<-done
|
||||
}
|
||||
return newToolResult("ok", map[string]any{"id": a.ID}), nil
|
||||
}
|
||||
return entered, func() { close(done) }
|
||||
}
|
||||
|
||||
func listFilesCall(t *testing.T, s *Server, id string) (any, *rpcError) {
|
||||
t.Helper()
|
||||
return s.callTool(context.Background(), json.RawMessage(
|
||||
`{"name":"list_files","arguments":{"id":"`+id+`","path":"/"}}`))
|
||||
}
|
||||
|
||||
func TestDeviceLockRejectsSecondCall(t *testing.T) {
|
||||
s := testServer(t, false)
|
||||
entered, release := blockingListFiles(t, s, "1001")
|
||||
|
||||
type outcome struct {
|
||||
res any
|
||||
err *rpcError
|
||||
}
|
||||
first := make(chan outcome, 1)
|
||||
go func() {
|
||||
res, rerr := listFilesCall(t, s, "1001")
|
||||
first <- outcome{res, rerr}
|
||||
}()
|
||||
<-entered
|
||||
|
||||
_, rerr := listFilesCall(t, s, "1001")
|
||||
if rerr == nil || rerr.Code != CodeBusy {
|
||||
t.Fatalf("second same-host call error = %+v, want -32003", rerr)
|
||||
}
|
||||
if !strings.Contains(rerr.Message, "tool=list_files") || !strings.Contains(rerr.Message, "elapsed=") {
|
||||
t.Fatalf("busy message = %q, want tool and elapsed", rerr.Message)
|
||||
}
|
||||
|
||||
// A different host is a different lock and must not be blocked.
|
||||
if _, rerr = listFilesCall(t, s, "2002"); rerr != nil {
|
||||
t.Fatalf("other-host call error = %+v, want success", rerr)
|
||||
}
|
||||
|
||||
release()
|
||||
if got := <-first; got.err != nil {
|
||||
t.Fatalf("first call error = %+v, want success", got.err)
|
||||
}
|
||||
// The lock is released once the call returns.
|
||||
if _, rerr = listFilesCall(t, s, "1001"); rerr != nil {
|
||||
t.Fatalf("call after release error = %+v, want success", rerr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeviceLockReleasedOnContextCancel(t *testing.T) {
|
||||
s := testServer(t, false)
|
||||
entered := make(chan struct{})
|
||||
var once sync.Once
|
||||
s.handlers["list_files"] = func(ctx context.Context, _ json.RawMessage) (any, *rpcError) {
|
||||
once.Do(func() { close(entered) })
|
||||
<-ctx.Done()
|
||||
return nil, errf(CodeTimeout, "request cancelled")
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
_, _ = s.callTool(ctx, json.RawMessage(
|
||||
`{"name":"list_files","arguments":{"id":"1001"}}`))
|
||||
}()
|
||||
<-entered
|
||||
cancel()
|
||||
<-done
|
||||
|
||||
// Replace the cancelling handler before reusing the host: the lock must
|
||||
// already be free, and this handler returns immediately.
|
||||
s.handlers["list_files"] = func(_ context.Context, _ json.RawMessage) (any, *rpcError) {
|
||||
return newToolResult("ok", map[string]any{"id": "1001"}), nil
|
||||
}
|
||||
if _, rerr := listFilesCall(t, s, "1001"); rerr != nil {
|
||||
t.Fatalf("call after cancel error = %+v, want success (lock must be free)", rerr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGlobalConcurrencyGate(t *testing.T) {
|
||||
log := logger.New(logger.Config{Level: logger.LevelError,
|
||||
File: filepath.Join(t.TempDir(), "mcp-test.log")})
|
||||
t.Cleanup(func() { _ = log.Close() })
|
||||
s := New(Config{Token: testToken, MaxConcurrency: 1, Log: log})
|
||||
entered, release := blockingListFiles(t, s, "1001")
|
||||
|
||||
type outcome struct {
|
||||
res any
|
||||
err *rpcError
|
||||
}
|
||||
first := make(chan outcome, 1)
|
||||
go func() {
|
||||
res, rerr := listFilesCall(t, s, "1001")
|
||||
first <- outcome{res, rerr}
|
||||
}()
|
||||
<-entered
|
||||
|
||||
// A different host still needs a global slot, and there is only one.
|
||||
_, rerr := listFilesCall(t, s, "2002")
|
||||
if rerr == nil || rerr.Code != CodeBusy {
|
||||
t.Fatalf("second call error = %+v, want -32003", rerr)
|
||||
}
|
||||
if !strings.Contains(rerr.Message, "concurrent") {
|
||||
t.Fatalf("concurrency message = %q", rerr.Message)
|
||||
}
|
||||
|
||||
release()
|
||||
if got := <-first; got.err != nil {
|
||||
t.Fatalf("first call error = %+v", got.err)
|
||||
}
|
||||
if _, rerr = listFilesCall(t, s, "2002"); rerr != nil {
|
||||
t.Fatalf("call after slot freed error = %+v, want success", rerr)
|
||||
}
|
||||
}
|
||||
|
||||
// readAuditRecords returns the audit JSON lines written so far.
|
||||
func readAuditRecords(t *testing.T, path string) []map[string]any {
|
||||
t.Helper()
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatalf("read audit file: %v", err)
|
||||
}
|
||||
var out []map[string]any
|
||||
for line := range strings.SplitSeq(strings.TrimSpace(string(data)), "\n") {
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
var rec map[string]any
|
||||
if err := json.Unmarshal([]byte(line), &rec); err != nil {
|
||||
t.Fatalf("parse audit line %q: %v", line, err)
|
||||
}
|
||||
out = append(out, rec)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestToolCallAudit(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
auditPath := filepath.Join(dir, "audit.log")
|
||||
log := logger.New(logger.Config{
|
||||
Level: logger.LevelError,
|
||||
File: filepath.Join(dir, "server.log"),
|
||||
AuditFile: auditPath,
|
||||
})
|
||||
t.Cleanup(func() { _ = log.Close() })
|
||||
s := New(Config{Token: testToken, Log: log})
|
||||
s.handlers["terminal_exec"] = func(_ context.Context, _ json.RawMessage) (any, *rpcError) {
|
||||
return newToolResult("done", map[string]any{"output": "secret-output"}), nil
|
||||
}
|
||||
|
||||
text, _, rerr := callLocal(t, s, "terminal_exec",
|
||||
`{"id":"1001","command":"mysql -pTopSecret --batch"}`)
|
||||
if rerr != nil {
|
||||
t.Fatalf("terminal_exec error = %+v (text %q)", rerr, text)
|
||||
}
|
||||
if _, _, rerr = callLocal(t, s, "nope", `{}`); rerr == nil || rerr.Code != CodeMethodNotFound {
|
||||
t.Fatalf("unknown tool error = %+v, want -32601", rerr)
|
||||
}
|
||||
// A local tool has no device and must audit device "-".
|
||||
if _, _, rerr = callLocal(t, s, "get_server_status", `{}`); rerr != nil {
|
||||
t.Fatalf("get_server_status error = %+v", rerr)
|
||||
}
|
||||
|
||||
recs := readAuditRecords(t, auditPath)
|
||||
if len(recs) != 3 {
|
||||
t.Fatalf("audit records = %d, want 3", len(recs))
|
||||
}
|
||||
|
||||
ok := recs[0]
|
||||
if ok["event"] != "mcp.tool.call" || ok["actor"] != "mcp" || ok["role"] != "admin" || ok["source"] != "mcp" {
|
||||
t.Fatalf("identity fields = %v", ok)
|
||||
}
|
||||
if ok["tool"] != "terminal_exec" || ok["device"] != "1001" {
|
||||
t.Fatalf("tool/device = %v/%v", ok["tool"], ok["device"])
|
||||
}
|
||||
if ok["ok"] != true || ok["code"].(float64) != 0 {
|
||||
t.Fatalf("ok/code = %v/%v", ok["ok"], ok["code"])
|
||||
}
|
||||
if _, hasMS := ok["ms"]; !hasMS {
|
||||
t.Fatal("missing ms")
|
||||
}
|
||||
args, _ := ok["args"].(string)
|
||||
if !strings.Contains(args, "mysql (len=") {
|
||||
t.Fatalf("args = %q, want first word + length", args)
|
||||
}
|
||||
if strings.Contains(args, "TopSecret") {
|
||||
t.Fatalf("args leaked the command body: %q", args)
|
||||
}
|
||||
if res, _ := ok["result"].(string); !strings.Contains(res, "bytes") {
|
||||
t.Fatalf("result = %q, want byte summary", res)
|
||||
}
|
||||
|
||||
bad := recs[1]
|
||||
if bad["tool"] != "nope" || bad["ok"] != false || bad["code"].(float64) != CodeMethodNotFound {
|
||||
t.Fatalf("failed call record = %v", bad)
|
||||
}
|
||||
if bad["device"] != "-" {
|
||||
t.Fatalf("unknown tool device = %v, want -", bad["device"])
|
||||
}
|
||||
if res, _ := bad["result"].(string); !strings.Contains(res, "unknown tool") {
|
||||
t.Fatalf("failure result = %q", res)
|
||||
}
|
||||
|
||||
local := recs[2]
|
||||
if local["tool"] != "get_server_status" || local["device"] != "-" || local["ok"] != true {
|
||||
t.Fatalf("local tool record = %v", local)
|
||||
}
|
||||
}
|
||||
|
||||
// A panicking handler must not take the connection down and must not be
|
||||
// audited as a success.
|
||||
func TestToolCallPanicAuditedAsFailure(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
auditPath := filepath.Join(dir, "audit.log")
|
||||
log := logger.New(logger.Config{
|
||||
Level: logger.LevelError,
|
||||
File: filepath.Join(dir, "server.log"),
|
||||
AuditFile: auditPath,
|
||||
})
|
||||
t.Cleanup(func() { _ = log.Close() })
|
||||
s := New(Config{Token: testToken, Log: log})
|
||||
s.handlers["terminal_exec"] = func(_ context.Context, _ json.RawMessage) (any, *rpcError) {
|
||||
panic("boom")
|
||||
}
|
||||
|
||||
if _, rerr := s.callTool(context.Background(), json.RawMessage(
|
||||
`{"name":"terminal_exec","arguments":{"id":"1001","command":"dir"}}`)); rerr == nil ||
|
||||
rerr.Code != CodeInternal {
|
||||
t.Fatalf("panic call error = %+v, want -32000", rerr)
|
||||
}
|
||||
|
||||
recs := readAuditRecords(t, auditPath)
|
||||
if len(recs) != 1 {
|
||||
t.Fatalf("audit records = %d, want 1", len(recs))
|
||||
}
|
||||
if recs[0]["ok"] != false || recs[0]["code"].(float64) != CodeInternal {
|
||||
t.Fatalf("panic record = %v, want ok=false code=-32000", recs[0])
|
||||
}
|
||||
// The host lock must be free again despite the panic.
|
||||
s.handlers["terminal_exec"] = func(_ context.Context, _ json.RawMessage) (any, *rpcError) {
|
||||
return newToolResult("ok", nil), nil
|
||||
}
|
||||
if _, rerr := s.callTool(context.Background(), json.RawMessage(
|
||||
`{"name":"terminal_exec","arguments":{"id":"1001"}}`)); rerr != nil {
|
||||
t.Fatalf("call after panic error = %+v, want success", rerr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSummarizeArgsRedactsSensitiveValues(t *testing.T) {
|
||||
got := summarizeArgs(json.RawMessage(`{
|
||||
"id": "1001",
|
||||
"command": "mysql -pTopSecret --batch",
|
||||
"text": "hello secret",
|
||||
"message": "msg secret",
|
||||
"body": "{\"key\":\"secret\"}",
|
||||
"headers": {"Authorization": "Bearer tok"},
|
||||
"password": "pw"
|
||||
}`))
|
||||
for _, leak := range []string{"TopSecret", "hello secret", "msg secret", "Bearer tok", "pw"} {
|
||||
if strings.Contains(got, leak) {
|
||||
t.Fatalf("args leaked %q: %s", leak, got)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(got, "mysql (len=") {
|
||||
t.Fatalf("command digest missing: %s", got)
|
||||
}
|
||||
if !strings.Contains(got, "redacted(") {
|
||||
t.Fatalf("redaction marker missing: %s", got)
|
||||
}
|
||||
if len(got) > auditArgsMaxBytes {
|
||||
t.Fatalf("digest = %d bytes, want <= %d", len(got), auditArgsMaxBytes)
|
||||
}
|
||||
|
||||
// The ellipsis counts toward the cap.
|
||||
long := summarizeArgs(json.RawMessage(`{"note":"` + strings.Repeat("a", 800) + `"}`))
|
||||
if len(long) > auditArgsMaxBytes || !strings.HasSuffix(long, "…") {
|
||||
t.Fatalf("truncated digest = %d bytes, tail %q", len(long), long[len(long)-3:])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,424 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/jpeg"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/connection"
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/protocol"
|
||||
)
|
||||
|
||||
// get_screenshot uses the main-connection preview RPC
|
||||
// (COMMAND_SCREEN_PREVIEW_REQ → TOKEN_SCREEN_PREVIEW_RSP): the client captures,
|
||||
// scales and encodes the frame itself, so the request opens no sub-connection
|
||||
// and competes with nobody for the per-device screen slot (design §7.1).
|
||||
const (
|
||||
screenPreviewDefaultWidth = 1024
|
||||
screenPreviewMinWidth = 64
|
||||
screenPreviewMaxWidth = 1920
|
||||
screenPreviewJPEGQuality = 80
|
||||
|
||||
// screenPreviewRspHeaderLen is sizeof(ScreenPreviewRspHeader) with
|
||||
// #pragma pack(1) (common/commands.h); the image bytes follow directly.
|
||||
screenPreviewRspHeaderLen = 16
|
||||
screenPreviewOffReqID = 1
|
||||
screenPreviewOffStatus = 3
|
||||
screenPreviewOffFormat = 4
|
||||
screenPreviewOffWidth = 5
|
||||
screenPreviewOffHeight = 7
|
||||
screenPreviewOffBytes = 9
|
||||
)
|
||||
|
||||
// ScreenPreviewStatus / ScreenPreviewFormat values (common/commands.h). Only
|
||||
// two formats exist on the wire: Windows clients send JPEG, Linux clients send
|
||||
// BGRX because they carry no JPEG encoder — the server encodes it here.
|
||||
const (
|
||||
screenPreviewStatusOK byte = 0
|
||||
screenPreviewStatusCaptureFailed byte = 1
|
||||
screenPreviewStatusEncodeFailed byte = 2
|
||||
screenPreviewStatusNotSupported byte = 3
|
||||
screenPreviewStatusBadTarget byte = 4
|
||||
|
||||
screenPreviewFmtJPEG byte = 0
|
||||
screenPreviewFmtBGRX byte = 3
|
||||
)
|
||||
|
||||
// screenPreviewTimeout bounds one round trip. It is a variable rather than a
|
||||
// constant only so tests can shorten it; production code never changes it.
|
||||
// There is deliberately no cancellation on timeout: the request rides the
|
||||
// device's main connection, where MFC likewise refuses CancelIO (§7.4) — the
|
||||
// pending entry is dropped and a late reply fails the reqId match.
|
||||
var screenPreviewTimeout = 8 * time.Second
|
||||
|
||||
// screenshotArgs is the published inputSchema as Go. Pointer fields separate
|
||||
// "absent" from an explicit value: mode=screen must still reject the
|
||||
// region/window/monitor parameters instead of silently ignoring them.
|
||||
type screenshotArgs struct {
|
||||
ID string `json:"id"`
|
||||
MaxWidth *int `json:"max_width"`
|
||||
Mode string `json:"mode"`
|
||||
HWND *json.RawMessage `json:"hwnd"`
|
||||
X *int `json:"x"`
|
||||
Y *int `json:"y"`
|
||||
Width *int `json:"width"`
|
||||
Height *int `json:"height"`
|
||||
Monitor *int `json:"monitor"`
|
||||
}
|
||||
|
||||
// screenshotImage / screenshotCapture are the structuredContent fields the
|
||||
// shared outputSchema defines. Fields the v1 RPC cannot report are omitted
|
||||
// rather than faked (design §3.2).
|
||||
type screenshotImage struct {
|
||||
MimeType string `json:"mimeType"`
|
||||
Width int `json:"width"`
|
||||
Height int `json:"height"`
|
||||
Bytes int `json:"bytes"`
|
||||
}
|
||||
|
||||
type screenshotCapture struct {
|
||||
Mode string `json:"mode"`
|
||||
}
|
||||
|
||||
type screenshotOutput struct {
|
||||
Image screenshotImage `json:"image"`
|
||||
Capture screenshotCapture `json:"capture"`
|
||||
}
|
||||
|
||||
// previewReply is one decoded TOKEN_SCREEN_PREVIEW_RSP.
|
||||
type previewReply struct {
|
||||
status byte
|
||||
format byte
|
||||
width uint16
|
||||
height uint16
|
||||
payload []byte
|
||||
}
|
||||
|
||||
// previewRequest is one in-flight screenshot. ch is buffered so delivery never
|
||||
// blocks the TCP read loop.
|
||||
type previewRequest struct {
|
||||
reqID uint16
|
||||
ch chan previewReply
|
||||
}
|
||||
|
||||
// previewTable matches a client reply to the call waiting for it. The
|
||||
// per-device call lock already serialises MCP screenshots, so at most one
|
||||
// entry exists per device; responses are still keyed by device because the
|
||||
// reply itself carries no device id — only the connection does.
|
||||
type previewTable struct {
|
||||
mu sync.Mutex
|
||||
byDevice map[string]*previewRequest
|
||||
nextID atomic.Uint32
|
||||
}
|
||||
|
||||
func newPreviewTable() *previewTable {
|
||||
return &previewTable{byDevice: make(map[string]*previewRequest)}
|
||||
}
|
||||
|
||||
// nextReqID mirrors MFC's NextPreviewReqId: increment and skip 0, which would
|
||||
// otherwise match an "unset" reqId on the client side.
|
||||
func (t *previewTable) nextReqID() uint16 {
|
||||
for {
|
||||
if v := uint16(t.nextID.Add(1)); v != 0 {
|
||||
return v
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// begin reserves the device's single preview slot. nil means another request
|
||||
// is already pending (only possible if the call lock was bypassed).
|
||||
func (t *previewTable) begin(deviceID string) *previewRequest {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
if _, ok := t.byDevice[deviceID]; ok {
|
||||
return nil
|
||||
}
|
||||
r := &previewRequest{reqID: t.nextReqID(), ch: make(chan previewReply, 1)}
|
||||
t.byDevice[deviceID] = r
|
||||
return r
|
||||
}
|
||||
|
||||
// cancel drops a pending slot unless it was already delivered. The pointer
|
||||
// check keeps a slow caller from deleting a newer request for the same device.
|
||||
func (t *previewTable) cancel(deviceID string, r *previewRequest) {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
if t.byDevice[deviceID] == r {
|
||||
delete(t.byDevice, deviceID)
|
||||
}
|
||||
}
|
||||
|
||||
// deliver hands a matching reply to its waiter. A reply whose reqId does not
|
||||
// match — an expired request or one from another caller — is dropped, exactly
|
||||
// like MFC's TakePreviewResponse.
|
||||
func (t *previewTable) deliver(deviceID string, reqID uint16, reply previewReply) bool {
|
||||
t.mu.Lock()
|
||||
r, ok := t.byDevice[deviceID]
|
||||
if !ok || r.reqID != reqID {
|
||||
t.mu.Unlock()
|
||||
return false
|
||||
}
|
||||
delete(t.byDevice, deviceID)
|
||||
t.mu.Unlock()
|
||||
r.ch <- reply // buffered, and the entry is gone: nobody else can send
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Server) registerScreenTools() {
|
||||
s.handlers["get_screenshot"] = s.callGetScreenshot
|
||||
}
|
||||
|
||||
// OnPacket feeds one packet from a device connection to the MCP layer. It
|
||||
// reports whether MCP consumed the packet; anything MCP does not own returns
|
||||
// false and falls through to cmd's normal command dispatch.
|
||||
func (s *Server) OnPacket(ctx *connection.Context, data []byte) bool {
|
||||
if s == nil || len(data) == 0 || data[0] != protocol.TokenScreenPreviewRsp {
|
||||
return false
|
||||
}
|
||||
deviceID := ctx.GetInfo().ClientID
|
||||
rsp, err := parseScreenPreviewRsp(data)
|
||||
if err != nil {
|
||||
s.log.Warn("malformed screen preview response from conn %d (device=%q): %v",
|
||||
ctx.ID, deviceID, err)
|
||||
return true
|
||||
}
|
||||
if deviceID != "" {
|
||||
s.previews.deliver(deviceID, rsp.reqID, rsp.reply)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// parseScreenPreviewRsp validates the 16-byte header and copies the image
|
||||
// bytes out of the TCP read buffer. A declared length that overruns the packet
|
||||
// marks the whole response malformed: the client would otherwise hand us an
|
||||
// under-filled image.
|
||||
func parseScreenPreviewRsp(data []byte) (struct {
|
||||
reqID uint16
|
||||
reply previewReply
|
||||
}, error) {
|
||||
var rsp struct {
|
||||
reqID uint16
|
||||
reply previewReply
|
||||
}
|
||||
if len(data) < screenPreviewRspHeaderLen {
|
||||
return rsp, fmt.Errorf("packet is %d bytes, want at least %d",
|
||||
len(data), screenPreviewRspHeaderLen)
|
||||
}
|
||||
if data[0] != protocol.TokenScreenPreviewRsp {
|
||||
return rsp, fmt.Errorf("token %d, want %d", data[0], protocol.TokenScreenPreviewRsp)
|
||||
}
|
||||
rsp.reqID = binary.LittleEndian.Uint16(data[screenPreviewOffReqID:])
|
||||
rsp.reply.status = data[screenPreviewOffStatus]
|
||||
rsp.reply.format = data[screenPreviewOffFormat]
|
||||
rsp.reply.width = binary.LittleEndian.Uint16(data[screenPreviewOffWidth:])
|
||||
rsp.reply.height = binary.LittleEndian.Uint16(data[screenPreviewOffHeight:])
|
||||
n := binary.LittleEndian.Uint32(data[screenPreviewOffBytes:])
|
||||
if avail := len(data) - screenPreviewRspHeaderLen; n > uint32(avail) {
|
||||
return rsp, fmt.Errorf("declares %d image bytes but only %d follow", n, avail)
|
||||
}
|
||||
rsp.reply.payload = append([]byte(nil), data[screenPreviewRspHeaderLen:screenPreviewRspHeaderLen+int(n)]...)
|
||||
return rsp, nil
|
||||
}
|
||||
|
||||
// buildScreenPreviewReq renders the 8-byte v1 request (whole virtual desktop).
|
||||
// v2 (region/window/monitor) is gated behind CLIENT_CAP_SCREEN_REGION and is
|
||||
// not implemented by this server build.
|
||||
func buildScreenPreviewReq(reqID, maxWidth uint16, quality byte) []byte {
|
||||
buf := make([]byte, 8)
|
||||
buf[0] = protocol.CommandScreenPreviewReq
|
||||
binary.LittleEndian.PutUint16(buf[1:3], reqID)
|
||||
binary.LittleEndian.PutUint16(buf[3:5], maxWidth)
|
||||
buf[5] = quality
|
||||
return buf
|
||||
}
|
||||
|
||||
// callGetScreenshot captures one frame through the main-connection RPC.
|
||||
func (s *Server) callGetScreenshot(ctx context.Context, raw json.RawMessage) (any, *rpcError) {
|
||||
if s.cfg.Hub == nil {
|
||||
return nil, errf(CodeInternal, "server device registry is not configured")
|
||||
}
|
||||
var args screenshotArgs
|
||||
if rerr := decodeArgs(raw, &args); rerr != nil {
|
||||
return nil, rerr
|
||||
}
|
||||
if args.ID == "" {
|
||||
return nil, errf(CodeInvalidParams, "Missing required parameter: id")
|
||||
}
|
||||
if !isDecimalID(args.ID) {
|
||||
return nil, errf(CodeInvalidParams, "Invalid id: expected a decimal host id string")
|
||||
}
|
||||
if s.cfg.Hub.MainConn(args.ID) == nil {
|
||||
return nil, errf(CodeOffline, "Host not found or offline: %s", args.ID)
|
||||
}
|
||||
if !protocol.SupportsCap(s.cfg.Hub.Capability(args.ID), protocol.ClientCapScreenPreview) {
|
||||
return nil, errf(CodeUnsupported,
|
||||
"Host does not support screen preview: the client does not declare CLIENT_CAP_SCREEN_PREVIEW (upgrade the client)")
|
||||
}
|
||||
|
||||
mode := strings.TrimSpace(args.Mode)
|
||||
if mode == "" {
|
||||
mode = "screen"
|
||||
}
|
||||
if mode != "screen" {
|
||||
switch mode {
|
||||
case "region", "window", "monitor":
|
||||
return nil, errf(CodeUnsupported,
|
||||
"mode=%s needs the CLIENT_CAP_SCREEN_REGION extension, which this server build does not implement; use mode=screen", mode)
|
||||
default:
|
||||
return nil, errf(CodeInvalidParams,
|
||||
"Invalid mode: %s (expect screen|region|window|monitor)", mode)
|
||||
}
|
||||
}
|
||||
if name := firstRegionParam(&args); name != "" {
|
||||
return nil, errf(CodeUnsupported,
|
||||
"parameter %q needs the CLIENT_CAP_SCREEN_REGION extension, which this server build does not implement; use mode=screen with only id and max_width", name)
|
||||
}
|
||||
|
||||
maxWidth := screenPreviewDefaultWidth
|
||||
if args.MaxWidth != nil && *args.MaxWidth > 0 {
|
||||
maxWidth = min(max(*args.MaxWidth, screenPreviewMinWidth), screenPreviewMaxWidth)
|
||||
}
|
||||
|
||||
req := s.previews.begin(args.ID)
|
||||
if req == nil {
|
||||
return nil, errf(CodeBusy,
|
||||
"Device busy: another screenshot request is already pending for host %s", args.ID)
|
||||
}
|
||||
defer s.previews.cancel(args.ID, req)
|
||||
|
||||
if err := s.cfg.Hub.SendToDevice(args.ID,
|
||||
buildScreenPreviewReq(req.reqID, uint16(maxWidth), screenPreviewJPEGQuality)); err != nil {
|
||||
if errors.Is(err, hub.ErrDeviceOffline) {
|
||||
return nil, errf(CodeOffline, "Host not found or offline: %s", args.ID)
|
||||
}
|
||||
return nil, errf(CodeSendFailed, "Failed to send screenshot request to host: %v", err)
|
||||
}
|
||||
|
||||
timer := time.NewTimer(screenPreviewTimeout)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case reply := <-req.ch:
|
||||
return screenshotResult(reply, mode)
|
||||
case <-timer.C:
|
||||
return nil, errf(CodeTimeout,
|
||||
"Timeout waiting for the screenshot (the host did not answer in %s; a client without screen-preview support cannot be asked)", screenPreviewTimeout)
|
||||
case <-ctx.Done():
|
||||
return nil, errf(CodeTimeout, "Request cancelled while waiting for the screenshot")
|
||||
}
|
||||
}
|
||||
|
||||
// firstRegionParam names the first v2 capture parameter present in the call.
|
||||
// Checked in schema order so the error message is deterministic.
|
||||
func firstRegionParam(args *screenshotArgs) string {
|
||||
switch {
|
||||
case args.HWND != nil:
|
||||
return "hwnd"
|
||||
case args.X != nil:
|
||||
return "x"
|
||||
case args.Y != nil:
|
||||
return "y"
|
||||
case args.Width != nil:
|
||||
return "width"
|
||||
case args.Height != nil:
|
||||
return "height"
|
||||
case args.Monitor != nil:
|
||||
return "monitor"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// screenshotResult maps the device status/format onto the MCP result. Status 4
|
||||
// is a caller-visible parameter problem (target invalid), so it keeps -32602;
|
||||
// capture/encode failures are -32000 because retrying the same call cannot fix
|
||||
// them.
|
||||
func screenshotResult(reply previewReply, mode string) (any, *rpcError) {
|
||||
switch reply.status {
|
||||
case screenPreviewStatusOK:
|
||||
case screenPreviewStatusCaptureFailed:
|
||||
return nil, errf(CodeInternal, "Screenshot capture failed on the host (status 1)")
|
||||
case screenPreviewStatusEncodeFailed:
|
||||
return nil, errf(CodeInternal, "Screenshot encoding failed on the host (status 2)")
|
||||
case screenPreviewStatusNotSupported:
|
||||
return nil, errf(CodeUnsupported, "Host does not support screen capture (status 3)")
|
||||
case screenPreviewStatusBadTarget:
|
||||
return nil, errf(CodeInvalidParams, "Screenshot target is invalid (status 4)")
|
||||
default:
|
||||
return nil, errf(CodeInternal, "Screenshot failed with unknown status %d", reply.status)
|
||||
}
|
||||
|
||||
w, h := int(reply.width), int(reply.height)
|
||||
switch reply.format {
|
||||
case screenPreviewFmtJPEG:
|
||||
if len(reply.payload) == 0 {
|
||||
return nil, errf(CodeInternal, "Screenshot response carries no image data")
|
||||
}
|
||||
return imageResult(reply.payload, w, h, mode), nil
|
||||
case screenPreviewFmtBGRX:
|
||||
jpg, err := bgrxToJPEG(reply.payload, w, h)
|
||||
if err != nil {
|
||||
return nil, errf(CodeInternal, "Malformed BGRX screenshot from host: %v", err)
|
||||
}
|
||||
// The reported width/height describe the pixels, which do not change in
|
||||
// the JPEG encode; bytes describes what is actually returned.
|
||||
return imageResult(jpg, w, h, mode), nil
|
||||
default:
|
||||
return nil, errf(CodeInternal, "Unsupported screenshot format %d", reply.format)
|
||||
}
|
||||
}
|
||||
|
||||
// bgrxToJPEG converts a top-down 4-byte-per-pixel B,G,R,X frame (Linux
|
||||
// clients) into a JPEG. There is no row padding, and X is forced opaque.
|
||||
func bgrxToJPEG(src []byte, w, h int) ([]byte, error) {
|
||||
if w <= 0 || h <= 0 {
|
||||
return nil, fmt.Errorf("invalid dimensions %dx%d", w, h)
|
||||
}
|
||||
if len(src) != w*h*4 {
|
||||
return nil, fmt.Errorf("got %d bytes, want %d for %dx%d BGRX", len(src), w*h*4, w, h)
|
||||
}
|
||||
img := image.NewRGBA(image.Rect(0, 0, w, h))
|
||||
for i := 0; i < w*h; i++ {
|
||||
img.Pix[i*4+0] = src[i*4+2] // R ← B
|
||||
img.Pix[i*4+1] = src[i*4+1] // G
|
||||
img.Pix[i*4+2] = src[i*4+0] // B ← R
|
||||
img.Pix[i*4+3] = 0xFF
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: screenPreviewJPEGQuality}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
// imageResult wraps the encoded JPEG in the MCP envelope: one image content
|
||||
// item plus the metadata the outputSchema declares.
|
||||
func imageResult(jpg []byte, w, h int, mode string) toolResult {
|
||||
return toolResult{
|
||||
Content: []contentItem{{
|
||||
Type: "image",
|
||||
Data: base64.StdEncoding.EncodeToString(jpg),
|
||||
MimeType: "image/jpeg",
|
||||
}},
|
||||
StructuredContent: screenshotOutput{
|
||||
Image: screenshotImage{
|
||||
MimeType: "image/jpeg",
|
||||
Width: w,
|
||||
Height: h,
|
||||
Bytes: len(jpg),
|
||||
},
|
||||
// v1 sends no ScreenCaptureMeta, so the source rect and scale are
|
||||
// unknown; report the mode only rather than inventing values.
|
||||
Capture: screenshotCapture{Mode: mode},
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,458 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/jpeg"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/connection"
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/protocol"
|
||||
)
|
||||
|
||||
// screenRig is a live MCP server plus a hub whose main connection records the
|
||||
// outbound screenshot requests. Tests answer them through OnPacket, i.e.
|
||||
// exactly what cmd/main.go does from the TCP read loop.
|
||||
type screenRig struct {
|
||||
t *testing.T
|
||||
s *Server
|
||||
h *hub.Hub
|
||||
main *connection.Context
|
||||
writes chan []byte
|
||||
}
|
||||
|
||||
func newScreenRig(t *testing.T, capability string) *screenRig {
|
||||
t.Helper()
|
||||
h := hub.New()
|
||||
main := &connection.Context{RemoteAddr: "10.0.0.1:4000"}
|
||||
main.Info.ClientID = "1001"
|
||||
main.Info.ClientType = "EXE"
|
||||
rig := &screenRig{
|
||||
t: t, h: h, main: main,
|
||||
writes: make(chan []byte, 8),
|
||||
}
|
||||
h.SetSender(func(ctx *connection.Context, data []byte) error {
|
||||
if ctx == main {
|
||||
select {
|
||||
case rig.writes <- append([]byte(nil), data...):
|
||||
default:
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
h.Register(&hub.Device{ID: "1001", PeerIP: "10.0.0.1", Capability: capability}, main)
|
||||
rig.s = New(Config{Token: testToken, Hub: h})
|
||||
t.Cleanup(rig.s.Close)
|
||||
return rig
|
||||
}
|
||||
|
||||
type screenCall struct {
|
||||
res toolResult
|
||||
err *rpcError
|
||||
}
|
||||
|
||||
func (r *screenRig) call(args string) <-chan screenCall {
|
||||
ch := make(chan screenCall, 1)
|
||||
go func() {
|
||||
res, rerr := r.s.callGetScreenshot(context.Background(), []byte(args))
|
||||
if rerr != nil {
|
||||
ch <- screenCall{err: rerr}
|
||||
return
|
||||
}
|
||||
tr, ok := res.(toolResult)
|
||||
if !ok {
|
||||
ch <- screenCall{err: errf(CodeInternal, "unexpected result type %T", res)}
|
||||
return
|
||||
}
|
||||
ch <- screenCall{res: tr}
|
||||
}()
|
||||
return ch
|
||||
}
|
||||
|
||||
func (r *screenRig) wait(ch <-chan screenCall) screenCall {
|
||||
r.t.Helper()
|
||||
select {
|
||||
case c := <-ch:
|
||||
return c
|
||||
case <-time.After(5 * time.Second):
|
||||
r.t.Fatal("timed out waiting for the tool call")
|
||||
return screenCall{}
|
||||
}
|
||||
}
|
||||
|
||||
// nextRequest returns the reqId and maxWidth of the next outbound request.
|
||||
func (r *screenRig) nextRequest() (reqID, maxWidth uint16) {
|
||||
r.t.Helper()
|
||||
select {
|
||||
case b := <-r.writes:
|
||||
if len(b) != 8 || b[0] != protocol.CommandScreenPreviewReq {
|
||||
r.t.Fatalf("unexpected screenshot request wire %v", b)
|
||||
}
|
||||
if b[5] != screenPreviewJPEGQuality || b[6] != 0 || b[7] != 0 {
|
||||
r.t.Fatalf("request tail = %v, want quality %d and zero reserved", b[5:], screenPreviewJPEGQuality)
|
||||
}
|
||||
return binary.LittleEndian.Uint16(b[1:3]), binary.LittleEndian.Uint16(b[3:5])
|
||||
case <-time.After(5 * time.Second):
|
||||
r.t.Fatal("no screenshot request was sent")
|
||||
return 0, 0
|
||||
}
|
||||
}
|
||||
|
||||
func previewPacket(reqID uint16, status, format byte, w, h uint16, payload []byte) []byte {
|
||||
buf := make([]byte, screenPreviewRspHeaderLen+len(payload))
|
||||
buf[0] = protocol.TokenScreenPreviewRsp
|
||||
binary.LittleEndian.PutUint16(buf[screenPreviewOffReqID:], reqID)
|
||||
buf[screenPreviewOffStatus] = status
|
||||
buf[screenPreviewOffFormat] = format
|
||||
binary.LittleEndian.PutUint16(buf[screenPreviewOffWidth:], w)
|
||||
binary.LittleEndian.PutUint16(buf[screenPreviewOffHeight:], h)
|
||||
binary.LittleEndian.PutUint32(buf[screenPreviewOffBytes:], uint32(len(payload)))
|
||||
copy(buf[screenPreviewRspHeaderLen:], payload)
|
||||
return buf
|
||||
}
|
||||
|
||||
func solidJPEG(t *testing.T, w, h int, c color.RGBA) []byte {
|
||||
t.Helper()
|
||||
img := image.NewRGBA(image.Rect(0, 0, w, h))
|
||||
for i := 0; i < w*h; i++ {
|
||||
img.Pix[i*4+0] = c.R
|
||||
img.Pix[i*4+1] = c.G
|
||||
img.Pix[i*4+2] = c.B
|
||||
img.Pix[i*4+3] = 0xFF
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: 90}); err != nil {
|
||||
t.Fatalf("encode fixture: %v", err)
|
||||
}
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
// solidBGRX builds a top-down B,G,R,X frame of one colour.
|
||||
func solidBGRX(w, h int, b, g, r byte) []byte {
|
||||
out := make([]byte, w*h*4)
|
||||
for i := 0; i < w*h; i++ {
|
||||
out[i*4+0] = b
|
||||
out[i*4+1] = g
|
||||
out[i*4+2] = r
|
||||
out[i*4+3] = 0xFF
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestScreenshotReturnsJPEG(t *testing.T) {
|
||||
rig := newScreenRig(t, "0004")
|
||||
payload := solidJPEG(t, 4, 4, color.RGBA{255, 0, 0, 255})
|
||||
ch := rig.call(`{"id":"1001"}`)
|
||||
reqID, maxWidth := rig.nextRequest()
|
||||
if maxWidth != screenPreviewDefaultWidth {
|
||||
t.Fatalf("maxWidth = %d, want %d", maxWidth, screenPreviewDefaultWidth)
|
||||
}
|
||||
if !rig.s.OnPacket(rig.main, previewPacket(reqID, screenPreviewStatusOK, screenPreviewFmtJPEG, 4, 4, payload)) {
|
||||
t.Fatal("OnPacket did not consume the preview response")
|
||||
}
|
||||
c := rig.wait(ch)
|
||||
if c.err != nil {
|
||||
t.Fatalf("call error: %+v", c.err)
|
||||
}
|
||||
if len(c.res.Content) != 1 || c.res.Content[0].Type != "image" {
|
||||
t.Fatalf("content = %+v, want one image item", c.res.Content)
|
||||
}
|
||||
if c.res.Content[0].MimeType != "image/jpeg" {
|
||||
t.Fatalf("mimeType = %q", c.res.Content[0].MimeType)
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(c.res.Content[0].Data)
|
||||
if err != nil {
|
||||
t.Fatalf("base64: %v", err)
|
||||
}
|
||||
if !bytes.HasPrefix(raw, []byte{0xFF, 0xD8, 0xFF}) {
|
||||
t.Fatalf("payload does not start with the JPEG magic: %x", raw[:3])
|
||||
}
|
||||
out, ok := c.res.StructuredContent.(screenshotOutput)
|
||||
if !ok {
|
||||
t.Fatalf("structured content %T", c.res.StructuredContent)
|
||||
}
|
||||
if out.Image.Width != 4 || out.Image.Height != 4 || out.Image.Bytes != len(raw) {
|
||||
t.Fatalf("image metadata = %+v (raw %d bytes)", out.Image, len(raw))
|
||||
}
|
||||
if out.Image.MimeType != "image/jpeg" || out.Capture.Mode != "screen" {
|
||||
t.Fatalf("structured content = %+v", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestScreenshotConvertsBGRX(t *testing.T) {
|
||||
rig := newScreenRig(t, "0004")
|
||||
// Pure red in B,G,R,X order.
|
||||
frame := solidBGRX(8, 8, 0, 0, 255)
|
||||
ch := rig.call(`{"id":"1001"}`)
|
||||
reqID, _ := rig.nextRequest()
|
||||
rig.s.OnPacket(rig.main, previewPacket(reqID, screenPreviewStatusOK, screenPreviewFmtBGRX, 8, 8, frame))
|
||||
c := rig.wait(ch)
|
||||
if c.err != nil {
|
||||
t.Fatalf("call error: %+v", c.err)
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(c.res.Content[0].Data)
|
||||
if err != nil {
|
||||
t.Fatalf("base64: %v", err)
|
||||
}
|
||||
if !bytes.HasPrefix(raw, []byte{0xFF, 0xD8, 0xFF}) {
|
||||
t.Fatalf("payload does not start with the JPEG magic: %x", raw[:3])
|
||||
}
|
||||
img, err := jpeg.Decode(bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
t.Fatalf("decode returned JPEG: %v", err)
|
||||
}
|
||||
if b := img.Bounds(); b.Dx() != 8 || b.Dy() != 8 {
|
||||
t.Fatalf("image is %v, want 8x8", b)
|
||||
}
|
||||
r16, g16, b16, _ := img.At(4, 4).RGBA()
|
||||
// JPEG is lossy; a solid frame should still be clearly red.
|
||||
if r16>>8 < 200 || g16>>8 > 60 || b16>>8 > 60 {
|
||||
t.Fatalf("pixel = (%d,%d,%d), want red", r16>>8, g16>>8, b16>>8)
|
||||
}
|
||||
}
|
||||
|
||||
func TestScreenshotStatusMapping(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
status byte
|
||||
code int
|
||||
}{
|
||||
{"capture failed", screenPreviewStatusCaptureFailed, CodeInternal},
|
||||
{"encode failed", screenPreviewStatusEncodeFailed, CodeInternal},
|
||||
{"not supported", screenPreviewStatusNotSupported, CodeUnsupported},
|
||||
{"bad target", screenPreviewStatusBadTarget, CodeInvalidParams},
|
||||
{"unknown", 9, CodeInternal},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
rig := newScreenRig(t, "0004")
|
||||
ch := rig.call(`{"id":"1001"}`)
|
||||
reqID, _ := rig.nextRequest()
|
||||
rig.s.OnPacket(rig.main, previewPacket(reqID, tc.status, screenPreviewFmtJPEG, 0, 0, nil))
|
||||
c := rig.wait(ch)
|
||||
if c.err == nil || c.err.Code != tc.code {
|
||||
t.Fatalf("error = %+v, want code %d", c.err, tc.code)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestScreenshotDropsMismatchedReqID(t *testing.T) {
|
||||
rig := newScreenRig(t, "0004")
|
||||
payload := solidJPEG(t, 2, 2, color.RGBA{0, 255, 0, 255})
|
||||
ch := rig.call(`{"id":"1001"}`)
|
||||
reqID, _ := rig.nextRequest()
|
||||
|
||||
// A response for another request must be dropped, not handed to this one.
|
||||
rig.s.OnPacket(rig.main, previewPacket(reqID+1, screenPreviewStatusOK, screenPreviewFmtJPEG, 2, 2, payload))
|
||||
select {
|
||||
case c := <-ch:
|
||||
t.Fatalf("call finished on a foreign reqId: %+v", c)
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
}
|
||||
|
||||
rig.s.OnPacket(rig.main, previewPacket(reqID, screenPreviewStatusOK, screenPreviewFmtJPEG, 2, 2, payload))
|
||||
if c := rig.wait(ch); c.err != nil {
|
||||
t.Fatalf("matching response still failed: %+v", c.err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestScreenshotTimeoutDropsPending(t *testing.T) {
|
||||
old := screenPreviewTimeout
|
||||
screenPreviewTimeout = 50 * time.Millisecond
|
||||
t.Cleanup(func() { screenPreviewTimeout = old })
|
||||
|
||||
rig := newScreenRig(t, "0004")
|
||||
ch := rig.call(`{"id":"1001"}`)
|
||||
reqID, _ := rig.nextRequest()
|
||||
c := rig.wait(ch)
|
||||
if c.err == nil || c.err.Code != CodeTimeout {
|
||||
t.Fatalf("error = %+v, want -32001", c.err)
|
||||
}
|
||||
|
||||
rig.s.previews.mu.Lock()
|
||||
pending := len(rig.s.previews.byDevice)
|
||||
rig.s.previews.mu.Unlock()
|
||||
if pending != 0 {
|
||||
t.Fatalf("%d preview entries left after the timeout", pending)
|
||||
}
|
||||
// A late reply is consumed and discarded; it must not resurrect the entry.
|
||||
rig.s.OnPacket(rig.main, previewPacket(reqID, screenPreviewStatusOK, screenPreviewFmtJPEG, 1, 1, []byte{0xFF, 0xD8, 0xFF, 0xD9}))
|
||||
rig.s.previews.mu.Lock()
|
||||
pending = len(rig.s.previews.byDevice)
|
||||
rig.s.previews.mu.Unlock()
|
||||
if pending != 0 {
|
||||
t.Fatalf("%d preview entries after a late reply", pending)
|
||||
}
|
||||
}
|
||||
|
||||
func TestScreenshotRequiresCapability(t *testing.T) {
|
||||
rig := newScreenRig(t, "")
|
||||
c := rig.wait(rig.call(`{"id":"1001"}`))
|
||||
if c.err == nil || c.err.Code != CodeUnsupported {
|
||||
t.Fatalf("error = %+v, want -32005 for a client without CLIENT_CAP_SCREEN_PREVIEW", c.err)
|
||||
}
|
||||
if len(rig.writes) != 0 {
|
||||
t.Fatal("a request was sent to a host that cannot answer it")
|
||||
}
|
||||
}
|
||||
|
||||
func TestScreenshotClampsMaxWidth(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
args string
|
||||
want uint16
|
||||
}{
|
||||
{"absent", `{"id":"1001"}`, screenPreviewDefaultWidth},
|
||||
{"zero", `{"id":"1001","max_width":0}`, screenPreviewDefaultWidth},
|
||||
{"negative", `{"id":"1001","max_width":-5}`, screenPreviewDefaultWidth},
|
||||
{"below floor", `{"id":"1001","max_width":10}`, screenPreviewMinWidth},
|
||||
{"in range", `{"id":"1001","max_width":800}`, 800},
|
||||
{"above ceiling", `{"id":"1001","max_width":5000}`, screenPreviewMaxWidth},
|
||||
}
|
||||
rig := newScreenRig(t, "0004")
|
||||
payload := solidJPEG(t, 2, 2, color.RGBA{0, 0, 255, 255})
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
ch := rig.call(tc.args)
|
||||
reqID, got := rig.nextRequest()
|
||||
if got != tc.want {
|
||||
t.Fatalf("maxWidth = %d, want %d", got, tc.want)
|
||||
}
|
||||
rig.s.OnPacket(rig.main, previewPacket(reqID, screenPreviewStatusOK, screenPreviewFmtJPEG, 2, 2, payload))
|
||||
if c := rig.wait(ch); c.err != nil {
|
||||
t.Fatalf("call error: %+v", c.err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestScreenshotRejectsRegionParams(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
args string
|
||||
code int
|
||||
}{
|
||||
{"mode region", `{"id":"1001","mode":"region"}`, CodeUnsupported},
|
||||
{"mode window", `{"id":"1001","mode":"window"}`, CodeUnsupported},
|
||||
{"mode monitor", `{"id":"1001","mode":"monitor"}`, CodeUnsupported},
|
||||
{"hwnd", `{"id":"1001","hwnd":123}`, CodeUnsupported},
|
||||
{"hwnd string", `{"id":"1001","hwnd":"0x1F"}`, CodeUnsupported},
|
||||
{"x", `{"id":"1001","x":5}`, CodeUnsupported},
|
||||
{"y", `{"id":"1001","y":5}`, CodeUnsupported},
|
||||
{"width", `{"id":"1001","width":100}`, CodeUnsupported},
|
||||
{"height", `{"id":"1001","height":100}`, CodeUnsupported},
|
||||
{"monitor", `{"id":"1001","monitor":0}`, CodeUnsupported},
|
||||
{"invalid mode", `{"id":"1001","mode":"bogus"}`, CodeInvalidParams},
|
||||
}
|
||||
rig := newScreenRig(t, "0004")
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
c := rig.wait(rig.call(tc.args))
|
||||
if c.err == nil || c.err.Code != tc.code {
|
||||
t.Fatalf("error = %+v, want code %d", c.err, tc.code)
|
||||
}
|
||||
})
|
||||
}
|
||||
if len(rig.writes) != 0 {
|
||||
t.Fatal("a request was sent for a rejected capture mode")
|
||||
}
|
||||
}
|
||||
|
||||
func TestScreenshotRejectsBadArgs(t *testing.T) {
|
||||
rig := newScreenRig(t, "0004")
|
||||
cases := []struct {
|
||||
name string
|
||||
args string
|
||||
code int
|
||||
}{
|
||||
{"missing id", `{}`, CodeInvalidParams},
|
||||
{"non-decimal id", `{"id":"abc"}`, CodeInvalidParams},
|
||||
{"max_width type", `{"id":"1001","max_width":"wide"}`, CodeInvalidParams},
|
||||
{"offline", `{"id":"9999"}`, CodeOffline},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
c := rig.wait(rig.call(tc.args))
|
||||
if c.err == nil || c.err.Code != tc.code {
|
||||
t.Fatalf("error = %+v, want code %d", c.err, tc.code)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestScreenshotWithoutHub(t *testing.T) {
|
||||
s := New(Config{Token: testToken})
|
||||
defer s.Close()
|
||||
res, rerr := s.callGetScreenshot(context.Background(), []byte(`{"id":"1"}`))
|
||||
if res != nil || rerr == nil || rerr.Code != CodeInternal {
|
||||
t.Fatalf("res=%v err=%+v, want -32000 without a hub", res, rerr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseScreenPreviewRsp(t *testing.T) {
|
||||
valid := previewPacket(7, screenPreviewStatusOK, screenPreviewFmtJPEG, 2, 3, []byte{1, 2, 3, 4})
|
||||
if rsp, err := parseScreenPreviewRsp(valid); err != nil || rsp.reqID != 7 || len(rsp.reply.payload) != 4 {
|
||||
t.Fatalf("valid packet: rsp=%+v err=%v", rsp, err)
|
||||
}
|
||||
|
||||
// A metadata tail after the declared payload is legal and ignored.
|
||||
withMeta := append(append([]byte(nil), valid...), make([]byte, 24)...)
|
||||
rsp, err := parseScreenPreviewRsp(withMeta)
|
||||
if err != nil || len(rsp.reply.payload) != 4 {
|
||||
t.Fatalf("packet with meta tail: rsp=%+v err=%v", rsp, err)
|
||||
}
|
||||
|
||||
short := valid[:screenPreviewRspHeaderLen-1]
|
||||
if _, err := parseScreenPreviewRsp(short); err == nil {
|
||||
t.Fatal("accepted a packet shorter than the header")
|
||||
}
|
||||
wrongToken := append([]byte(nil), valid...)
|
||||
wrongToken[0] = protocol.TokenNextScreen
|
||||
if _, err := parseScreenPreviewRsp(wrongToken); err == nil {
|
||||
t.Fatal("accepted a packet with the wrong token")
|
||||
}
|
||||
overrun := append([]byte(nil), valid...)
|
||||
binary.LittleEndian.PutUint32(overrun[screenPreviewOffBytes:], 99)
|
||||
if _, err := parseScreenPreviewRsp(overrun); err == nil {
|
||||
t.Fatal("accepted a packet whose byte count overruns the packet")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBGRXToJPEGRejectsMalformed(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
src []byte
|
||||
w, h int
|
||||
}{
|
||||
{"zero width", make([]byte, 16), 0, 4},
|
||||
{"short frame", make([]byte, 15), 2, 2},
|
||||
{"long frame", make([]byte, 17), 2, 2},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if _, err := bgrxToJPEG(tc.src, tc.w, tc.h); err == nil {
|
||||
t.Fatal("converted a malformed BGRX frame")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnPacketIgnoresOtherTokens(t *testing.T) {
|
||||
rig := newScreenRig(t, "0004")
|
||||
if rig.s.OnPacket(rig.main, nil) {
|
||||
t.Fatal("consumed an empty packet")
|
||||
}
|
||||
if rig.s.OnPacket(rig.main, []byte{protocol.TokenNextScreen, 0}) {
|
||||
t.Fatal("consumed a screen frame")
|
||||
}
|
||||
if !rig.s.OnPacket(rig.main, []byte{protocol.TokenScreenPreviewRsp}) {
|
||||
t.Fatal("did not consume (and log) a truncated preview response")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,416 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/subtle"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"runtime/debug"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/devicehistory"
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/logger"
|
||||
)
|
||||
|
||||
const (
|
||||
// protocolVersion is the MCP revision this endpoint speaks. It matches the
|
||||
// Win32 server and mcp/tools.json.
|
||||
protocolVersion = "2025-06-18"
|
||||
|
||||
// maxBodyBytes bounds a single JSON-RPC request. tools/call arguments can
|
||||
// carry a file payload for uploads, so 8 MiB is generous but finite.
|
||||
maxBodyBytes = 8 << 20
|
||||
|
||||
defaultTermIdle = 180 * time.Second
|
||||
defaultMaxConcurrency = 16
|
||||
defaultReadMax = 2 << 20
|
||||
|
||||
// termSweepInterval is how often the reaper looks for sessions a model
|
||||
// forgot to close. The sweep itself is cheap: one mutex per session.
|
||||
termSweepInterval = 30 * time.Second
|
||||
)
|
||||
|
||||
// Config is filled by cmd/main.go from the YAMA_MCP_* environment variables;
|
||||
// the package itself never reads the environment, so tests are deterministic.
|
||||
type Config struct {
|
||||
Token string // static bearer token; empty disables the endpoint
|
||||
Readonly bool // hide (and refuse) write tools
|
||||
TermIdle time.Duration // terminal session idle reaping
|
||||
MaxConcurrency int // global in-flight tools/call cap
|
||||
ReadMax int64 // read_file whole-file limit
|
||||
Version string // serverInfo.version
|
||||
StartedAt time.Time // reported by get_server_status
|
||||
Log *logger.Logger
|
||||
|
||||
// Server-side state the local read tools answer from. A nil Hub means the
|
||||
// endpoint was built without a device registry: the host tools then fail
|
||||
// with -32000 instead of reporting an empty (and misleading) list.
|
||||
Hub *hub.Hub
|
||||
History *devicehistory.Store // nil: no offline history to merge
|
||||
AuditPath string // "" = audit file disabled (YAMA_AUDIT_LOG=off)
|
||||
Port int // web/MCP listening port, for get_server_status
|
||||
Bind string // listening address, for get_server_status
|
||||
}
|
||||
|
||||
// toolFunc implements one tools/call. It returns either a result value or a
|
||||
// JSON-RPC error; the caller wraps whichever it gets.
|
||||
type toolFunc func(ctx context.Context, args json.RawMessage) (any, *rpcError)
|
||||
|
||||
// Server is the stateless MCP endpoint. It owns the embedded tool definitions
|
||||
// and the tool handler table; per-device sessions arrive in later milestones.
|
||||
type Server struct {
|
||||
cfg Config
|
||||
log *logger.Logger
|
||||
tools *toolSet
|
||||
handlers map[string]toolFunc
|
||||
|
||||
// locks serialises device operations; sem bounds the global in-flight
|
||||
// tools/call count. Both are non-blocking: contention is -32003, not a
|
||||
// queue, so a slow call cannot pile up requests behind it (design §9).
|
||||
locks *deviceLocks
|
||||
sem chan struct{}
|
||||
sessions *sessionTable
|
||||
previews *previewTable // in-flight get_screenshot requests, keyed by device
|
||||
files *fileTable // in-flight list_files requests, keyed by device
|
||||
transfers *transferTable // in-flight read_file V2 transfers, keyed by device
|
||||
|
||||
// stop ends the idle reaper and reaperDone reports that it returned;
|
||||
// closeOnce makes Close idempotent (tests call it both explicitly and from
|
||||
// Cleanup). reaperDone is nil when no reaper was started (hub-less server).
|
||||
stop chan struct{}
|
||||
reaperDone chan struct{}
|
||||
closeOnce sync.Once
|
||||
}
|
||||
|
||||
// New builds the endpoint. Zero-valued knobs fall back to the documented
|
||||
// defaults so a partially-filled Config from cmd is still safe.
|
||||
func New(cfg Config) *Server {
|
||||
if cfg.TermIdle <= 0 {
|
||||
cfg.TermIdle = defaultTermIdle
|
||||
}
|
||||
if cfg.MaxConcurrency <= 0 {
|
||||
cfg.MaxConcurrency = defaultMaxConcurrency
|
||||
}
|
||||
if cfg.ReadMax <= 0 {
|
||||
cfg.ReadMax = defaultReadMax
|
||||
}
|
||||
if cfg.StartedAt.IsZero() {
|
||||
cfg.StartedAt = time.Now()
|
||||
}
|
||||
// Version is left exactly as injected: it may be empty in a build without
|
||||
// git/ldflags. The initialize response substitutes "dev" for such builds;
|
||||
// get_server_status reports the empty string rather than inventing a
|
||||
// version (design §3.2).
|
||||
if cfg.Log == nil {
|
||||
cfg.Log = logger.New(logger.Config{Level: logger.LevelError})
|
||||
}
|
||||
s := &Server{
|
||||
cfg: cfg,
|
||||
log: cfg.Log,
|
||||
tools: buildToolSet(toolsJSON),
|
||||
handlers: make(map[string]toolFunc),
|
||||
locks: newDeviceLocks(),
|
||||
sem: make(chan struct{}, cfg.MaxConcurrency),
|
||||
previews: newPreviewTable(),
|
||||
files: newFileTable(),
|
||||
transfers: newTransferTable(),
|
||||
stop: make(chan struct{}),
|
||||
}
|
||||
if cfg.Hub != nil {
|
||||
s.sessions = newSessionTable(cfg.Hub)
|
||||
} else {
|
||||
s.sessions = newSessionTable(nil)
|
||||
}
|
||||
s.registerLocalTools()
|
||||
s.registerScreenTools()
|
||||
s.registerFileTools()
|
||||
s.registerTerminalTools()
|
||||
if cfg.Hub != nil {
|
||||
// No hub means no shell can ever be opened, so there is nothing to
|
||||
// reap; skipping the goroutine keeps hub-less servers inert.
|
||||
s.reaperDone = make(chan struct{})
|
||||
go s.sweepLoop()
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// Enabled reports whether /mcp should be registered. An empty token disables
|
||||
// the endpoint entirely: the route is not mounted, so it 404s like any other
|
||||
// unknown path.
|
||||
func (s *Server) Enabled() bool { return s != nil && s.cfg.Token != "" }
|
||||
|
||||
// Close releases resources held by long-lived tool state: the reaper stops and
|
||||
// every terminal session MCP owns is torn down and the shell told to exit.
|
||||
func (s *Server) Close() {
|
||||
s.closeOnce.Do(func() {
|
||||
close(s.stop)
|
||||
if s.reaperDone != nil {
|
||||
<-s.reaperDone
|
||||
}
|
||||
s.sessions.closeAll()
|
||||
})
|
||||
}
|
||||
|
||||
// sweepLoop reclaims terminal sessions nobody closed. The interval shrinks to
|
||||
// TermIdle when that is shorter, so a test (or a deliberately tiny idle knob)
|
||||
// sees the sweep fire on schedule instead of up to 30 s late.
|
||||
func (s *Server) sweepLoop() {
|
||||
defer close(s.reaperDone)
|
||||
ticker := time.NewTicker(min(termSweepInterval, s.cfg.TermIdle))
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-s.stop:
|
||||
return
|
||||
case now := <-ticker.C:
|
||||
s.sessions.sweepIdle(now, s.cfg.TermIdle)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Handle serves POST /mcp. Transport-level failures (405/401/413) are answered
|
||||
// here; everything after a successfully parsed JSON-RPC request returns HTTP
|
||||
// 200 and carries the error in the JSON-RPC body.
|
||||
func (s *Server) Handle(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
w.Header().Set("Allow", http.MethodPost)
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
if !s.authorized(r) {
|
||||
// The MCP transport spec expects a transport-level failure here, not a
|
||||
// JSON-RPC error object, so the client can distinguish "bad credential"
|
||||
// from "server rejected the call".
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="mcp"`)
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxBodyBytes))
|
||||
if err != nil {
|
||||
var tooLarge *http.MaxBytesError
|
||||
if errors.As(err, &tooLarge) {
|
||||
http.Error(w, "request body too large", http.StatusRequestEntityTooLarge)
|
||||
return
|
||||
}
|
||||
http.Error(w, "failed to read request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
s.serveRPC(w, r, body)
|
||||
}
|
||||
|
||||
// serveRPC parses and dispatches one JSON-RPC request, writing the response.
|
||||
func (s *Server) serveRPC(w http.ResponseWriter, r *http.Request, body []byte) {
|
||||
body = bytes.TrimSpace(body)
|
||||
if len(body) == 0 {
|
||||
writeRPC(w, errorResponse(nil, errf(CodeParseError, "Parse error")))
|
||||
return
|
||||
}
|
||||
// Batch arrays are rejected rather than processed: gating, auditing and
|
||||
// locking assume one call at a time (design §4.1).
|
||||
if body[0] == '[' {
|
||||
writeRPC(w, errorResponse(nil, errf(CodeInvalidRequest, "batch requests are not supported")))
|
||||
return
|
||||
}
|
||||
|
||||
var req request
|
||||
if err := json.Unmarshal(body, &req); err != nil {
|
||||
writeRPC(w, errorResponse(nil, errf(CodeParseError, "Parse error")))
|
||||
return
|
||||
}
|
||||
if req.Method == "" {
|
||||
writeRPC(w, errorResponse(req.ID, errf(CodeInvalidRequest, "Invalid Request")))
|
||||
return
|
||||
}
|
||||
// Notifications (notifications/initialized, notifications/cancelled, …)
|
||||
// get no body. The MCP spec allows 202; we use 204 so there is nothing to
|
||||
// mistake for a result.
|
||||
if req.isNotification() {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
|
||||
result, rerr := s.dispatch(r.Context(), &req)
|
||||
if rerr != nil {
|
||||
writeRPC(w, errorResponse(req.ID, rerr))
|
||||
return
|
||||
}
|
||||
writeRPC(w, resultResponse(req.ID, result))
|
||||
}
|
||||
|
||||
// dispatch routes one method. Unknown methods are -32601; the MCP client is
|
||||
// expected to treat that as "this server does not support the feature".
|
||||
func (s *Server) dispatch(ctx context.Context, req *request) (any, *rpcError) {
|
||||
switch req.Method {
|
||||
case "initialize":
|
||||
return s.initializeResult(), nil
|
||||
case "ping":
|
||||
return struct{}{}, nil
|
||||
case "tools/list":
|
||||
return toolsListResult{Tools: s.tools.visible(s.cfg.Readonly)}, nil
|
||||
case "tools/call":
|
||||
return s.callTool(ctx, req.Params)
|
||||
default:
|
||||
return nil, errf(CodeMethodNotFound, "Method not found: %s", req.Method)
|
||||
}
|
||||
}
|
||||
|
||||
type serverInfo struct {
|
||||
Name string `json:"name"`
|
||||
Version string `json:"version"`
|
||||
}
|
||||
|
||||
type toolsCapability struct {
|
||||
ListChanged bool `json:"listChanged"`
|
||||
}
|
||||
|
||||
type serverCapabilities struct {
|
||||
Tools toolsCapability `json:"tools"`
|
||||
}
|
||||
|
||||
type initializeResult struct {
|
||||
ProtocolVersion string `json:"protocolVersion"`
|
||||
Capabilities serverCapabilities `json:"capabilities"`
|
||||
ServerInfo serverInfo `json:"serverInfo"`
|
||||
Instructions string `json:"instructions"`
|
||||
}
|
||||
|
||||
// initializeResult mirrors the Win32 server: same protocol version, same
|
||||
// serverInfo.name ("yama") so clients do not special-case the Go backend.
|
||||
// Differences are stated in instructions, which models read.
|
||||
func (s *Server) initializeResult() initializeResult {
|
||||
// "dev" is a serverInfo-only marker for an unversioned build; the status
|
||||
// tool keeps the raw (empty) value.
|
||||
version := s.cfg.Version
|
||||
if version == "" {
|
||||
version = "dev"
|
||||
}
|
||||
return initializeResult{
|
||||
ProtocolVersion: protocolVersion,
|
||||
Capabilities: serverCapabilities{Tools: toolsCapability{ListChanged: false}},
|
||||
ServerInfo: serverInfo{Name: "yama", Version: version},
|
||||
Instructions: serverInstructions,
|
||||
}
|
||||
}
|
||||
|
||||
// callTool parses tools/call, enforces visibility, takes the concurrency and
|
||||
// device gates, then hands the raw arguments to the handler. Readonly mode
|
||||
// refuses hidden write tools with -32006 rather than pretending they do not
|
||||
// exist. Every call that names a tool is audited, including rejected ones.
|
||||
func (s *Server) callTool(ctx context.Context, raw json.RawMessage) (result any, rerr *rpcError) {
|
||||
if len(raw) == 0 || string(raw) == "null" {
|
||||
return nil, errf(CodeInvalidParams, "tools/call requires params")
|
||||
}
|
||||
var params toolCallParams
|
||||
if err := json.Unmarshal(raw, ¶ms); err != nil {
|
||||
return nil, errf(CodeInvalidParams, "invalid params: %v", err)
|
||||
}
|
||||
if params.Name == "" {
|
||||
return nil, errf(CodeInvalidParams, "tool name is required")
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
deviceID := ""
|
||||
if !localReadTools[params.Name] {
|
||||
deviceID = deviceIDFromArgs(params.Arguments)
|
||||
}
|
||||
defer func() {
|
||||
// Convert a handler panic into -32000 instead of letting net/http drop
|
||||
// the connection, and make sure the audit record says the call failed:
|
||||
// without this the zero-valued rerr would be logged as success.
|
||||
if p := recover(); p != nil {
|
||||
s.log.Error("panic in MCP tool %s: %v\n%s", params.Name, p, debug.Stack())
|
||||
result = nil
|
||||
rerr = errf(CodeInternal, "internal error in tool %s", params.Name)
|
||||
}
|
||||
s.auditCall(params.Name, deviceID, params.Arguments, result, rerr, time.Since(start))
|
||||
}()
|
||||
|
||||
if !s.tools.known(params.Name) {
|
||||
return nil, errf(CodeMethodNotFound, "unknown tool: %s", params.Name)
|
||||
}
|
||||
if s.cfg.Readonly && writeTools[params.Name] {
|
||||
return nil, errf(CodeDenied, "tool %s is disabled in readonly mode", params.Name)
|
||||
}
|
||||
handler, ok := s.handlers[params.Name]
|
||||
if !ok {
|
||||
// The tool is listed but this build does not implement it yet. This is
|
||||
// a temporary state between milestones, not a client mistake.
|
||||
return nil, errf(CodeInternal, "tool %s is not implemented by this server build", params.Name)
|
||||
}
|
||||
|
||||
// Global slot first: a call that would be rejected for concurrency must
|
||||
// not squat on a device lock while it fails.
|
||||
select {
|
||||
case s.sem <- struct{}{}:
|
||||
defer func() { <-s.sem }()
|
||||
default:
|
||||
return nil, errf(CodeBusy, "Server busy: too many concurrent MCP calls (limit %d)",
|
||||
s.cfg.MaxConcurrency)
|
||||
}
|
||||
|
||||
if deviceID != "" && !unlockedTools[params.Name] {
|
||||
held, acquired := s.locks.tryAcquire(deviceID, params.Name)
|
||||
if !acquired {
|
||||
return nil, errf(CodeBusy, "%s", busyMessage(held))
|
||||
}
|
||||
defer s.locks.release(deviceID)
|
||||
}
|
||||
|
||||
return handler(ctx, params.Arguments)
|
||||
}
|
||||
|
||||
// authorized compares the bearer token without leaking its length or content
|
||||
// through timing. A missing or different-length header fails immediately, but
|
||||
// no branch reveals how much of the token matched.
|
||||
func (s *Server) authorized(r *http.Request) bool {
|
||||
const prefix = "Bearer "
|
||||
// An empty configured token would otherwise match an empty credential;
|
||||
// the route is not mounted in that case, but keep the check safe anyway.
|
||||
if s.cfg.Token == "" {
|
||||
return false
|
||||
}
|
||||
header := r.Header.Get("Authorization")
|
||||
if !strings.HasPrefix(header, prefix) {
|
||||
return false
|
||||
}
|
||||
got := header[len(prefix):]
|
||||
if len(got) != len(s.cfg.Token) {
|
||||
return false
|
||||
}
|
||||
return subtle.ConstantTimeCompare([]byte(got), []byte(s.cfg.Token)) == 1
|
||||
}
|
||||
|
||||
// writeRPC writes a single JSON-RPC response. Marshal failures are impossible
|
||||
// for the value types used here, but are reported rather than dropping the
|
||||
// connection silently.
|
||||
func writeRPC(w http.ResponseWriter, resp *response) {
|
||||
body, err := json.Marshal(resp)
|
||||
if err != nil {
|
||||
http.Error(w, "failed to encode response", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write(body)
|
||||
}
|
||||
|
||||
// serverInstructions is the Go backend's initialization guide. The Win32 MCP
|
||||
// server ships a much larger text covering its 54 tools; this one describes
|
||||
// only what the minimal Go server exposes and where it behaves differently.
|
||||
const serverInstructions = `这是 YAMA 服务端的 MCP 端点(Go 实现)。工具集比 Windows 主控端小,以下规则优先于各工具的描述。
|
||||
|
||||
1) 主机 id 是 64 位无符号十进制字符串,由服务端分配,无法从 IP 或计算机名推算。需要 id 时先用 list_hosts 取得,拿不到就向用户确认,不要猜。
|
||||
2) tools/list 只返回当前模式允许的工具;只读模式隐藏 terminal_exec / terminal_close,直接调用被隐藏的工具返回 -32006。
|
||||
3) 错误码与动作:-32002 主机离线或不存在(先刷新列表);-32003 主机忙(同一台主机同一时刻只允许一个操作,重试无效,等前一个结束);-32004 命令未送达(多为链路瞬断,可重试一次);-32005 主机不支持该能力(换主机或换工具,改参数无用;老客户端不声明 CLIENT_CAP_V2 时 read_file 也返回 -32005,需升级客户端);-32006 只读模式拒绝(terminal_exec / terminal_close;重试无效,需管理员关掉只读);-32001 多为超时,也可能是工具自身失败或已被取消:工具支持 timeout_ms 时先加大重试一次;子连接/会话没建立或同一主机反复超时通常重试无效(主机卡住、链路断或老客户端不认命令);message 写 Request cancelled 的表示客户端已中止,可直接重试;-32602 参数错误(按 message 修正)。
|
||||
4) get_screenshot 只支持 mode=screen(按链路状况自适应缩放,max_width 省略时最大 1024);本实现没有 CLIENT_CAP_SCREEN_REGION 扩展,mode=region/window/monitor 与区域类参数一律返回 -32005。
|
||||
5) list_files / read_file 走文件传输通道;list_files 支持 ids 批量(最多 50 台、整批 50 秒)。read_file 只接受单个普通文件且整文件不超过 2 MiB,目录用 list_files;本实现没有 download_file / search_file,超限文件只能改用 terminal_exec 分段查看,或连 Windows 主控端的完整服务端。
|
||||
6) terminal_exec 需要客户端支持终端(CLIENT_CAP_TERMINAL),会在目标主机上创建持久会话;用完调用 terminal_close 释放,闲置会话由服务端回收。调用被取消时返回的 message 里带 session_id,可用它轮询或关闭。
|
||||
7) 本实现不维护备注与授权状态:list_hosts / get_host_detail 不返回 remark/authStatus/tls;get_server_status 只报版本、在线台数与监听地址,没有 switches/sessions。
|
||||
8) 列表与详情都是调用时刻的快照,主机可能在操作期间掉线;写操作前先读一次现状,动作后再复核。`
|
||||
@@ -0,0 +1,395 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/logger"
|
||||
)
|
||||
|
||||
const testToken = "0123456789abcdef0123456789abcdef"
|
||||
|
||||
func testServer(t *testing.T, readonly bool) *Server {
|
||||
t.Helper()
|
||||
log := logger.New(logger.Config{
|
||||
Level: logger.LevelError,
|
||||
File: filepath.Join(t.TempDir(), "mcp-test.log"),
|
||||
})
|
||||
return New(Config{
|
||||
Token: testToken,
|
||||
Readonly: readonly,
|
||||
Version: "test-1.0",
|
||||
Log: log,
|
||||
})
|
||||
}
|
||||
|
||||
// rpcEnvelope decodes a JSON-RPC response without committing to a result type.
|
||||
type rpcEnvelope struct {
|
||||
JSONRPC string `json:"jsonrpc"`
|
||||
ID json.RawMessage `json:"id"`
|
||||
Result json.RawMessage `json:"result"`
|
||||
Error *rpcError `json:"error"`
|
||||
}
|
||||
|
||||
func call(t *testing.T, s *Server, body string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
rec := httptest.NewRecorder()
|
||||
s.Handle(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
func authedCall(t *testing.T, s *Server, body string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(body))
|
||||
req.Header.Set("Authorization", "Bearer "+testToken)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
rec := httptest.NewRecorder()
|
||||
s.Handle(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
func decodeEnvelope(t *testing.T, rec *httptest.ResponseRecorder) rpcEnvelope {
|
||||
t.Helper()
|
||||
var env rpcEnvelope
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &env); err != nil {
|
||||
t.Fatalf("response is not JSON: %v\nbody: %s", err, rec.Body.String())
|
||||
}
|
||||
return env
|
||||
}
|
||||
|
||||
func TestEnabledRequiresToken(t *testing.T) {
|
||||
if New(Config{}).Enabled() {
|
||||
t.Fatal("endpoint without a token must report disabled")
|
||||
}
|
||||
if !testServer(t, false).Enabled() {
|
||||
t.Fatal("endpoint with a token must report enabled")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuth(t *testing.T) {
|
||||
s := testServer(t, false)
|
||||
body := `{"jsonrpc":"2.0","id":1,"method":"ping"}`
|
||||
|
||||
t.Run("missing", func(t *testing.T) {
|
||||
rec := call(t, s, body)
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("status = %d, want 401", rec.Code)
|
||||
}
|
||||
if got := rec.Header().Get("WWW-Authenticate"); !strings.Contains(got, "Bearer") {
|
||||
t.Fatalf("WWW-Authenticate = %q, want a Bearer challenge", got)
|
||||
}
|
||||
if strings.Contains(rec.Body.String(), "jsonrpc") {
|
||||
t.Fatalf("401 must not carry a JSON-RPC body: %s", rec.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("wrong same length", func(t *testing.T) {
|
||||
req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(body))
|
||||
req.Header.Set("Authorization", "Bearer "+strings.Repeat("f", len(testToken)))
|
||||
rec := httptest.NewRecorder()
|
||||
s.Handle(rec, req)
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("status = %d, want 401", rec.Code)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("wrong different length", func(t *testing.T) {
|
||||
req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(body))
|
||||
req.Header.Set("Authorization", "Bearer "+testToken+"x")
|
||||
rec := httptest.NewRecorder()
|
||||
s.Handle(rec, req)
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("status = %d, want 401", rec.Code)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("missing scheme", func(t *testing.T) {
|
||||
req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(body))
|
||||
req.Header.Set("Authorization", testToken)
|
||||
rec := httptest.NewRecorder()
|
||||
s.Handle(rec, req)
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("status = %d, want 401", rec.Code)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("correct", func(t *testing.T) {
|
||||
rec := authedCall(t, s, body)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200 (body: %s)", rec.Code, rec.Body.String())
|
||||
}
|
||||
if ct := rec.Header().Get("Content-Type"); !strings.HasPrefix(ct, "application/json") {
|
||||
t.Fatalf("Content-Type = %q, want application/json", ct)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestInitialize(t *testing.T) {
|
||||
s := testServer(t, false)
|
||||
rec := authedCall(t, s, `{"jsonrpc":"2.0","id":7,"method":"initialize"}`)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200", rec.Code)
|
||||
}
|
||||
env := decodeEnvelope(t, rec)
|
||||
if env.Error != nil {
|
||||
t.Fatalf("unexpected error: %+v", env.Error)
|
||||
}
|
||||
if string(env.ID) != "7" {
|
||||
t.Fatalf("id = %s, want 7", env.ID)
|
||||
}
|
||||
var result struct {
|
||||
ProtocolVersion string `json:"protocolVersion"`
|
||||
Capabilities struct {
|
||||
Tools struct {
|
||||
ListChanged bool `json:"listChanged"`
|
||||
} `json:"tools"`
|
||||
} `json:"capabilities"`
|
||||
ServerInfo struct {
|
||||
Name string `json:"name"`
|
||||
Version string `json:"version"`
|
||||
} `json:"serverInfo"`
|
||||
Instructions string `json:"instructions"`
|
||||
}
|
||||
if err := json.Unmarshal(env.Result, &result); err != nil {
|
||||
t.Fatalf("decode result: %v", err)
|
||||
}
|
||||
if result.ProtocolVersion != protocolVersion {
|
||||
t.Fatalf("protocolVersion = %q, want %q", result.ProtocolVersion, protocolVersion)
|
||||
}
|
||||
if result.Capabilities.Tools.ListChanged {
|
||||
t.Fatal("tools.listChanged must be false: the list is static")
|
||||
}
|
||||
if result.ServerInfo.Name != "yama" {
|
||||
t.Fatalf("serverInfo.name = %q, want yama", result.ServerInfo.Name)
|
||||
}
|
||||
if result.ServerInfo.Version != "test-1.0" {
|
||||
t.Fatalf("serverInfo.version = %q, want test-1.0", result.ServerInfo.Version)
|
||||
}
|
||||
if strings.TrimSpace(result.Instructions) == "" {
|
||||
t.Fatal("instructions must not be empty")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPing(t *testing.T) {
|
||||
s := testServer(t, false)
|
||||
env := decodeEnvelope(t, authedCall(t, s, `{"jsonrpc":"2.0","id":"abc","method":"ping"}`))
|
||||
if env.Error != nil {
|
||||
t.Fatalf("unexpected error: %+v", env.Error)
|
||||
}
|
||||
if string(env.ID) != `"abc"` {
|
||||
t.Fatalf("id = %s, want \"abc\" (string ids echo unchanged)", env.ID)
|
||||
}
|
||||
var result map[string]any
|
||||
if err := json.Unmarshal(env.Result, &result); err != nil {
|
||||
t.Fatalf("decode result: %v", err)
|
||||
}
|
||||
if len(result) != 0 {
|
||||
t.Fatalf("ping result = %v, want empty object", result)
|
||||
}
|
||||
}
|
||||
|
||||
func listTools(t *testing.T, s *Server) []json.RawMessage {
|
||||
t.Helper()
|
||||
env := decodeEnvelope(t, authedCall(t, s, `{"jsonrpc":"2.0","id":1,"method":"tools/list"}`))
|
||||
if env.Error != nil {
|
||||
t.Fatalf("tools/list error: %+v", env.Error)
|
||||
}
|
||||
var result struct {
|
||||
Tools []json.RawMessage `json:"tools"`
|
||||
}
|
||||
if err := json.Unmarshal(env.Result, &result); err != nil {
|
||||
t.Fatalf("decode result: %v", err)
|
||||
}
|
||||
return result.Tools
|
||||
}
|
||||
|
||||
// TestToolsListMatchesEmbedded pins the published definitions to the embedded
|
||||
// file: same order, same content, no annotations. tools_minimal.json in turn is
|
||||
// checked against mcp/tools.json by gen_go_tools.py --check.
|
||||
func TestToolsListMatchesEmbedded(t *testing.T) {
|
||||
var want []any
|
||||
if err := json.Unmarshal(toolsJSON, &want); err != nil {
|
||||
t.Fatalf("embedded tools: %v", err)
|
||||
}
|
||||
|
||||
for _, readonly := range []bool{false, true} {
|
||||
got := listTools(t, testServer(t, readonly))
|
||||
if readonly {
|
||||
if len(got) != 7 {
|
||||
t.Fatalf("readonly tools = %d, want 7", len(got))
|
||||
}
|
||||
} else if len(got) != len(want) {
|
||||
t.Fatalf("tools = %d, want %d", len(got), len(want))
|
||||
}
|
||||
|
||||
wantIdx := 0
|
||||
for _, raw := range got {
|
||||
var tool map[string]any
|
||||
if err := json.Unmarshal(raw, &tool); err != nil {
|
||||
t.Fatalf("tool is not an object: %v", err)
|
||||
}
|
||||
name, _ := tool["name"].(string)
|
||||
if _, ok := tool["annotations"]; ok {
|
||||
t.Fatalf("tool %s must not carry annotations (MFC compatibility)", name)
|
||||
}
|
||||
if readonly && (name == "terminal_exec" || name == "terminal_close") {
|
||||
t.Fatalf("readonly mode must hide %s", name)
|
||||
}
|
||||
|
||||
// Skip over tools the filter removed, keeping the order check.
|
||||
for wantIdx < len(want) && want[wantIdx].(map[string]any)["name"] != name {
|
||||
wantIdx++
|
||||
}
|
||||
if wantIdx == len(want) {
|
||||
t.Fatalf("tool %s is not in tools_minimal.json in this order", name)
|
||||
}
|
||||
if !reflect.DeepEqual(tool, want[wantIdx]) {
|
||||
t.Fatalf("tool %s differs from tools_minimal.json", name)
|
||||
}
|
||||
wantIdx++
|
||||
}
|
||||
if wantIdx != len(want) {
|
||||
t.Fatalf("filtered list stopped at %d of %d embedded tools", wantIdx, len(want))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotification(t *testing.T) {
|
||||
s := testServer(t, false)
|
||||
rec := authedCall(t, s, `{"jsonrpc":"2.0","method":"notifications/initialized"}`)
|
||||
if rec.Code != http.StatusNoContent {
|
||||
t.Fatalf("status = %d, want 204", rec.Code)
|
||||
}
|
||||
if rec.Body.Len() != 0 {
|
||||
t.Fatalf("notification response body = %q, want empty", rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnknownMethod(t *testing.T) {
|
||||
env := decodeEnvelope(t, authedCall(t, testServer(t, false),
|
||||
`{"jsonrpc":"2.0","id":1,"method":"does/not/exist"}`))
|
||||
if env.Error == nil || env.Error.Code != CodeMethodNotFound {
|
||||
t.Fatalf("error = %+v, want code %d", env.Error, CodeMethodNotFound)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTransportErrors(t *testing.T) {
|
||||
s := testServer(t, false)
|
||||
|
||||
t.Run("get", func(t *testing.T) {
|
||||
req := httptest.NewRequest(http.MethodGet, "/mcp", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+testToken)
|
||||
rec := httptest.NewRecorder()
|
||||
s.Handle(rec, req)
|
||||
if rec.Code != http.StatusMethodNotAllowed {
|
||||
t.Fatalf("status = %d, want 405", rec.Code)
|
||||
}
|
||||
if got := rec.Header().Get("Allow"); got != http.MethodPost {
|
||||
t.Fatalf("Allow = %q, want POST", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("delete", func(t *testing.T) {
|
||||
req := httptest.NewRequest(http.MethodDelete, "/mcp", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+testToken)
|
||||
rec := httptest.NewRecorder()
|
||||
s.Handle(rec, req)
|
||||
if rec.Code != http.StatusMethodNotAllowed {
|
||||
t.Fatalf("status = %d, want 405", rec.Code)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("batch", func(t *testing.T) {
|
||||
env := decodeEnvelope(t, authedCall(t, s,
|
||||
`[{"jsonrpc":"2.0","id":1,"method":"ping"},{"jsonrpc":"2.0","id":2,"method":"ping"}]`))
|
||||
if env.Error == nil || env.Error.Code != CodeInvalidRequest {
|
||||
t.Fatalf("error = %+v, want code %d", env.Error, CodeInvalidRequest)
|
||||
}
|
||||
if string(env.ID) != "null" {
|
||||
t.Fatalf("id = %s, want null", env.ID)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("oversize", func(t *testing.T) {
|
||||
body := `{"jsonrpc":"2.0","id":1,"method":"ping","params":"` +
|
||||
strings.Repeat("x", maxBodyBytes) + `"}`
|
||||
rec := authedCall(t, s, body)
|
||||
if rec.Code != http.StatusRequestEntityTooLarge {
|
||||
t.Fatalf("status = %d, want 413", rec.Code)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("parse error", func(t *testing.T) {
|
||||
env := decodeEnvelope(t, authedCall(t, s, `{"jsonrpc":`))
|
||||
if env.Error == nil || env.Error.Code != CodeParseError {
|
||||
t.Fatalf("error = %+v, want code %d", env.Error, CodeParseError)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("missing method", func(t *testing.T) {
|
||||
env := decodeEnvelope(t, authedCall(t, s, `{"jsonrpc":"2.0","id":1}`))
|
||||
if env.Error == nil || env.Error.Code != CodeInvalidRequest {
|
||||
t.Fatalf("error = %+v, want code %d", env.Error, CodeInvalidRequest)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestToolsCallGates(t *testing.T) {
|
||||
s := testServer(t, false)
|
||||
readonly := testServer(t, true)
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
srv *Server
|
||||
body string
|
||||
code int
|
||||
}{
|
||||
{
|
||||
name: "unknown tool",
|
||||
srv: s,
|
||||
body: `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"nope"}}`,
|
||||
code: CodeMethodNotFound,
|
||||
},
|
||||
{
|
||||
name: "missing name",
|
||||
srv: s,
|
||||
body: `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{}}`,
|
||||
code: CodeInvalidParams,
|
||||
},
|
||||
{
|
||||
name: "missing params",
|
||||
srv: s,
|
||||
body: `{"jsonrpc":"2.0","id":1,"method":"tools/call"}`,
|
||||
code: CodeInvalidParams,
|
||||
},
|
||||
{
|
||||
// testServer has no hub: the handler exists (M2) and must fail
|
||||
// loudly rather than report an empty device list.
|
||||
name: "local tool without device registry",
|
||||
srv: s,
|
||||
body: `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"list_hosts"}}`,
|
||||
code: CodeInternal,
|
||||
},
|
||||
{
|
||||
name: "readonly refuses write tool",
|
||||
srv: readonly,
|
||||
body: `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"terminal_exec"}}`,
|
||||
code: CodeDenied,
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
env := decodeEnvelope(t, authedCall(t, tc.srv, tc.body))
|
||||
if env.Error == nil || env.Error.Code != tc.code {
|
||||
t.Fatalf("error = %+v, want code %d", env.Error, tc.code)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,374 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/protocol"
|
||||
)
|
||||
|
||||
// errNoDeviceHub means the endpoint was built without a device registry, so
|
||||
// no shell can be opened. Mirrors the local tools' nil-Hub behaviour (-32000).
|
||||
var errNoDeviceHub = errors.New("no device hub configured")
|
||||
|
||||
// terminalHub is the slice of *hub.Hub the session table needs. An interface
|
||||
// keeps the table testable and documents that MCP never touches a terminal
|
||||
// sub-connection directly — it goes through the hub's single-viewer lease.
|
||||
type terminalHub interface {
|
||||
OpenTerminalSessionLease(deviceID string) (uint64, error)
|
||||
CloseTerminalSessionLease(deviceID string, lease uint64) bool
|
||||
HasTerminalSession(deviceID string) bool
|
||||
SendToTerminal(deviceID string, data []byte) error
|
||||
}
|
||||
|
||||
// sessionTable owns the MCP-created terminal sessions, keyed by device. A
|
||||
// session is created before hub.OpenTerminalSession so OnTerminalReady (which
|
||||
// can fire on another goroutine as soon as the client answers) always finds
|
||||
// the object; a failed open rolls the entry back.
|
||||
type sessionTable struct {
|
||||
hub terminalHub
|
||||
|
||||
mu sync.Mutex
|
||||
byDevice map[string]*termSession
|
||||
}
|
||||
|
||||
func newSessionTable(h terminalHub) *sessionTable {
|
||||
return &sessionTable{hub: h, byDevice: make(map[string]*termSession)}
|
||||
}
|
||||
|
||||
func (t *sessionTable) get(deviceID string) *termSession {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
return t.byDevice[deviceID]
|
||||
}
|
||||
|
||||
// errSessionClosed means the session disappeared while its open was in
|
||||
// flight (shutdown or an explicit close raced it).
|
||||
var errSessionClosed = errors.New("terminal session closed during open")
|
||||
|
||||
// open claims a shell for the device. ErrTerminalBusy comes back when a web
|
||||
// console (or another MCP call) already holds it; the hub enforces the
|
||||
// single-viewer lease, so v1 never pre-empts a human.
|
||||
func (t *sessionTable) open(deviceID string) (*termSession, error) {
|
||||
if t.hub == nil {
|
||||
return nil, errNoDeviceHub
|
||||
}
|
||||
t.mu.Lock()
|
||||
if _, ok := t.byDevice[deviceID]; ok {
|
||||
t.mu.Unlock()
|
||||
return nil, hub.ErrTerminalBusy
|
||||
}
|
||||
sess := newTermSession(deviceID)
|
||||
// Until the hub call returns, any OnTerminalClosed for this device belongs
|
||||
// to the viewer that just released the lease, not to this session.
|
||||
sess.opening = true
|
||||
t.byDevice[deviceID] = sess
|
||||
t.mu.Unlock()
|
||||
|
||||
lease, err := t.hub.OpenTerminalSessionLease(deviceID)
|
||||
if err != nil {
|
||||
t.mu.Lock()
|
||||
delete(t.byDevice, deviceID)
|
||||
t.mu.Unlock()
|
||||
sess.mu.Lock()
|
||||
sess.opening = false
|
||||
sess.closed = true
|
||||
sess.closeReason = "open failed"
|
||||
sess.cond.Broadcast()
|
||||
sess.mu.Unlock()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
sess.mu.Lock()
|
||||
sess.opening = false
|
||||
sess.lease = lease
|
||||
sess.mu.Unlock()
|
||||
|
||||
// An explicit close (or shutdown) may have removed the entry while the hub
|
||||
// call was in flight. The hub lease is ours by now, so release it instead
|
||||
// of returning a session nobody can reach.
|
||||
t.mu.Lock()
|
||||
cur, ok := t.byDevice[deviceID]
|
||||
t.mu.Unlock()
|
||||
if !ok || cur != sess {
|
||||
t.hub.CloseTerminalSessionLease(deviceID, lease)
|
||||
return nil, errSessionClosed
|
||||
}
|
||||
return sess, nil
|
||||
}
|
||||
|
||||
// ready records that the shell sub-conn is bound. Called from the hub's TCP
|
||||
// read loop, so it must stay short (a mutex and a broadcast).
|
||||
func (t *sessionTable) ready(deviceID string, isPTY bool) {
|
||||
sess := t.get(deviceID)
|
||||
if sess == nil {
|
||||
return
|
||||
}
|
||||
sess.mu.Lock()
|
||||
sess.isPTY = isPTY
|
||||
sess.ready = true
|
||||
sess.lastUsed = time.Now()
|
||||
sess.cond.Broadcast()
|
||||
sess.mu.Unlock()
|
||||
}
|
||||
|
||||
// closed runs when the shell ends for any reason — device-side exit, sub-conn
|
||||
// drop, or an explicit teardown. Waiters wake up and deliver whatever output
|
||||
// is already buffered.
|
||||
//
|
||||
// A session with a command still in flight stays in the table even after the
|
||||
// shell is gone: the bytes it produced but nobody has polled yet must remain
|
||||
// reachable (MFC's closed branch keeps it for the same reason). The entry is
|
||||
// dropped by forget once the tail is delivered, or by the M4c idle reaper if
|
||||
// the model never comes back.
|
||||
func (t *sessionTable) closed(deviceID, reason string) {
|
||||
// A web console's teardown can race a fresh open: by the time this event is
|
||||
// delivered, the hub lease may already belong to a new MCP session. The hub
|
||||
// is the authority on whether a session still exists; if it does, the event
|
||||
// described the previous viewer and must not touch ours.
|
||||
if t.hub != nil && t.hub.HasTerminalSession(deviceID) {
|
||||
return
|
||||
}
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
sess, ok := t.byDevice[deviceID]
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
sess.mu.Lock()
|
||||
defer sess.mu.Unlock()
|
||||
if sess.opening {
|
||||
// Our own hub call has not returned yet, so any close for this device
|
||||
// still refers to whoever held the lease before us.
|
||||
return
|
||||
}
|
||||
if !sess.hasUndrainedLocked() {
|
||||
delete(t.byDevice, deviceID)
|
||||
}
|
||||
sess.closed = true
|
||||
sess.closeReason = reason
|
||||
sess.cond.Broadcast()
|
||||
}
|
||||
|
||||
// hasUndrainedLocked reports whether the in-flight command still has output the
|
||||
// client has not received. An ended shell delivers everything up to total, so a
|
||||
// running command's undelivered bytes all count.
|
||||
func (s *termSession) hasUndrainedLocked() bool {
|
||||
p := s.pending
|
||||
if p == nil {
|
||||
return false
|
||||
}
|
||||
end := s.total
|
||||
if p.done {
|
||||
end = min(p.outputEnd, s.total)
|
||||
}
|
||||
return s.delivered < end
|
||||
}
|
||||
|
||||
// forget removes a session whose shell is already gone. It must not call the
|
||||
// hub: the device may have reconnected and a new viewer may hold a fresh shell
|
||||
// by now.
|
||||
func (t *sessionTable) forget(deviceID string, want *termSession) {
|
||||
t.mu.Lock()
|
||||
if t.byDevice[deviceID] == want {
|
||||
delete(t.byDevice, deviceID)
|
||||
}
|
||||
t.mu.Unlock()
|
||||
}
|
||||
|
||||
// closeSession tears down the MCP-owned session for deviceID, if any. It is
|
||||
// idempotent: a call for a device MCP does not own returns false and leaves
|
||||
// the web console's session alone.
|
||||
func (t *sessionTable) closeSession(deviceID string) bool {
|
||||
return t.closeSessionIf(deviceID, nil)
|
||||
}
|
||||
|
||||
// closeSessionIf closes the device's session only if the table still holds
|
||||
// exactly want. The identity check matters for sweepIdle: between its scan
|
||||
// and the close, the stale session can be replaced by a fresh one.
|
||||
func (t *sessionTable) closeSessionIf(deviceID string, want *termSession) bool {
|
||||
return t.closeIf(deviceID, want, func(*termSession) string { return "closed" })
|
||||
}
|
||||
|
||||
// closeIf closes a session if decide says so. decide runs with both locks held
|
||||
// (table then session), so it must read only session fields and lock nothing:
|
||||
// the staleness reaper uses it to re-check under the same lock that deletes,
|
||||
// closing the scan-then-close window where a poll could refresh the session.
|
||||
// A returned "" cancels the close and nothing is touched.
|
||||
func (t *sessionTable) closeIf(deviceID string, want *termSession, decide func(*termSession) string) bool {
|
||||
t.mu.Lock()
|
||||
sess, ok := t.byDevice[deviceID]
|
||||
if !ok || (want != nil && sess != want) {
|
||||
t.mu.Unlock()
|
||||
return false
|
||||
}
|
||||
sess.mu.Lock()
|
||||
reason := decide(sess)
|
||||
if reason == "" {
|
||||
sess.mu.Unlock()
|
||||
t.mu.Unlock()
|
||||
return false
|
||||
}
|
||||
delete(t.byDevice, deviceID)
|
||||
wasClosed := sess.closed
|
||||
lease := sess.lease
|
||||
sess.closed = true
|
||||
sess.closeReason = reason
|
||||
sess.cond.Broadcast()
|
||||
sess.mu.Unlock()
|
||||
t.mu.Unlock()
|
||||
// A session that was already closed lost its hub lease when the close event
|
||||
// arrived; the hub may since have handed a fresh shell to another viewer (a
|
||||
// reconnected device). Only an explicit close of a live session may touch
|
||||
// it, and even then only the lease MCP itself opened (the generation check
|
||||
// in the hub), never whatever lease the device holds now.
|
||||
if t.hub != nil && !wasClosed && lease != 0 {
|
||||
t.hub.CloseTerminalSessionLease(deviceID, lease)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// termBusyMax bounds how long one command may hold a session with nobody
|
||||
// polling it. Without it a hung command — or a model that never comes back —
|
||||
// would lock the device's single terminal slot forever. MFC reclaims at the
|
||||
// same one-hour limit (McpServer.cpp:4674).
|
||||
const termBusyMax = time.Hour
|
||||
|
||||
// sweepIdle closes sessions whose last use is older than idle, plus live
|
||||
// commands that outlived termBusyMax. Intended for the periodic reaper: a
|
||||
// model that forgets terminal_close must not lock a human out of the device's
|
||||
// shell.
|
||||
//
|
||||
// A session with a live command (pending, not done) is skipped no matter how
|
||||
// quiet it is: a sleep or a slow download still owns the lease and must not be
|
||||
// reaped just because it printed nothing for a while. A session whose shell is
|
||||
// already gone is reaped on idle alone — its only remaining value is the
|
||||
// undelivered tail, and a model that never polls it must not pin the slot.
|
||||
// A session that never became ready is left alone: its open is still waiting
|
||||
// on a caller, which releases it (with a lease-checked close) on its own.
|
||||
func (t *sessionTable) sweepIdle(now time.Time, idle time.Duration) int {
|
||||
type entry struct {
|
||||
id string
|
||||
sess *termSession
|
||||
}
|
||||
var candidates []entry
|
||||
t.mu.Lock()
|
||||
for id, sess := range t.byDevice {
|
||||
candidates = append(candidates, entry{id, sess})
|
||||
}
|
||||
t.mu.Unlock()
|
||||
|
||||
n := 0
|
||||
for _, e := range candidates {
|
||||
if t.closeIf(e.id, e.sess, func(s *termSession) string {
|
||||
return s.reclaimReasonLocked(now, idle)
|
||||
}) {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// reclaimReasonLocked returns why the session should be dropped, or "" to keep
|
||||
// it. Callers hold s.mu.
|
||||
func (s *termSession) reclaimReasonLocked(now time.Time, idle time.Duration) string {
|
||||
inactive := func() string {
|
||||
return fmt.Sprintf(
|
||||
"Terminal session was reclaimed after %s of inactivity; call terminal_exec again to open a new one", idle)
|
||||
}
|
||||
if !s.ready {
|
||||
// Still waiting for the shell to bind; a caller holds this session and
|
||||
// releases it when its own wait ends. Reaping here would kill a live
|
||||
// open (and, if the lease changed hands meanwhile, someone else's).
|
||||
return ""
|
||||
}
|
||||
if s.closed {
|
||||
if now.Sub(s.lastUsed) >= idle {
|
||||
return inactive()
|
||||
}
|
||||
return ""
|
||||
}
|
||||
if p := s.pending; p != nil && !p.done {
|
||||
if now.Sub(p.busySince) >= termBusyMax {
|
||||
return fmt.Sprintf(
|
||||
"Terminal session was reclaimed after the command ran longer than %s; call terminal_exec again to open a new one", termBusyMax)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
if now.Sub(s.lastUsed) >= idle {
|
||||
return inactive()
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// closeAll drops every session; used at shutdown. The hub teardown is still
|
||||
// best-effort because the TCP servers may already be stopping.
|
||||
func (t *sessionTable) closeAll() {
|
||||
t.mu.Lock()
|
||||
ids := make([]string, 0, len(t.byDevice))
|
||||
for id := range t.byDevice {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
t.mu.Unlock()
|
||||
for _, id := range ids {
|
||||
t.closeSession(id)
|
||||
}
|
||||
}
|
||||
|
||||
// sessionIDFallback numbers ids when crypto/rand is unavailable. It is only a
|
||||
// last resort: ids are opaque to clients, and uniqueness matters, not secrecy.
|
||||
var sessionIDFallback atomic.Uint32
|
||||
|
||||
func newSessionID() string {
|
||||
var b [3]byte
|
||||
if _, err := rand.Read(b[:]); err == nil {
|
||||
return "s-" + hex.EncodeToString(b[:])
|
||||
}
|
||||
return fmt.Sprintf("s-%06x", sessionIDFallback.Add(1)&0xffffff)
|
||||
}
|
||||
|
||||
// Server implements hub.EventHandler so the endpoint can observe shell
|
||||
// traffic. Only the terminal events do work; the screen and lifecycle events
|
||||
// are ignored (the web console owns those views).
|
||||
var _ hub.EventHandler = (*Server)(nil)
|
||||
|
||||
func (s *Server) OnDeviceOnline(hub.DeviceInfo) {}
|
||||
func (s *Server) OnDeviceOffline(string) {}
|
||||
func (s *Server) OnDeviceUpdate(string, int, string) {}
|
||||
func (s *Server) OnScreenFrame(string, []byte, bool) {}
|
||||
func (s *Server) OnResolutionChange(string, int, int) {}
|
||||
func (s *Server) OnCursorChange(string, byte, int, int) {}
|
||||
func (s *Server) OnClipboardText(string, string) {}
|
||||
func (s *Server) OnTerminalReady(deviceID string, isPTY bool) { s.sessions.ready(deviceID, isPTY) }
|
||||
func (s *Server) OnTerminalClosed(deviceID, reason string) { s.sessions.closed(deviceID, reason) }
|
||||
|
||||
// OnTerminalData runs on the device's TCP read loop. It must never block:
|
||||
// look up the session, strip the browser demux prefix, append to the ring,
|
||||
// check the in-flight sentinel and wake any waiter. Sessions MCP did not
|
||||
// create (the web console's) are dropped at the map lookup with no work.
|
||||
func (s *Server) OnTerminalData(deviceID string, packet []byte) {
|
||||
sess := s.sessions.get(deviceID)
|
||||
if sess == nil {
|
||||
return
|
||||
}
|
||||
if len(packet) >= len(protocol.TerminalBinaryMagic) &&
|
||||
bytes.Equal(packet[:len(protocol.TerminalBinaryMagic)], protocol.TerminalBinaryMagic[:]) {
|
||||
packet = packet[len(protocol.TerminalBinaryMagic):]
|
||||
}
|
||||
sess.mu.Lock()
|
||||
if sess.closed {
|
||||
sess.mu.Unlock()
|
||||
return
|
||||
}
|
||||
sess.appendLocked(packet)
|
||||
sess.scanPendingLocked()
|
||||
sess.cond.Broadcast()
|
||||
sess.mu.Unlock()
|
||||
}
|
||||
@@ -0,0 +1,545 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/connection"
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
|
||||
)
|
||||
|
||||
// terminalTestServer builds a server backed by a real hub with one online
|
||||
// device (1001) whose shell commands are accepted by a no-op sender.
|
||||
func terminalTestServer(t *testing.T) (*Server, *hub.Hub) {
|
||||
t.Helper()
|
||||
h := hub.New()
|
||||
h.SetSender(func(*connection.Context, []byte) error { return nil })
|
||||
h.Register(&hub.Device{ID: "1001", PeerIP: "10.0.0.1"},
|
||||
&connection.Context{RemoteAddr: "10.0.0.1:54321"})
|
||||
s := New(Config{Token: testToken, Hub: h})
|
||||
t.Cleanup(s.Close)
|
||||
return s, h
|
||||
}
|
||||
|
||||
// termPacket wraps shell output the way cmd/main.go publishes it.
|
||||
func termPacket(s string) []byte {
|
||||
p := make([]byte, 4+len(s))
|
||||
copy(p, "TRM1")
|
||||
copy(p[4:], s)
|
||||
return p
|
||||
}
|
||||
|
||||
func TestTermRingTrimsOldest(t *testing.T) {
|
||||
sess := newTermSession("1001")
|
||||
payload := make([]byte, 1<<20)
|
||||
for i := range payload {
|
||||
payload[i] = byte(i*7 + 1)
|
||||
}
|
||||
|
||||
sess.mu.Lock()
|
||||
sess.appendLocked(payload)
|
||||
data, next, lost := sess.readLocked(0, 1<<20)
|
||||
size, total, dropped := sess.size, sess.total, sess.droppedBytes
|
||||
sess.mu.Unlock()
|
||||
|
||||
if size != termRingCap {
|
||||
t.Fatalf("retained = %d, want cap %d", size, termRingCap)
|
||||
}
|
||||
if total != 1<<20 {
|
||||
t.Fatalf("total = %d, want %d", total, 1<<20)
|
||||
}
|
||||
if dropped != uint64((1<<20)-termRingCap) {
|
||||
t.Fatalf("dropped = %d, want %d", dropped, (1<<20)-termRingCap)
|
||||
}
|
||||
if !lost {
|
||||
t.Fatal("reading from 0 after overflow should report lost data")
|
||||
}
|
||||
if len(data) != termRingCap || next != 1<<20 {
|
||||
t.Fatalf("read len/next = %d/%d, want %d/%d", len(data), next, termRingCap, 1<<20)
|
||||
}
|
||||
if want := payload[(1<<20)-termRingCap:]; !bytes.Equal(data, want) {
|
||||
t.Fatal("retained data is not the newest window of the stream")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTermRingWraps(t *testing.T) {
|
||||
sess := newTermSession("1001")
|
||||
var want []byte
|
||||
for i := range 10 {
|
||||
chunk := bytes.Repeat([]byte{byte('a' + i)}, 40<<10)
|
||||
want = append(want, chunk...)
|
||||
sess.mu.Lock()
|
||||
sess.appendLocked(chunk)
|
||||
sess.mu.Unlock()
|
||||
}
|
||||
|
||||
sess.mu.Lock()
|
||||
base, total := sess.baseLocked(), sess.total
|
||||
data, next, lost := sess.readLocked(0, termRingCap)
|
||||
tail, _, _ := sess.readLocked(total-100, 100)
|
||||
sess.mu.Unlock()
|
||||
|
||||
if !lost {
|
||||
t.Fatal("reading from 0 after wraparound should report lost data")
|
||||
}
|
||||
if base != uint64(len(want)-termRingCap) {
|
||||
t.Fatalf("base = %d, want %d", base, len(want)-termRingCap)
|
||||
}
|
||||
if next != total {
|
||||
t.Fatalf("next = %d, want total %d", next, total)
|
||||
}
|
||||
if wantWin := want[len(want)-termRingCap:]; !bytes.Equal(data, wantWin) {
|
||||
t.Fatal("wrapped ring does not return the newest window in order")
|
||||
}
|
||||
if wantTail := want[len(want)-100:]; !bytes.Equal(tail, wantTail) {
|
||||
t.Fatal("tail read is not the newest bytes")
|
||||
}
|
||||
}
|
||||
|
||||
func TestScanSentinel(t *testing.T) {
|
||||
const sentinel = "__MCP_DONE_abc123__"
|
||||
cases := []struct {
|
||||
name string
|
||||
in string
|
||||
code int
|
||||
ok bool
|
||||
}{
|
||||
{"plain", "x\r\n" + sentinel + "0\r\n", 0, true},
|
||||
{"nonzero", sentinel + "42", 42, true},
|
||||
{"negative", sentinel + "-1073741510", -1073741510, true},
|
||||
{"echo then real", sentinel + "%errorlevel%\r\n" + sentinel + "1\r\n", 1, true},
|
||||
{"posix echo then real", sentinel + "$?\n" + sentinel + "0\n", 0, true},
|
||||
{"command echo only", sentinel + "%errorlevel%", 0, false},
|
||||
{"absent", "hello world", 0, false},
|
||||
{"empty", "", 0, false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
code, start, end, ok := scanSentinel([]byte(tc.in), sentinel)
|
||||
if ok != tc.ok {
|
||||
t.Errorf("%s: ok = %v, want %v", tc.name, ok, tc.ok)
|
||||
continue
|
||||
}
|
||||
if ok && code != tc.code {
|
||||
t.Errorf("%s: code = %d, want %d", tc.name, code, tc.code)
|
||||
}
|
||||
if ok && (start < 0 || start >= end || end > len(tc.in)) {
|
||||
t.Errorf("%s: start/end = %d/%d, want 0<=start<end<=%d", tc.name, start, end, len(tc.in))
|
||||
}
|
||||
}
|
||||
if _, _, _, ok := scanSentinel([]byte("123"), ""); ok {
|
||||
t.Fatal("empty sentinel must never match")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenSessionWaitsForReadyAndBuffers(t *testing.T) {
|
||||
s, h := terminalTestServer(t)
|
||||
|
||||
sess, err := s.sessions.open("1001")
|
||||
if err != nil {
|
||||
t.Fatalf("open: %v", err)
|
||||
}
|
||||
if !strings.HasPrefix(sess.id, "s-") || len(sess.id) != 8 {
|
||||
t.Fatalf("session id = %q, want s-XXXXXX", sess.id)
|
||||
}
|
||||
sess.mu.Lock()
|
||||
ready := sess.ready
|
||||
sess.mu.Unlock()
|
||||
if ready {
|
||||
t.Fatal("session must not be ready before OnTerminalReady")
|
||||
}
|
||||
|
||||
s.OnTerminalReady("1001", true)
|
||||
sess.mu.Lock()
|
||||
ready, isPTY := sess.ready, sess.isPTY
|
||||
sess.mu.Unlock()
|
||||
if !ready || !isPTY {
|
||||
t.Fatalf("after ready: ready=%v isPTY=%v", ready, isPTY)
|
||||
}
|
||||
|
||||
// The browser demux prefix is stripped; a raw chunk is accepted as-is.
|
||||
s.OnTerminalData("1001", termPacket("hello "))
|
||||
s.OnTerminalData("1001", []byte("world"))
|
||||
sess.mu.Lock()
|
||||
data, next, lost := sess.readLocked(0, 1<<10)
|
||||
sess.mu.Unlock()
|
||||
if string(data) != "hello world" || next != 11 || lost {
|
||||
t.Fatalf("buffered = %q next=%d lost=%v", data, next, lost)
|
||||
}
|
||||
|
||||
// Simulate a genuine teardown: the hub releases the lease first, then its
|
||||
// event reaches the MCP subscriber.
|
||||
h.CloseTerminalSession("1001")
|
||||
s.OnTerminalClosed("1001", "closed")
|
||||
if s.sessions.get("1001") != nil {
|
||||
t.Fatal("closed session still in the table")
|
||||
}
|
||||
sess.mu.Lock()
|
||||
closed, reason := sess.closed, sess.closeReason
|
||||
sess.mu.Unlock()
|
||||
if !closed || reason != "closed" {
|
||||
t.Fatalf("session state: closed=%v reason=%q", closed, reason)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenSessionBusyWithBrowser(t *testing.T) {
|
||||
s, h := terminalTestServer(t)
|
||||
_ = s
|
||||
|
||||
// The web console opens the shell first (same call it makes today).
|
||||
if err := h.OpenTerminalSession("1001"); err != nil {
|
||||
t.Fatalf("browser open: %v", err)
|
||||
}
|
||||
tbl := newSessionTable(h)
|
||||
if _, err := tbl.open("1001"); !errors.Is(err, hub.ErrTerminalBusy) {
|
||||
t.Fatalf("open while browser holds it = %v, want ErrTerminalBusy", err)
|
||||
}
|
||||
if tbl.get("1001") != nil {
|
||||
t.Fatal("failed open must not leave a session marker behind")
|
||||
}
|
||||
|
||||
// After the browser closes, MCP can claim the shell.
|
||||
h.CloseTerminalSession("1001")
|
||||
if _, err := tbl.open("1001"); err != nil {
|
||||
t.Fatalf("open after browser closed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTerminalSentinelWakesPending(t *testing.T) {
|
||||
s, _ := terminalTestServer(t)
|
||||
sess, err := s.sessions.open("1001")
|
||||
if err != nil {
|
||||
t.Fatalf("open: %v", err)
|
||||
}
|
||||
s.OnTerminalReady("1001", true)
|
||||
sess.mu.Lock()
|
||||
sess.pending = &pendingCmd{sentinel: "__MCP_DONE_abc123__"}
|
||||
sess.mu.Unlock()
|
||||
|
||||
s.OnTerminalData("1001", termPacket("dir\r\nfile.txt\r\n__MCP_DONE_abc123__1\r\n"))
|
||||
|
||||
sess.mu.Lock()
|
||||
p := sess.pending
|
||||
done, code, end := p.done, p.exitCode, p.outputEnd
|
||||
sess.mu.Unlock()
|
||||
if !done || code != 1 {
|
||||
t.Fatalf("pending: done=%v code=%d", done, code)
|
||||
}
|
||||
if end == 0 {
|
||||
t.Fatal("sentinel end offset not recorded")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionIdleSweep(t *testing.T) {
|
||||
s, _ := terminalTestServer(t)
|
||||
sess, err := s.sessions.open("1001")
|
||||
if err != nil {
|
||||
t.Fatalf("open: %v", err)
|
||||
}
|
||||
sess.mu.Lock()
|
||||
sess.ready = true
|
||||
sess.lastUsed = time.Now().Add(-time.Hour)
|
||||
sess.mu.Unlock()
|
||||
|
||||
if n := s.sessions.sweepIdle(time.Now(), time.Minute); n != 1 {
|
||||
t.Fatalf("swept = %d, want 1", n)
|
||||
}
|
||||
if s.sessions.get("1001") != nil {
|
||||
t.Fatal("idle session still in the table")
|
||||
}
|
||||
sess.mu.Lock()
|
||||
closed := sess.closed
|
||||
sess.mu.Unlock()
|
||||
if !closed {
|
||||
t.Fatal("swept session not marked closed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionTableCloseAll(t *testing.T) {
|
||||
s, h := terminalTestServer(t)
|
||||
h.Register(&hub.Device{ID: "2002", PeerIP: "10.0.0.2"},
|
||||
&connection.Context{RemoteAddr: "10.0.0.2:54321"})
|
||||
for _, id := range []string{"1001", "2002"} {
|
||||
if _, err := s.sessions.open(id); err != nil {
|
||||
t.Fatalf("open %s: %v", id, err)
|
||||
}
|
||||
}
|
||||
|
||||
s.Close()
|
||||
for _, id := range []string{"1001", "2002"} {
|
||||
if s.sessions.get(id) != nil {
|
||||
t.Fatalf("session %s survived Close", id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A close event emitted by the previous viewer's teardown must not delete a
|
||||
// session whose open already owns the hub lease. Regression for the race where
|
||||
// the web console closes as MCP opens.
|
||||
func TestStaleTerminalCloseKeepsSession(t *testing.T) {
|
||||
s, h := terminalTestServer(t)
|
||||
sess, err := s.sessions.open("1001")
|
||||
if err != nil {
|
||||
t.Fatalf("open: %v", err)
|
||||
}
|
||||
|
||||
// The hub still holds our (new) pending lease, so this event describes the
|
||||
// viewer that just went away.
|
||||
s.OnTerminalClosed("1001", "closed")
|
||||
if got := s.sessions.get("1001"); got != sess {
|
||||
t.Fatal("stale close event removed the fresh session")
|
||||
}
|
||||
sess.mu.Lock()
|
||||
closed := sess.closed
|
||||
sess.mu.Unlock()
|
||||
if closed {
|
||||
t.Fatal("stale close event marked the fresh session closed")
|
||||
}
|
||||
|
||||
// Once the hub really has no session, the event is genuine.
|
||||
h.CloseTerminalSession("1001")
|
||||
s.OnTerminalClosed("1001", "closed")
|
||||
if s.sessions.get("1001") != nil {
|
||||
t.Fatal("genuine close event did not remove the session")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClosedIgnoredWhileOpening(t *testing.T) {
|
||||
tbl := newSessionTable(nil)
|
||||
sess := newTermSession("1001")
|
||||
sess.opening = true
|
||||
tbl.byDevice["1001"] = sess
|
||||
|
||||
tbl.closed("1001", "closed")
|
||||
if tbl.get("1001") != sess {
|
||||
t.Fatal("close event during open removed the session")
|
||||
}
|
||||
|
||||
sess.mu.Lock()
|
||||
sess.opening = false
|
||||
sess.mu.Unlock()
|
||||
tbl.closed("1001", "closed")
|
||||
if tbl.get("1001") != nil {
|
||||
t.Fatal("close after open finished did not remove the session")
|
||||
}
|
||||
}
|
||||
|
||||
// sweepIdle snapshots sessions before closing them; if the entry was replaced
|
||||
// in between, the close must not take out the new session.
|
||||
func TestSweepSkipsReplacedSession(t *testing.T) {
|
||||
tbl := newSessionTable(nil)
|
||||
old := newTermSession("1001")
|
||||
old.lastUsed = old.lastUsed.Add(-time.Hour)
|
||||
fresh := newTermSession("1001")
|
||||
tbl.byDevice["1001"] = fresh
|
||||
|
||||
if tbl.closeSessionIf("1001", old) {
|
||||
t.Fatal("closeSessionIf closed a session it did not own")
|
||||
}
|
||||
if tbl.get("1001") != fresh {
|
||||
t.Fatal("replacement session was removed")
|
||||
}
|
||||
if n := tbl.sweepIdle(time.Now(), time.Minute); n != 0 {
|
||||
t.Fatalf("swept = %d, want 0", n)
|
||||
}
|
||||
}
|
||||
|
||||
// A draining session's close must not tear down a hub lease that a reconnected
|
||||
// viewer has since opened: the shell the session referred to is already gone.
|
||||
func TestCloseOfEndedSessionLeavesNewHubLease(t *testing.T) {
|
||||
s, h := terminalTestServer(t)
|
||||
sess, err := s.sessions.open("1001")
|
||||
if err != nil {
|
||||
t.Fatalf("open: %v", err)
|
||||
}
|
||||
s.OnTerminalReady("1001", true)
|
||||
if _, rerr := sess.beginCommand("ab12cd34", "cmd", ""); rerr != nil {
|
||||
t.Fatalf("begin: %v", rerr)
|
||||
}
|
||||
s.OnTerminalData("1001", termPacket("out\r\n"))
|
||||
|
||||
// The shell ends with output the client has not polled yet: the session
|
||||
// stays in the table so the tail can still be collected. The hub event is
|
||||
// delivered to subscribers by cmd/main.go's wiring.
|
||||
h.CloseTerminalSession("1001")
|
||||
s.OnTerminalClosed("1001", "closed")
|
||||
if s.sessions.get("1001") != sess {
|
||||
t.Fatal("draining session was dropped")
|
||||
}
|
||||
|
||||
// Another viewer (or the same device after reconnecting) gets a fresh lease.
|
||||
if err := h.OpenTerminalSession("1001"); err != nil {
|
||||
t.Fatalf("new lease: %v", err)
|
||||
}
|
||||
if !h.HasTerminalSession("1001") {
|
||||
t.Fatal("new lease not established")
|
||||
}
|
||||
|
||||
if !s.sessions.closeSessionIf("1001", sess) {
|
||||
t.Fatal("close did not remove the draining session")
|
||||
}
|
||||
if !h.HasTerminalSession("1001") {
|
||||
t.Fatal("closing the ended session tore down the new viewer's shell")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSentinelSplitAcrossChunks(t *testing.T) {
|
||||
s, _ := terminalTestServer(t)
|
||||
sess, err := s.sessions.open("1001")
|
||||
if err != nil {
|
||||
t.Fatalf("open: %v", err)
|
||||
}
|
||||
s.OnTerminalReady("1001", true)
|
||||
sess.mu.Lock()
|
||||
sess.pending = &pendingCmd{sentinel: "__MCP_DONE_abc123__"}
|
||||
sess.mu.Unlock()
|
||||
|
||||
// The sentinel prefix ends more than 64 bytes before the chunk boundary,
|
||||
// so the retained overlap is what lets the second chunk complete it.
|
||||
s.OnTerminalData("1001", termPacket(strings.Repeat("x", 100)+"__MCP_DONE_ab"))
|
||||
s.OnTerminalData("1001", termPacket("c123__3\r\n"))
|
||||
|
||||
sess.mu.Lock()
|
||||
p := sess.pending
|
||||
done, code := p.done, p.exitCode
|
||||
sess.mu.Unlock()
|
||||
if !done || code != 3 {
|
||||
t.Fatalf("split sentinel: done=%v code=%d", done, code)
|
||||
}
|
||||
}
|
||||
|
||||
// A quiet command still owns the device's shell lease: the reaper must not
|
||||
// reclaim a session just because it printed nothing for a while.
|
||||
func TestSweepKeepsRunningCommand(t *testing.T) {
|
||||
tbl := newSessionTable(nil)
|
||||
sess := newTermSession("1001")
|
||||
sess.ready = true
|
||||
sess.lastUsed = sess.lastUsed.Add(-time.Hour)
|
||||
sess.pending = &pendingCmd{start: 0, busySince: time.Now()}
|
||||
tbl.byDevice["1001"] = sess
|
||||
|
||||
if n := tbl.sweepIdle(time.Now(), time.Minute); n != 0 {
|
||||
t.Fatalf("swept = %d, want 0 while the command runs", n)
|
||||
}
|
||||
if tbl.get("1001") != sess {
|
||||
t.Fatal("running session was removed")
|
||||
}
|
||||
}
|
||||
|
||||
// Once the shell is gone, only the undelivered tail keeps the session alive;
|
||||
// a model that never polls must not pin the slot indefinitely.
|
||||
func TestSweepReapsClosedDrainingSession(t *testing.T) {
|
||||
tbl := newSessionTable(nil)
|
||||
sess := newTermSession("1001")
|
||||
sess.ready = true
|
||||
sess.closed = true
|
||||
sess.pending = &pendingCmd{busySince: time.Now()}
|
||||
sess.lastUsed = sess.lastUsed.Add(-time.Hour)
|
||||
tbl.byDevice["1001"] = sess
|
||||
|
||||
if n := tbl.sweepIdle(time.Now(), time.Minute); n != 1 {
|
||||
t.Fatalf("swept = %d, want 1", n)
|
||||
}
|
||||
if tbl.get("1001") != nil {
|
||||
t.Fatal("draining session not removed")
|
||||
}
|
||||
}
|
||||
|
||||
// The reaper is wired to a ticker in New: an idle session is reclaimed without
|
||||
// any further tool call.
|
||||
func TestSweepTickerReclaimsIdleSession(t *testing.T) {
|
||||
h := hub.New()
|
||||
h.SetSender(func(*connection.Context, []byte) error { return nil })
|
||||
h.Register(&hub.Device{ID: "1001", PeerIP: "10.0.0.1"},
|
||||
&connection.Context{RemoteAddr: "10.0.0.1:54321"})
|
||||
s := New(Config{Token: testToken, Hub: h, TermIdle: 100 * time.Millisecond})
|
||||
t.Cleanup(s.Close)
|
||||
|
||||
if _, err := s.sessions.open("1001"); err != nil {
|
||||
t.Fatalf("open: %v", err)
|
||||
}
|
||||
s.OnTerminalReady("1001", true)
|
||||
|
||||
deadline := time.Now().Add(3 * time.Second)
|
||||
for s.sessions.get("1001") != nil {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("idle session was not reaped by the ticker")
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
if h.HasTerminalSession("1001") {
|
||||
t.Fatal("reaped session still holds the hub lease")
|
||||
}
|
||||
}
|
||||
|
||||
// A command that outlives the busy cap is reclaimed even with no output and no
|
||||
// poller, so a hung shell cannot hold the device slot forever.
|
||||
func TestSweepReapsOverdueCommand(t *testing.T) {
|
||||
tbl := newSessionTable(nil)
|
||||
sess := newTermSession("1001")
|
||||
sess.ready = true
|
||||
sess.lastUsed = sess.lastUsed.Add(-time.Minute)
|
||||
sess.pending = &pendingCmd{start: 0, busySince: time.Now().Add(-termBusyMax - time.Second)}
|
||||
tbl.byDevice["1001"] = sess
|
||||
|
||||
if n := tbl.sweepIdle(time.Now(), time.Minute); n != 1 {
|
||||
t.Fatalf("swept = %d, want 1 for an overdue command", n)
|
||||
}
|
||||
if tbl.get("1001") != nil {
|
||||
t.Fatal("overdue session not removed")
|
||||
}
|
||||
}
|
||||
|
||||
// A session whose shell never bound has a caller still waiting on it; the
|
||||
// reaper must leave it to that caller's own release path.
|
||||
func TestSweepKeepsNotReadySession(t *testing.T) {
|
||||
tbl := newSessionTable(nil)
|
||||
sess := newTermSession("1001")
|
||||
sess.lastUsed = sess.lastUsed.Add(-time.Hour)
|
||||
tbl.byDevice["1001"] = sess
|
||||
|
||||
if n := tbl.sweepIdle(time.Now(), time.Minute); n != 0 {
|
||||
t.Fatalf("swept = %d, want 0 for a session still opening", n)
|
||||
}
|
||||
if tbl.get("1001") != sess {
|
||||
t.Fatal("not-ready session was removed")
|
||||
}
|
||||
}
|
||||
|
||||
// A device re-login drops a pending lease without emitting OnTerminalClosed.
|
||||
// If a human then takes the freed slot, a late close from the MCP session that
|
||||
// lost it must not tear the human's shell down (design §6.2: never pre-empt).
|
||||
func TestCloseLeavesRenewedLeaseAlone(t *testing.T) {
|
||||
s, h := terminalTestServer(t)
|
||||
sess, err := s.sessions.open("1001")
|
||||
if err != nil {
|
||||
t.Fatalf("open: %v", err)
|
||||
}
|
||||
// Register carries the terminal generation over, exactly like a real
|
||||
// re-login racing the old connection's disconnect.
|
||||
h.Register(&hub.Device{ID: "1001", PeerIP: "10.0.0.1"},
|
||||
&connection.Context{RemoteAddr: "10.0.0.1:54321"})
|
||||
if err := h.OpenTerminalSession("1001"); err != nil {
|
||||
t.Fatalf("human open: %v", err)
|
||||
}
|
||||
|
||||
if !s.sessions.closeSessionIf("1001", sess) {
|
||||
t.Fatal("close did not remove the stale session")
|
||||
}
|
||||
if !h.HasTerminalSession("1001") {
|
||||
t.Fatal("close tore down a lease the stale session no longer owned")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCloseStopsReaper(t *testing.T) {
|
||||
s, _ := terminalTestServer(t)
|
||||
s.Close()
|
||||
select {
|
||||
case <-s.reaperDone:
|
||||
default:
|
||||
t.Fatal("Close returned before the reaper stopped")
|
||||
}
|
||||
s.Close() // idempotent; the Cleanup will call it a third time
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// termRingCap bounds one session's retained output. A shell that floods the
|
||||
// session (a log tail, a build) must not grow server memory without bound;
|
||||
// the oldest bytes are dropped and the loss is surfaced as truncated output
|
||||
// (design §6.3).
|
||||
const termRingCap = 256 << 10
|
||||
|
||||
// pendingCmd is one command whose output is still being collected. It lives
|
||||
// on the session so a timed-out terminal_exec can hand the same command back
|
||||
// to a later polling call: the shell keeps running and its output keeps
|
||||
// accumulating whether or not an HTTP request is attached.
|
||||
type pendingCmd struct {
|
||||
sentinel string // "__MCP_DONE_<6 hex>__"
|
||||
nonce string // the 6-hex id inside sentinel, for output cleaning
|
||||
cmdLine string // wire command line, removed from the PTY's echo
|
||||
sentLine string // wire sentinel line, removed from the PTY's echo
|
||||
start uint64 // absolute offset where this command's output begins
|
||||
scanPos uint64 // absolute offset scanned so far (sentinel may span chunks)
|
||||
deadline time.Time // when the current waiter gives up (the session survives)
|
||||
done bool
|
||||
exitCode int
|
||||
outputEnd uint64 // absolute offset where the delivered output ends (sentinel start)
|
||||
lost uint64 // this command's bytes evicted by the ring, cumulative
|
||||
|
||||
// firstChunk is true until the command's first delivery window is cleaned:
|
||||
// the PTY echoes the input exactly once, at the start.
|
||||
firstChunk bool
|
||||
busySince time.Time // when the command started, for the M4c busy reaper
|
||||
}
|
||||
|
||||
// termSession is the server-side view of one shell child. All mutable state
|
||||
// is guarded by mu; cond wakes a waiter when data arrives, the command ends,
|
||||
// or the session closes.
|
||||
type termSession struct {
|
||||
id string
|
||||
deviceID string
|
||||
createdAt time.Time
|
||||
|
||||
mu sync.Mutex
|
||||
cond *sync.Cond
|
||||
lastUsed time.Time
|
||||
buf []byte // ring of termRingCap bytes
|
||||
head int // index the next write goes to
|
||||
size int // valid bytes in buf
|
||||
total uint64 // bytes the shell produced, including dropped ones
|
||||
delivered uint64 // absolute offset already handed to the client
|
||||
droppedBytes uint64
|
||||
|
||||
isPTY bool
|
||||
ready bool // OnTerminalReady seen
|
||||
sawOutput bool // shell printed its first screen (prompt); bootstrap done
|
||||
opening bool // hub.OpenTerminalSession still in flight
|
||||
lease uint64 // hub lease generation; 0 until the open completes
|
||||
closed bool
|
||||
closeReason string
|
||||
|
||||
pending *pendingCmd // nil = idle
|
||||
}
|
||||
|
||||
func newTermSession(deviceID string) *termSession {
|
||||
now := time.Now()
|
||||
s := &termSession{
|
||||
id: newSessionID(),
|
||||
deviceID: deviceID,
|
||||
createdAt: now,
|
||||
lastUsed: now,
|
||||
buf: make([]byte, termRingCap),
|
||||
}
|
||||
s.cond = sync.NewCond(&s.mu)
|
||||
return s
|
||||
}
|
||||
|
||||
// baseLocked is the absolute offset of the oldest retained byte.
|
||||
func (s *termSession) baseLocked() uint64 { return s.total - uint64(s.size) }
|
||||
|
||||
// appendLocked writes p into the ring, dropping the oldest bytes on overflow.
|
||||
// total counts every byte the shell produced, including dropped ones, so the
|
||||
// absolute offsets stay monotonic and a client can tell that it lost data.
|
||||
func (s *termSession) appendLocked(p []byte) {
|
||||
s.lastUsed = time.Now()
|
||||
if len(p) == 0 {
|
||||
return
|
||||
}
|
||||
s.sawOutput = true
|
||||
if len(p) > len(s.buf) {
|
||||
drop := len(p) - len(s.buf)
|
||||
s.droppedBytes += uint64(drop)
|
||||
s.total += uint64(drop)
|
||||
p = p[drop:]
|
||||
}
|
||||
if overflow := s.size + len(p) - len(s.buf); overflow > 0 {
|
||||
// The oldest overflow bytes are simply forgotten: head still marks
|
||||
// the next write, and size now describes a shorter prefix.
|
||||
s.droppedBytes += uint64(overflow)
|
||||
s.size -= overflow
|
||||
}
|
||||
if n := copy(s.buf[s.head:], p); n < len(p) {
|
||||
copy(s.buf, p[n:])
|
||||
}
|
||||
s.head = (s.head + len(p)) % len(s.buf)
|
||||
s.size += len(p)
|
||||
s.total += uint64(len(p))
|
||||
}
|
||||
|
||||
// readLocked returns up to max bytes starting at absolute offset. lost is
|
||||
// true when the requested offset predates the ring's oldest byte; the data
|
||||
// then starts at the oldest retained byte instead.
|
||||
func (s *termSession) readLocked(offset uint64, max int) (data []byte, next uint64, lost bool) {
|
||||
if max <= 0 {
|
||||
return nil, offset, false
|
||||
}
|
||||
base := s.baseLocked()
|
||||
if offset < base {
|
||||
offset = base
|
||||
lost = true
|
||||
}
|
||||
if offset >= s.total {
|
||||
return nil, s.total, lost
|
||||
}
|
||||
n := int(min(s.total-offset, uint64(max)))
|
||||
idx := (s.head - s.size + int(offset-base)) % len(s.buf)
|
||||
if idx < 0 {
|
||||
idx += len(s.buf)
|
||||
}
|
||||
data = make([]byte, n)
|
||||
first := copy(data, s.buf[idx:min(idx+n, len(s.buf))])
|
||||
copy(data[first:], s.buf[:n-first])
|
||||
return data, offset + uint64(n), lost
|
||||
}
|
||||
|
||||
// scanPendingLocked looks for the in-flight command's sentinel in the bytes
|
||||
// appended since the last look. A tail overlap is retained so a sentinel split
|
||||
// across two TCP reads is still found.
|
||||
func (s *termSession) scanPendingLocked() {
|
||||
p := s.pending
|
||||
if p == nil || p.done {
|
||||
return
|
||||
}
|
||||
from := max(p.scanPos, s.baseLocked())
|
||||
if from >= s.total {
|
||||
return
|
||||
}
|
||||
data, next, _ := s.readLocked(from, int(s.total-from))
|
||||
if code, start, _, ok := scanSentinel(data, p.sentinel); ok {
|
||||
p.done = true
|
||||
p.exitCode = code
|
||||
// Deliver only up to the sentinel itself: the echoed sentinel line and
|
||||
// the prompt printed after it are not the command's output.
|
||||
p.outputEnd = from + uint64(start)
|
||||
s.cond.Broadcast()
|
||||
return
|
||||
}
|
||||
// Keep the last few bytes: the next chunk may complete a sentinel whose
|
||||
// prefix sits just before the boundary.
|
||||
const overlap = 64
|
||||
if next > overlap {
|
||||
next -= overlap
|
||||
}
|
||||
if next > p.scanPos {
|
||||
p.scanPos = next
|
||||
}
|
||||
}
|
||||
|
||||
// scanSentinel finds the first occurrence of sentinel followed by a decimal
|
||||
// exit code. The Windows %errorlevel% is signed (0xC000013A prints as
|
||||
// -1073741510), so a leading '-' is accepted. start is where the sentinel
|
||||
// begins (delivery stops there); end is one past the last digit.
|
||||
//
|
||||
// Echoed command lines contain the sentinel too but not the exit code
|
||||
// ("__MCP_DONE_x__$?" / "__MCP_DONE_x__%errorlevel%"), so occurrences without
|
||||
// digits are skipped rather than reported.
|
||||
func scanSentinel(data []byte, sentinel string) (code, start, end int, ok bool) {
|
||||
if sentinel == "" {
|
||||
// Defensive: an empty needle matches everywhere and would spin the
|
||||
// device read loop. Callers always mint a non-empty sentinel.
|
||||
return 0, 0, 0, false
|
||||
}
|
||||
needle := []byte(sentinel)
|
||||
from := 0
|
||||
for {
|
||||
idx := bytes.Index(data[from:], needle)
|
||||
if idx < 0 {
|
||||
return 0, 0, 0, false
|
||||
}
|
||||
idx += from
|
||||
rest := data[idx+len(needle):]
|
||||
i := 0
|
||||
if i < len(rest) && rest[i] == '-' {
|
||||
i++
|
||||
}
|
||||
digits := i
|
||||
for i < len(rest) && rest[i] >= '0' && rest[i] <= '9' {
|
||||
i++
|
||||
}
|
||||
if i > digits {
|
||||
if n, err := strconv.Atoi(string(rest[:i])); err == nil {
|
||||
return n, idx, idx + len(needle) + i, true
|
||||
}
|
||||
}
|
||||
from = idx + len(needle)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
"encoding/json"
|
||||
)
|
||||
|
||||
// tools_minimal.json is generated from mcp/tools.json by
|
||||
// tools/mcp_tools/gen_go_tools.py — never edit it by hand. It is embedded so
|
||||
// tools/list is a compile-time constant: no disk I/O, no drift between the
|
||||
// schema the model sees and the schema the handlers were written against.
|
||||
//
|
||||
//go:embed tools_minimal.json
|
||||
var toolsJSON []byte
|
||||
|
||||
// writeTools are hidden from tools/list in readonly mode and rejected with
|
||||
// -32006 if called anyway (design §3.1: readonly exposes 7 of 9 tools).
|
||||
var writeTools = map[string]bool{
|
||||
"terminal_exec": true,
|
||||
"terminal_close": true,
|
||||
}
|
||||
|
||||
// unlockedTools run without the per-device lock. terminal_close must be usable
|
||||
// while a terminal_exec call is still waiting on the same device: that call
|
||||
// holds the lock for its whole timeout, and a close that answers -32003 could
|
||||
// never interrupt it.
|
||||
var unlockedTools = map[string]bool{
|
||||
"terminal_close": true,
|
||||
}
|
||||
|
||||
// toolDef holds one published definition plus its name, so filtering does not
|
||||
// re-parse the JSON on every tools/list call.
|
||||
type toolDef struct {
|
||||
name string
|
||||
raw json.RawMessage
|
||||
}
|
||||
|
||||
type toolSet struct {
|
||||
defs []toolDef
|
||||
names map[string]bool
|
||||
}
|
||||
|
||||
// buildToolSet validates the embedded payload once at startup. A malformed
|
||||
// file is a build defect, so panic loudly rather than serve a broken list.
|
||||
func buildToolSet(raw []byte) *toolSet {
|
||||
var raws []json.RawMessage
|
||||
if err := json.Unmarshal(raw, &raws); err != nil {
|
||||
panic("mcp: embedded tools_minimal.json is not a JSON array: " + err.Error())
|
||||
}
|
||||
ts := &toolSet{defs: make([]toolDef, 0, len(raws)), names: make(map[string]bool, len(raws))}
|
||||
for _, r := range raws {
|
||||
var head struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
if err := json.Unmarshal(r, &head); err != nil || head.Name == "" {
|
||||
panic("mcp: embedded tool definition without a name")
|
||||
}
|
||||
if ts.names[head.Name] {
|
||||
panic("mcp: duplicate embedded tool " + head.Name)
|
||||
}
|
||||
ts.names[head.Name] = true
|
||||
ts.defs = append(ts.defs, toolDef{name: head.Name, raw: r})
|
||||
}
|
||||
return ts
|
||||
}
|
||||
|
||||
// visible returns the tool definitions to publish, preserving tools.json
|
||||
// order. The raw bytes are passed through untouched, so descriptions and
|
||||
// schemas stay exactly what mcp/tools.json says (no annotations, like MFC).
|
||||
func (ts *toolSet) visible(readonly bool) []json.RawMessage {
|
||||
out := make([]json.RawMessage, 0, len(ts.defs))
|
||||
for _, def := range ts.defs {
|
||||
if readonly && writeTools[def.name] {
|
||||
continue
|
||||
}
|
||||
out = append(out, def.raw)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// known reports whether name is a tool this server defines, including tools
|
||||
// hidden by readonly mode. Unknown names are -32601; hidden ones are -32006.
|
||||
func (ts *toolSet) known(name string) bool { return ts.names[name] }
|
||||
|
||||
// toolsListResult is the MCP tools/list payload.
|
||||
type toolsListResult struct {
|
||||
Tools []json.RawMessage `json:"tools"`
|
||||
}
|
||||
@@ -0,0 +1,694 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/auditquery"
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/protocol"
|
||||
)
|
||||
|
||||
// Local read tools: they answer from the server's own state (device hub,
|
||||
// device history, audit file) and never open a channel to a client. The
|
||||
// remote tools (screenshot, files, terminal) live in later milestones.
|
||||
|
||||
const (
|
||||
// Page size bounds shared by list_hosts and get_audit_log, matching the
|
||||
// tool descriptions in mcp/tools.json.
|
||||
listDefaultLimit = 100
|
||||
listMaxLimit = 1000
|
||||
|
||||
// batchMaxIDs is the per-call cap for get_host_detail.ids, matching the
|
||||
// Win32 server.
|
||||
batchMaxIDs = 50
|
||||
)
|
||||
|
||||
// toolResult is the MCP tools/call success envelope, byte-compatible with the
|
||||
// Win32 server: one text item plus structuredContent. Failures are JSON-RPC
|
||||
// error objects at the top level, not isError results.
|
||||
type toolResult struct {
|
||||
Content []contentItem `json:"content"`
|
||||
StructuredContent any `json:"structuredContent"`
|
||||
IsError bool `json:"isError"`
|
||||
}
|
||||
|
||||
// contentItem is one MCP content block. Text tools fill Text; get_screenshot
|
||||
// emits an image block (Data is base64, MimeType image/jpeg), so both the text
|
||||
// and image fields are optional on the wire.
|
||||
type contentItem struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text,omitempty"`
|
||||
Data string `json:"data,omitempty"`
|
||||
MimeType string `json:"mimeType,omitempty"`
|
||||
}
|
||||
|
||||
func newToolResult(text string, structured any) toolResult {
|
||||
return toolResult{
|
||||
Content: []contentItem{{Type: "text", Text: text}},
|
||||
StructuredContent: structured,
|
||||
IsError: false,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) registerLocalTools() {
|
||||
s.handlers["list_hosts"] = s.callListHosts
|
||||
s.handlers["get_host_detail"] = s.callGetHostDetail
|
||||
s.handlers["get_server_status"] = s.callGetServerStatus
|
||||
s.handlers["get_audit_log"] = s.callGetAuditLog
|
||||
}
|
||||
|
||||
// decodeArgs unmarshals tools/call arguments into v. An absent/null arguments
|
||||
// object leaves v at its zero value, which is valid for the all-optional tools.
|
||||
func decodeArgs(raw json.RawMessage, v any) *rpcError {
|
||||
if len(raw) == 0 || string(raw) == "null" {
|
||||
return nil
|
||||
}
|
||||
if err := json.Unmarshal(raw, v); err != nil {
|
||||
return errf(CodeInvalidParams, "invalid arguments: %v", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ----- list_hosts -----------------------------------------------------------
|
||||
|
||||
type listHostsArgs struct {
|
||||
ClientType string `json:"client_type"`
|
||||
Group string `json:"group"`
|
||||
IncludeOffline *bool `json:"include_offline"`
|
||||
IP string `json:"ip"`
|
||||
Limit int `json:"limit"`
|
||||
Name string `json:"name"`
|
||||
Offset int `json:"offset"`
|
||||
Online *bool `json:"online"`
|
||||
OS string `json:"os"`
|
||||
Query string `json:"query"`
|
||||
}
|
||||
|
||||
func (s *Server) callListHosts(_ context.Context, raw json.RawMessage) (any, *rpcError) {
|
||||
if s.cfg.Hub == nil {
|
||||
return nil, errf(CodeInternal, "server device registry is not configured")
|
||||
}
|
||||
var args listHostsArgs
|
||||
if rerr := decodeArgs(raw, &args); rerr != nil {
|
||||
return nil, rerr
|
||||
}
|
||||
|
||||
// online defaults to true (only online hosts). online=false means "only
|
||||
// offline"; include_offline=true merges history behind the online hosts.
|
||||
online := true
|
||||
if args.Online != nil {
|
||||
online = *args.Online
|
||||
}
|
||||
includeOffline := args.IncludeOffline != nil && *args.IncludeOffline
|
||||
|
||||
onlineDevices := s.cfg.Hub.ListDevices()
|
||||
onlineSet := make(map[string]struct{}, len(onlineDevices))
|
||||
for _, d := range onlineDevices {
|
||||
onlineSet[d.ID] = struct{}{}
|
||||
}
|
||||
offlineDevices := s.offlineDevices(onlineSet)
|
||||
|
||||
var pool []hub.DeviceInfo
|
||||
switch {
|
||||
case !online:
|
||||
pool = offlineDevices
|
||||
case includeOffline:
|
||||
pool = make([]hub.DeviceInfo, 0, len(onlineDevices)+len(offlineDevices))
|
||||
pool = append(pool, onlineDevices...)
|
||||
pool = append(pool, offlineDevices...)
|
||||
default:
|
||||
pool = onlineDevices
|
||||
}
|
||||
totalAll := len(pool)
|
||||
|
||||
// All filters are optional, ANDed, and substring matches. ASCII case
|
||||
// folding is what the tool description promises; strings.ToLower is a
|
||||
// superset and cannot change an ASCII-only match.
|
||||
q := strings.ToLower(args.Query)
|
||||
nameF := strings.ToLower(args.Name)
|
||||
ipF := strings.ToLower(args.IP)
|
||||
groupF := strings.ToLower(args.Group)
|
||||
osF := strings.ToLower(args.OS)
|
||||
ctF := strings.ToLower(args.ClientType)
|
||||
|
||||
matched := make([]hub.DeviceInfo, 0, len(pool))
|
||||
for _, d := range pool {
|
||||
group := d.Group
|
||||
if group == "" {
|
||||
group = "default"
|
||||
}
|
||||
ip := d.IP
|
||||
if ip == "" {
|
||||
ip = d.PeerIP
|
||||
}
|
||||
clientType := ""
|
||||
if d.Online {
|
||||
clientType = s.clientType(d.ID)
|
||||
}
|
||||
// query matches computer name, remark and IP. The two servers keep no
|
||||
// remark column, so name+IP is the full set here.
|
||||
if q != "" && !strings.Contains(strings.ToLower(d.Name), q) && !strings.Contains(strings.ToLower(ip), q) {
|
||||
continue
|
||||
}
|
||||
if nameF != "" && !strings.Contains(strings.ToLower(d.Name), nameF) {
|
||||
continue
|
||||
}
|
||||
if ipF != "" && !strings.Contains(strings.ToLower(ip), ipF) {
|
||||
continue
|
||||
}
|
||||
if groupF != "" && !strings.Contains(strings.ToLower(group), groupF) {
|
||||
continue
|
||||
}
|
||||
if osF != "" && !strings.Contains(strings.ToLower(d.OS), osF) {
|
||||
continue
|
||||
}
|
||||
if ctF != "" && !strings.Contains(strings.ToLower(clientType), ctF) {
|
||||
continue
|
||||
}
|
||||
matched = append(matched, d)
|
||||
}
|
||||
|
||||
limit := clampPageLimit(args.Limit)
|
||||
offset := max(args.Offset, 0)
|
||||
total := len(matched)
|
||||
begin := min(offset, total)
|
||||
end := min(begin+limit, total)
|
||||
hosts := make([]map[string]any, 0, end-begin)
|
||||
for _, d := range matched[begin:end] {
|
||||
hosts = append(hosts, s.hostJSON(d))
|
||||
}
|
||||
|
||||
structured := map[string]any{
|
||||
"hosts": hosts,
|
||||
"total": total,
|
||||
"totalAll": totalAll,
|
||||
"limit": limit,
|
||||
"offset": offset,
|
||||
"hasMore": end < total,
|
||||
}
|
||||
text := pageSummary(total, limit, offset, "台主机")
|
||||
if total != totalAll {
|
||||
text += fmt.Sprintf("过滤前共 %d 台。", totalAll)
|
||||
}
|
||||
text = appendHostRows(text, hosts)
|
||||
return newToolResult(text, structured), nil
|
||||
}
|
||||
|
||||
// hostJSON projects a hub device onto the list_hosts/get_host_detail schema.
|
||||
// Fields the Go server does not know (authStatus, tls, remark, clientType of
|
||||
// an offline entry) are omitted rather than fabricated.
|
||||
func (s *Server) hostJSON(d hub.DeviceInfo) map[string]any {
|
||||
group := d.Group
|
||||
if group == "" {
|
||||
group = "default"
|
||||
}
|
||||
h := map[string]any{
|
||||
"id": d.ID,
|
||||
"name": d.Name,
|
||||
"group": group,
|
||||
"online": d.Online,
|
||||
}
|
||||
if d.Version != "" {
|
||||
h["version"] = d.Version
|
||||
}
|
||||
if d.OS != "" {
|
||||
h["os"] = d.OS
|
||||
}
|
||||
ip := d.IP
|
||||
if ip == "" {
|
||||
ip = d.PeerIP
|
||||
}
|
||||
if ip != "" {
|
||||
h["ip"] = ip
|
||||
}
|
||||
if d.Location != "" {
|
||||
h["location"] = d.Location
|
||||
}
|
||||
if d.InstallTime != "" {
|
||||
h["install_time"] = d.InstallTime
|
||||
}
|
||||
if d.Screen != "" {
|
||||
h["screen"] = d.Screen
|
||||
}
|
||||
if d.Online {
|
||||
// RTT 0 means "no heartbeat yet", not "zero latency".
|
||||
if d.RTT > 0 {
|
||||
h["rtt"] = strconv.Itoa(d.RTT)
|
||||
}
|
||||
if d.ActiveWindow != "" {
|
||||
h["activeWindow"] = d.ActiveWindow
|
||||
}
|
||||
if ct := s.clientType(d.ID); ct != "" {
|
||||
h["clientType"] = ct
|
||||
}
|
||||
} else if d.LastSeen > 0 {
|
||||
h["last_seen"] = time.Unix(d.LastSeen, 0).Format("2006-01-02 15:04:05")
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
// clientType reads the RES_CLIENT_TYPE the client reported at login. It lives
|
||||
// on the main connection's ClientInfo, not on the hub's Device projection.
|
||||
func (s *Server) clientType(deviceID string) string {
|
||||
if s.cfg.Hub == nil {
|
||||
return ""
|
||||
}
|
||||
if ctx := s.cfg.Hub.MainConn(deviceID); ctx != nil {
|
||||
return ctx.GetInfo().ClientType
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// offlineDevices returns history entries that are not currently online. A nil
|
||||
// history store (server started without persistence) yields no entries.
|
||||
func (s *Server) offlineDevices(online map[string]struct{}) []hub.DeviceInfo {
|
||||
if s.cfg.History == nil {
|
||||
return nil
|
||||
}
|
||||
return s.cfg.History.Offline(online)
|
||||
}
|
||||
|
||||
// ----- get_host_detail ------------------------------------------------------
|
||||
|
||||
type getHostDetailArgs struct {
|
||||
ID string `json:"id"`
|
||||
IDs []string `json:"ids"`
|
||||
}
|
||||
|
||||
func (s *Server) callGetHostDetail(_ context.Context, raw json.RawMessage) (any, *rpcError) {
|
||||
if s.cfg.Hub == nil {
|
||||
return nil, errf(CodeInternal, "server device registry is not configured")
|
||||
}
|
||||
var args getHostDetailArgs
|
||||
if rerr := decodeArgs(raw, &args); rerr != nil {
|
||||
return nil, rerr
|
||||
}
|
||||
if len(args.IDs) > 0 {
|
||||
return s.hostDetailBatch(args.IDs)
|
||||
}
|
||||
if args.ID == "" {
|
||||
return nil, errf(CodeInvalidParams, "Missing required parameter: id or ids")
|
||||
}
|
||||
online, offline := s.hostMaps()
|
||||
host, rerr := s.lookupHost(args.ID, online, offline)
|
||||
if rerr != nil {
|
||||
return nil, rerr
|
||||
}
|
||||
return newToolResult(hostDetailText(host), map[string]any{"host": host}), nil
|
||||
}
|
||||
|
||||
func (s *Server) hostDetailBatch(ids []string) (any, *rpcError) {
|
||||
if len(ids) > batchMaxIDs {
|
||||
return nil, errf(CodeInvalidParams,
|
||||
"Too many ids: %d (max %d per batch)", len(ids), batchMaxIDs)
|
||||
}
|
||||
online, offline := s.hostMaps()
|
||||
results := make([]map[string]any, 0, len(ids))
|
||||
succeeded, failed := 0, 0
|
||||
for _, id := range ids {
|
||||
host, rerr := s.lookupHost(id, online, offline)
|
||||
if rerr != nil {
|
||||
results = append(results, map[string]any{
|
||||
"id": id,
|
||||
"ok": false,
|
||||
"text": rerr.Message,
|
||||
"error": map[string]any{"code": rerr.Code, "message": rerr.Message},
|
||||
})
|
||||
failed++
|
||||
continue
|
||||
}
|
||||
results = append(results, map[string]any{
|
||||
"id": id,
|
||||
"ok": true,
|
||||
"text": hostSummary(host),
|
||||
"data": map[string]any{"host": host},
|
||||
})
|
||||
succeeded++
|
||||
}
|
||||
structured := map[string]any{
|
||||
"tool": "get_host_detail",
|
||||
"total": len(ids),
|
||||
"succeeded": succeeded,
|
||||
"failed": failed,
|
||||
"skipped": 0, // no batch deadline: every id is answered locally
|
||||
"results": results,
|
||||
}
|
||||
text := fmt.Sprintf("批量调用 get_host_detail:共 %d 台,成功 %d 台,失败 %d 台。",
|
||||
len(ids), succeeded, failed)
|
||||
text = appendBatchRows(text, results)
|
||||
return newToolResult(text, structured), nil
|
||||
}
|
||||
|
||||
// hostMaps indexes the online devices and offline history by ID. Building both
|
||||
// once per call keeps a 50-id batch at one hub snapshot instead of 50.
|
||||
func (s *Server) hostMaps() (online, offline map[string]hub.DeviceInfo) {
|
||||
onlineDevices := s.cfg.Hub.ListDevices()
|
||||
online = make(map[string]hub.DeviceInfo, len(onlineDevices))
|
||||
onlineSet := make(map[string]struct{}, len(onlineDevices))
|
||||
for _, d := range onlineDevices {
|
||||
online[d.ID] = d
|
||||
onlineSet[d.ID] = struct{}{}
|
||||
}
|
||||
offlineDevices := s.offlineDevices(onlineSet)
|
||||
offline = make(map[string]hub.DeviceInfo, len(offlineDevices))
|
||||
for _, d := range offlineDevices {
|
||||
offline[d.ID] = d
|
||||
}
|
||||
return online, offline
|
||||
}
|
||||
|
||||
// lookupHost resolves one host: online first, then the last-known history
|
||||
// record. It mirrors the Win32 server, which answers offline hosts with their
|
||||
// final snapshot instead of an error.
|
||||
func (s *Server) lookupHost(id string, online, offline map[string]hub.DeviceInfo) (map[string]any, *rpcError) {
|
||||
if !isDecimalID(id) {
|
||||
return nil, errf(CodeInvalidParams, "Invalid id: expected a decimal host id string")
|
||||
}
|
||||
if d, ok := online[id]; ok {
|
||||
h := s.hostJSON(d)
|
||||
h["capabilities"] = s.capabilities(d)
|
||||
return h, nil
|
||||
}
|
||||
if d, ok := offline[id]; ok {
|
||||
return s.hostJSON(d), nil
|
||||
}
|
||||
return nil, errf(CodeOffline, "Host not found or offline: %s", id)
|
||||
}
|
||||
|
||||
// capabilities answers "what can this host do" from the capability hex string
|
||||
// the client reported at login. v2 is deliberately absent: CLIENT_CAP_V2 is
|
||||
// set by every platform, so listing it would only mislead.
|
||||
func (s *Server) capabilities(d hub.DeviceInfo) map[string]any {
|
||||
platform := s.clientType(d.ID)
|
||||
windows := platform != "LNX" && platform != "MAC" && platform != "APK"
|
||||
monitors := monitorCount(d.Screen)
|
||||
// Multi-monitor Windows needs whole-virtual-desktop capture for the
|
||||
// observed and injected coordinate spaces to line up; monitorCount 0
|
||||
// means the client did not report the "N:W*H" form (legacy) and passes,
|
||||
// matching the Win32 server's remote_open gate.
|
||||
virtualDesktopOK := monitors <= 1 || !windows ||
|
||||
protocol.SupportsCap(d.Capability, protocol.ClientCapVirtualDesktop)
|
||||
caps := map[string]any{
|
||||
"screenPreview": protocol.SupportsCap(d.Capability, protocol.ClientCapScreenPreview),
|
||||
"screenRegion": protocol.SupportsCap(d.Capability, protocol.ClientCapScreenRegion),
|
||||
"windowInfo": protocol.SupportsCap(d.Capability, protocol.ClientCapWindowInfo),
|
||||
"fileTransferV2": protocol.SupportsCap(d.Capability, protocol.ClientCapV2),
|
||||
"c2cPaths": protocol.SupportsCap(d.Capability, protocol.ClientCapC2CPaths),
|
||||
"registry": windows,
|
||||
"remoteControl": (windows || platform == "LNX" || platform == "APK") && virtualDesktopOK,
|
||||
}
|
||||
if platform != "" {
|
||||
caps["platform"] = platform
|
||||
}
|
||||
return caps
|
||||
}
|
||||
|
||||
// hostSummary is the human-readable text item for one host.
|
||||
func hostSummary(h map[string]any) string {
|
||||
name, _ := h["name"].(string)
|
||||
ip, _ := h["ip"].(string)
|
||||
if online, _ := h["online"].(bool); !online {
|
||||
return fmt.Sprintf("主机 %s (%s) 当前离线,以下为其最后一次登录时的记录。", name, ip)
|
||||
}
|
||||
return fmt.Sprintf("主机 %s (%s) 的详情。", name, ip)
|
||||
}
|
||||
|
||||
// hostDetailText is the text block for one host: the summary line followed by
|
||||
// the host object as compact JSON. Text-only MCP clients never surface
|
||||
// structuredContent, so without this they would see neither the id nor any
|
||||
// field of the host they just asked about.
|
||||
func hostDetailText(h map[string]any) string {
|
||||
summary := hostSummary(h)
|
||||
b, err := json.Marshal(h)
|
||||
if err != nil {
|
||||
return summary
|
||||
}
|
||||
return summary + "\n" + string(b)
|
||||
}
|
||||
|
||||
// appendHostRows renders the returned page as a tab-separated table. The host
|
||||
// id comes first because every follow-up tool (read_file, get_host_detail,
|
||||
// terminal_exec, ...) is addressed by it.
|
||||
func appendHostRows(text string, hosts []map[string]any) string {
|
||||
rows := make([][]string, 0, len(hosts))
|
||||
for _, h := range hosts {
|
||||
online, _ := h["online"].(bool)
|
||||
rows = append(rows, []string{
|
||||
tableText(h["id"]), tableText(h["name"]), tableText(h["ip"]),
|
||||
tableText(h["group"]), tableText(h["os"]), strconv.FormatBool(online),
|
||||
tableText(h["clientType"]), tableText(h["last_seen"]),
|
||||
})
|
||||
}
|
||||
return appendRows(text,
|
||||
[]string{"id", "name", "ip", "group", "os", "online", "clientType", "last_seen"},
|
||||
rows)
|
||||
}
|
||||
|
||||
// appendBatchRows lists each batch result on its own line: failures carry the
|
||||
// error message, successes the full host JSON.
|
||||
func appendBatchRows(text string, results []map[string]any) string {
|
||||
rows := make([][]string, 0, len(results))
|
||||
for _, r := range results {
|
||||
ok, _ := r["ok"].(bool)
|
||||
var detail string
|
||||
if ok {
|
||||
if data, _ := r["data"].(map[string]any); data != nil {
|
||||
if b, err := json.Marshal(data["host"]); err == nil {
|
||||
detail = string(b)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
detail, _ = r["text"].(string)
|
||||
}
|
||||
rows = append(rows, []string{tableText(r["id"]), strconv.FormatBool(ok), detail})
|
||||
}
|
||||
return appendRows(text, []string{"id", "ok", "detail"}, rows)
|
||||
}
|
||||
|
||||
// ----- get_server_status ----------------------------------------------------
|
||||
|
||||
func (s *Server) callGetServerStatus(_ context.Context, _ json.RawMessage) (any, *rpcError) {
|
||||
uptime := max(int64(time.Since(s.cfg.StartedAt).Seconds()), 0)
|
||||
status := map[string]any{
|
||||
"version": s.cfg.Version,
|
||||
"uptime_sec": uptime,
|
||||
}
|
||||
text := fmt.Sprintf("YAMA Go 服务端已运行 %d 秒", uptime)
|
||||
if s.cfg.Version != "" {
|
||||
text = fmt.Sprintf("YAMA Go 服务端 %s 已运行 %d 秒", s.cfg.Version, uptime)
|
||||
}
|
||||
if s.cfg.Hub != nil {
|
||||
onlineDevices := s.cfg.Hub.ListDevices()
|
||||
onlineSet := make(map[string]struct{}, len(onlineDevices))
|
||||
for _, d := range onlineDevices {
|
||||
onlineSet[d.ID] = struct{}{}
|
||||
}
|
||||
offline := len(s.offlineDevices(onlineSet))
|
||||
status["hosts"] = map[string]any{"online": len(onlineDevices), "offline": offline}
|
||||
text += fmt.Sprintf(";在线 %d 台,离线 %d 台", len(onlineDevices), offline)
|
||||
}
|
||||
// MCP is mounted on the web server, so its listening address is the web
|
||||
// server's. Port/bind stay absent when the caller did not provide them.
|
||||
if s.cfg.Port > 0 {
|
||||
status["port"] = s.cfg.Port
|
||||
}
|
||||
if s.cfg.Bind != "" {
|
||||
status["bind"] = s.cfg.Bind
|
||||
text += ",监听 " + s.cfg.Bind
|
||||
}
|
||||
// The status fields are flat in structuredContent (the outputSchema has no
|
||||
// "status" wrapper object).
|
||||
return newToolResult(text+"。", status), nil
|
||||
}
|
||||
|
||||
// ----- get_audit_log --------------------------------------------------------
|
||||
|
||||
type getAuditLogArgs struct {
|
||||
Keyword string `json:"keyword"`
|
||||
Limit int `json:"limit"`
|
||||
Offset int `json:"offset"`
|
||||
Type string `json:"type"`
|
||||
}
|
||||
|
||||
func (s *Server) callGetAuditLog(_ context.Context, raw json.RawMessage) (any, *rpcError) {
|
||||
if s.cfg.AuditPath == "" {
|
||||
return nil, errf(CodeInternal,
|
||||
"audit log file is disabled on this server (YAMA_AUDIT_LOG=off)")
|
||||
}
|
||||
var args getAuditLogArgs
|
||||
if rerr := decodeArgs(raw, &args); rerr != nil {
|
||||
return nil, rerr
|
||||
}
|
||||
q := auditquery.Query{
|
||||
Keyword: args.Keyword,
|
||||
// The tool's "type" column is a case-insensitive substring of the
|
||||
// event name; the web UI's exact/prefix Event filter does not fit.
|
||||
EventContains: args.Type,
|
||||
}
|
||||
q.Limit = auditquery.ClampLimit(args.Limit, auditquery.MaxLimit)
|
||||
q.Offset = auditquery.ClampOffset(args.Offset)
|
||||
|
||||
res, err := auditquery.Scan(s.cfg.AuditPath, q)
|
||||
if err != nil {
|
||||
return nil, errf(CodeInternal, "failed to read audit log: %v", err)
|
||||
}
|
||||
entries := make([]map[string]any, 0, len(res.Events))
|
||||
for _, rec := range res.Events {
|
||||
entries = append(entries, map[string]any{
|
||||
"type": auditquery.StringField(rec, "event"),
|
||||
"time": auditquery.StringField(rec, "time"),
|
||||
"msg": auditMessage(rec),
|
||||
})
|
||||
}
|
||||
// Scan caps Offset at auditquery.MaxOffset, so a page that reaches that
|
||||
// point must not advertise a next page: the follow-up offset would be
|
||||
// clamped back and return the same records forever.
|
||||
reached := q.Offset + len(entries)
|
||||
structured := map[string]any{
|
||||
"entries": entries,
|
||||
"total": res.Total,
|
||||
"totalAll": res.TotalAll,
|
||||
"limit": q.Limit,
|
||||
"offset": q.Offset,
|
||||
"hasMore": reached < res.Total && reached < auditquery.MaxOffset,
|
||||
}
|
||||
text := pageSummary(res.Total, q.Limit, q.Offset, "条日志")
|
||||
if res.Total != res.TotalAll {
|
||||
text += fmt.Sprintf("过滤前共 %d 条。", res.TotalAll)
|
||||
}
|
||||
if res.Truncated {
|
||||
text += "(审计文件较大,仅扫描最近 32 MB。)"
|
||||
}
|
||||
rows := make([][]string, 0, len(entries))
|
||||
for _, e := range entries {
|
||||
rows = append(rows, []string{tableText(e["time"]), tableText(e["type"]), tableText(e["msg"])})
|
||||
}
|
||||
text = appendRows(text, []string{"time", "type", "msg"}, rows)
|
||||
return newToolResult(text, structured), nil
|
||||
}
|
||||
|
||||
// auditMessage renders the non-envelope fields as compact JSON. The web audit
|
||||
// page shows the raw record; the MCP entry has dedicated type/time columns, so
|
||||
// repeating them inside msg would only add noise.
|
||||
func auditMessage(rec map[string]any) string {
|
||||
rest := make(map[string]any, len(rec))
|
||||
for k, v := range rec {
|
||||
switch k {
|
||||
case "audit", "level", "time", "event":
|
||||
continue
|
||||
}
|
||||
rest[k] = v
|
||||
}
|
||||
if len(rest) == 0 {
|
||||
return ""
|
||||
}
|
||||
b, err := json.Marshal(rest)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// ----- shared helpers -------------------------------------------------------
|
||||
|
||||
func clampPageLimit(n int) int {
|
||||
if n <= 0 {
|
||||
return listDefaultLimit
|
||||
}
|
||||
if n > listMaxLimit {
|
||||
return listMaxLimit
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// appendRows appends a tab-separated table to a summary line. The first
|
||||
// column is always the addressable key (host id, file name, ...), because a
|
||||
// text-only client sees only content[].text and needs the key for the next
|
||||
// call. structuredContent remains the authoritative, exact copy.
|
||||
func appendRows(text string, header []string, rows [][]string) string {
|
||||
if len(rows) == 0 {
|
||||
return text
|
||||
}
|
||||
var b strings.Builder
|
||||
b.WriteString(text)
|
||||
b.WriteByte('\n')
|
||||
b.WriteString(strings.Join(header, "\t"))
|
||||
for _, row := range rows {
|
||||
b.WriteByte('\n')
|
||||
for i, cell := range row {
|
||||
if i > 0 {
|
||||
b.WriteByte('\t')
|
||||
}
|
||||
b.WriteString(oneLine(cell))
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// tableText extracts a string field. An absent field yields "", which oneLine
|
||||
// renders as "-".
|
||||
func tableText(v any) string {
|
||||
s, _ := v.(string)
|
||||
return s
|
||||
}
|
||||
|
||||
// oneLine keeps a table cell on one line: a tab or newline inside a value
|
||||
// would break the column layout. The exact value stays in structuredContent.
|
||||
func oneLine(s string) string {
|
||||
if s == "" {
|
||||
return "-"
|
||||
}
|
||||
return strings.NewReplacer("\t", " ", "\r", " ", "\n", " ").Replace(s)
|
||||
}
|
||||
|
||||
// pageSummary mirrors the Win32 server's summary line:
|
||||
// 「共 N 台主机,本次返回第 1-100 条(还有更多,可用 offset 继续取)。」
|
||||
func pageSummary(total, limit, offset int, unit string) string {
|
||||
out := fmt.Sprintf("共 %d %s", total, unit)
|
||||
if total == 0 {
|
||||
return out + "。"
|
||||
}
|
||||
begin := min(offset, total)
|
||||
if begin >= total {
|
||||
return out + ",offset 超出范围,本次返回 0 条。"
|
||||
}
|
||||
end := min(begin+limit, total)
|
||||
out += fmt.Sprintf(",本次返回第 %d-%d 条", begin+1, end)
|
||||
if end < total {
|
||||
out += "(还有更多,可用 offset 继续取)"
|
||||
}
|
||||
return out + "。"
|
||||
}
|
||||
|
||||
// isDecimalID reports whether id is a non-empty decimal string. Host IDs are
|
||||
// uint64 rendered in decimal; anything else is a caller mistake.
|
||||
func isDecimalID(id string) bool {
|
||||
if id == "" {
|
||||
return false
|
||||
}
|
||||
for _, r := range id {
|
||||
if r < '0' || r > '9' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// monitorCount parses the "N:W*H" screen string the client reports. 0 means
|
||||
// "not reported / not in that form".
|
||||
func monitorCount(screen string) int {
|
||||
i := strings.IndexByte(screen, ':')
|
||||
if i <= 0 {
|
||||
return 0
|
||||
}
|
||||
n, err := strconv.Atoi(strings.TrimSpace(screen[:i]))
|
||||
if err != nil || n < 0 {
|
||||
return 0
|
||||
}
|
||||
return n
|
||||
}
|
||||
@@ -0,0 +1,712 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/auditquery"
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/connection"
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/devicehistory"
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
|
||||
)
|
||||
|
||||
// localFixture is the shared setup for the four local read tools: three online
|
||||
// hosts (two Windows in one group, one Linux), two offline history entries, and
|
||||
// a history store that is subscribed to the hub.
|
||||
type localFixture struct {
|
||||
srv *Server
|
||||
hub *hub.Hub
|
||||
hist *devicehistory.Store
|
||||
}
|
||||
|
||||
func newLocalFixture(t *testing.T) *localFixture {
|
||||
t.Helper()
|
||||
h := hub.New()
|
||||
hist, err := devicehistory.Open(filepath.Join(t.TempDir(), "devices.json"), 100, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("open history: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = hist.Close() })
|
||||
h.Subscribe(hist)
|
||||
|
||||
now := time.Now()
|
||||
register := func(d hub.Device, clientType string) {
|
||||
h.Register(&d, &connection.Context{
|
||||
RemoteAddr: d.PeerIP + ":40000",
|
||||
Info: connection.ClientInfo{ClientType: clientType},
|
||||
})
|
||||
}
|
||||
register(hub.Device{
|
||||
ID: "1001", Name: "ALPHA", Version: "1.2.3", Capability: "0005",
|
||||
OS: "Windows 10", PublicIP: "10.0.0.1", PeerIP: "192.168.1.1",
|
||||
Resolution: "1:1920*1080", ConnectedAt: now.Add(-3 * time.Minute),
|
||||
}, "EXE")
|
||||
register(hub.Device{
|
||||
ID: "1002", Name: "BETA", Group: "Office", Version: "1.2.3", Capability: "0005",
|
||||
OS: "Windows 11", PeerIP: "192.168.1.2",
|
||||
Resolution: "2:3840*2160", ConnectedAt: now.Add(-2 * time.Minute),
|
||||
}, "EXE")
|
||||
register(hub.Device{
|
||||
ID: "1003", Name: "GAMMA", Group: "Office", Version: "1.1.0",
|
||||
OS: "Ubuntu 24.04", PublicIP: "10.1.0.3", PeerIP: "192.168.1.3",
|
||||
Resolution: "1:2560*1440", ConnectedAt: now.Add(-time.Minute),
|
||||
}, "LNX")
|
||||
h.UpdateLive("1001", 42, "Notepad")
|
||||
h.UpdateLive("1003", 120, "")
|
||||
|
||||
// Two devices that logged in and then left, so the history store has
|
||||
// offline entries to merge into listings.
|
||||
register(hub.Device{
|
||||
ID: "2001", Name: "OLDWIN", Group: "Legacy", Version: "0.9.0", Capability: "0002",
|
||||
OS: "Windows 7", PublicIP: "10.9.0.1", PeerIP: "192.168.9.1",
|
||||
Resolution: "1:1280*1024", ConnectedAt: now.Add(-10 * time.Minute),
|
||||
}, "EXE")
|
||||
register(hub.Device{
|
||||
ID: "2002", Name: "OLDMAC", Version: "0.8.0",
|
||||
OS: "macOS 14", PublicIP: "10.9.0.2", PeerIP: "192.168.9.2",
|
||||
Resolution: "1:1440*900", ConnectedAt: now.Add(-9 * time.Minute),
|
||||
}, "MAC")
|
||||
h.Unregister("2001")
|
||||
h.Unregister("2002")
|
||||
|
||||
srv := New(Config{
|
||||
Token: "test-token",
|
||||
Hub: h,
|
||||
History: hist,
|
||||
Version: "v9.9.9",
|
||||
StartedAt: time.Now().Add(-90 * time.Second),
|
||||
Port: 6544,
|
||||
Bind: "0.0.0.0",
|
||||
})
|
||||
return &localFixture{srv: srv, hub: h, hist: hist}
|
||||
}
|
||||
|
||||
// callLocal drives one tools/call through the same gate the HTTP path uses and
|
||||
// returns the decoded structuredContent plus the text item.
|
||||
func callLocal(t *testing.T, s *Server, name, args string) (string, map[string]any, *rpcError) {
|
||||
t.Helper()
|
||||
params := fmt.Sprintf(`{"name":%q,"arguments":%s}`, name, args)
|
||||
res, rerr := s.callTool(context.Background(), json.RawMessage(params))
|
||||
if rerr != nil {
|
||||
return "", nil, rerr
|
||||
}
|
||||
raw, err := json.Marshal(res)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal tool result: %v", err)
|
||||
}
|
||||
var env struct {
|
||||
Content []struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text"`
|
||||
} `json:"content"`
|
||||
StructuredContent map[string]any `json:"structuredContent"`
|
||||
IsError bool `json:"isError"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &env); err != nil {
|
||||
t.Fatalf("decode tool result: %v", err)
|
||||
}
|
||||
if env.IsError {
|
||||
t.Fatalf("isError = true on success path: %s", raw)
|
||||
}
|
||||
if len(env.Content) != 1 || env.Content[0].Type != "text" {
|
||||
t.Fatalf("content = %+v, want one text item", env.Content)
|
||||
}
|
||||
return env.Content[0].Text, env.StructuredContent, nil
|
||||
}
|
||||
|
||||
func mustCallLocal(t *testing.T, s *Server, name, args string) (string, map[string]any) {
|
||||
t.Helper()
|
||||
text, sc, rerr := callLocal(t, s, name, args)
|
||||
if rerr != nil {
|
||||
t.Fatalf("%s returned error %d: %s", name, rerr.Code, rerr.Message)
|
||||
}
|
||||
return text, sc
|
||||
}
|
||||
|
||||
func intField(t *testing.T, m map[string]any, key string) int {
|
||||
t.Helper()
|
||||
v, ok := m[key]
|
||||
if !ok {
|
||||
t.Fatalf("missing %q in %v", key, m)
|
||||
}
|
||||
f, ok := v.(float64)
|
||||
if !ok {
|
||||
t.Fatalf("%q = %v (%T), want number", key, v, v)
|
||||
}
|
||||
return int(f)
|
||||
}
|
||||
|
||||
func boolField(t *testing.T, m map[string]any, key string) bool {
|
||||
t.Helper()
|
||||
v, ok := m[key]
|
||||
if !ok {
|
||||
t.Fatalf("missing %q in %v", key, m)
|
||||
}
|
||||
b, ok := v.(bool)
|
||||
if !ok {
|
||||
t.Fatalf("%q = %v (%T), want bool", key, v, v)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func strField(t *testing.T, m map[string]any, key string) string {
|
||||
t.Helper()
|
||||
v, ok := m[key]
|
||||
if !ok {
|
||||
t.Fatalf("missing %q in %v", key, m)
|
||||
}
|
||||
s, ok := v.(string)
|
||||
if !ok {
|
||||
t.Fatalf("%q = %v (%T), want string", key, v, v)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func hostList(t *testing.T, sc map[string]any) []map[string]any {
|
||||
t.Helper()
|
||||
raw, ok := sc["hosts"].([]any)
|
||||
if !ok {
|
||||
t.Fatalf("hosts = %v (%T), want array", sc["hosts"], sc["hosts"])
|
||||
}
|
||||
out := make([]map[string]any, 0, len(raw))
|
||||
for _, item := range raw {
|
||||
m, ok := item.(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("host entry = %v (%T), want object", item, item)
|
||||
}
|
||||
out = append(out, m)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func hostIDs(hosts []map[string]any) []string {
|
||||
ids := make([]string, 0, len(hosts))
|
||||
for _, h := range hosts {
|
||||
ids = append(ids, h["id"].(string))
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
func wantIDs(t *testing.T, hosts []map[string]any, want ...string) {
|
||||
t.Helper()
|
||||
got := hostIDs(hosts)
|
||||
if strings.Join(got, ",") != strings.Join(want, ",") {
|
||||
t.Fatalf("ids = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppendRowsSanitizesCells(t *testing.T) {
|
||||
got := appendRows("head", []string{"a", "b"},
|
||||
[][]string{{"x\ty", "line\nbreak"}, {"", ""}})
|
||||
want := "head\na\tb\nx y\tline break\n-\t-"
|
||||
if got != want {
|
||||
t.Fatalf("appendRows = %q, want %q", got, want)
|
||||
}
|
||||
if got := appendRows("head", []string{"a"}, nil); got != "head" {
|
||||
t.Fatalf("empty rows = %q, want unchanged summary", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListHostsPoolsAndProjection(t *testing.T) {
|
||||
f := newLocalFixture(t)
|
||||
|
||||
text, sc := mustCallLocal(t, f.srv, "list_hosts", `{}`)
|
||||
hosts := hostList(t, sc)
|
||||
wantIDs(t, hosts, "1001", "1002", "1003")
|
||||
if got := intField(t, sc, "total"); got != 3 {
|
||||
t.Fatalf("total = %d, want 3", got)
|
||||
}
|
||||
if got := intField(t, sc, "totalAll"); got != 3 {
|
||||
t.Fatalf("totalAll = %d, want 3", got)
|
||||
}
|
||||
if got := intField(t, sc, "limit"); got != 100 {
|
||||
t.Fatalf("limit = %d, want default 100", got)
|
||||
}
|
||||
if boolField(t, sc, "hasMore") {
|
||||
t.Fatal("hasMore = true for a full 3-host page")
|
||||
}
|
||||
if !strings.Contains(text, "共 3 台主机") {
|
||||
t.Fatalf("text = %q, want host count", text)
|
||||
}
|
||||
// Text-only MCP clients never see structuredContent, so the table in the
|
||||
// text block must carry the id every follow-up call is addressed by.
|
||||
if !strings.Contains(text, "id\tname\tip\tgroup\tos\tonline\tclientType\tlast_seen") {
|
||||
t.Fatalf("text = %q, want host table header", text)
|
||||
}
|
||||
if !strings.Contains(text, "1001\tALPHA\t10.0.0.1\tdefault\tWindows 10\ttrue\tEXE\t-") {
|
||||
t.Fatalf("text = %q, want ALPHA row with id first", text)
|
||||
}
|
||||
|
||||
alpha := hosts[0]
|
||||
if got := strField(t, alpha, "name"); got != "ALPHA" {
|
||||
t.Fatalf("name = %q", got)
|
||||
}
|
||||
if got := strField(t, alpha, "group"); got != "default" {
|
||||
t.Fatalf("group = %q, want normalized default", got)
|
||||
}
|
||||
if got := strField(t, alpha, "clientType"); got != "EXE" {
|
||||
t.Fatalf("clientType = %q", got)
|
||||
}
|
||||
if got := strField(t, alpha, "rtt"); got != "42" {
|
||||
t.Fatalf("rtt = %q, want decimal string", got)
|
||||
}
|
||||
if got := strField(t, alpha, "activeWindow"); got != "Notepad" {
|
||||
t.Fatalf("activeWindow = %q", got)
|
||||
}
|
||||
if got := strField(t, alpha, "ip"); got != "10.0.0.1" {
|
||||
t.Fatalf("ip = %q, want client-reported public IP", got)
|
||||
}
|
||||
if got := strField(t, alpha, "screen"); got != "1:1920*1080" {
|
||||
t.Fatalf("screen = %q", got)
|
||||
}
|
||||
if _, ok := alpha["last_seen"]; ok {
|
||||
t.Fatal("online host carries last_seen")
|
||||
}
|
||||
for _, absent := range []string{"remark", "authStatus", "tls"} {
|
||||
if _, ok := alpha[absent]; ok {
|
||||
t.Fatalf("%s present but the Go server has no such data", absent)
|
||||
}
|
||||
}
|
||||
|
||||
// include_offline merges history behind the online hosts.
|
||||
_, sc = mustCallLocal(t, f.srv, "list_hosts", `{"include_offline":true}`)
|
||||
hosts = hostList(t, sc)
|
||||
wantIDs(t, hosts, "1001", "1002", "1003", "2001", "2002")
|
||||
if got := intField(t, sc, "totalAll"); got != 5 {
|
||||
t.Fatalf("totalAll = %d, want 5", got)
|
||||
}
|
||||
for _, h := range hosts[:3] {
|
||||
if !boolField(t, h, "online") {
|
||||
t.Fatalf("%s should be online", h["id"])
|
||||
}
|
||||
}
|
||||
for _, h := range hosts[3:] {
|
||||
if boolField(t, h, "online") {
|
||||
t.Fatalf("%s should be offline", h["id"])
|
||||
}
|
||||
if h["last_seen"] == "" || h["last_seen"] == nil {
|
||||
t.Fatalf("%s missing last_seen", h["id"])
|
||||
}
|
||||
}
|
||||
|
||||
// online=false lists offline only.
|
||||
_, sc = mustCallLocal(t, f.srv, "list_hosts", `{"online":false}`)
|
||||
hosts = hostList(t, sc)
|
||||
wantIDs(t, hosts, "2001", "2002")
|
||||
if got := intField(t, sc, "totalAll"); got != 2 {
|
||||
t.Fatalf("totalAll = %d, want 2 offline hosts", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListHostsFilters(t *testing.T) {
|
||||
f := newLocalFixture(t)
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
args string
|
||||
want []string
|
||||
}{
|
||||
{"name substring", `{"name":"beta"}`, []string{"1002"}},
|
||||
{"group substring", `{"group":"office"}`, []string{"1002", "1003"}},
|
||||
{"os substring case-insensitive", `{"os":"windows"}`, []string{"1001", "1002"}},
|
||||
{"client type", `{"client_type":"lnx"}`, []string{"1003"}},
|
||||
{"public ip substring", `{"ip":"10.1.0"}`, []string{"1003"}},
|
||||
{"peer ip fallback", `{"ip":"192.168.1.2"}`, []string{"1002"}},
|
||||
{"query matches name", `{"query":"gamma"}`, []string{"1003"}},
|
||||
{"query matches ip", `{"query":"10.0.0.1"}`, []string{"1001"}},
|
||||
{"filters are ANDed", `{"group":"office","os":"ubuntu"}`, []string{"1003"}},
|
||||
{"no match", `{"name":"zzz"}`, nil},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
text, sc := mustCallLocal(t, f.srv, "list_hosts", tc.args)
|
||||
hosts := hostList(t, sc)
|
||||
wantIDs(t, hosts, tc.want...)
|
||||
if got := intField(t, sc, "total"); got != len(tc.want) {
|
||||
t.Fatalf("total = %d, want %d (text %q)", got, len(tc.want), text)
|
||||
}
|
||||
// totalAll stays the unfiltered pool size.
|
||||
if got := intField(t, sc, "totalAll"); got != 3 {
|
||||
t.Fatalf("totalAll = %d, want 3", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// An empty result must be a JSON array, never null.
|
||||
_, sc := mustCallLocal(t, f.srv, "list_hosts", `{"name":"zzz"}`)
|
||||
raw, err := json.Marshal(sc)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
if !strings.Contains(string(raw), `"hosts":[]`) {
|
||||
t.Fatalf("hosts not an empty array: %s", raw)
|
||||
}
|
||||
|
||||
// client_type cannot match an offline record: history keeps no client type.
|
||||
_, sc = mustCallLocal(t, f.srv, "list_hosts", `{"online":false,"client_type":"EXE"}`)
|
||||
if hosts := hostList(t, sc); len(hosts) != 0 {
|
||||
t.Fatalf("offline client_type filter matched %v, want none", hostIDs(hosts))
|
||||
}
|
||||
}
|
||||
|
||||
func TestListHostsPaging(t *testing.T) {
|
||||
f := newLocalFixture(t)
|
||||
|
||||
_, sc := mustCallLocal(t, f.srv, "list_hosts", `{"limit":2}`)
|
||||
hosts := hostList(t, sc)
|
||||
wantIDs(t, hosts, "1001", "1002")
|
||||
if got := intField(t, sc, "total"); got != 3 {
|
||||
t.Fatalf("total = %d, want 3", got)
|
||||
}
|
||||
if !boolField(t, sc, "hasMore") {
|
||||
t.Fatal("hasMore = false, want true")
|
||||
}
|
||||
|
||||
_, sc = mustCallLocal(t, f.srv, "list_hosts", `{"limit":2,"offset":2}`)
|
||||
hosts = hostList(t, sc)
|
||||
wantIDs(t, hosts, "1003")
|
||||
if boolField(t, sc, "hasMore") {
|
||||
t.Fatal("hasMore = true on the last page")
|
||||
}
|
||||
if got := intField(t, sc, "offset"); got != 2 {
|
||||
t.Fatalf("offset = %d, want 2", got)
|
||||
}
|
||||
|
||||
text, sc := mustCallLocal(t, f.srv, "list_hosts", `{"offset":99}`)
|
||||
if hosts := hostList(t, sc); len(hosts) != 0 {
|
||||
t.Fatalf("offset past end returned %v", hostIDs(hosts))
|
||||
}
|
||||
if !strings.Contains(text, "offset 超出范围") {
|
||||
t.Fatalf("text = %q, want out-of-range note", text)
|
||||
}
|
||||
|
||||
_, sc = mustCallLocal(t, f.srv, "list_hosts", `{"limit":5000}`)
|
||||
if got := intField(t, sc, "limit"); got != listMaxLimit {
|
||||
t.Fatalf("limit = %d, want clamped to %d", got, listMaxLimit)
|
||||
}
|
||||
_, sc = mustCallLocal(t, f.srv, "list_hosts", `{"limit":-5}`)
|
||||
if got := intField(t, sc, "limit"); got != listDefaultLimit {
|
||||
t.Fatalf("limit = %d, want default %d", got, listDefaultLimit)
|
||||
}
|
||||
|
||||
// Malformed arguments are a caller error, not an empty list.
|
||||
if _, _, rerr := callLocal(t, f.srv, "list_hosts", `{"limit":"many"}`); rerr == nil || rerr.Code != CodeInvalidParams {
|
||||
t.Fatalf("malformed limit error = %+v, want -32602", rerr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetHostDetailOnlineAndOffline(t *testing.T) {
|
||||
f := newLocalFixture(t)
|
||||
|
||||
text, sc := mustCallLocal(t, f.srv, "get_host_detail", `{"id":"1001"}`)
|
||||
if !strings.Contains(text, "\n") || !strings.Contains(text, `"id":"1001"`) ||
|
||||
!strings.Contains(text, `"name":"ALPHA"`) {
|
||||
t.Fatalf("text = %q, want summary plus host JSON", text)
|
||||
}
|
||||
host, ok := sc["host"].(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("host = %v", sc["host"])
|
||||
}
|
||||
if !boolField(t, host, "online") {
|
||||
t.Fatal("1001 should be online")
|
||||
}
|
||||
caps, ok := host["capabilities"].(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("capabilities = %v", host["capabilities"])
|
||||
}
|
||||
if !boolField(t, caps, "screenPreview") || !boolField(t, caps, "fileTransferV2") {
|
||||
t.Fatalf("caps = %v, want preview+V2 from 0x0005", caps)
|
||||
}
|
||||
if boolField(t, caps, "screenRegion") {
|
||||
t.Fatalf("caps = %v, screenRegion set without 0x0200", caps)
|
||||
}
|
||||
if !boolField(t, caps, "registry") {
|
||||
t.Fatalf("caps = %v, Windows client must have registry", caps)
|
||||
}
|
||||
if !boolField(t, caps, "remoteControl") {
|
||||
t.Fatalf("caps = %v, single-monitor Windows must allow remote control", caps)
|
||||
}
|
||||
if got := strField(t, caps, "platform"); got != "EXE" {
|
||||
t.Fatalf("platform = %q", got)
|
||||
}
|
||||
if _, ok := caps["v2"]; ok {
|
||||
t.Fatal("v2 must not be reported: every platform sets it")
|
||||
}
|
||||
|
||||
// A multi-monitor Windows client without whole-desktop capture is not
|
||||
// remotely controllable (coordinate spaces would not line up).
|
||||
f.hub.Register(&hub.Device{
|
||||
ID: "1004", Name: "DUAL", Capability: "0005",
|
||||
OS: "Windows 11", PublicIP: "10.0.0.4", PeerIP: "192.168.1.4",
|
||||
Resolution: "2:3840*2160", ConnectedAt: time.Now(),
|
||||
}, &connection.Context{RemoteAddr: "192.168.1.4:40000",
|
||||
Info: connection.ClientInfo{ClientType: "EXE"}})
|
||||
_, sc = mustCallLocal(t, f.srv, "get_host_detail", `{"id":"1004"}`)
|
||||
caps = sc["host"].(map[string]any)["capabilities"].(map[string]any)
|
||||
if boolField(t, caps, "remoteControl") {
|
||||
t.Fatalf("caps = %v, dual-monitor without VIRTUAL_DESKTOP must not allow remote control", caps)
|
||||
}
|
||||
|
||||
// Offline detail comes from history: no capabilities (the device is gone),
|
||||
// but the last-known fields are intact.
|
||||
_, sc = mustCallLocal(t, f.srv, "get_host_detail", `{"id":"2001"}`)
|
||||
host = sc["host"].(map[string]any)
|
||||
if boolField(t, host, "online") {
|
||||
t.Fatal("2001 should be offline")
|
||||
}
|
||||
if got := strField(t, host, "version"); got != "0.9.0" {
|
||||
t.Fatalf("version = %q", got)
|
||||
}
|
||||
if _, ok := host["capabilities"]; ok {
|
||||
t.Fatal("offline host must not report capabilities")
|
||||
}
|
||||
|
||||
if _, _, rerr := callLocal(t, f.srv, "get_host_detail", `{"id":"9999"}`); rerr == nil || rerr.Code != CodeOffline {
|
||||
t.Fatalf("unknown host error = %+v, want -32002", rerr)
|
||||
}
|
||||
if _, _, rerr := callLocal(t, f.srv, "get_host_detail", `{"id":"12ab"}`); rerr == nil || rerr.Code != CodeInvalidParams {
|
||||
t.Fatalf("non-decimal id error = %+v, want -32602", rerr)
|
||||
}
|
||||
if _, _, rerr := callLocal(t, f.srv, "get_host_detail", `{}`); rerr == nil || rerr.Code != CodeInvalidParams {
|
||||
t.Fatalf("missing id error = %+v, want -32602", rerr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetHostDetailBatch(t *testing.T) {
|
||||
f := newLocalFixture(t)
|
||||
|
||||
text, sc := mustCallLocal(t, f.srv, "get_host_detail", `{"ids":["1001","9999","2001"]}`)
|
||||
if !strings.Contains(text, "id\tok\tdetail") ||
|
||||
!strings.Contains(text, "1001\ttrue\t{") ||
|
||||
!strings.Contains(text, "9999\tfalse\t") {
|
||||
t.Fatalf("text = %q, want one row per id", text)
|
||||
}
|
||||
if got := strField(t, sc, "tool"); got != "get_host_detail" {
|
||||
t.Fatalf("tool = %q", got)
|
||||
}
|
||||
if got := intField(t, sc, "total"); got != 3 {
|
||||
t.Fatalf("total = %d, want 3", got)
|
||||
}
|
||||
if got := intField(t, sc, "succeeded"); got != 2 {
|
||||
t.Fatalf("succeeded = %d, want 2", got)
|
||||
}
|
||||
if got := intField(t, sc, "failed"); got != 1 {
|
||||
t.Fatalf("failed = %d, want 1", got)
|
||||
}
|
||||
if got := intField(t, sc, "skipped"); got != 0 {
|
||||
t.Fatalf("skipped = %d, want 0", got)
|
||||
}
|
||||
results, ok := sc["results"].([]any)
|
||||
if !ok || len(results) != 3 {
|
||||
t.Fatalf("results = %v", sc["results"])
|
||||
}
|
||||
first := results[0].(map[string]any)
|
||||
if !boolField(t, first, "ok") {
|
||||
t.Fatal("first result should be ok")
|
||||
}
|
||||
data := first["data"].(map[string]any)
|
||||
if id := strField(t, data["host"].(map[string]any), "id"); id != "1001" {
|
||||
t.Fatalf("first host id = %q", id)
|
||||
}
|
||||
second := results[1].(map[string]any)
|
||||
if boolField(t, second, "ok") {
|
||||
t.Fatal("second result should fail")
|
||||
}
|
||||
errObj := second["error"].(map[string]any)
|
||||
if got := intField(t, errObj, "code"); got != CodeOffline {
|
||||
t.Fatalf("per-entry code = %d, want %d", got, CodeOffline)
|
||||
}
|
||||
third := results[2].(map[string]any)
|
||||
if !boolField(t, third, "ok") {
|
||||
t.Fatal("offline history entry should succeed in a batch")
|
||||
}
|
||||
|
||||
ids := make([]string, batchMaxIDs+1)
|
||||
for i := range ids {
|
||||
ids[i] = "1001"
|
||||
}
|
||||
payload, _ := json.Marshal(map[string]any{"ids": ids})
|
||||
if _, _, rerr := callLocal(t, f.srv, "get_host_detail", string(payload)); rerr == nil || rerr.Code != CodeInvalidParams {
|
||||
t.Fatalf("oversized batch error = %+v, want -32602", rerr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetServerStatus(t *testing.T) {
|
||||
f := newLocalFixture(t)
|
||||
|
||||
_, sc := mustCallLocal(t, f.srv, "get_server_status", `{}`)
|
||||
if got := strField(t, sc, "version"); got != "v9.9.9" {
|
||||
t.Fatalf("version = %q", got)
|
||||
}
|
||||
// StartedAt is 90s in the past; the exact value depends on test runtime.
|
||||
if got := intField(t, sc, "uptime_sec"); got < 90 {
|
||||
t.Fatalf("uptime_sec = %d, want >= 90", got)
|
||||
}
|
||||
hosts, ok := sc["hosts"].(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("hosts = %v", sc["hosts"])
|
||||
}
|
||||
if got := intField(t, hosts, "online"); got != 3 {
|
||||
t.Fatalf("online = %d, want 3", got)
|
||||
}
|
||||
if got := intField(t, hosts, "offline"); got != 2 {
|
||||
t.Fatalf("offline = %d, want 2", got)
|
||||
}
|
||||
if got := intField(t, sc, "port"); got != 6544 {
|
||||
t.Fatalf("port = %d", got)
|
||||
}
|
||||
if got := strField(t, sc, "bind"); got != "0.0.0.0" {
|
||||
t.Fatalf("bind = %q", got)
|
||||
}
|
||||
if _, ok := sc["sessions"]; ok {
|
||||
t.Fatal("sessions reported before the MCP session table exists")
|
||||
}
|
||||
}
|
||||
|
||||
// A build without link-time version injection must not invent one: the status
|
||||
// tool reports the empty string, and only initialize substitutes "dev".
|
||||
func TestUnversionedBuild(t *testing.T) {
|
||||
s := New(Config{Token: "test-token"})
|
||||
|
||||
_, sc := mustCallLocal(t, s, "get_server_status", `{}`)
|
||||
if got, ok := sc["version"]; !ok || got != "" {
|
||||
t.Fatalf("status version = %#v, want empty string", got)
|
||||
}
|
||||
if got := s.initializeResult().ServerInfo.Version; got != "dev" {
|
||||
t.Fatalf("initialize version = %q, want dev", got)
|
||||
}
|
||||
}
|
||||
|
||||
func writeAuditFile(t *testing.T, lines ...string) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "audit.log")
|
||||
body := strings.Join(lines, "\n") + "\n"
|
||||
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
|
||||
t.Fatalf("write audit file: %v", err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func TestGetAuditLog(t *testing.T) {
|
||||
path := writeAuditFile(t,
|
||||
`{"audit":true,"time":"2026-11-12T10:00:00Z","level":"info","event":"web.login.success","actor":"admin","ip":"1.2.3.4"}`,
|
||||
`{"audit":true,"time":"2026-11-12T10:01:00Z","level":"info","event":"web.login.failure","actor":"bob","ip":"5.6.7.8"}`,
|
||||
`{"audit":true,"time":"2026-11-12T10:02:00Z","level":"warn","event":"authz.denied","actor":"admin","ip":"1.2.3.4","detail":"readonly"}`,
|
||||
`{"audit":true,"time":"2026-11-12T10:03:00Z","level":"info","event":"device.online","device_id":"1001"}`,
|
||||
)
|
||||
s := New(Config{Token: "test-token", AuditPath: path})
|
||||
|
||||
text, sc := mustCallLocal(t, s, "get_audit_log", `{}`)
|
||||
if !strings.Contains(text, "time\ttype\tmsg") ||
|
||||
!strings.Contains(text, "2026-11-12T10:03:00Z\tdevice.online\t") {
|
||||
t.Fatalf("text = %q, want audit rows", text)
|
||||
}
|
||||
entries, ok := sc["entries"].([]any)
|
||||
if !ok || len(entries) != 4 {
|
||||
t.Fatalf("entries = %v, want 4", sc["entries"])
|
||||
}
|
||||
if got := intField(t, sc, "total"); got != 4 {
|
||||
t.Fatalf("total = %d, want 4", got)
|
||||
}
|
||||
if got := intField(t, sc, "totalAll"); got != 4 {
|
||||
t.Fatalf("totalAll = %d, want 4", got)
|
||||
}
|
||||
if boolField(t, sc, "hasMore") {
|
||||
t.Fatal("hasMore = true for a complete page")
|
||||
}
|
||||
newest := entries[0].(map[string]any)
|
||||
if got := strField(t, newest, "type"); got != "device.online" {
|
||||
t.Fatalf("newest type = %q, want newest first", got)
|
||||
}
|
||||
if got := strField(t, newest, "time"); got != "2026-11-12T10:03:00Z" {
|
||||
t.Fatalf("newest time = %q", got)
|
||||
}
|
||||
msg := strField(t, newest, "msg")
|
||||
if !strings.Contains(msg, `"device_id":"1001"`) {
|
||||
t.Fatalf("msg = %q, want remaining fields", msg)
|
||||
}
|
||||
for _, envelope := range []string{`"audit"`, `"event"`, `"level"`, `"time"`} {
|
||||
if strings.Contains(msg, envelope) {
|
||||
t.Fatalf("msg repeats envelope key %s: %s", envelope, msg)
|
||||
}
|
||||
}
|
||||
|
||||
// type is a case-insensitive substring of the event name.
|
||||
_, sc = mustCallLocal(t, s, "get_audit_log", `{"type":"LOGIN"}`)
|
||||
if got := intField(t, sc, "total"); got != 2 {
|
||||
t.Fatalf("login total = %d, want 2", got)
|
||||
}
|
||||
if got := intField(t, sc, "totalAll"); got != 4 {
|
||||
t.Fatalf("login totalAll = %d, want unfiltered 4", got)
|
||||
}
|
||||
_, sc = mustCallLocal(t, s, "get_audit_log", `{"type":"login","keyword":"1.2.3.4"}`)
|
||||
if got := intField(t, sc, "total"); got != 1 {
|
||||
t.Fatalf("type+keyword total = %d, want 1", got)
|
||||
}
|
||||
|
||||
// Paging: limit 2 → hasMore; the tail page stops there.
|
||||
_, sc = mustCallLocal(t, s, "get_audit_log", `{"limit":2}`)
|
||||
if got := len(sc["entries"].([]any)); got != 2 {
|
||||
t.Fatalf("entries = %d, want 2", got)
|
||||
}
|
||||
if !boolField(t, sc, "hasMore") {
|
||||
t.Fatal("hasMore = false with 2 of 4")
|
||||
}
|
||||
_, sc = mustCallLocal(t, s, "get_audit_log", `{"limit":2,"offset":3}`)
|
||||
if got := len(sc["entries"].([]any)); got != 1 {
|
||||
t.Fatalf("tail entries = %d, want 1", got)
|
||||
}
|
||||
if boolField(t, sc, "hasMore") {
|
||||
t.Fatal("hasMore = true on the tail page")
|
||||
}
|
||||
|
||||
// Empty result is an array, and the file is scanned only up to its size.
|
||||
_, sc = mustCallLocal(t, s, "get_audit_log", `{"keyword":"no-such-thing"}`)
|
||||
raw, _ := json.Marshal(sc)
|
||||
if !strings.Contains(string(raw), `"entries":[]`) {
|
||||
t.Fatalf("entries not an empty array: %s", raw)
|
||||
}
|
||||
|
||||
// Missing file: an empty log, not an error.
|
||||
f := newLocalFixture(t)
|
||||
f.srv.cfg.AuditPath = filepath.Join(t.TempDir(), "missing.log")
|
||||
if _, sc = mustCallLocal(t, f.srv, "get_audit_log", `{}`); intField(t, sc, "total") != 0 {
|
||||
t.Fatalf("missing file total = %d, want 0", intField(t, sc, "total"))
|
||||
}
|
||||
|
||||
// Disabled audit file (YAMA_AUDIT_LOG=off) is a configuration error.
|
||||
off := New(Config{Token: "test-token"})
|
||||
if _, _, rerr := callLocal(t, off, "get_audit_log", `{}`); rerr == nil || rerr.Code != CodeInternal {
|
||||
t.Fatalf("disabled audit error = %+v, want -32000", rerr)
|
||||
}
|
||||
|
||||
// Offset is clamped at auditquery.MaxOffset. A page that ends exactly
|
||||
// there must not advertise a next page: the follow-up offset would be
|
||||
// clamped back and return the same records forever.
|
||||
var big strings.Builder
|
||||
for i := range auditquery.MaxOffset + 2000 {
|
||||
fmt.Fprintf(&big, `{"audit":true,"time":"2026-11-12T10:00:00Z","level":"info","event":"device.online","n":%d}`+"\n", i)
|
||||
}
|
||||
bigPath := filepath.Join(t.TempDir(), "audit.log")
|
||||
if err := os.WriteFile(bigPath, []byte(big.String()), 0o600); err != nil {
|
||||
t.Fatalf("write big audit file: %v", err)
|
||||
}
|
||||
bigSrv := New(Config{Token: "test-token", AuditPath: bigPath})
|
||||
_, sc = mustCallLocal(t, bigSrv, "get_audit_log", `{"limit":500}`)
|
||||
if !boolField(t, sc, "hasMore") {
|
||||
t.Fatal("hasMore = false on the first page of a large log")
|
||||
}
|
||||
_, sc = mustCallLocal(t, bigSrv, "get_audit_log", `{"limit":500,"offset":9500}`)
|
||||
if got := len(sc["entries"].([]any)); got != 500 {
|
||||
t.Fatalf("entries at cap = %d, want 500", got)
|
||||
}
|
||||
if boolField(t, sc, "hasMore") {
|
||||
t.Fatal("hasMore = true at the MaxOffset cap, paging would loop")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,979 @@
|
||||
[
|
||||
{
|
||||
"name": "list_hosts",
|
||||
"description": "列主机:默认只返回在线主机(含计算机名、IP、操作系统、版本、备注、分组、活动窗口、延迟等实时信息),include_offline=true 时连离线主机(历史连接过、当前未连接,来自主机列表记录)一起返回,在线主机排在最前面。query 子串匹配计算机名/备注/IP;group / os / client_type 为附加过滤条件(均可选、AND 组合、子串匹配、ASCII 不区分大小写);online=false 只看离线主机。过滤在分页之前生效:total 为命中台数,totalAll 为过滤前的主机库台数。结果按 limit/offset 分页(默认 100 条,上限 1000),hasMore 表示还有下一页。离线主机另有 last_seen(最后一次登录时间)、install_time 字段,但没有 rtt/version/activeWindow 等实时字段,也没有 clientType(按平台筛历史主机请用 os),group 恒为 default。authStatus 为主机授权状态(unauthorized/authorized_by_super/authorized_by_admin/forbidden)。tls=true 表示该客户端登录时使用了 TLS 加密传输(登录时上报,老客户端恒为 false)。",
|
||||
"inputSchema": {
|
||||
"properties": {
|
||||
"client_type": {
|
||||
"description": "按客户端类型过滤(子串,不区分大小写,如 EXE、LNX、MAC)。离线主机没有该字段,不会命中。省略则不过滤。",
|
||||
"type": "string"
|
||||
},
|
||||
"group": {
|
||||
"description": "按分组过滤(子串,不区分大小写)。省略则不过滤。",
|
||||
"type": "string"
|
||||
},
|
||||
"include_offline": {
|
||||
"description": "是否把离线主机一起返回,默认 false(只给在线);online=false 时无意义。list_all_hosts 别名默认 true。",
|
||||
"type": "boolean"
|
||||
},
|
||||
"ip": {
|
||||
"description": "只按 IP 过滤(search_hosts 的旧参数);与 query 同时给出时两者都需满足。",
|
||||
"type": "string"
|
||||
},
|
||||
"limit": {
|
||||
"description": "本次最多返回的条数,默认 100,上限 1000。",
|
||||
"type": "integer"
|
||||
},
|
||||
"name": {
|
||||
"description": "只按计算机名/备注过滤(search_hosts 的旧参数);与 query 同时给出时两者都需满足。",
|
||||
"type": "string"
|
||||
},
|
||||
"offset": {
|
||||
"description": "跳过前 N 条,默认 0;配合返回的 total/hasMore 翻页。",
|
||||
"type": "integer"
|
||||
},
|
||||
"online": {
|
||||
"description": "true(默认)返回在线主机;false 只返回离线主机(历史连接过、当前未连接)。",
|
||||
"type": "boolean"
|
||||
},
|
||||
"os": {
|
||||
"description": "按操作系统过滤(子串,不区分大小写,如 Windows、Linux、Android)。省略则不过滤。",
|
||||
"type": "string"
|
||||
},
|
||||
"query": {
|
||||
"description": "关键字:子串匹配计算机名、备注或 IP(ASCII 不区分大小写)。省略则不过滤。",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"outputSchema": {
|
||||
"properties": {
|
||||
"hasMore": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"hosts": {
|
||||
"items": {
|
||||
"properties": {
|
||||
"activeWindow": {
|
||||
"type": "string"
|
||||
},
|
||||
"authStatus": {
|
||||
"type": "string"
|
||||
},
|
||||
"clientType": {
|
||||
"type": "string"
|
||||
},
|
||||
"group": {
|
||||
"type": "string"
|
||||
},
|
||||
"id": {
|
||||
"type": "string"
|
||||
},
|
||||
"install_time": {
|
||||
"type": "string"
|
||||
},
|
||||
"ip": {
|
||||
"type": "string"
|
||||
},
|
||||
"last_seen": {
|
||||
"type": "string"
|
||||
},
|
||||
"location": {
|
||||
"type": "string"
|
||||
},
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"online": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"os": {
|
||||
"type": "string"
|
||||
},
|
||||
"remark": {
|
||||
"type": "string"
|
||||
},
|
||||
"rtt": {
|
||||
"type": "string"
|
||||
},
|
||||
"screen": {
|
||||
"type": "string"
|
||||
},
|
||||
"tls": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"version": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"limit": {
|
||||
"type": "integer"
|
||||
},
|
||||
"offset": {
|
||||
"type": "integer"
|
||||
},
|
||||
"total": {
|
||||
"type": "integer"
|
||||
},
|
||||
"totalAll": {
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"hosts"
|
||||
],
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "get_host_detail",
|
||||
"description": "获取单台在线主机的详细信息(id、计算机名、IP、操作系统、备注、分组、活动窗口、屏幕分辨率、客户端类型等)。tls=true 表示该客户端登录时使用了 TLS 加密传输(登录时上报,老客户端恒为 false)。",
|
||||
"inputSchema": {
|
||||
"anyOf": [
|
||||
{
|
||||
"required": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
{
|
||||
"required": [
|
||||
"ids"
|
||||
]
|
||||
}
|
||||
],
|
||||
"properties": {
|
||||
"id": {
|
||||
"description": "主机 id,取 list_hosts 返回的 id 字段;与 ids 二选一",
|
||||
"type": "string"
|
||||
},
|
||||
"ids": {
|
||||
"description": "批量查询:一次传多台主机 id(最多 50 个),结果按台汇总在 results 里。与 id 二选一,仅只读工具支持;limit/offset 对每台主机各自生效。",
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"outputSchema": {
|
||||
"anyOf": [
|
||||
{
|
||||
"properties": {
|
||||
"host": {
|
||||
"properties": {
|
||||
"activeWindow": {
|
||||
"type": "string"
|
||||
},
|
||||
"authStatus": {
|
||||
"type": "string"
|
||||
},
|
||||
"capabilities": {
|
||||
"properties": {
|
||||
"c2cPaths": {
|
||||
"description": "能否按路径清单接收另一台主机的文件(copy_files_c2c 源端的前提)",
|
||||
"type": "boolean"
|
||||
},
|
||||
"fileTransferV2": {
|
||||
"description": "是否支持 V2 文件传输(download_file / upload_file 的前提)",
|
||||
"type": "boolean"
|
||||
},
|
||||
"platform": {
|
||||
"description": "客户端形态:EXE/DLL/MEXE/SC/MDLL(Windows)、LNX(Linux)、MAC、APK",
|
||||
"type": "string"
|
||||
},
|
||||
"registry": {
|
||||
"description": "是否有 Windows 注册表可查(list_registry);仅 Windows 客户端为 true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"remoteControl": {
|
||||
"description": "能否建立远程控制会话(remote_open/remote_mouse/remote_keyboard 的前提);Android 客户端只支持整屏目标,且需要已授权录屏与无障碍服务;还要求服务端 Web 远程服务已启动(WebSvrPort>0)",
|
||||
"type": "boolean"
|
||||
},
|
||||
"screenPreview": {
|
||||
"description": "能否截屏(get_screenshot 的前提)",
|
||||
"type": "boolean"
|
||||
},
|
||||
"screenRegion": {
|
||||
"description": "能否按区域/窗口/显示器原生分辨率截屏(get_screenshot 的 mode=region/window/monitor 前提);仅声明 CLIENT_CAP_SCREEN_REGION 的新 Windows 客户端为 true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"windowInfo": {
|
||||
"description": "是否支持窗口信息(get_foreground_window、host_inspect 的 windows 项坐标/前后台字段、operate_window/host_control_window 的 activate);仅声明 CLIENT_CAP_WINDOW_INFO 的新客户端为 true",
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"clientType": {
|
||||
"type": "string"
|
||||
},
|
||||
"group": {
|
||||
"type": "string"
|
||||
},
|
||||
"id": {
|
||||
"type": "string"
|
||||
},
|
||||
"install_time": {
|
||||
"type": "string"
|
||||
},
|
||||
"ip": {
|
||||
"type": "string"
|
||||
},
|
||||
"last_seen": {
|
||||
"type": "string"
|
||||
},
|
||||
"location": {
|
||||
"type": "string"
|
||||
},
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"online": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"os": {
|
||||
"type": "string"
|
||||
},
|
||||
"remark": {
|
||||
"type": "string"
|
||||
},
|
||||
"rtt": {
|
||||
"type": "string"
|
||||
},
|
||||
"screen": {
|
||||
"type": "string"
|
||||
},
|
||||
"tls": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"version": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"host"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"failed": {
|
||||
"description": "失败的台数",
|
||||
"type": "integer"
|
||||
},
|
||||
"results": {
|
||||
"items": {
|
||||
"properties": {
|
||||
"data": {
|
||||
"description": "该台成功时的单机 structuredContent(字段随工具而定)",
|
||||
"type": "object"
|
||||
},
|
||||
"error": {
|
||||
"description": "该台失败时的错误对象(code / message)",
|
||||
"type": "object"
|
||||
},
|
||||
"id": {
|
||||
"description": "主机 id",
|
||||
"type": "string"
|
||||
},
|
||||
"ok": {
|
||||
"description": "该台是否成功",
|
||||
"type": "boolean"
|
||||
},
|
||||
"text": {
|
||||
"description": "该台失败时的错误文字",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"skipped": {
|
||||
"description": "因整体时限用尽而未下发的台数(不是主机侧错误)",
|
||||
"type": "integer"
|
||||
},
|
||||
"succeeded": {
|
||||
"description": "成功的台数",
|
||||
"type": "integer"
|
||||
},
|
||||
"tool": {
|
||||
"description": "被批量调用的工具名",
|
||||
"type": "string"
|
||||
},
|
||||
"total": {
|
||||
"description": "请求里的 id 台数",
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"results"
|
||||
],
|
||||
"type": "object"
|
||||
}
|
||||
],
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "get_screenshot",
|
||||
"description": "截取指定在线主机的一帧画面,返回 base64 编码的 JPEG 图片:图片在 content 的 image 块(data 为 base64,mimeType=image/jpeg);structuredContent.image 只有 mimeType/width/height/bytes 元数据,不含图片数据。支持 Windows 与带 X11 桌面的 Linux 客户端(能力位 CLIENT_CAP_SCREEN_PREVIEW),主连接 RPC、一次性返回。Android 客户端用无障碍服务 takeScreenshot 抓屏(Android 11+ 且开启无障碍服务,此时登录会声明该能力位;只支持 mode=screen)。mode 可选 screen(默认,整虚拟桌面)/region(指定矩形)/window(指定 hwnd)/monitor(指定显示器);后三种默认按源尺寸 1:1 原生分辨率抓取(适合 OCR/视觉读字),需要较新的 Windows 客户端(CLIENT_CAP_SCREEN_REGION,否则 -32005),结果在 structuredContent.capture 里回报实际源矩形与缩放比例。",
|
||||
"inputSchema": {
|
||||
"allOf": [
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"mode": {
|
||||
"enum": [
|
||||
"region"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"mode"
|
||||
]
|
||||
},
|
||||
"then": {
|
||||
"required": [
|
||||
"width",
|
||||
"height"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"mode": {
|
||||
"enum": [
|
||||
"window"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"mode"
|
||||
]
|
||||
},
|
||||
"then": {
|
||||
"required": [
|
||||
"hwnd"
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"properties": {
|
||||
"height": {
|
||||
"description": "region 模式必填:矩形高度(像素,1~8192)。超出虚拟桌面的部分会被裁剪。",
|
||||
"type": "integer"
|
||||
},
|
||||
"hwnd": {
|
||||
"description": "window 模式必填:窗口句柄(整数或 0x 前缀字符串),取 host_inspect 的 windows 项 / get_foreground_window 返回的 hwnd。窗口最小化时无法抓取(返回错误),先 activate/restore。",
|
||||
"type": [
|
||||
"integer",
|
||||
"string"
|
||||
]
|
||||
},
|
||||
"id": {
|
||||
"description": "主机 id,取 list_hosts 返回的 id 字段",
|
||||
"type": "string"
|
||||
},
|
||||
"max_width": {
|
||||
"description": "期望图片最大宽度(像素,钳制到 64~1920)。screen 模式省略或传 0 时沿用 RTT 自适应缩略图档位(最大 1024);region/window/monitor 模式省略/传 0 时按源尺寸 1:1 抓取(原生分辨率),显式传入才等比缩小。",
|
||||
"type": "integer"
|
||||
},
|
||||
"mode": {
|
||||
"description": "抓取范围,默认 screen。screen=整个虚拟桌面(可缩放);region=指定矩形;window=指定窗口;monitor=指定显示器。region/window/monitor 默认按源尺寸 1:1 抓取(原生分辨率,适合 OCR/视觉读字),只有显式传 max_width 才缩放;这三种需要较新的 Windows 客户端(能力位 CLIENT_CAP_SCREEN_REGION),否则返回 -32005。",
|
||||
"enum": [
|
||||
"screen",
|
||||
"region",
|
||||
"window",
|
||||
"monitor"
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
"monitor": {
|
||||
"description": "monitor 模式:显示器序号,0=主显示器(默认),1..N 为其余显示器(按系统枚举顺序)。序号越界返回错误。",
|
||||
"type": "integer"
|
||||
},
|
||||
"width": {
|
||||
"description": "region 模式必填:矩形宽度(像素,1~8192)。超出虚拟桌面的部分会被裁剪。",
|
||||
"type": "integer"
|
||||
},
|
||||
"x": {
|
||||
"description": "region 模式:矩形左上角的虚拟桌面 X 坐标(可为负;多显示器时以虚拟桌面左上角为原点)。省略按 0 处理。",
|
||||
"type": "integer"
|
||||
},
|
||||
"y": {
|
||||
"description": "region 模式:矩形左上角的虚拟桌面 Y 坐标(可为负)。省略按 0 处理。",
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"outputSchema": {
|
||||
"properties": {
|
||||
"capture": {
|
||||
"properties": {
|
||||
"height": {
|
||||
"type": "integer"
|
||||
},
|
||||
"mode": {
|
||||
"type": "string"
|
||||
},
|
||||
"native": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"scale": {
|
||||
"type": "integer"
|
||||
},
|
||||
"width": {
|
||||
"type": "integer"
|
||||
},
|
||||
"x": {
|
||||
"type": "integer"
|
||||
},
|
||||
"y": {
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"image": {
|
||||
"properties": {
|
||||
"bytes": {
|
||||
"type": "integer"
|
||||
},
|
||||
"height": {
|
||||
"type": "integer"
|
||||
},
|
||||
"mimeType": {
|
||||
"type": "string"
|
||||
},
|
||||
"width": {
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"image"
|
||||
],
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "list_files",
|
||||
"description": "列举指定在线主机的目录。省略或空 path 返回驱动器列表(drives);给定 path 返回该目录一层内的文件/子目录(files,含 name/isDir/size/mtime),整目录解析后按 limit/offset 分页(默认 100 条、上限 1000 条,total/hasMore 是真实的目录条目数;目录超过 10 万条时按上限截断并返回 truncated=true)。Windows 上 \".\"/\"/\"/\"\\\\\" 视同省略 path;Linux/macOS 上 \"/\" 是根目录。只读。",
|
||||
"inputSchema": {
|
||||
"anyOf": [
|
||||
{
|
||||
"required": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
{
|
||||
"required": [
|
||||
"ids"
|
||||
]
|
||||
}
|
||||
],
|
||||
"properties": {
|
||||
"id": {
|
||||
"description": "主机 id,取 list_hosts 返回的 id 字段",
|
||||
"type": "string"
|
||||
},
|
||||
"ids": {
|
||||
"description": "批量查询:一次传多台主机 id(最多 50 个),结果按台汇总在 results 里。与 id 二选一,仅只读工具支持;limit/offset 对每台主机各自生效。",
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"limit": {
|
||||
"description": "本次最多返回的条数,默认 100,上限 1000。",
|
||||
"type": "integer"
|
||||
},
|
||||
"offset": {
|
||||
"description": "跳过前 N 条,默认 0;配合返回的 total/hasMore 翻页。",
|
||||
"type": "integer"
|
||||
},
|
||||
"path": {
|
||||
"description": "要列举的目录路径(如 C:\\Windows 或 /etc)。省略或传空返回驱动器列表;Windows 上 \".\"、\"/\"、\"\\\\\" 视同省略;Linux/macOS 上 \"/\" 是根目录,按真实目录列举。",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"outputSchema": {
|
||||
"anyOf": [
|
||||
{
|
||||
"properties": {
|
||||
"drives": {
|
||||
"items": {
|
||||
"properties": {
|
||||
"drive": {
|
||||
"type": "string"
|
||||
},
|
||||
"fileSystem": {
|
||||
"type": "string"
|
||||
},
|
||||
"freeMB": {
|
||||
"type": "integer"
|
||||
},
|
||||
"totalMB": {
|
||||
"type": "integer"
|
||||
},
|
||||
"type": {
|
||||
"type": "integer"
|
||||
},
|
||||
"typeName": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"files": {
|
||||
"items": {
|
||||
"properties": {
|
||||
"isDir": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"mtime": {
|
||||
"type": "integer"
|
||||
},
|
||||
"name": {
|
||||
"type": "string"
|
||||
},
|
||||
"size": {
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"hasMore": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"limit": {
|
||||
"type": "integer"
|
||||
},
|
||||
"offset": {
|
||||
"type": "integer"
|
||||
},
|
||||
"total": {
|
||||
"type": "integer"
|
||||
},
|
||||
"totalAll": {
|
||||
"type": "integer"
|
||||
},
|
||||
"truncated": {
|
||||
"description": "目录条目超过服务端解析上限(100000 条)时为 true;仅在返回 files 时可能出现,此时 total 不是真实总数。",
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"failed": {
|
||||
"description": "失败的台数",
|
||||
"type": "integer"
|
||||
},
|
||||
"results": {
|
||||
"items": {
|
||||
"properties": {
|
||||
"data": {
|
||||
"description": "该台成功时的单机 structuredContent(字段随工具而定)",
|
||||
"type": "object"
|
||||
},
|
||||
"error": {
|
||||
"description": "该台失败时的错误对象(code / message)",
|
||||
"type": "object"
|
||||
},
|
||||
"id": {
|
||||
"description": "主机 id",
|
||||
"type": "string"
|
||||
},
|
||||
"ok": {
|
||||
"description": "该台是否成功",
|
||||
"type": "boolean"
|
||||
},
|
||||
"text": {
|
||||
"description": "该台失败时的错误文字",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"skipped": {
|
||||
"description": "因整体时限用尽而未下发的台数(不是主机侧错误)",
|
||||
"type": "integer"
|
||||
},
|
||||
"succeeded": {
|
||||
"description": "成功的台数",
|
||||
"type": "integer"
|
||||
},
|
||||
"tool": {
|
||||
"description": "被批量调用的工具名",
|
||||
"type": "string"
|
||||
},
|
||||
"total": {
|
||||
"description": "请求里的 id 台数",
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"results"
|
||||
],
|
||||
"type": "object"
|
||||
}
|
||||
],
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "get_audit_log",
|
||||
"description": "获取 YAMA 服务端主界面的消息/审计日志(主机上线/下线、操作结果、告警等),按 limit/offset 分页(新在前,服务端只保留最近 1000 条)。可选 type 按类型列做不区分大小写的子串过滤(如 MCP、主机),keyword 按正文字串过滤;过滤在分页之前生效,total 为命中条数、totalAll 为镜像里的全部条数。只读、纯内存。",
|
||||
"inputSchema": {
|
||||
"properties": {
|
||||
"keyword": {
|
||||
"description": "正文子串过滤,不区分大小写(如 445、timeout)。省略则不过滤。",
|
||||
"type": "string"
|
||||
},
|
||||
"limit": {
|
||||
"description": "本次最多返回的条数,默认 100,上限 1000。",
|
||||
"type": "integer"
|
||||
},
|
||||
"offset": {
|
||||
"description": "跳过前 N 条,默认 0;配合返回的 total/hasMore 翻页。",
|
||||
"type": "integer"
|
||||
},
|
||||
"type": {
|
||||
"description": "类型列的子串过滤,不区分大小写(如 MCP、主机上线)。省略则不过滤。",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [],
|
||||
"type": "object"
|
||||
},
|
||||
"outputSchema": {
|
||||
"properties": {
|
||||
"entries": {
|
||||
"items": {
|
||||
"properties": {
|
||||
"msg": {
|
||||
"type": "string"
|
||||
},
|
||||
"time": {
|
||||
"type": "string"
|
||||
},
|
||||
"type": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"hasMore": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"limit": {
|
||||
"type": "integer"
|
||||
},
|
||||
"offset": {
|
||||
"type": "integer"
|
||||
},
|
||||
"total": {
|
||||
"type": "integer"
|
||||
},
|
||||
"totalAll": {
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"entries"
|
||||
],
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "get_server_status",
|
||||
"description": "获取 YAMA 服务端自身的状态:程序版本与 exe 构建时间、进程已运行秒数、MCP 监听地址与端口、各功能开关(只读/终端/远程控制/文件传输/管理/主机管理/高风险操作/键盘记录/远程交谈)、在线与离线主机数、各类在飞会话数、当前被封禁的来源 IP 数。只读、纯内存,不返回 token。",
|
||||
"inputSchema": {
|
||||
"properties": {},
|
||||
"required": [],
|
||||
"type": "object"
|
||||
},
|
||||
"outputSchema": {
|
||||
"properties": {
|
||||
"app_name": {
|
||||
"type": "string"
|
||||
},
|
||||
"bind": {
|
||||
"type": "string"
|
||||
},
|
||||
"blocked_auth_ips": {
|
||||
"type": "integer"
|
||||
},
|
||||
"exe_build_time": {
|
||||
"type": "string"
|
||||
},
|
||||
"hosts": {
|
||||
"type": "object"
|
||||
},
|
||||
"port": {
|
||||
"type": "integer"
|
||||
},
|
||||
"sessions": {
|
||||
"type": "object"
|
||||
},
|
||||
"switches": {
|
||||
"type": "object"
|
||||
},
|
||||
"uptime_sec": {
|
||||
"type": "integer"
|
||||
},
|
||||
"version": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [],
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "terminal_exec",
|
||||
"description": "在已打开的持久会话中执行一条命令,或轮询取回正在运行的命令输出。带 command 时执行并在 timeout_ms 内等待;等待超时返回 done:false 与已产生的部分输出,会话不销毁(命令仍在远端运行)。session_id 可省略:自动复用该主机已有的持久会话,没有就隐式打开一个(结果里有 session_id 与 reused),不必先 terminal_open。不带 command、只传 session_id 时进入轮询模式:继续等待并取回增量输出,直到 done:true(此时有 exit_code)。命令不受白名单约束。PTY 会话(新 Windows 客户端 ConPTY / Linux 与新版 Android 的 POSIX PTY)下可用管道 | 与 && / || 串联,退出码取整条管道/串联,适合「ls -1 | wc -l」这类先过滤再回传的用法;不要用后台执行符 &(POSIX)或换行。老非 PTY Windows 客户端仍不支持 & 与 |,请拆成多条调用。",
|
||||
"inputSchema": {
|
||||
"anyOf": [
|
||||
{
|
||||
"required": [
|
||||
"command"
|
||||
]
|
||||
},
|
||||
{
|
||||
"required": [
|
||||
"session_id"
|
||||
]
|
||||
}
|
||||
],
|
||||
"properties": {
|
||||
"command": {
|
||||
"description": "要执行的命令(完整 shell,不受白名单约束)。省略时进入轮询模式:不执行新命令,只等待并取回当前会话的增量输出(上一条命令超时后用这个方式继续取)。PTY 会话(Windows ConPTY / Linux PTY)下可用管道 | 与 && / || 串联,退出码取整条管道/串联;不要用后台执行符 &(POSIX)或换行。老非 PTY 客户端仍不支持 & 与 |,请拆成多条调用。Linux 下通过 POSIX shell 执行,可用 ; 串联且退出码取最后一条命令",
|
||||
"type": "string"
|
||||
},
|
||||
"id": {
|
||||
"description": "主机 id,取 list_hosts 返回的 id 字段",
|
||||
"type": "string"
|
||||
},
|
||||
"max_output_bytes": {
|
||||
"description": "单次返回的原始输出上限(可选,默认 65536,最小 1024,最大 1048576);超出按换行边界截断并置 truncated:true,再轮询一次可取回剩余",
|
||||
"type": "integer"
|
||||
},
|
||||
"session_id": {
|
||||
"description": "会话 token。带 command 时可省略:自动复用该主机已有的持久会话,没有就在内部打开一个(结果里有 session_id 与 reused)。轮询模式必须提供",
|
||||
"type": "string"
|
||||
},
|
||||
"timeout_ms": {
|
||||
"description": "本次调用最多等待的毫秒数(可选,默认 20000,上限 600000)。等待超时不算失败:返回 done:false 与已产生的输出,命令仍在远端运行,继续轮询即可",
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"outputSchema": {
|
||||
"properties": {
|
||||
"done": {
|
||||
"description": "false=命令仍在运行,用同一工具只传 session_id 继续取增量;true=命令已结束,exit_code 有效",
|
||||
"type": "boolean"
|
||||
},
|
||||
"dropped_bytes": {
|
||||
"description": "因单条命令输出超过 8MB 上限被丢弃的最旧字节数(该命令累计,0 或省略=无丢失)",
|
||||
"type": "integer"
|
||||
},
|
||||
"elapsed_ms": {
|
||||
"description": "本次调用实际等待的毫秒数",
|
||||
"type": "integer"
|
||||
},
|
||||
"exit_code": {
|
||||
"description": "退出码(done=true 时提供):PTY 客户端(Windows ConPTY / Linux PTY)为命令的真实退出码;老客户端(非 PTY)仅区分 0/非 0;-1=未知(shell 进程退出)",
|
||||
"type": "integer"
|
||||
},
|
||||
"is_pty": {
|
||||
"description": "true=PTY(UTF-8)(Windows ConPTY / Linux PTY);false=老 cmd 管道(GBK)",
|
||||
"type": "boolean"
|
||||
},
|
||||
"reused": {
|
||||
"description": "true=复用了该主机已有的持久会话;false=本次隐式新建(省略 session_id 时)",
|
||||
"type": "boolean"
|
||||
},
|
||||
"session_id": {
|
||||
"description": "会话 token,原样回传,便于续接轮询",
|
||||
"type": "string"
|
||||
},
|
||||
"stdout": {
|
||||
"description": "本次新增的输出(已剥哨兵与 ANSI 转义)",
|
||||
"type": "string"
|
||||
},
|
||||
"truncated": {
|
||||
"description": "true=本次受 max_output_bytes 限制仍有剩余输出,立即再轮询即可取回",
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"stdout",
|
||||
"done",
|
||||
"session_id"
|
||||
],
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "terminal_close",
|
||||
"description": "关闭并释放指定持久会话(幂等:会话已不存在也返回成功)。",
|
||||
"inputSchema": {
|
||||
"properties": {
|
||||
"id": {
|
||||
"description": "主机 id,取 list_hosts 返回的 id 字段",
|
||||
"type": "string"
|
||||
},
|
||||
"session_id": {
|
||||
"description": "terminal_open 返回的 session_id",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"session_id"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"outputSchema": {
|
||||
"properties": {
|
||||
"closed": {
|
||||
"description": "恒为 true(关闭幂等)",
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"closed"
|
||||
],
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "read_file",
|
||||
"description": "按字节读取指定在线主机上的一个文本文件(分页 + 编码识别 + 整文件 SHA-256),只支持单个普通文件。path 为远程绝对路径:Windows 用 D:\\cfg\\app.ini 这类盘符路径,Linux/macOS 用 /etc/app.conf 这类 POSIX 路径。offset 支持负数(-200 = 最后 200 行,看日志尾部);limit 为最多返回的行数(默认 2000);encoding=auto 时按 BOM → UTF-8 合法性 → GBK 回退识别,也可显式传 utf-8 / gbk / latin1;max_bytes 限制本次返回的文本字节数(默认 262144=256KB,超出按 truncated=true 截断)。目录、或大于 2MB 的文件返回 -32602(请改用 download_file)。返回 size/encoding/eol/lines_total/offset/lines_returned/truncated/text/sha256(sha256 是整个文件,不是本次片段)。读配置文件/日志时用它,不要用 exec_command 的 type/Get-Content(GBK 会乱码、行尾会被归一化);看被管业务程序的日志尾部用 offset=-N(如 offset=-200,N 为行数)。",
|
||||
"inputSchema": {
|
||||
"properties": {
|
||||
"encoding": {
|
||||
"description": "auto(默认,按 BOM → UTF-8 合法性 → GBK 回退)/ utf-8 / gbk / gb18030 / latin1",
|
||||
"type": "string"
|
||||
},
|
||||
"id": {
|
||||
"description": "主机 id,取 list_hosts 返回的 id 字段",
|
||||
"type": "string"
|
||||
},
|
||||
"limit": {
|
||||
"description": "最多返回的行数(1..200000,默认 2000)",
|
||||
"type": "integer"
|
||||
},
|
||||
"max_bytes": {
|
||||
"description": "本次返回文本的字节上限(1024..2097152,默认 262144=256KB),超出按 truncated=true 截断",
|
||||
"type": "integer"
|
||||
},
|
||||
"offset": {
|
||||
"description": "起始行(0 基)。负数表示从末尾倒数:-200 = 最后 200 行;默认 0",
|
||||
"type": "integer"
|
||||
},
|
||||
"path": {
|
||||
"description": "远程文件的绝对路径。Windows 用 D:\\cfg\\app.ini 这类盘符路径;Linux/macOS 用 /etc/app.conf 这类 POSIX 路径。必须是单个普通文件(目录或大于 2MB 的文件返回 -32602)",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"path"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"outputSchema": {
|
||||
"properties": {
|
||||
"encoding": {
|
||||
"description": "实际使用的编码:utf-8 / utf-16le / utf-16be / gbk / gb18030 / latin1",
|
||||
"type": "string"
|
||||
},
|
||||
"eol": {
|
||||
"description": "行尾风格:crlf / lf / cr / mixed / none",
|
||||
"type": "string"
|
||||
},
|
||||
"lines_returned": {
|
||||
"description": "本次返回的行数",
|
||||
"type": "integer"
|
||||
},
|
||||
"lines_total": {
|
||||
"description": "文件总行数(末尾换行不计空行)",
|
||||
"type": "integer"
|
||||
},
|
||||
"offset": {
|
||||
"description": "本次实际起始行(负数已换算成绝对行号)",
|
||||
"type": "integer"
|
||||
},
|
||||
"path": {
|
||||
"description": "远程路径(原样回传)",
|
||||
"type": "string"
|
||||
},
|
||||
"sha256": {
|
||||
"description": "整个文件的 SHA-256(不是本次片段),可与 download_file 的结果比对",
|
||||
"type": "string"
|
||||
},
|
||||
"size": {
|
||||
"description": "文件总字节数",
|
||||
"type": "integer"
|
||||
},
|
||||
"text": {
|
||||
"description": "文件内容(UTF-8,行以 \\n 分隔,已去掉 BOM)",
|
||||
"type": "string"
|
||||
},
|
||||
"truncated": {
|
||||
"description": "true=还有内容没返回(超出 limit / max_bytes),可调整 offset 继续读",
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"path",
|
||||
"size",
|
||||
"encoding",
|
||||
"eol",
|
||||
"lines_total",
|
||||
"offset",
|
||||
"lines_returned",
|
||||
"truncated",
|
||||
"text",
|
||||
"sha256"
|
||||
],
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,621 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/protocol"
|
||||
)
|
||||
|
||||
// terminal_exec bounds. They mirror the Win32 server (McpServer.cpp:4669-4674)
|
||||
// except the per-command buffer, which is the M4a session ring (256 KiB).
|
||||
const (
|
||||
termDefaultTimeoutMS = 20000
|
||||
termMaxTimeoutMS = 600000
|
||||
termDefaultMaxOutput = 65536
|
||||
termMinMaxOutput = 1024
|
||||
termMaxMaxOutput = 1 << 20
|
||||
// termTruncBackup is how far back a truncated window may move to end on a
|
||||
// newline: neither UTF-8 nor GBK can hide a '\n' inside a multibyte char,
|
||||
// so truncating on a line boundary never corrupts the encoding.
|
||||
termTruncBackup = 4096
|
||||
// termBootstrapWait is the longest we wait for a POSIX shell's first
|
||||
// prompt before writing, so the line discipline does not echo our input
|
||||
// twice (MFC WaitTerminalBootstrap).
|
||||
termBootstrapWait = 2 * time.Second
|
||||
)
|
||||
|
||||
// terminalExecArgs is the published inputSchema as Go.
|
||||
type terminalExecArgs struct {
|
||||
ID string `json:"id"`
|
||||
Command string `json:"command"`
|
||||
SessionID string `json:"session_id"`
|
||||
TimeoutMS int `json:"timeout_ms"`
|
||||
MaxOutputBytes int `json:"max_output_bytes"`
|
||||
}
|
||||
|
||||
type terminalExecOutput struct {
|
||||
Stdout string `json:"stdout"`
|
||||
Done bool `json:"done"`
|
||||
SessionID string `json:"session_id"`
|
||||
IsPTY bool `json:"is_pty"`
|
||||
Reused bool `json:"reused"`
|
||||
ExitCode *int `json:"exit_code,omitempty"`
|
||||
Truncated bool `json:"truncated"`
|
||||
DroppedBytes uint64 `json:"dropped_bytes,omitempty"`
|
||||
ElapsedMS int64 `json:"elapsed_ms"`
|
||||
}
|
||||
|
||||
// terminalCloseArgs is the published inputSchema as Go.
|
||||
type terminalCloseArgs struct {
|
||||
ID string `json:"id"`
|
||||
SessionID string `json:"session_id"`
|
||||
}
|
||||
|
||||
type terminalCloseOutput struct {
|
||||
Closed bool `json:"closed"`
|
||||
}
|
||||
|
||||
func (s *Server) registerTerminalTools() {
|
||||
s.handlers["terminal_exec"] = s.callTerminalExec
|
||||
s.handlers["terminal_close"] = s.callTerminalClose
|
||||
}
|
||||
|
||||
// callTerminalClose releases the persistent session MCP opened for a device.
|
||||
//
|
||||
// It is idempotent for the session it is given: a session that is already gone
|
||||
// still answers closed, so a retried close after a timeout does not fail. Only
|
||||
// sessions in MCP's own table are touched — the web console's shell is left
|
||||
// alone, and the hub-side close is lease-checked, so a session whose lease was
|
||||
// taken over is never torn down.
|
||||
//
|
||||
// A session_id that names a different live session is a caller mistake
|
||||
// (-32002), mirroring the Win32 server (McpServer.cpp BuildTerminalClose).
|
||||
func (s *Server) callTerminalClose(_ context.Context, raw json.RawMessage) (any, *rpcError) {
|
||||
if s.cfg.Hub == nil {
|
||||
return nil, errf(CodeInternal, "server device registry is not configured")
|
||||
}
|
||||
var args terminalCloseArgs
|
||||
if rerr := decodeArgs(raw, &args); rerr != nil {
|
||||
return nil, rerr
|
||||
}
|
||||
if args.ID == "" {
|
||||
return nil, errf(CodeInvalidParams, "Missing required parameter: id")
|
||||
}
|
||||
if !isDecimalID(args.ID) {
|
||||
return nil, errf(CodeInvalidParams, "Invalid id: expected a decimal host id string")
|
||||
}
|
||||
if args.SessionID == "" {
|
||||
return nil, errf(CodeInvalidParams, "Missing required parameter: session_id")
|
||||
}
|
||||
if sess := s.sessions.get(args.ID); sess != nil {
|
||||
if sess.id != args.SessionID {
|
||||
return nil, errf(CodeOffline, "Terminal session_id mismatch: %s", args.SessionID)
|
||||
}
|
||||
// Wakes any terminal_exec still waiting on the command; it delivers the
|
||||
// bytes buffered so far (done=true, exit_code=-1) before it returns.
|
||||
s.sessions.closeSessionIf(args.ID, sess)
|
||||
}
|
||||
return toolResult{
|
||||
Content: []contentItem{{Type: "text", Text: "closed"}},
|
||||
StructuredContent: terminalCloseOutput{Closed: true},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// callTerminalExec runs one command or polls the output of the previous one.
|
||||
//
|
||||
// A call without session_id reuses the device's existing MCP session or opens
|
||||
// one implicitly, so the model never needs a separate open/close round trip.
|
||||
// A timeout never destroys the session: the command keeps running on the
|
||||
// target and the next call with only session_id continues from the delivered
|
||||
// cursor (design §6.6).
|
||||
func (s *Server) callTerminalExec(ctx context.Context, raw json.RawMessage) (any, *rpcError) {
|
||||
if s.cfg.Hub == nil {
|
||||
return nil, errf(CodeInternal, "server device registry is not configured")
|
||||
}
|
||||
var args terminalExecArgs
|
||||
if rerr := decodeArgs(raw, &args); rerr != nil {
|
||||
return nil, rerr
|
||||
}
|
||||
if args.ID == "" {
|
||||
return nil, errf(CodeInvalidParams, "Missing required parameter: id")
|
||||
}
|
||||
if !isDecimalID(args.ID) {
|
||||
return nil, errf(CodeInvalidParams, "Invalid id: expected a decimal host id string")
|
||||
}
|
||||
|
||||
command := strings.TrimSpace(args.Command)
|
||||
isPoll := command == ""
|
||||
if isPoll && args.SessionID == "" {
|
||||
return nil, errf(CodeInvalidParams,
|
||||
"Missing required parameter: session_id (polling needs the session token)")
|
||||
}
|
||||
|
||||
// Polling never writes to the target, so a host that went offline can still
|
||||
// drain the output already buffered for its ended shell. Everything that
|
||||
// touches the device (platform gates, validation, opening) is command-only.
|
||||
var posix bool
|
||||
if !isPoll {
|
||||
main := s.cfg.Hub.MainConn(args.ID)
|
||||
if main == nil {
|
||||
return nil, errf(CodeOffline, "Host not found or offline: %s", args.ID)
|
||||
}
|
||||
platform := main.GetInfo().ClientType
|
||||
posix = platform == "LNX" || platform == "APK"
|
||||
if platform == "MAC" {
|
||||
return nil, errf(CodeUnsupported,
|
||||
"terminal_exec is only supported on Windows, Linux and Android hosts")
|
||||
}
|
||||
if platform == "APK" &&
|
||||
!protocol.SupportsCap(s.cfg.Hub.Capability(args.ID), protocol.ClientCapTerminal) {
|
||||
return nil, errf(CodeUnsupported,
|
||||
"Android client is too old for terminal_exec: the APK has no COMMAND_SHELL handler, upgrade the client first")
|
||||
}
|
||||
// Validate before opening a shell: a rejected command must not reserve
|
||||
// the device's single terminal slot.
|
||||
if containsControlChar(command) {
|
||||
return nil, errf(CodeInvalidParams,
|
||||
"Command contains a control character (newline/tab); send one line per call")
|
||||
}
|
||||
if posix && hasPosixBackgroundAmpersand(command) {
|
||||
return nil, errf(CodeInvalidParams,
|
||||
"Background execution (&) breaks output capture; use && to chain commands or run it in a separate session")
|
||||
}
|
||||
}
|
||||
timeout := termTimeout(args.TimeoutMS)
|
||||
maxOut := termMaxOutput(args.MaxOutputBytes)
|
||||
started := time.Now()
|
||||
|
||||
sess, reused, rerr := s.terminalSessionFor(args.ID, args.SessionID)
|
||||
if rerr != nil {
|
||||
return nil, rerr
|
||||
}
|
||||
if !isPoll {
|
||||
if rerr := s.waitTermReady(ctx, sess, timeout); rerr != nil {
|
||||
// A shell that ended with undrained output is kept so the next
|
||||
// session_id poll can still collect its tail; say so, since the
|
||||
// caller cannot see the session behind an implicit open.
|
||||
if sess.isClosed() && sess.hasPending() {
|
||||
return nil, errf(rerr.Code,
|
||||
"%s. Its output is still buffered; call terminal_exec with only session_id %s to collect it",
|
||||
rerr.Message, sess.id)
|
||||
}
|
||||
// A shell that never came up would otherwise hold the device's single
|
||||
// terminal slot until an idle sweep; release it now (MFC erases too).
|
||||
s.sessions.closeSessionIf(args.ID, sess)
|
||||
return nil, rerr
|
||||
}
|
||||
}
|
||||
sess.mu.Lock()
|
||||
isPTY := sess.isPTY
|
||||
sess.mu.Unlock()
|
||||
if !isPoll && !isPTY {
|
||||
s.sessions.closeSessionIf(args.ID, sess)
|
||||
return nil, errf(CodeUnsupported,
|
||||
"The client on host %s uses the legacy non-PTY shell; this server only supports PTY sessions (ConPTY / POSIX PTY). Upgrade the client",
|
||||
args.ID)
|
||||
}
|
||||
|
||||
var p *pendingCmd
|
||||
if isPoll {
|
||||
p, rerr = sess.pollPending()
|
||||
if rerr != nil {
|
||||
return nil, rerr
|
||||
}
|
||||
} else {
|
||||
nonce := newTermNonce()
|
||||
cmdLine, sentLine := buildSentinelLines(true, posix, command, nonce)
|
||||
p, rerr = sess.beginCommand(nonce, cmdLine, sentLine)
|
||||
if rerr != nil {
|
||||
return nil, rerr
|
||||
}
|
||||
// A first command can race the shell's own startup; writing before the
|
||||
// prompt appears makes the driver echo the input a second time.
|
||||
if posix {
|
||||
s.waitTermBootstrap(ctx, sess, timeout)
|
||||
}
|
||||
if !sess.isClosed() {
|
||||
if err := s.sessions.send(args.ID, buildTerminalWire(posix, cmdLine, sentLine)); err != nil {
|
||||
sess.abortCommand(p)
|
||||
return nil, errf(CodeSendFailed, "Failed to send command to host: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
out, rerr := s.awaitAndDeliver(ctx, sess, p, maxOut, timeout)
|
||||
if rerr != nil {
|
||||
return nil, rerr
|
||||
}
|
||||
// An ended shell's session outlives it only until its last bytes are
|
||||
// delivered (sessionTable.closed keeps it); drop it now without touching the
|
||||
// hub, which may already belong to a new viewer.
|
||||
if out.Done && sess.isClosed() && !sess.hasPending() {
|
||||
s.sessions.forget(args.ID, sess)
|
||||
}
|
||||
out.SessionID = sess.id
|
||||
out.IsPTY = isPTY
|
||||
out.Reused = reused
|
||||
out.ElapsedMS = time.Since(started).Milliseconds()
|
||||
return terminalExecResult(out), nil
|
||||
}
|
||||
|
||||
// terminalSessionFor resolves the session: an explicit id must match the
|
||||
// device's MCP session; without one, an existing session is reused, otherwise
|
||||
// a new shell is opened.
|
||||
func (s *Server) terminalSessionFor(deviceID, sessionID string) (*termSession, bool, *rpcError) {
|
||||
if sessionID != "" {
|
||||
sess := s.sessions.get(deviceID)
|
||||
if sess == nil {
|
||||
return nil, true, errf(CodeOffline,
|
||||
"Terminal session not found: %s (pass a command without session_id to open a new one)", sessionID)
|
||||
}
|
||||
if sess.id != sessionID {
|
||||
return nil, true, errf(CodeOffline, "Terminal session_id mismatch: %s", sessionID)
|
||||
}
|
||||
return sess, true, nil
|
||||
}
|
||||
if sess := s.sessions.get(deviceID); sess != nil {
|
||||
return sess, true, nil
|
||||
}
|
||||
sess, err := s.sessions.open(deviceID)
|
||||
if err == nil {
|
||||
return sess, false, nil
|
||||
}
|
||||
switch {
|
||||
case errors.Is(err, hub.ErrTerminalBusy):
|
||||
// The holder is the web console: an existing MCP session is reused above,
|
||||
// so there is no MCP session_id to hand out or close here.
|
||||
return nil, false, errf(CodeBusy,
|
||||
"Device busy: the terminal on host %s is held by the web console (a human viewer); there is no MCP session_id to close — wait for the viewer to disconnect", deviceID)
|
||||
case errors.Is(err, hub.ErrDeviceOffline):
|
||||
return nil, false, errf(CodeOffline, "Host not found or offline: %s", deviceID)
|
||||
case errors.Is(err, errNoDeviceHub):
|
||||
return nil, false, errf(CodeInternal, "server device registry is not configured")
|
||||
case errors.Is(err, errSessionClosed):
|
||||
return nil, false, errf(CodeBusy,
|
||||
"Device busy: the terminal session for host %s closed while opening; retry", deviceID)
|
||||
default:
|
||||
return nil, false, errf(CodeSendFailed, "Failed to open terminal on host: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// waitTermReady waits for OnTerminalReady. Failing here means no shell exists to
|
||||
// command, so the caller releases the slot.
|
||||
func (s *Server) waitTermReady(ctx context.Context, sess *termSession, timeout time.Duration) *rpcError {
|
||||
deadline := time.Now().Add(timeout)
|
||||
stop := wakeOn(ctx, sess, deadline)
|
||||
defer stop()
|
||||
|
||||
sess.mu.Lock()
|
||||
defer sess.mu.Unlock()
|
||||
for !sess.ready && !sess.closed && ctx.Err() == nil && time.Now().Before(deadline) {
|
||||
sess.cond.Wait()
|
||||
}
|
||||
if sess.ready && !sess.closed {
|
||||
return nil
|
||||
}
|
||||
if sess.closed {
|
||||
reason := sess.closeReason
|
||||
if reason == "" {
|
||||
reason = "closed"
|
||||
}
|
||||
return errf(CodeOffline, "Terminal session ended while starting: %s", reason)
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return errf(CodeTimeout, "Request cancelled while waiting for the shell to start")
|
||||
}
|
||||
return errf(CodeTimeout,
|
||||
"Timeout waiting for shell to start (the client may not support remote shell, or the host is unresponsive)")
|
||||
}
|
||||
|
||||
// waitTermBootstrap waits for the shell's first screen so the input is echoed
|
||||
// once, not twice. The wait is bounded by the call's own timeout as well as the
|
||||
// bootstrap cap (MFC uses min(timeoutMs, 2000)); a timeout is not an error: the
|
||||
// command is still written.
|
||||
func (s *Server) waitTermBootstrap(ctx context.Context, sess *termSession, timeout time.Duration) {
|
||||
deadline := time.Now().Add(min(timeout, termBootstrapWait))
|
||||
stop := wakeOn(ctx, sess, deadline)
|
||||
defer stop()
|
||||
|
||||
sess.mu.Lock()
|
||||
defer sess.mu.Unlock()
|
||||
for !sess.sawOutput && !sess.closed && ctx.Err() == nil && time.Now().Before(deadline) {
|
||||
sess.cond.Wait()
|
||||
}
|
||||
}
|
||||
|
||||
// awaitAndDeliver waits for the command to finish (or the call's deadline) and
|
||||
// returns the next window of output. The session survives either outcome; only
|
||||
// its delivered cursor moves.
|
||||
func (s *Server) awaitAndDeliver(ctx context.Context, sess *termSession, p *pendingCmd,
|
||||
maxOut int, timeout time.Duration) (terminalExecOutput, *rpcError) {
|
||||
deadline := time.Now().Add(timeout)
|
||||
sess.mu.Lock()
|
||||
p.deadline = deadline
|
||||
sess.mu.Unlock()
|
||||
|
||||
stop := wakeOn(ctx, sess, deadline)
|
||||
defer stop()
|
||||
|
||||
sess.mu.Lock()
|
||||
defer sess.mu.Unlock()
|
||||
for !p.done && !sess.closed && ctx.Err() == nil && time.Now().Before(deadline) {
|
||||
sess.cond.Wait()
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
// The HTTP client is gone; the command keeps running (design §6.6). The
|
||||
// caller never saw a result, so the message has to carry the session id
|
||||
// it needs to poll or close the shell.
|
||||
return terminalExecOutput{}, errf(CodeTimeout,
|
||||
"Request cancelled; the command is still running on session_id=%s — poll terminal_exec with that session_id (empty command) or release it with terminal_close", sess.id)
|
||||
}
|
||||
|
||||
var out terminalExecOutput
|
||||
out.Done = p.done || sess.closed
|
||||
if p.done && !sess.closed {
|
||||
code := p.exitCode
|
||||
out.ExitCode = &code
|
||||
} else if out.Done {
|
||||
code := -1 // shell exited or was closed: the real code is unknown
|
||||
out.ExitCode = &code
|
||||
}
|
||||
|
||||
base := sess.baseLocked()
|
||||
if base > sess.delivered {
|
||||
// The ring evicted bytes this command produced but never delivered.
|
||||
p.lost += base - sess.delivered
|
||||
sess.delivered = base
|
||||
}
|
||||
end := sess.total
|
||||
if p.done {
|
||||
end = min(p.outputEnd, sess.total)
|
||||
}
|
||||
if sess.delivered > end {
|
||||
sess.delivered = end
|
||||
}
|
||||
|
||||
window, truncated := readDeliveryWindow(sess, sess.delivered, end, maxOut)
|
||||
sess.delivered += uint64(len(window))
|
||||
sess.lastUsed = time.Now()
|
||||
|
||||
finalChunk := out.Done && !truncated
|
||||
out.Stdout = cleanTerminalOutput(window, sess.isPTY, p.firstChunk,
|
||||
p.cmdLine, p.sentLine, p.nonce, finalChunk)
|
||||
// The PTY echoes the input exactly once, so the flag may only fall after a
|
||||
// window actually carried bytes: a call that timed out before the echo
|
||||
// arrived must not leave the echo for the next poll to print.
|
||||
if len(window) > 0 {
|
||||
p.firstChunk = false
|
||||
}
|
||||
out.Truncated = truncated
|
||||
out.DroppedBytes = p.lost
|
||||
|
||||
// The identity check matters when a command was started after the previous
|
||||
// one finished but before this call could collect its last window: that
|
||||
// waiter must not clear the new command's pending entry.
|
||||
if out.Done && sess.delivered >= end && sess.pending == p {
|
||||
// Fully delivered: the session is idle again. Keeping the pending entry
|
||||
// would make the next command answer "busy" forever.
|
||||
sess.pending = nil
|
||||
sess.cond.Broadcast()
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// readDeliveryWindow returns the next window of raw output starting at from,
|
||||
// bounded by maxOut and, when truncated, backed up to the last newline within
|
||||
// termTruncBackup bytes. It never returns bytes past end (the sentinel start
|
||||
// when the command finished).
|
||||
func readDeliveryWindow(sess *termSession, from, end uint64, maxOut int) ([]byte, bool) {
|
||||
if from >= end {
|
||||
return nil, false
|
||||
}
|
||||
want := end - from
|
||||
n := int(min(want, uint64(maxOut)))
|
||||
window, _, _ := sess.readLocked(from, n)
|
||||
truncated := want > uint64(n)
|
||||
if truncated {
|
||||
floor := 0
|
||||
if len(window) > termTruncBackup {
|
||||
floor = len(window) - termTruncBackup
|
||||
}
|
||||
for i := len(window); i > floor; i-- {
|
||||
if window[i-1] == '\n' {
|
||||
window = window[:i]
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return window, truncated
|
||||
}
|
||||
|
||||
// ----- session state machine ------------------------------------------------
|
||||
|
||||
// beginCommand marks the session busy with a new command. The output cursor
|
||||
// starts at the current end of the stream, so earlier prompt/output bytes are
|
||||
// never delivered as this command's result.
|
||||
func (s *termSession) beginCommand(nonce, cmdLine, sentLine string) (*pendingCmd, *rpcError) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.closed {
|
||||
return nil, errf(CodeOffline, "Terminal session ended: %s", s.closeReason)
|
||||
}
|
||||
if !s.ready {
|
||||
return nil, errf(CodeOffline, "Terminal session is not ready yet: %s", s.id)
|
||||
}
|
||||
if s.pending != nil {
|
||||
if !s.pending.done {
|
||||
return nil, errf(CodeBusy, "Device busy: another terminal_exec is already running for this session")
|
||||
}
|
||||
end := min(s.pending.outputEnd, s.total)
|
||||
if s.delivered < end {
|
||||
return nil, errf(CodeBusy,
|
||||
"Device busy: the previous command finished but its output is not fully drained; call terminal_exec with only session_id to collect the rest first")
|
||||
}
|
||||
// The finished command has no bytes left to collect (a waiter timed out
|
||||
// after the sentinel was seen). Start the new command instead of making
|
||||
// the caller poll for nothing; a stale waiter still holding the old
|
||||
// pointer is fenced by the identity check in awaitAndDeliver.
|
||||
s.pending = nil
|
||||
}
|
||||
now := time.Now()
|
||||
p := &pendingCmd{
|
||||
sentinel: "__MCP_DONE_" + nonce + "__",
|
||||
nonce: nonce,
|
||||
cmdLine: cmdLine,
|
||||
sentLine: sentLine,
|
||||
start: s.total,
|
||||
scanPos: s.total,
|
||||
busySince: now,
|
||||
firstChunk: true,
|
||||
}
|
||||
s.pending = p
|
||||
s.delivered = s.total
|
||||
s.lastUsed = now
|
||||
s.cond.Broadcast()
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// pollPending returns the command already in flight, including the tail of one
|
||||
// whose shell has ended (the session stays reachable until the bytes are
|
||||
// delivered). Polling an idle session is a caller mistake: it would otherwise
|
||||
// wait out the whole timeout.
|
||||
func (s *termSession) pollPending() (*pendingCmd, *rpcError) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.pending == nil {
|
||||
if s.closed {
|
||||
return nil, errf(CodeOffline, "Terminal session ended: %s", s.closeReason)
|
||||
}
|
||||
return nil, errf(CodeOffline,
|
||||
"Terminal session is idle: no command is running; pass command to execute one")
|
||||
}
|
||||
return s.pending, nil
|
||||
}
|
||||
|
||||
// hasPending reports whether a command still owns the session. Its output may
|
||||
// be undrained even when the shell has already ended.
|
||||
func (s *termSession) hasPending() bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.pending != nil
|
||||
}
|
||||
|
||||
// abortCommand clears a command whose bytes could not be written, so the
|
||||
// session does not stay busy for a command that never existed.
|
||||
func (s *termSession) abortCommand(p *pendingCmd) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.pending == p {
|
||||
s.pending = nil
|
||||
s.cond.Broadcast()
|
||||
}
|
||||
}
|
||||
|
||||
func (t *sessionTable) send(deviceID string, data []byte) error {
|
||||
if t.hub == nil {
|
||||
return errNoDeviceHub
|
||||
}
|
||||
return t.hub.SendToTerminal(deviceID, data)
|
||||
}
|
||||
|
||||
// isClosed reports the session's terminal state. Its fields are immutable
|
||||
// once set, so this is race-free with the lock held briefly.
|
||||
func (s *termSession) isClosed() bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.closed
|
||||
}
|
||||
|
||||
// wakeOn broadcasts on the session's condition when ctx ends, the deadline
|
||||
// passes, or the returned stop function is called. sync.Cond has no timeout or
|
||||
// cancellation, so every waiter pairs it with this helper.
|
||||
func wakeOn(ctx context.Context, sess *termSession, deadline time.Time) func() {
|
||||
timer := time.NewTimer(time.Until(deadline))
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-timer.C:
|
||||
case <-done:
|
||||
}
|
||||
sess.mu.Lock()
|
||||
sess.cond.Broadcast()
|
||||
sess.mu.Unlock()
|
||||
}()
|
||||
return func() {
|
||||
timer.Stop()
|
||||
close(done)
|
||||
}
|
||||
}
|
||||
|
||||
// terminalExecResult wraps the output in the MCP result shape. The text item
|
||||
// carries stdout; a second compact-JSON item carries the status fields so a
|
||||
// client that only reads content still sees done/exit_code/truncated.
|
||||
func terminalExecResult(out terminalExecOutput) toolResult {
|
||||
text := out.Stdout
|
||||
if text == "" {
|
||||
if out.Done {
|
||||
text = "(无输出)"
|
||||
} else {
|
||||
text = "(暂无新输出,命令仍在运行,继续轮询)"
|
||||
}
|
||||
}
|
||||
status := map[string]any{
|
||||
"done": out.Done,
|
||||
"session_id": out.SessionID,
|
||||
"truncated": out.Truncated,
|
||||
}
|
||||
if out.ExitCode != nil {
|
||||
status["exit_code"] = *out.ExitCode
|
||||
}
|
||||
if out.DroppedBytes > 0 {
|
||||
status["dropped_bytes"] = out.DroppedBytes
|
||||
}
|
||||
statusJSON, err := json.Marshal(status)
|
||||
if err != nil {
|
||||
statusJSON = []byte("{}")
|
||||
}
|
||||
return toolResult{
|
||||
Content: []contentItem{
|
||||
{Type: "text", Text: text},
|
||||
{Type: "text", Text: string(statusJSON)},
|
||||
},
|
||||
StructuredContent: out,
|
||||
IsError: false,
|
||||
}
|
||||
}
|
||||
|
||||
func termTimeout(ms int) time.Duration {
|
||||
if ms <= 0 || ms > termMaxTimeoutMS {
|
||||
ms = termDefaultTimeoutMS
|
||||
}
|
||||
return time.Duration(ms) * time.Millisecond
|
||||
}
|
||||
|
||||
func termMaxOutput(n int) int {
|
||||
if n < termMinMaxOutput || n > termMaxMaxOutput {
|
||||
return termDefaultMaxOutput
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// termNonceFallback numbers nonces when crypto/rand is unavailable. The nonce
|
||||
// only has to be unique enough that output cannot contain the marker.
|
||||
var termNonceFallback atomic.Uint32
|
||||
|
||||
func newTermNonce() string {
|
||||
var b [4]byte
|
||||
if _, err := rand.Read(b[:]); err == nil {
|
||||
return hex.EncodeToString(b[:])
|
||||
}
|
||||
return fmt.Sprintf("%08x", termNonceFallback.Add(1))
|
||||
}
|
||||
@@ -0,0 +1,769 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/connection"
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/protocol"
|
||||
)
|
||||
|
||||
// termRig is a live MCP server plus a hub whose device's shell answers every
|
||||
// open request immediately. Tests drive the shell by feeding OnTerminalData
|
||||
// packets, i.e. exactly what cmd/main.go delivers from the TCP read loop.
|
||||
type termRig struct {
|
||||
t *testing.T
|
||||
s *Server
|
||||
h *hub.Hub
|
||||
main *connection.Context
|
||||
sub *connection.Context
|
||||
writes chan []byte
|
||||
opened chan struct{}
|
||||
stop chan struct{}
|
||||
}
|
||||
|
||||
func newTermRig(t *testing.T, clientType, capability string, isPTY bool) *termRig {
|
||||
t.Helper()
|
||||
h := hub.New()
|
||||
main := &connection.Context{RemoteAddr: "10.0.0.1:4000"}
|
||||
main.Info.ClientType = clientType
|
||||
// The hub closes the shell sub-conn 500 ms after teardown; a real net.Conn
|
||||
// keeps that path from dereferencing nil.
|
||||
shellConn, peer := net.Pipe()
|
||||
t.Cleanup(func() { _ = shellConn.Close(); _ = peer.Close() })
|
||||
sub := &connection.Context{RemoteAddr: "10.0.0.1:4001", Conn: shellConn}
|
||||
rig := &termRig{
|
||||
t: t, h: h, main: main, sub: sub,
|
||||
writes: make(chan []byte, 64),
|
||||
opened: make(chan struct{}, 4),
|
||||
stop: make(chan struct{}),
|
||||
}
|
||||
h.SetSender(func(ctx *connection.Context, data []byte) error {
|
||||
switch ctx {
|
||||
case main:
|
||||
if len(data) == 1 && data[0] == protocol.CommandShell {
|
||||
select {
|
||||
case rig.opened <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
case sub:
|
||||
select {
|
||||
case rig.writes <- append([]byte(nil), data...):
|
||||
default:
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
h.Register(&hub.Device{ID: "1001", PeerIP: "10.0.0.1", Capability: capability}, main)
|
||||
rig.s = New(Config{Token: testToken, Hub: h})
|
||||
t.Cleanup(func() { close(rig.stop) })
|
||||
// Subscribe like cmd/main.go does, so OnTerminalReady/Data/Closed flow.
|
||||
unsub := h.Subscribe(rig.s)
|
||||
t.Cleanup(unsub)
|
||||
t.Cleanup(rig.s.Close)
|
||||
|
||||
// The device answers COMMAND_SHELL by opening a shell sub-connection. The
|
||||
// loop keeps answering, so a test can close a session and reopen at once.
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
case <-rig.opened:
|
||||
h.BindTerminalConn("1001", sub, isPTY)
|
||||
case <-rig.stop:
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
return rig
|
||||
}
|
||||
|
||||
type termCall struct {
|
||||
out terminalExecOutput
|
||||
err *rpcError
|
||||
}
|
||||
|
||||
func (r *termRig) callAsync(args string) <-chan termCall {
|
||||
ch := make(chan termCall, 1)
|
||||
go func() {
|
||||
res, rerr := r.s.callTerminalExec(context.Background(), json.RawMessage(args))
|
||||
if rerr != nil {
|
||||
ch <- termCall{err: rerr}
|
||||
return
|
||||
}
|
||||
tr, ok := res.(toolResult)
|
||||
if !ok {
|
||||
ch <- termCall{err: errf(CodeInternal, "unexpected result type %T", res)}
|
||||
return
|
||||
}
|
||||
out, ok := tr.StructuredContent.(terminalExecOutput)
|
||||
if !ok {
|
||||
ch <- termCall{err: errf(CodeInternal, "unexpected structured content %T", tr.StructuredContent)}
|
||||
return
|
||||
}
|
||||
ch <- termCall{out: out}
|
||||
}()
|
||||
return ch
|
||||
}
|
||||
|
||||
func (r *termRig) wait(ch <-chan termCall) termCall {
|
||||
r.t.Helper()
|
||||
select {
|
||||
case c := <-ch:
|
||||
return c
|
||||
case <-time.After(5 * time.Second):
|
||||
r.t.Fatal("timed out waiting for the tool call")
|
||||
return termCall{}
|
||||
}
|
||||
}
|
||||
|
||||
// nextCommandWire returns the next write to the shell that carries a sentinel
|
||||
// and the nonce embedded in it.
|
||||
func (r *termRig) nextCommandWire() (wire, nonce string) {
|
||||
r.t.Helper()
|
||||
deadline := time.After(5 * time.Second)
|
||||
for {
|
||||
select {
|
||||
case b := <-r.writes:
|
||||
s := string(b)
|
||||
i := strings.Index(s, "__MCP_DONE_")
|
||||
if i < 0 {
|
||||
continue
|
||||
}
|
||||
rest := s[i+len("__MCP_DONE_"):]
|
||||
j := strings.Index(rest, "__")
|
||||
if j <= 0 {
|
||||
continue
|
||||
}
|
||||
return s, rest[:j]
|
||||
case <-deadline:
|
||||
r.t.Fatal("timed out waiting for the command wire")
|
||||
return "", ""
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (r *termRig) feed(text string) {
|
||||
r.s.OnTerminalData("1001", termPacket(text))
|
||||
}
|
||||
|
||||
// callClose runs terminal_close directly on the handler, bypassing the HTTP
|
||||
// layer's device lock (which the handler must ignore anyway).
|
||||
func (r *termRig) callClose(args string) (terminalCloseOutput, *rpcError) {
|
||||
r.t.Helper()
|
||||
res, rerr := r.s.callTerminalClose(context.Background(), json.RawMessage(args))
|
||||
if rerr != nil {
|
||||
return terminalCloseOutput{}, rerr
|
||||
}
|
||||
tr, ok := res.(toolResult)
|
||||
if !ok {
|
||||
r.t.Fatalf("unexpected close result type %T", res)
|
||||
}
|
||||
if len(tr.Content) != 1 || tr.Content[0].Text != "closed" {
|
||||
r.t.Fatalf("close content = %+v", tr.Content)
|
||||
}
|
||||
out, ok := tr.StructuredContent.(terminalCloseOutput)
|
||||
if !ok {
|
||||
r.t.Fatalf("unexpected close structured content %T", tr.StructuredContent)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// runToCompletion runs one command through the rig to its sentinel.
|
||||
func (r *termRig) runToCompletion(command, output string) termCall {
|
||||
r.t.Helper()
|
||||
ch := r.callAsync(fmt.Sprintf(`{"id":"1001","command":%q,"timeout_ms":5000}`, command))
|
||||
_, nonce := r.nextCommandWire()
|
||||
r.feed("@" + "echo off & " + command + "\r\n" + output + "\r\n__MCP_DONE_" + nonce + "__0\r\n")
|
||||
res := r.wait(ch)
|
||||
if res.err != nil || !res.out.Done {
|
||||
r.t.Fatalf("runToCompletion(%q) = %+v / %v", command, res.out, res.err)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func TestTerminalExecRunsCommand(t *testing.T) {
|
||||
rig := newTermRig(t, "", "", true)
|
||||
ch := rig.callAsync(`{"id":"1001","command":"echo hello","timeout_ms":5000}`)
|
||||
wire, nonce := rig.nextCommandWire()
|
||||
if !strings.HasPrefix(wire, "@echo off & echo hello\r\necho __MCP_DONE_"+nonce+"__%errorlevel%\r\n") {
|
||||
t.Fatalf("wire = %q", wire)
|
||||
}
|
||||
|
||||
// ConPTY: the first line is the echoed command; the real output follows.
|
||||
rig.feed("@echo off & echo hello\r\nhello\r\n__MCP_DONE_" + nonce + "__0\r\n")
|
||||
res := rig.wait(ch)
|
||||
if res.err != nil {
|
||||
t.Fatalf("call failed: %v", res.err)
|
||||
}
|
||||
out := res.out
|
||||
if out.Stdout != "hello" || !out.Done || out.ExitCode == nil || *out.ExitCode != 0 {
|
||||
t.Fatalf("out = %+v", out)
|
||||
}
|
||||
if !out.IsPTY || out.Reused || out.Truncated || out.DroppedBytes != 0 {
|
||||
t.Fatalf("flags = %+v", out)
|
||||
}
|
||||
if !strings.HasPrefix(out.SessionID, "s-") {
|
||||
t.Fatalf("session id = %q", out.SessionID)
|
||||
}
|
||||
if out.ElapsedMS < 0 {
|
||||
t.Fatalf("elapsed = %d", out.ElapsedMS)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTerminalExecTimeoutThenPoll(t *testing.T) {
|
||||
rig := newTermRig(t, "", "", true)
|
||||
ch := rig.callAsync(`{"id":"1001","command":"ping -n 30 127.0.0.1","timeout_ms":100}`)
|
||||
_, nonce := rig.nextCommandWire()
|
||||
|
||||
res := rig.wait(ch)
|
||||
if res.err != nil {
|
||||
t.Fatalf("first call: %v", res.err)
|
||||
}
|
||||
if res.out.Done || res.out.Stdout != "" {
|
||||
t.Fatalf("timeout result = %+v", res.out)
|
||||
}
|
||||
sid := res.out.SessionID
|
||||
|
||||
rig.feed("part1\r\n")
|
||||
ch = rig.callAsync(fmt.Sprintf(`{"id":"1001","session_id":%q,"timeout_ms":100}`, sid))
|
||||
res = rig.wait(ch)
|
||||
if res.err != nil {
|
||||
t.Fatalf("poll 1: %v", res.err)
|
||||
}
|
||||
if res.out.Done || res.out.Stdout != "part1\n" {
|
||||
t.Fatalf("poll 1 = %+v", res.out)
|
||||
}
|
||||
if res.out.SessionID != sid {
|
||||
t.Fatalf("poll 1 session id = %q, want %q", res.out.SessionID, sid)
|
||||
}
|
||||
|
||||
rig.feed("part2\r\n__MCP_DONE_" + nonce + "__3\r\n")
|
||||
ch = rig.callAsync(fmt.Sprintf(`{"id":"1001","session_id":%q,"timeout_ms":1000}`, sid))
|
||||
res = rig.wait(ch)
|
||||
if res.err != nil {
|
||||
t.Fatalf("poll 2: %v", res.err)
|
||||
}
|
||||
if !res.out.Done || res.out.Stdout != "part2" || res.out.ExitCode == nil || *res.out.ExitCode != 3 {
|
||||
t.Fatalf("poll 2 = %+v", res.out)
|
||||
}
|
||||
|
||||
// The command is drained; polling an idle session is a caller mistake.
|
||||
ch = rig.callAsync(fmt.Sprintf(`{"id":"1001","session_id":%q,"timeout_ms":100}`, sid))
|
||||
res = rig.wait(ch)
|
||||
if res.err == nil || res.err.Code != CodeOffline || !strings.Contains(res.err.Message, "idle") {
|
||||
t.Fatalf("idle poll = %+v", res.err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTerminalExecBusyWhileRunning(t *testing.T) {
|
||||
rig := newTermRig(t, "", "", true)
|
||||
ch := rig.callAsync(`{"id":"1001","command":"ping -n 30 127.0.0.1","timeout_ms":50}`)
|
||||
_, nonce := rig.nextCommandWire()
|
||||
if res := rig.wait(ch); res.err != nil || res.out.Done {
|
||||
t.Fatalf("first call = %+v / %v", res.out, res.err)
|
||||
}
|
||||
|
||||
ch = rig.callAsync(`{"id":"1001","command":"echo again","timeout_ms":100}`)
|
||||
res := rig.wait(ch)
|
||||
if res.err == nil || res.err.Code != CodeBusy {
|
||||
t.Fatalf("busy call = %+v", res.err)
|
||||
}
|
||||
|
||||
// Finish the first command so cleanup does not tear down a running shell.
|
||||
rig.feed("__MCP_DONE_" + nonce + "__0\r\n")
|
||||
}
|
||||
|
||||
func TestTerminalExecRejectsNonPTY(t *testing.T) {
|
||||
rig := newTermRig(t, "", "", false)
|
||||
ch := rig.callAsync(`{"id":"1001","command":"echo hi","timeout_ms":1000}`)
|
||||
res := rig.wait(ch)
|
||||
if res.err == nil || res.err.Code != CodeUnsupported || !strings.Contains(res.err.Message, "PTY") {
|
||||
t.Fatalf("non-PTY = %+v", res.err)
|
||||
}
|
||||
if rig.s.sessions.get("1001") != nil {
|
||||
t.Fatal("rejected session still in the table")
|
||||
}
|
||||
if rig.h.HasTerminalSession("1001") {
|
||||
t.Fatal("rejected session still holds the hub lease")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTerminalExecUnknownSession(t *testing.T) {
|
||||
rig := newTermRig(t, "", "", true)
|
||||
ch := rig.callAsync(`{"id":"1001","session_id":"s-abcdef","timeout_ms":100}`)
|
||||
res := rig.wait(ch)
|
||||
if res.err == nil || res.err.Code != CodeOffline || !strings.Contains(res.err.Message, "not found") {
|
||||
t.Fatalf("unknown session = %+v", res.err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTerminalExecRejectsBadArgs(t *testing.T) {
|
||||
rig := newTermRig(t, "", "", true)
|
||||
cases := []string{
|
||||
`{"id":"1001","timeout_ms":100}`, // poll without session_id
|
||||
`{"id":"1001","command":"a\nb","timeout_ms":100}`, // control char
|
||||
`{"command":"echo hi","timeout_ms":100}`, // missing id
|
||||
`{"id":"abc","command":"echo hi","timeout_ms":100}`, // id not decimal
|
||||
}
|
||||
for _, args := range cases {
|
||||
ch := rig.callAsync(args)
|
||||
res := rig.wait(ch)
|
||||
if res.err == nil || res.err.Code != CodeInvalidParams {
|
||||
t.Fatalf("%s: %+v", args, res.err)
|
||||
}
|
||||
}
|
||||
select {
|
||||
case b := <-rig.writes:
|
||||
t.Fatalf("rejected command was written to the shell: %q", b)
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
func TestTerminalExecAPKCapabilityGate(t *testing.T) {
|
||||
rig := newTermRig(t, "APK", "0400", true) // no CLIENT_CAP_TERMINAL (0x8000)
|
||||
ch := rig.callAsync(`{"id":"1001","command":"echo hi","timeout_ms":100}`)
|
||||
res := rig.wait(ch)
|
||||
if res.err == nil || res.err.Code != CodeUnsupported || !strings.Contains(res.err.Message, "too old") {
|
||||
t.Fatalf("APK gate = %+v", res.err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTerminalExecAPKWithTerminalCap(t *testing.T) {
|
||||
rig := newTermRig(t, "APK", "8400", true) // 0x8000 | 0x0400
|
||||
ch := rig.callAsync(`{"id":"1001","command":"echo hi","timeout_ms":5000}`)
|
||||
wire, nonce := rig.nextCommandWire()
|
||||
// POSIX PTY: PS1 is cleared first and the sentinel uses $?.
|
||||
if !strings.HasPrefix(wire, "PS1=\r\necho hi\r\necho __MCP_DONE_"+nonce+"__$?\r\n") {
|
||||
t.Fatalf("POSIX wire = %q", wire)
|
||||
}
|
||||
rig.feed("PS1=\r\necho hi\r\nhi\r\n__MCP_DONE_" + nonce + "__0\r\n")
|
||||
res := rig.wait(ch)
|
||||
if res.err != nil {
|
||||
t.Fatalf("APK exec: %v", res.err)
|
||||
}
|
||||
if res.out.Stdout != "hi" || !res.out.Done {
|
||||
t.Fatalf("APK out = %+v", res.out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTerminalExecMACRejected(t *testing.T) {
|
||||
rig := newTermRig(t, "MAC", "", true)
|
||||
ch := rig.callAsync(`{"id":"1001","command":"echo hi","timeout_ms":100}`)
|
||||
res := rig.wait(ch)
|
||||
if res.err == nil || res.err.Code != CodeUnsupported {
|
||||
t.Fatalf("MAC = %+v", res.err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTerminalExecTruncatesOnLineBoundary(t *testing.T) {
|
||||
rig := newTermRig(t, "", "", true)
|
||||
ch := rig.callAsync(`{"id":"1001","command":"dump","timeout_ms":5000,"max_output_bytes":1024}`)
|
||||
_, nonce := rig.nextCommandWire()
|
||||
|
||||
var payload strings.Builder
|
||||
for i := 0; i < 300; i++ {
|
||||
fmt.Fprintf(&payload, "line-%03d-xxxxxxxxxxxxxx\r\n", i)
|
||||
}
|
||||
payload.WriteString("__MCP_DONE_" + nonce + "__0\r\n")
|
||||
rig.feed(payload.String())
|
||||
|
||||
var got strings.Builder
|
||||
const wantLines = 300
|
||||
for i := 0; i < 100; i++ {
|
||||
res := rig.wait(ch)
|
||||
if res.err != nil {
|
||||
t.Fatalf("window %d: %v", i, res.err)
|
||||
}
|
||||
got.WriteString(res.out.Stdout)
|
||||
if res.out.ExitCode == nil || *res.out.ExitCode != 0 {
|
||||
t.Fatalf("window %d exit = %+v", i, res.out)
|
||||
}
|
||||
if !res.out.Done {
|
||||
t.Fatalf("window %d: command should already be done", i)
|
||||
}
|
||||
if !res.out.Truncated {
|
||||
break
|
||||
}
|
||||
if len(res.out.Stdout) > 1024 {
|
||||
t.Fatalf("window %d exceeded max_output_bytes: %d", i, len(res.out.Stdout))
|
||||
}
|
||||
ch = rig.callAsync(fmt.Sprintf(
|
||||
`{"id":"1001","session_id":%q,"timeout_ms":5000,"max_output_bytes":1024}`, res.out.SessionID))
|
||||
}
|
||||
|
||||
lines := strings.Split(strings.TrimRight(got.String(), "\n"), "\n")
|
||||
if len(lines) != wantLines {
|
||||
t.Fatalf("got %d lines, want %d", len(lines), wantLines)
|
||||
}
|
||||
for i, line := range lines {
|
||||
if want := fmt.Sprintf("line-%03d-xxxxxxxxxxxxxx", i); line != want {
|
||||
t.Fatalf("line %d = %q, want %q", i, line, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A shell that dies mid-command keeps its undelivered output in the session:
|
||||
// the device is offline, but the next poll must still collect the tail.
|
||||
func TestTerminalExecDrainsAfterClose(t *testing.T) {
|
||||
rig := newTermRig(t, "", "", true)
|
||||
ch := rig.callAsync(`{"id":"1001","command":"ping -n 30 127.0.0.1","timeout_ms":50}`)
|
||||
_, _ = rig.nextCommandWire()
|
||||
first := rig.wait(ch)
|
||||
if first.err != nil || first.out.Done {
|
||||
t.Fatalf("first call = %+v / %v", first.out, first.err)
|
||||
}
|
||||
sid := first.out.SessionID
|
||||
|
||||
rig.feed("partial output\r\n")
|
||||
// The device goes away: the hub releases the shell, then the main conn.
|
||||
rig.h.CloseTerminalSession("1001")
|
||||
rig.h.Unregister("1001")
|
||||
|
||||
ch = rig.callAsync(fmt.Sprintf(`{"id":"1001","session_id":%q,"timeout_ms":1000}`, sid))
|
||||
res := rig.wait(ch)
|
||||
if res.err != nil {
|
||||
t.Fatalf("drain poll: %v", res.err)
|
||||
}
|
||||
if res.out.Stdout != "partial output" || !res.out.Done {
|
||||
t.Fatalf("drain = %+v", res.out)
|
||||
}
|
||||
if res.out.ExitCode == nil || *res.out.ExitCode != -1 {
|
||||
t.Fatalf("closed exit code = %+v", res.out.ExitCode)
|
||||
}
|
||||
if res.out.SessionID != sid {
|
||||
t.Fatalf("session id = %q, want %q", res.out.SessionID, sid)
|
||||
}
|
||||
|
||||
// Fully delivered: the ended session is released, so the offline host now
|
||||
// reports it as gone instead of serving it forever.
|
||||
ch = rig.callAsync(fmt.Sprintf(`{"id":"1001","session_id":%q,"timeout_ms":100}`, sid))
|
||||
res = rig.wait(ch)
|
||||
if res.err == nil || res.err.Code != CodeOffline || !strings.Contains(res.err.Message, "not found") {
|
||||
t.Fatalf("post-drain poll = %+v", res.err)
|
||||
}
|
||||
}
|
||||
|
||||
// Closing with more than max_output_bytes buffered must still deliver every
|
||||
// line across polls, even though the shell is gone after the first window.
|
||||
func TestTerminalExecCloseKeepsTruncatedTail(t *testing.T) {
|
||||
rig := newTermRig(t, "", "", true)
|
||||
ch := rig.callAsync(`{"id":"1001","command":"dump","timeout_ms":50}`)
|
||||
_, _ = rig.nextCommandWire()
|
||||
first := rig.wait(ch)
|
||||
if first.err != nil || first.out.Done {
|
||||
t.Fatalf("first call = %+v / %v", first.out, first.err)
|
||||
}
|
||||
sid := first.out.SessionID
|
||||
|
||||
var payload strings.Builder
|
||||
for i := 0; i < 100; i++ {
|
||||
fmt.Fprintf(&payload, "line-%03d-xxxxxxxx\r\n", i)
|
||||
}
|
||||
rig.feed(payload.String())
|
||||
rig.h.CloseTerminalSession("1001")
|
||||
|
||||
var got strings.Builder
|
||||
ch = rig.callAsync(fmt.Sprintf(
|
||||
`{"id":"1001","session_id":%q,"timeout_ms":1000,"max_output_bytes":1024}`, sid))
|
||||
for i := 0; i < 20; i++ {
|
||||
res := rig.wait(ch)
|
||||
if res.err != nil {
|
||||
t.Fatalf("window %d: %v", i, res.err)
|
||||
}
|
||||
got.WriteString(res.out.Stdout)
|
||||
if !res.out.Done {
|
||||
t.Fatalf("window %d should be done: %+v", i, res.out)
|
||||
}
|
||||
if res.out.ExitCode == nil || *res.out.ExitCode != -1 {
|
||||
t.Fatalf("window %d exit = %+v", i, res.out.ExitCode)
|
||||
}
|
||||
if !res.out.Truncated {
|
||||
break
|
||||
}
|
||||
ch = rig.callAsync(fmt.Sprintf(
|
||||
`{"id":"1001","session_id":%q,"timeout_ms":1000,"max_output_bytes":1024}`, sid))
|
||||
}
|
||||
lines := strings.Split(strings.TrimRight(got.String(), "\n"), "\n")
|
||||
if len(lines) != 100 {
|
||||
t.Fatalf("got %d lines, want 100", len(lines))
|
||||
}
|
||||
for i, line := range lines {
|
||||
if want := fmt.Sprintf("line-%03d-xxxxxxxx", i); line != want {
|
||||
t.Fatalf("line %d = %q, want %q", i, line, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The PTY echo can arrive after the command call timed out. The poll must still
|
||||
// recognise it as the echo and not print the command line as output.
|
||||
func TestTerminalExecPollStripsLateEcho(t *testing.T) {
|
||||
rig := newTermRig(t, "", "", true)
|
||||
ch := rig.callAsync(`{"id":"1001","command":"echo hello","timeout_ms":50}`)
|
||||
_, nonce := rig.nextCommandWire()
|
||||
first := rig.wait(ch)
|
||||
if first.err != nil || first.out.Done || first.out.Stdout != "" {
|
||||
t.Fatalf("first = %+v / %v", first.out, first.err)
|
||||
}
|
||||
|
||||
rig.feed("@echo off & echo hello\r\nhello\r\n__MCP_DONE_" + nonce + "__0\r\n")
|
||||
ch = rig.callAsync(fmt.Sprintf(`{"id":"1001","session_id":%q,"timeout_ms":1000}`, first.out.SessionID))
|
||||
res := rig.wait(ch)
|
||||
if res.err != nil {
|
||||
t.Fatalf("poll: %v", res.err)
|
||||
}
|
||||
if res.out.Stdout != "hello" || !res.out.Done {
|
||||
t.Fatalf("poll = %+v, want the echo removed", res.out)
|
||||
}
|
||||
}
|
||||
|
||||
// A finished command with nothing left to collect must not answer "busy": its
|
||||
// stale pending entry is dropped and the new command runs.
|
||||
func TestTerminalExecCommandAfterDrainedFinish(t *testing.T) {
|
||||
rig := newTermRig(t, "", "", true)
|
||||
ch := rig.callAsync(`{"id":"1001","command":"slow","timeout_ms":50}`)
|
||||
_, nonce := rig.nextCommandWire()
|
||||
rig.feed("early\r\n")
|
||||
first := rig.wait(ch)
|
||||
if first.err != nil || first.out.Done || first.out.Stdout != "early\n" {
|
||||
t.Fatalf("first = %+v / %v", first.out, first.err)
|
||||
}
|
||||
|
||||
// The sentinel arrives after the call returned; everything it ends was
|
||||
// already delivered, so the session is effectively idle.
|
||||
rig.feed("__MCP_DONE_" + nonce + "__0\r\n")
|
||||
|
||||
ch = rig.callAsync(`{"id":"1001","command":"echo next","timeout_ms":5000}`)
|
||||
_, nonce2 := rig.nextCommandWire()
|
||||
rig.feed("next-out\r\n__MCP_DONE_" + nonce2 + "__0\r\n")
|
||||
res := rig.wait(ch)
|
||||
if res.err != nil {
|
||||
t.Fatalf("next command: %v", res.err)
|
||||
}
|
||||
if res.out.Stdout != "next-out" || !res.out.Done {
|
||||
t.Fatalf("next command = %+v", res.out)
|
||||
}
|
||||
}
|
||||
|
||||
// A command naming a session that already ended must not destroy the tail it
|
||||
// still holds; the caller is told to poll instead.
|
||||
func TestTerminalExecEndedSessionAsksForPoll(t *testing.T) {
|
||||
rig := newTermRig(t, "", "", true)
|
||||
ch := rig.callAsync(`{"id":"1001","command":"ping -n 30 127.0.0.1","timeout_ms":50}`)
|
||||
_, _ = rig.nextCommandWire()
|
||||
first := rig.wait(ch)
|
||||
if first.err != nil || first.out.Done {
|
||||
t.Fatalf("first = %+v / %v", first.out, first.err)
|
||||
}
|
||||
sid := first.out.SessionID
|
||||
|
||||
rig.feed("tail\r\n")
|
||||
rig.h.CloseTerminalSession("1001")
|
||||
ch = rig.callAsync(fmt.Sprintf(
|
||||
`{"id":"1001","session_id":%q,"command":"echo again","timeout_ms":200}`, sid))
|
||||
if res := rig.wait(ch); res.err == nil ||
|
||||
!strings.Contains(res.err.Message, sid) || !strings.Contains(res.err.Message, "session_id") {
|
||||
t.Fatalf("command on an ended session = %+v, want a pointer to drain it by id", res.err)
|
||||
}
|
||||
|
||||
ch = rig.callAsync(fmt.Sprintf(`{"id":"1001","session_id":%q,"timeout_ms":1000}`, sid))
|
||||
res := rig.wait(ch)
|
||||
if res.err != nil {
|
||||
t.Fatalf("drain after ended command: %v", res.err)
|
||||
}
|
||||
if res.out.Stdout != "tail" || !res.out.Done {
|
||||
t.Fatalf("drain = %+v", res.out)
|
||||
}
|
||||
}
|
||||
|
||||
// The POSIX bootstrap wait is capped by the call's own timeout, not always 2 s.
|
||||
func TestTerminalExecBootstrapHonoursCallTimeout(t *testing.T) {
|
||||
rig := newTermRig(t, "APK", "8400", true) // POSIX: the bootstrap wait applies
|
||||
start := time.Now()
|
||||
ch := rig.callAsync(`{"id":"1001","command":"echo hi","timeout_ms":300}`)
|
||||
_, _ = rig.nextCommandWire()
|
||||
res := rig.wait(ch)
|
||||
if res.err != nil {
|
||||
t.Fatalf("call: %v", res.err)
|
||||
}
|
||||
if elapsed := time.Since(start); elapsed > 1500*time.Millisecond {
|
||||
t.Fatalf("bootstrap ignored the call timeout: %v", elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
// terminal_close releases the MCP-owned session and is idempotent: a second
|
||||
// close (or a close after a reap) still answers closed instead of an error.
|
||||
func TestTerminalCloseIsIdempotent(t *testing.T) {
|
||||
rig := newTermRig(t, "", "", true)
|
||||
sid := rig.runToCompletion("echo hello", "hello").out.SessionID
|
||||
|
||||
out, rerr := rig.callClose(fmt.Sprintf(`{"id":"1001","session_id":%q}`, sid))
|
||||
if rerr != nil || !out.Closed {
|
||||
t.Fatalf("close = %+v / %v", out, rerr)
|
||||
}
|
||||
if rig.s.sessions.get("1001") != nil {
|
||||
t.Fatal("closed session still in the table")
|
||||
}
|
||||
if rig.h.HasTerminalSession("1001") {
|
||||
t.Fatal("closed session still holds the hub lease")
|
||||
}
|
||||
|
||||
out, rerr = rig.callClose(fmt.Sprintf(`{"id":"1001","session_id":%q}`, sid))
|
||||
if rerr != nil || !out.Closed {
|
||||
t.Fatalf("second close = %+v / %v", out, rerr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTerminalCloseRejectsMismatchedSession(t *testing.T) {
|
||||
rig := newTermRig(t, "", "", true)
|
||||
rig.runToCompletion("echo hello", "hello")
|
||||
|
||||
_, rerr := rig.callClose(`{"id":"1001","session_id":"s-000000"}`)
|
||||
if rerr == nil || rerr.Code != CodeOffline || !strings.Contains(rerr.Message, "mismatch") {
|
||||
t.Fatalf("mismatched close = %+v", rerr)
|
||||
}
|
||||
if rig.s.sessions.get("1001") == nil {
|
||||
t.Fatal("mismatched close removed the session")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTerminalCloseRejectsBadArgs(t *testing.T) {
|
||||
rig := newTermRig(t, "", "", true)
|
||||
for _, args := range []string{
|
||||
`{"session_id":"s-abcdef"}`, // missing id
|
||||
`{"id":"abc","session_id":"s-abcdef"}`, // id not decimal
|
||||
`{"id":"1001"}`, // missing session_id
|
||||
} {
|
||||
if _, rerr := rig.callClose(args); rerr == nil || rerr.Code != CodeInvalidParams {
|
||||
t.Fatalf("%s: %+v", args, rerr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A terminal_close that lands while terminal_exec is waiting must wake that
|
||||
// call: it delivers the bytes buffered so far and reports the shell gone.
|
||||
func TestTerminalCloseInterruptsRunningCommand(t *testing.T) {
|
||||
rig := newTermRig(t, "", "", true)
|
||||
ch := rig.callAsync(`{"id":"1001","command":"ping -n 30 127.0.0.1","timeout_ms":5000}`)
|
||||
_, _ = rig.nextCommandWire()
|
||||
rig.feed("partial output\r\n")
|
||||
|
||||
sess := rig.s.sessions.get("1001")
|
||||
if sess == nil {
|
||||
t.Fatal("session missing while the command runs")
|
||||
}
|
||||
if out, rerr := rig.callClose(fmt.Sprintf(`{"id":"1001","session_id":%q}`, sess.id)); rerr != nil || !out.Closed {
|
||||
t.Fatalf("close = %+v / %v", out, rerr)
|
||||
}
|
||||
|
||||
res := rig.wait(ch)
|
||||
if res.err != nil {
|
||||
t.Fatalf("exec after close: %v", res.err)
|
||||
}
|
||||
if res.out.Stdout != "partial output" || !res.out.Done {
|
||||
t.Fatalf("exec after close = %+v, want the buffered tail", res.out)
|
||||
}
|
||||
if res.out.ExitCode == nil || *res.out.ExitCode != -1 {
|
||||
t.Fatalf("exit code = %+v, want -1", res.out.ExitCode)
|
||||
}
|
||||
if rig.s.sessions.get("1001") != nil {
|
||||
t.Fatal("closed session still in the table")
|
||||
}
|
||||
}
|
||||
|
||||
// With no waiter, close discards the tail but still releases the device slot:
|
||||
// the next poll reports the session gone rather than serving stale bytes.
|
||||
func TestTerminalCloseWithoutWaiterReleasesSlot(t *testing.T) {
|
||||
rig := newTermRig(t, "", "", true)
|
||||
ch := rig.callAsync(`{"id":"1001","command":"ping -n 30 127.0.0.1","timeout_ms":100}`)
|
||||
_, _ = rig.nextCommandWire()
|
||||
first := rig.wait(ch)
|
||||
if first.err != nil || first.out.Done {
|
||||
t.Fatalf("first call = %+v / %v", first.out, first.err)
|
||||
}
|
||||
sid := first.out.SessionID
|
||||
rig.feed("orphan\r\n")
|
||||
|
||||
if out, rerr := rig.callClose(fmt.Sprintf(`{"id":"1001","session_id":%q}`, sid)); rerr != nil || !out.Closed {
|
||||
t.Fatalf("close = %+v / %v", out, rerr)
|
||||
}
|
||||
if rig.s.sessions.get("1001") != nil {
|
||||
t.Fatal("closed session still in the table")
|
||||
}
|
||||
if rig.h.HasTerminalSession("1001") {
|
||||
t.Fatal("closed session still holds the hub lease")
|
||||
}
|
||||
|
||||
ch = rig.callAsync(fmt.Sprintf(`{"id":"1001","session_id":%q,"timeout_ms":100}`, sid))
|
||||
res := rig.wait(ch)
|
||||
if res.err == nil || res.err.Code != CodeOffline || !strings.Contains(res.err.Message, "not found") {
|
||||
t.Fatalf("poll after close = %+v", res.err)
|
||||
}
|
||||
}
|
||||
|
||||
// A closed session must not keep the device slot: the very next command opens
|
||||
// a fresh shell immediately.
|
||||
func TestTerminalCloseAllowsImmediateReopen(t *testing.T) {
|
||||
rig := newTermRig(t, "", "", true)
|
||||
sid := rig.runToCompletion("echo one", "one").out.SessionID
|
||||
if _, rerr := rig.callClose(fmt.Sprintf(`{"id":"1001","session_id":%q}`, sid)); rerr != nil {
|
||||
t.Fatalf("close: %v", rerr)
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
res := rig.runToCompletion("echo two", "two")
|
||||
if elapsed := time.Since(start); elapsed > time.Second {
|
||||
t.Fatalf("reopen took %v, want under 1s", elapsed)
|
||||
}
|
||||
if res.out.SessionID == sid {
|
||||
t.Fatalf("reopen reused the closed session id %q", sid)
|
||||
}
|
||||
if res.out.Stdout != "two" {
|
||||
t.Fatalf("reopen output = %q", res.out.Stdout)
|
||||
}
|
||||
}
|
||||
|
||||
// terminal_close only knows MCP's own table: a shell the web console holds has
|
||||
// no MCP session, so the call is a no-op for the hub lease.
|
||||
func TestTerminalCloseLeavesBrowserSessionAlone(t *testing.T) {
|
||||
rig := newTermRig(t, "", "", true)
|
||||
if err := rig.h.OpenTerminalSession("1001"); err != nil {
|
||||
t.Fatalf("browser open: %v", err)
|
||||
}
|
||||
if out, rerr := rig.callClose(`{"id":"1001","session_id":"s-abcdef"}`); rerr != nil || !out.Closed {
|
||||
t.Fatalf("close = %+v / %v", out, rerr)
|
||||
}
|
||||
if !rig.h.HasTerminalSession("1001") {
|
||||
t.Fatal("terminal_close released a browser-held lease")
|
||||
}
|
||||
}
|
||||
|
||||
// The HTTP layer must not make terminal_close wait on the per-device lock:
|
||||
// an in-flight terminal_exec holds it for the whole call timeout.
|
||||
func TestTerminalCloseIgnoresDeviceLock(t *testing.T) {
|
||||
rig := newTermRig(t, "", "", true)
|
||||
rig.runToCompletion("echo hello", "hello") // the session stays open after a finished command
|
||||
|
||||
sess := rig.s.sessions.get("1001")
|
||||
if sess == nil {
|
||||
t.Fatal("session missing")
|
||||
}
|
||||
if _, ok := rig.s.locks.tryAcquire("1001", "terminal_exec"); !ok {
|
||||
t.Fatal("could not take the device lock")
|
||||
}
|
||||
defer rig.s.locks.release("1001")
|
||||
|
||||
if _, rerr := rig.s.callTool(context.Background(), json.RawMessage(
|
||||
fmt.Sprintf(`{"name":"terminal_close","arguments":{"id":"1001","session_id":%q}}`, sess.id))); rerr != nil {
|
||||
t.Fatalf("close through tools/call: %v", rerr)
|
||||
}
|
||||
if rig.s.sessions.get("1001") != nil {
|
||||
t.Fatal("close through tools/call did not release the session")
|
||||
}
|
||||
}
|
||||
+102
-11
@@ -37,6 +37,28 @@ func GbkToUTF8(data []byte) string {
|
||||
return cleanString(buf.String())
|
||||
}
|
||||
|
||||
// UTF8ToGBK converts a Go string to the GBK bytes a client-side C string field
|
||||
// expects. Every platform's file manager works on GBK on the wire: Windows uses
|
||||
// the ANSI APIs (CP936), and the POSIX clients convert with iconv before
|
||||
// sending (`gbkToUtf8` in common/FileManager.h). Bytes that GBK cannot
|
||||
// represent are replaced; callers that care should check the round trip.
|
||||
func UTF8ToGBK(s string) []byte {
|
||||
if s == "" {
|
||||
return nil
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
w := transform.NewWriter(&buf, simplifiedchinese.GBK.NewEncoder())
|
||||
if _, err := w.Write([]byte(s)); err != nil {
|
||||
// Unrepresentable input: fall back to the raw UTF-8 bytes, which is
|
||||
// exactly what the C++ iconv helper does on failure.
|
||||
return []byte(s)
|
||||
}
|
||||
if err := w.Close(); err != nil {
|
||||
return []byte(s)
|
||||
}
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
// Utf8CleanString trims at the first NUL and strips non-printables — the
|
||||
// UTF-8 counterpart of GbkToUTF8 for clients that have the CLIENT_CAP_UTF8
|
||||
// capability bit. Decoding as GBK in that case would mangle multi-byte
|
||||
@@ -69,6 +91,17 @@ const (
|
||||
ClientCapV2 uint32 = 0x0001 // CLIENT_CAP_V2 — V2 file transfer
|
||||
ClientCapUTF8 uint32 = 0x0002 // CLIENT_CAP_UTF8 — UTF-8 protocol strings (activeWindow, key-log titles, ...)
|
||||
ClientCapScreenPreview uint32 = 0x0004 // CLIENT_CAP_SCREEN_PREVIEW
|
||||
ClientCapC2CPaths uint32 = 0x0008 // CLIENT_CAP_C2C_PATHS — path-list driven host-to-host transfer
|
||||
// Bits 0x0010 (C2C recv ack), 0x0020 (protocol switch) and 0x0040
|
||||
// (embedded anchor) are not consumed by the Go server yet. They are simply
|
||||
// skipped by the constants below.
|
||||
ClientCapVirtualDesktop uint32 = 0x0080 // CLIENT_CAP_VIRTUAL_DESKTOP — whole virtual desktop capture
|
||||
ClientCapWindowInfo uint32 = 0x0100 // CLIENT_CAP_WINDOW_INFO — window enumeration / rects
|
||||
ClientCapScreenRegion uint32 = 0x0200 // CLIENT_CAP_SCREEN_REGION — region/window/monitor capture
|
||||
// CLIENT_CAP_TERMINAL is only declared by recent Android builds: Windows
|
||||
// and Linux always had COMMAND_SHELL but never advertise it, so this bit
|
||||
// must only gate the APK path (common/commands.h:151).
|
||||
ClientCapTerminal uint32 = 0x8000 // CLIENT_CAP_TERMINAL — PTY shell sub-connection
|
||||
)
|
||||
|
||||
// SupportsCap returns true when the client's reported capability hex string
|
||||
@@ -104,6 +137,8 @@ func DecodeClientString(data []byte, capability, clientType string) string {
|
||||
const (
|
||||
// Server -> Client commands
|
||||
CommandActived byte = 0 // COMMAND_ACTIVED
|
||||
CommandListDrive byte = 1 // COMMAND_LIST_DRIVE - open the file-manager sub-conn and list drives
|
||||
CommandListFiles byte = 2 // COMMAND_LIST_FILES - [cmd][path\0] on the file-manager sub-conn
|
||||
CommandScreenSpy byte = 16 // COMMAND_SCREEN_SPY - start screen capture
|
||||
CommandScreenControl byte = 20 // COMMAND_SCREEN_CONTROL - mouse/keyboard input (MSG64 batches)
|
||||
CommandScreenGetClipboard byte = 24 // COMMAND_SCREEN_GET_CLIPBOARD - request remote clipboard (single byte)
|
||||
@@ -113,6 +148,9 @@ const (
|
||||
CommandUninstall byte = 63 // TOKEN_UNINSTALL - uninstall the host agent (single byte)
|
||||
CommandTerminalRsize byte = 81 // CMD_TERMINAL_RESIZE - [cmd:1][cols:2 LE][rows:2 LE]
|
||||
CmdRestoreConsole byte = 82 // CMD_RESTORE_CONSOLE - RDP session "归位": switch back to the console session and restart capture
|
||||
CommandSendFileV2 byte = 85 // COMMAND_SEND_FILE_V2 - one V2 file chunk (77-byte packed header + name + data)
|
||||
CommandFileCompleteV2 byte = 91 // COMMAND_FILE_COMPLETE_V2 - end of one V2 file, carries its SHA-256
|
||||
CmdDownFilesV2 byte = 94 // CMD_DOWN_FILES_V2 - [cmd][targetDir\0][path\0][\0] on the file-manager sub-conn
|
||||
CommandScreenKeyframeReq byte = 169 // COMMAND_SCREEN_KEYFRAME_REQ - force the client to emit an IDR immediately
|
||||
CommandBye byte = 204 // COMMAND_BYE - disconnect
|
||||
CommandHeartbeat byte = 216 // CMD_HEARTBEAT_ACK
|
||||
@@ -121,17 +159,33 @@ const (
|
||||
TokenAuth byte = 100 // TOKEN_AUTH - authorization required
|
||||
TokenHeartbeat byte = 101 // TOKEN_HEARTBEAT
|
||||
TokenLogin byte = 102 // TOKEN_LOGIN - login packet
|
||||
TokenDriveList byte = 103 // TOKEN_DRIVE_LIST - file-manager sub-conn first packet, drive records
|
||||
TokenFileList byte = 104 // TOKEN_FILE_LIST - one directory's entries, [token] + records
|
||||
TokenBitmapInfo byte = 115 // TOKEN_BITMAPINFO - screen sub-connection header
|
||||
TokenFirstScreen byte = 116 // TOKEN_FIRSTSCREEN - raw BGRA baseline frame (NOT H264)
|
||||
TokenNextScreen byte = 117 // TOKEN_NEXTSCREEN - non-keyframe H264 (P-frame)
|
||||
TokenClipboardText byte = 118 // TOKEN_CLIPBOARD_TEXT - remote clipboard text [118][UTF-8][NUL]
|
||||
TokenShellStart byte = 128 // TOKEN_SHELL_START - legacy cmd-pipe shell sub-conn open
|
||||
TokenKeyframe byte = 134 // TOKEN_KEYFRAME - H264 IDR (sent on GOP boundary)
|
||||
// TOKEN_FILE_LIST_ERROR is the modern clients' structured "cannot list this
|
||||
// directory" reply: [token:1][win32err:4 LE]. Legacy clients send nothing,
|
||||
// which the server can only report as a timeout.
|
||||
TokenFileListError byte = 171 // TOKEN_FILE_LIST_ERROR - directory listing failed
|
||||
// TOKEN_DOWNLOAD_ERROR is the file-manager sub-conn's "nothing to send"
|
||||
// reply to CMD_DOWN_FILES_V2: [token:1][win32err:4 LE]. The transfer sub-conn
|
||||
// is not created in that case, so this is the only failure signal.
|
||||
TokenDownloadError byte = 173 // TOKEN_DOWNLOAD_ERROR - download request rejected
|
||||
TokenTerminalStart byte = 232 // TOKEN_TERMINAL_START - modern PTY shell sub-conn open
|
||||
TokenTerminalClose byte = 233 // TOKEN_TERMINAL_CLOSE - shell exited / close ack
|
||||
TokenConnAuth byte = 246 // TOKEN_CONN_AUTH - sub-connection identity handshake
|
||||
CmdCursorImage byte = 93 // CMD_CURSOR_IMAGE - custom cursor bitmap (Phase 5+ feature)
|
||||
CmdSockDllLoader byte = 210 // SOCKET_DLLLOADER - shellcode/memory-DLL loader requests the full DLL payload
|
||||
// COMMAND_SCREEN_PREVIEW_REQ / TOKEN_SCREEN_PREVIEW_RSP are a main-connection
|
||||
// RPC pair: the client captures, scales and JPEG-encodes a frame itself. It
|
||||
// opens no sub-connection and holds no screen-session slot, so it can run
|
||||
// alongside a live screen viewer (design §7.1).
|
||||
CommandScreenPreviewReq byte = 247 // COMMAND_SCREEN_PREVIEW_REQ - [cmd:1][reqId:2][maxWidth:2][quality:1][reserved:2]
|
||||
TokenScreenPreviewRsp byte = 248 // TOKEN_SCREEN_PREVIEW_RSP - [token:1][reqId:2][status:1][format:1][w:2][h:2][bytes:4][reserved:3][data]
|
||||
CmdCursorImage byte = 93 // CMD_CURSOR_IMAGE - custom cursor bitmap (Phase 5+ feature)
|
||||
CmdSockDllLoader byte = 210 // SOCKET_DLLLOADER - shellcode/memory-DLL loader requests the full DLL payload
|
||||
)
|
||||
|
||||
// HeartbeatACK (CMD_HEARTBEAT_ACK) response layout — mirrors the HeartbeatACK
|
||||
@@ -487,15 +541,51 @@ type LoginInfo struct {
|
||||
Reserved string // Contains additional info separated by |
|
||||
}
|
||||
|
||||
// DecodeLoginAnsiField decodes a LOGIN_INFOR text field that is *not* covered
|
||||
// by CLIENT_CAP_UTF8 (computer name, OS string). On Windows those are filled
|
||||
// from narrow Win32/CRT APIs — gethostname() at client/LoginServer.cpp:380 —
|
||||
// and carry the system code page (CP936/GBK on Chinese installs) even when the
|
||||
// client advertises UTF-8 support; the capability bit only promises UTF-8 for
|
||||
// the protocol string fields it lists (active window, window titles, file
|
||||
// paths). The MFC server decodes these same fields with CP_ACP
|
||||
// (HostJson.cpp::AnsiToUtf8), which is why a Chinese computer name renders
|
||||
// correctly there and showed up as "����" in the Go server's web console.
|
||||
// POSIX and Android clients build the field as UTF-8, so keep their bytes.
|
||||
// "macOS" is the client-type string of pre-1.0 macOS builds (GetClientType
|
||||
// returns "MAC" today; the MFC server still accepts both, see
|
||||
// WebService.cpp's dblclick branch). Those builds also send UTF-8 names, so
|
||||
// they must not fall into the GBK path or the same login decodes differently
|
||||
// in the Go server than in the C++ one.
|
||||
//
|
||||
// GBK is hard-coded because the Go server has no equivalent of the server
|
||||
// machine's CP_ACP; that matches the MFC deployment everyone runs (a Chinese
|
||||
// server). Consequence worth knowing: a Windows machine with the "Beta: Use
|
||||
// Unicode UTF-8" locale option sends UTF-8 here too and will show mojibake —
|
||||
// the MFC server mangles that case as well, and sniffing UTF-8 instead would
|
||||
// misfire on real GBK names (measured: 930 of 6763 GBK hanzi validate as a
|
||||
// UTF-8 two-byte sequence, so ~2% of two-character host names would be
|
||||
// misread), so the deterministic rule is the safer side of the trade.
|
||||
func DecodeLoginAnsiField(data []byte, clientType string) string {
|
||||
switch clientType {
|
||||
case "LNX", "MAC", "macOS", "APK":
|
||||
return Utf8CleanString(data)
|
||||
}
|
||||
return GbkToUTF8(data)
|
||||
}
|
||||
|
||||
// ParseLoginInfo parses LOGIN_INFOR from data.
|
||||
//
|
||||
// Encoding: text fields are GBK on legacy Windows clients and UTF-8 on modern
|
||||
// clients that set CLIENT_CAP_UTF8 (always on for LNX / MAC). Picking the
|
||||
// wrong codec mangles non-ASCII characters — e.g. a German location string
|
||||
// "Nürnberg" sent as UTF-8 (4E C3 BC 72 ...) and force-decoded as GBK turns
|
||||
// into mojibake. The heartbeat path already honors this via DecodeClientString
|
||||
// (see cmd/main.go handleHeartbeat); ParseLoginInfo previously did not, so
|
||||
// every login string from a UTF-8 client was being misread.
|
||||
// Encoding: Reserved (file path, location, ...) is GBK on legacy Windows
|
||||
// clients and UTF-8 on modern clients that set CLIENT_CAP_UTF8 (always on for
|
||||
// LNX / MAC). Picking the wrong codec mangles non-ASCII characters — e.g. a
|
||||
// German location string "Nürnberg" sent as UTF-8 (4E C3 BC 72 ...) and
|
||||
// force-decoded as GBK turns into mojibake. The heartbeat path already honors
|
||||
// this via DecodeClientString (see cmd/main.go handleHeartbeat); ParseLoginInfo
|
||||
// previously did not, so every login string from a UTF-8 client was misread.
|
||||
//
|
||||
// Computer name and OS use a different rule: they are ANSI on Windows
|
||||
// regardless of the capability bit (see DecodeLoginAnsiField), so they are
|
||||
// decoded by client type, not by capability.
|
||||
//
|
||||
// To get encoding right we have a chicken-and-egg problem: capability lives
|
||||
// in ModuleVersion (offset 164) and clientType lives in Reserved field 0
|
||||
@@ -546,11 +636,12 @@ func ParseLoginInfo(data []byte) (*LoginInfo, error) {
|
||||
// Now decode every user-text field with the client's actual codec.
|
||||
decode := func(b []byte) string { return DecodeClientString(b, capability, clientType) }
|
||||
|
||||
// Computer name / OS: ANSI on Windows whatever the capability says.
|
||||
if len(data) >= OffsetOsVerInfoEx+156 {
|
||||
info.OsVerInfo = decode(data[OffsetOsVerInfoEx : OffsetOsVerInfoEx+156])
|
||||
info.OsVerInfo = DecodeLoginAnsiField(data[OffsetOsVerInfoEx:OffsetOsVerInfoEx+156], clientType)
|
||||
}
|
||||
if len(data) >= OffsetPCName+240 {
|
||||
info.PCName = decode(data[OffsetPCName : OffsetPCName+240])
|
||||
info.PCName = DecodeLoginAnsiField(data[OffsetPCName:OffsetPCName+240], clientType)
|
||||
}
|
||||
if len(data) >= OffsetMasterID+20 {
|
||||
info.MasterID = decode(data[OffsetMasterID : OffsetMasterID+20])
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
package protocol
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSignMessageHMACVector(t *testing.T) {
|
||||
// Standard HMAC-SHA256 sanity vector. Anchors that SignMessage matches
|
||||
@@ -45,3 +52,54 @@ func TestIsH264KeyframeBasic(t *testing.T) {
|
||||
t.Fatal("non-H264 bytes should not match")
|
||||
}
|
||||
}
|
||||
|
||||
// TestCommandTokenConstantsAreUnique guards the command/token byte values in
|
||||
// commands.go against a silent collision. The tokens are matched against the
|
||||
// first byte of every inbound packet, so two names sharing a value means the
|
||||
// wrong handler eats the packet — an added file-manager token that reuses
|
||||
// TOKEN_LOGIN's value would swallow the device's login. Constants outside the
|
||||
// Command*/Token*/Cmd* families are skipped: the file also defines field
|
||||
// offsets, which legitimately repeat small numbers (offset 1 in two packets).
|
||||
func TestCommandTokenConstantsAreUnique(t *testing.T) {
|
||||
fset := token.NewFileSet()
|
||||
file, err := parser.ParseFile(fset, "commands.go", nil, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("parse commands.go: %v", err)
|
||||
}
|
||||
seen := make(map[int64]string)
|
||||
ast.Inspect(file, func(n ast.Node) bool {
|
||||
spec, ok := n.(*ast.ValueSpec)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
for i, name := range spec.Names {
|
||||
// A name without its own expression repeats the previous value.
|
||||
if i >= len(spec.Values) || !isCommandTokenName(name.Name) {
|
||||
continue
|
||||
}
|
||||
lit, ok := spec.Values[i].(*ast.BasicLit)
|
||||
if !ok || lit.Kind != token.INT {
|
||||
continue
|
||||
}
|
||||
v, err := strconv.ParseInt(lit.Value, 0, 64)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if prev, dup := seen[v]; dup {
|
||||
t.Errorf("%s and %s both use %d", prev, name.Name, v)
|
||||
continue
|
||||
}
|
||||
seen[v] = name.Name
|
||||
}
|
||||
return true
|
||||
})
|
||||
if len(seen) < 20 {
|
||||
t.Fatalf("only %d command/token constants scanned; did commands.go change shape?", len(seen))
|
||||
}
|
||||
}
|
||||
|
||||
func isCommandTokenName(name string) bool {
|
||||
return strings.HasPrefix(name, "Command") ||
|
||||
strings.HasPrefix(name, "Token") ||
|
||||
strings.HasPrefix(name, "Cmd")
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
package protocol
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// buildLoginInfo lays out a synthetic LOGIN_INFOR packet. The C++ struct is
|
||||
// fixed-width and NUL-padded; fields not touched here stay zero.
|
||||
func buildLoginInfo(moduleVersion, clientType string, pcName []byte) []byte {
|
||||
b := make([]byte, OffsetReserved+512)
|
||||
b[0] = TokenLogin
|
||||
copy(b[OffsetModuleVersion:], moduleVersion)
|
||||
copy(b[OffsetPCName:OffsetPCName+240], pcName)
|
||||
copy(b[OffsetReserved:], clientType)
|
||||
return b
|
||||
}
|
||||
|
||||
// A Chinese Windows host name arrives as ANSI (CP936/GBK) bytes: the client
|
||||
// fills LOGIN_INFOR.szPCName from gethostname(), a narrow Win32 API, whatever
|
||||
// CLIENT_CAP_UTF8 says (client/LoginServer.cpp:380). The MFC server converts
|
||||
// this field with CP_ACP, so it renders correctly; the Go server used to feed
|
||||
// it to the UTF-8 decoder for every modern client, turning each GBK byte into
|
||||
// U+FFFD ("����") in the web console.
|
||||
func TestLoginInfoGBKHostNameFromUTF8CapableClient(t *testing.T) {
|
||||
name := "我的电脑/研发组"
|
||||
raw := buildLoginInfo("Oct 20 2025-0006", "EXE", UTF8ToGBK(name))
|
||||
|
||||
info, err := ParseLoginInfo(raw)
|
||||
if err != nil {
|
||||
t.Fatalf("ParseLoginInfo: %v", err)
|
||||
}
|
||||
if info.PCName != name {
|
||||
t.Fatalf("PCName = %q, want %q", info.PCName, name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginInfoGBKHostNameFromLegacyClient(t *testing.T) {
|
||||
name := "张三的电脑"
|
||||
raw := buildLoginInfo("Dec 19 2024", "EXE", UTF8ToGBK(name))
|
||||
|
||||
info, err := ParseLoginInfo(raw)
|
||||
if err != nil {
|
||||
t.Fatalf("ParseLoginInfo: %v", err)
|
||||
}
|
||||
if info.PCName != name {
|
||||
t.Fatalf("PCName = %q, want %q", info.PCName, name)
|
||||
}
|
||||
}
|
||||
|
||||
// POSIX clients build szPCName from gethostname() on a UTF-8 system, so their
|
||||
// non-ASCII names must not be run through the GBK decoder.
|
||||
func TestLoginInfoUTF8HostNameFromLinuxClient(t *testing.T) {
|
||||
name := "Nürnberg-PC"
|
||||
raw := buildLoginInfo("Oct 20 2025-0006", "LNX", []byte(name))
|
||||
|
||||
info, err := ParseLoginInfo(raw)
|
||||
if err != nil {
|
||||
t.Fatalf("ParseLoginInfo: %v", err)
|
||||
}
|
||||
if info.PCName != name {
|
||||
t.Fatalf("PCName = %q, want %q", info.PCName, name)
|
||||
}
|
||||
}
|
||||
|
||||
// The APK client sends the Android device model as UTF-8.
|
||||
func TestLoginInfoUTF8HostNameFromAndroidClient(t *testing.T) {
|
||||
name := "小米14"
|
||||
raw := buildLoginInfo("Oct 20 2025-8007", "APK", []byte(name))
|
||||
|
||||
info, err := ParseLoginInfo(raw)
|
||||
if err != nil {
|
||||
t.Fatalf("ParseLoginInfo: %v", err)
|
||||
}
|
||||
if info.PCName != name {
|
||||
t.Fatalf("PCName = %q, want %q", info.PCName, name)
|
||||
}
|
||||
}
|
||||
|
||||
// Pre-1.0 macOS builds report the client type as "macOS" (current builds send
|
||||
// "MAC"); their host names are UTF-8 too and must not be GBK-decoded.
|
||||
func TestLoginInfoUTF8HostNameFromLegacyMacClient(t *testing.T) {
|
||||
name := "München-Mac"
|
||||
raw := buildLoginInfo("Dec 19 2024", "macOS", []byte(name))
|
||||
|
||||
info, err := ParseLoginInfo(raw)
|
||||
if err != nil {
|
||||
t.Fatalf("ParseLoginInfo: %v", err)
|
||||
}
|
||||
if info.PCName != name {
|
||||
t.Fatalf("PCName = %q, want %q", info.PCName, name)
|
||||
}
|
||||
}
|
||||
|
||||
// Reserved must keep following CLIENT_CAP_UTF8: RES_FILE_PATH is UTF-8 on
|
||||
// modern clients (client/LoginServer.cpp:411) while legacy clients sent
|
||||
// CP_ACP, and the location field is UTF-8 for modern clients too.
|
||||
func TestLoginInfoReservedStillHonorsCapability(t *testing.T) {
|
||||
path := `C:\Users\张三\Desktop\样本.exe`
|
||||
reserved := strings.Join([]string{
|
||||
"EXE", // 0 client type
|
||||
"64", // 1 system bits
|
||||
"8", // 2 cpu
|
||||
"16", // 3 memory
|
||||
path, // 4 file path (UTF-8 on capable clients)
|
||||
"?", // 5
|
||||
"2025-01-02", // 6 install time
|
||||
"?", // 7
|
||||
"64", // 8 program bits
|
||||
"", // 9
|
||||
"北京/朝阳", // 10 location (UTF-8 on capable clients)
|
||||
"1.2.3.4", // 11 public ip
|
||||
"v1.0", // 12 version
|
||||
"user", // 13 username
|
||||
"0", // 14 admin
|
||||
}, "|")
|
||||
raw := buildLoginInfo("Oct 20 2025-0006", "", UTF8ToGBK("PC"))
|
||||
copy(raw[OffsetReserved:], reserved)
|
||||
// clientType itself lives in field 0 of the very same Reserved bytes.
|
||||
if !bytes.HasPrefix(raw[OffsetReserved:], []byte("EXE|")) {
|
||||
t.Fatal("test fixture broken")
|
||||
}
|
||||
|
||||
info, err := ParseLoginInfo(raw)
|
||||
if err != nil {
|
||||
t.Fatalf("ParseLoginInfo: %v", err)
|
||||
}
|
||||
if got := info.GetReservedField(ResFieldFilePath); got != path {
|
||||
t.Fatalf("file path = %q, want %q", got, path)
|
||||
}
|
||||
if got := info.GetReservedField(ResFieldClientLoc); got != "北京/朝阳" {
|
||||
t.Fatalf("location = %q, want %q", got, "北京/朝阳")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginInfoBinaryFieldsUnaffected(t *testing.T) {
|
||||
raw := buildLoginInfo("Oct 20 2025-0006", "EXE", UTF8ToGBK("PC"))
|
||||
binary.LittleEndian.PutUint32(raw[OffsetCPUMHz:], 3600)
|
||||
raw[OffsetWebCamExist] = 1
|
||||
binary.LittleEndian.PutUint32(raw[OffsetSpeed:], 123)
|
||||
|
||||
info, err := ParseLoginInfo(raw)
|
||||
if err != nil {
|
||||
t.Fatalf("ParseLoginInfo: %v", err)
|
||||
}
|
||||
if info.CPUMHz != 3600 || !info.WebCamExist || info.Speed != 123 {
|
||||
t.Fatalf("binary fields = %d/%v/%d", info.CPUMHz, info.WebCamExist, info.Speed)
|
||||
}
|
||||
if info.PCName != "PC" {
|
||||
t.Fatalf("PCName = %q", info.PCName)
|
||||
}
|
||||
}
|
||||
+13
-250
@@ -1,57 +1,21 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/auditquery"
|
||||
)
|
||||
|
||||
// Audit-log query support for the admin-only "Audit Log" page.
|
||||
//
|
||||
// The server reads its own JSON-lines audit file (logs/audit.log) back to the
|
||||
// browser. Records are already redacted at write time (see logger.AuditAt), so
|
||||
// returning raw lines is safe as long as we never widen what is written.
|
||||
//
|
||||
// Only the CURRENT audit file is searched. Rotated files (audit-*.log[.gz])
|
||||
// are deliberately out of scope: they need gzip support and a separate index,
|
||||
// and the UI is meant for recent-window triage ("what happened just now").
|
||||
const (
|
||||
auditQueryDefaultLimit = 100
|
||||
auditQueryMaxLimit = 500
|
||||
auditQueryMaxOffset = 10000
|
||||
// The scanner itself (file tail, filters, paging) lives in package
|
||||
// auditquery so the MCP get_audit_log tool can share it; this file keeps only
|
||||
// the WebSocket command handler and the reply shaping specific to the UI.
|
||||
|
||||
// auditQueryScanBudget bounds how much of the audit file a single query
|
||||
// reads. The tail is read when the file is larger, so the newest records
|
||||
// (what operators actually triage) are always covered and a multi-GB log
|
||||
// cannot stall the WS goroutine.
|
||||
auditQueryScanBudget = 32 << 20 // 32 MB
|
||||
)
|
||||
|
||||
// auditQueryRequest is the JSON body of the `query_audit` command.
|
||||
type auditQueryRequest struct {
|
||||
From string `json:"from"` // RFC3339 ("2026-10-18T10:00:00Z"), optional
|
||||
To string `json:"to"` // RFC3339, optional
|
||||
Event string `json:"event"` // exact ("web.login.failure"), prefix ("web." / "web.*"), or ""
|
||||
Actor string `json:"actor"` // exact, case-insensitive
|
||||
IP string `json:"ip"` // exact
|
||||
DeviceID string `json:"device_id"`
|
||||
Keyword string `json:"keyword"` // case-insensitive substring of the raw record
|
||||
WarnOnly bool `json:"warn_only"` // only level=warn records
|
||||
Limit int `json:"limit"`
|
||||
Offset int `json:"offset"` // skip the newest N matching records
|
||||
}
|
||||
|
||||
// auditQueryResult is the internal result of scanning the audit file.
|
||||
type auditQueryResult struct {
|
||||
Events []map[string]any
|
||||
Total int // matching records in the scanned window
|
||||
FileExists bool
|
||||
FileSize int64
|
||||
ScannedBytes int64
|
||||
Truncated bool // the file was larger than auditQueryScanBudget
|
||||
}
|
||||
// auditQueryMaxLimit caps the page size of the audit page. It is tighter than
|
||||
// auditquery.MaxLimit (the protocol-wide cap the MCP tool uses) because the
|
||||
// admin table is meant to be paged, not downloaded.
|
||||
const auditQueryMaxLimit = 500
|
||||
|
||||
// handleQueryAudit implements the admin-only audit query command. The reply is
|
||||
// `{cmd:"audit_result", ok, events, total, ...}`; events are newest-first.
|
||||
@@ -60,13 +24,13 @@ func (h *wsHub) handleQueryAudit(c *wsClient, raw []byte) {
|
||||
if !h.requireAdmin(c, raw, replyCmd) {
|
||||
return
|
||||
}
|
||||
var in auditQueryRequest
|
||||
var in auditquery.Query
|
||||
if err := json.Unmarshal(raw, &in); err != nil {
|
||||
c.queue(mustJSON(map[string]any{"cmd": replyCmd, "ok": false, "msg": "Invalid request"}))
|
||||
return
|
||||
}
|
||||
in.Limit = clampAuditLimit(in.Limit)
|
||||
in.Offset = clampAuditOffset(in.Offset)
|
||||
in.Limit = auditquery.ClampLimit(in.Limit, auditQueryMaxLimit)
|
||||
in.Offset = auditquery.ClampOffset(in.Offset)
|
||||
|
||||
path := h.log.AuditPath()
|
||||
if path == "" {
|
||||
@@ -81,7 +45,7 @@ func (h *wsHub) handleQueryAudit(c *wsClient, raw []byte) {
|
||||
return
|
||||
}
|
||||
|
||||
res, err := queryAuditLog(path, in)
|
||||
res, err := auditquery.Scan(path, in)
|
||||
if err != nil {
|
||||
h.audit(c, true, auditQuery, map[string]any{
|
||||
"ok": false,
|
||||
@@ -125,204 +89,3 @@ func (h *wsHub) handleQueryAudit(c *wsClient, raw []byte) {
|
||||
"truncated": res.Truncated,
|
||||
}))
|
||||
}
|
||||
|
||||
func clampAuditLimit(n int) int {
|
||||
if n <= 0 {
|
||||
return auditQueryDefaultLimit
|
||||
}
|
||||
if n > auditQueryMaxLimit {
|
||||
return auditQueryMaxLimit
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func clampAuditOffset(n int) int {
|
||||
if n < 0 {
|
||||
return 0
|
||||
}
|
||||
if n > auditQueryMaxOffset {
|
||||
return auditQueryMaxOffset
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// queryAuditLog scans path for audit records matching q. The returned events
|
||||
// are the newest limit records after skipping offset, in newest-first order.
|
||||
func queryAuditLog(path string, q auditQueryRequest) (auditQueryResult, error) {
|
||||
res := auditQueryResult{Events: []map[string]any{}}
|
||||
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
// No audit record has been written yet (lumberjack creates the file
|
||||
// lazily). An empty result is correct, not an error.
|
||||
return res, nil
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
info, err := f.Stat()
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
res.FileExists = true
|
||||
res.FileSize = info.Size()
|
||||
|
||||
// For very large files, scan only the tail; the newest matches live there.
|
||||
start := int64(0)
|
||||
if info.Size() > auditQueryScanBudget {
|
||||
start = info.Size() - auditQueryScanBudget
|
||||
if _, err := f.Seek(start, 0); err != nil {
|
||||
return res, err
|
||||
}
|
||||
res.Truncated = true
|
||||
}
|
||||
|
||||
from, hasFrom := parseAuditTime(q.From)
|
||||
to, hasTo := parseAuditTime(q.To)
|
||||
|
||||
keep := q.Offset + q.Limit
|
||||
ring := make([]map[string]any, keep)
|
||||
filled := 0
|
||||
|
||||
sc := bufio.NewScanner(f)
|
||||
// Sanitized values are capped at 4096 bytes each; a record with many
|
||||
// fields stays well under 1 MB. Allow headroom rather than aborting the
|
||||
// whole query on one long line.
|
||||
sc.Buffer(make([]byte, 64*1024), 4*1024*1024)
|
||||
|
||||
first := true
|
||||
for sc.Scan() {
|
||||
line := sc.Text()
|
||||
if start > 0 && first {
|
||||
// Seeking into the middle of the file lands mid-line. Drop that
|
||||
// partial record.
|
||||
first = false
|
||||
continue
|
||||
}
|
||||
first = false
|
||||
res.ScannedBytes += int64(len(line)) + 1
|
||||
|
||||
line = strings.TrimSpace(line)
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
var rec map[string]any
|
||||
if err := json.Unmarshal([]byte(line), &rec); err != nil {
|
||||
continue // tolerate a torn line instead of failing the page
|
||||
}
|
||||
if _, ok := rec["event"].(string); !ok {
|
||||
continue
|
||||
}
|
||||
// Only audit records belong on the page. The dedicated file contains
|
||||
// nothing else, but a hand-edited or mixed file must not surface
|
||||
// ordinary operational lines here.
|
||||
if rec["audit"] != true {
|
||||
continue
|
||||
}
|
||||
if !auditRecordMatches(rec, line, q, from, hasFrom, to, hasTo) {
|
||||
continue
|
||||
}
|
||||
// Ring buffer of the last `keep` matches (file order is chronological).
|
||||
ring[res.Total%keep] = rec
|
||||
if filled < keep {
|
||||
filled++
|
||||
}
|
||||
res.Total++
|
||||
}
|
||||
if err := sc.Err(); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
// Newest first, skipping Offset. The match with 0-based index i lives at
|
||||
// ring[i%keep] as long as i >= Total-filled.
|
||||
for i := res.Total - 1 - q.Offset; i >= 0 && i >= res.Total-filled; i-- {
|
||||
res.Events = append(res.Events, ring[i%keep])
|
||||
if len(res.Events) >= q.Limit {
|
||||
break
|
||||
}
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// auditRecordMatches applies the non-time and time filters to one record.
|
||||
// line is the raw JSON line, used for the keyword substring search.
|
||||
func auditRecordMatches(rec map[string]any, line string, q auditQueryRequest, from time.Time, hasFrom bool, to time.Time, hasTo bool) bool {
|
||||
if q.Event != "" && !auditEventFilterMatches(q.Event, auditStringField(rec, "event")) {
|
||||
return false
|
||||
}
|
||||
if q.Actor != "" && !strings.EqualFold(auditStringField(rec, "actor"), q.Actor) {
|
||||
return false
|
||||
}
|
||||
if q.IP != "" && auditStringField(rec, "ip") != q.IP {
|
||||
return false
|
||||
}
|
||||
if q.DeviceID != "" && auditStringField(rec, "device_id") != q.DeviceID {
|
||||
return false
|
||||
}
|
||||
if q.WarnOnly && auditStringField(rec, "level") != "warn" {
|
||||
return false
|
||||
}
|
||||
if q.Keyword != "" && !strings.Contains(strings.ToLower(line), strings.ToLower(q.Keyword)) {
|
||||
return false
|
||||
}
|
||||
if hasFrom || hasTo {
|
||||
t, ok := parseAuditTime(auditStringField(rec, "time"))
|
||||
if !ok {
|
||||
return false // cannot prove it is in range
|
||||
}
|
||||
if hasFrom && t.Before(from) {
|
||||
return false
|
||||
}
|
||||
if hasTo && t.After(to) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// auditEventFilterMatches supports three forms so the UI stays simple:
|
||||
//
|
||||
// "web.login.failure" exact
|
||||
// "web.*" prefix (trailing "*")
|
||||
// "web." prefix (trailing ".")
|
||||
func auditEventFilterMatches(filter, event string) bool {
|
||||
switch {
|
||||
case strings.HasSuffix(filter, "*"):
|
||||
return strings.HasPrefix(event, strings.TrimSuffix(filter, "*"))
|
||||
case strings.HasSuffix(filter, "."):
|
||||
return strings.HasPrefix(event, filter)
|
||||
default:
|
||||
return event == filter
|
||||
}
|
||||
}
|
||||
|
||||
func auditStringField(rec map[string]any, key string) string {
|
||||
s, _ := rec[key].(string)
|
||||
return s
|
||||
}
|
||||
|
||||
// parseAuditTime accepts the formats operators and browsers realistically send.
|
||||
// Layouts without an explicit zone are parsed as UTC; the frontend always sends
|
||||
// Date.toISOString(), so the RFC3339 path is what production uses.
|
||||
func parseAuditTime(s string) (time.Time, bool) {
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" {
|
||||
return time.Time{}, false
|
||||
}
|
||||
layouts := []string{
|
||||
time.RFC3339Nano,
|
||||
time.RFC3339,
|
||||
"2006-01-02T15:04:05",
|
||||
"2006-01-02T15:04",
|
||||
"2006-01-02 15:04:05",
|
||||
"2006-01-02",
|
||||
}
|
||||
for _, layout := range layouts {
|
||||
if t, err := time.Parse(layout, s); err == nil {
|
||||
return t, true
|
||||
}
|
||||
}
|
||||
return time.Time{}, false
|
||||
}
|
||||
@@ -2,17 +2,20 @@ package web
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/auditquery"
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/logger"
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/wsauth"
|
||||
)
|
||||
|
||||
// The scanner has its own tests in package auditquery; this file covers the
|
||||
// WebSocket command handler and its reply shape.
|
||||
|
||||
// newAuditTestHubWithoutAuditFile builds a hub whose logger has no dedicated
|
||||
// audit file, mirroring a server started with YAMA_AUDIT_LOG=off.
|
||||
func newAuditTestHubWithoutAuditFile(t *testing.T, dir string) (*wsHub, string) {
|
||||
@@ -43,189 +46,6 @@ func readQueuedJSON(t *testing.T, c *wsClient) map[string]any {
|
||||
}
|
||||
}
|
||||
|
||||
// writeAuditFixture writes JSON-lines audit records (oldest first) and returns
|
||||
// the file path. Times are UTC RFC3339 so the tests are timezone-independent.
|
||||
func writeAuditFixture(t *testing.T, records []map[string]any) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "audit.log")
|
||||
var b strings.Builder
|
||||
for _, rec := range records {
|
||||
line, err := json.Marshal(rec)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal fixture: %v", err)
|
||||
}
|
||||
b.Write(line)
|
||||
b.WriteByte('\n')
|
||||
}
|
||||
if err := os.WriteFile(path, []byte(b.String()), 0o644); err != nil {
|
||||
t.Fatalf("write fixture: %v", err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func auditFixtureRecords() []map[string]any {
|
||||
at := func(hhmm string) string {
|
||||
tm, err := time.Parse("2006-01-02T15:04", "2026-10-18T"+hhmm)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return tm.Format(time.RFC3339)
|
||||
}
|
||||
return []map[string]any{
|
||||
{"level": "info", "time": at("10:00"), "audit": true, "event": "web.login.success", "actor": "admin", "ip": "203.0.113.1"},
|
||||
{"level": "warn", "time": at("10:01"), "audit": true, "event": "web.login.failure", "actor": "alice", "ip": "203.0.113.2", "reason": "invalid_credentials"},
|
||||
{"level": "info", "time": at("10:02"), "audit": true, "event": "remote.screen.start", "actor": "admin", "role": "admin", "ip": "203.0.113.1", "device_id": "dev1"},
|
||||
{"level": "info", "time": at("10:03"), "audit": true, "event": "admin.user.delete", "actor": "admin", "ip": "203.0.113.1", "target": "bob"},
|
||||
}
|
||||
}
|
||||
|
||||
func runAuditQuery(t *testing.T, path string, q auditQueryRequest) auditQueryResult {
|
||||
t.Helper()
|
||||
q.Limit = clampAuditLimit(q.Limit)
|
||||
q.Offset = clampAuditOffset(q.Offset)
|
||||
res, err := queryAuditLog(path, q)
|
||||
if err != nil {
|
||||
t.Fatalf("queryAuditLog: %v", err)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func eventNames(res auditQueryResult) []string {
|
||||
out := make([]string, 0, len(res.Events))
|
||||
for _, e := range res.Events {
|
||||
out = append(out, auditStringField(e, "event"))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestAuditQueryNoFilterNewestFirst(t *testing.T) {
|
||||
path := writeAuditFixture(t, auditFixtureRecords())
|
||||
res := runAuditQuery(t, path, auditQueryRequest{Limit: 100})
|
||||
if res.Total != 4 || len(res.Events) != 4 {
|
||||
t.Fatalf("total=%d events=%d, want 4/4", res.Total, len(res.Events))
|
||||
}
|
||||
got := eventNames(res)
|
||||
want := []string{"admin.user.delete", "remote.screen.start", "web.login.failure", "web.login.success"}
|
||||
if strings.Join(got, ",") != strings.Join(want, ",") {
|
||||
t.Fatalf("events = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuditQueryEventFilters(t *testing.T) {
|
||||
path := writeAuditFixture(t, auditFixtureRecords())
|
||||
cases := []struct {
|
||||
filter string
|
||||
want []string
|
||||
}{
|
||||
{"web.", []string{"web.login.failure", "web.login.success"}},
|
||||
{"web.*", []string{"web.login.failure", "web.login.success"}},
|
||||
{"web.login.failure", []string{"web.login.failure"}},
|
||||
{"remote.*", []string{"remote.screen.start"}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
res := runAuditQuery(t, path, auditQueryRequest{Event: tc.filter, Limit: 100})
|
||||
got := eventNames(res)
|
||||
if strings.Join(got, ",") != strings.Join(tc.want, ",") {
|
||||
t.Errorf("filter %q → %v, want %v", tc.filter, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuditQueryFieldFilters(t *testing.T) {
|
||||
path := writeAuditFixture(t, auditFixtureRecords())
|
||||
from, _ := time.Parse(time.RFC3339, "2026-10-18T10:01:00Z")
|
||||
to, _ := time.Parse(time.RFC3339, "2026-10-18T10:02:00Z")
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
q auditQueryRequest
|
||||
want []string
|
||||
}{
|
||||
{"actor case-insensitive", auditQueryRequest{Actor: "ALICE", Limit: 100}, []string{"web.login.failure"}},
|
||||
{"ip", auditQueryRequest{IP: "203.0.113.2", Limit: 100}, []string{"web.login.failure"}},
|
||||
{"device", auditQueryRequest{DeviceID: "dev1", Limit: 100}, []string{"remote.screen.start"}},
|
||||
{"warn only", auditQueryRequest{WarnOnly: true, Limit: 100}, []string{"web.login.failure"}},
|
||||
{"keyword target", auditQueryRequest{Keyword: "BOB", Limit: 100}, []string{"admin.user.delete"}},
|
||||
{"time range", auditQueryRequest{
|
||||
From: from.Format(time.RFC3339), To: to.Format(time.RFC3339), Limit: 100,
|
||||
}, []string{"remote.screen.start", "web.login.failure"}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
res := runAuditQuery(t, path, tc.q)
|
||||
got := eventNames(res)
|
||||
if strings.Join(got, ",") != strings.Join(tc.want, ",") {
|
||||
t.Errorf("%s → %v, want %v", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuditQueryOffsetAndLimit(t *testing.T) {
|
||||
path := writeAuditFixture(t, auditFixtureRecords())
|
||||
res := runAuditQuery(t, path, auditQueryRequest{Limit: 2, Offset: 1})
|
||||
if res.Total != 4 {
|
||||
t.Fatalf("total = %d, want 4", res.Total)
|
||||
}
|
||||
got := eventNames(res)
|
||||
want := []string{"remote.screen.start", "web.login.failure"}
|
||||
if strings.Join(got, ",") != strings.Join(want, ",") {
|
||||
t.Fatalf("events = %v, want %v", got, want)
|
||||
}
|
||||
|
||||
// Offsetting past the end yields no events but keeps the total.
|
||||
res = runAuditQuery(t, path, auditQueryRequest{Limit: 2, Offset: 4})
|
||||
if res.Total != 4 || len(res.Events) != 0 {
|
||||
t.Fatalf("offset past end: total=%d events=%v", res.Total, eventNames(res))
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuditQuerySkipsNonAuditAndTornLines(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "audit.log")
|
||||
content := `{"event":"device.online","actor":"x"}
|
||||
not json at all
|
||||
{"level":"info","time":"2026-10-18T10:00:00Z","audit":true,"event":"web.login.success","actor":"admin"}`
|
||||
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
res := runAuditQuery(t, path, auditQueryRequest{Limit: 100})
|
||||
if res.Total != 1 || len(res.Events) != 1 {
|
||||
t.Fatalf("total=%d events=%v, want the single valid record", res.Total, eventNames(res))
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuditQueryMissingFile(t *testing.T) {
|
||||
res := runAuditQuery(t, filepath.Join(t.TempDir(), "does-not-exist.log"), auditQueryRequest{Limit: 10})
|
||||
if res.FileExists {
|
||||
t.Error("FileExists = true for a missing file")
|
||||
}
|
||||
if res.Total != 0 || len(res.Events) != 0 {
|
||||
t.Errorf("total=%d events=%v, want empty", res.Total, eventNames(res))
|
||||
}
|
||||
if res.Events == nil {
|
||||
t.Error("Events is nil; JSON would encode null instead of []")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuditQueryClampsPaging(t *testing.T) {
|
||||
if got := clampAuditLimit(0); got != auditQueryDefaultLimit {
|
||||
t.Errorf("limit(0) = %d, want default %d", got, auditQueryDefaultLimit)
|
||||
}
|
||||
if got := clampAuditLimit(-3); got != auditQueryDefaultLimit {
|
||||
t.Errorf("limit(-3) = %d, want default %d", got, auditQueryDefaultLimit)
|
||||
}
|
||||
if got := clampAuditLimit(9999); got != auditQueryMaxLimit {
|
||||
t.Errorf("limit(9999) = %d, want max %d", got, auditQueryMaxLimit)
|
||||
}
|
||||
if got := clampAuditLimit(50); got != 50 {
|
||||
t.Errorf("limit(50) = %d, want 50", got)
|
||||
}
|
||||
if got := clampAuditOffset(-5); got != 0 {
|
||||
t.Errorf("offset(-5) = %d, want 0", got)
|
||||
}
|
||||
if got := clampAuditOffset(1 << 30); got != auditQueryMaxOffset {
|
||||
t.Errorf("offset(huge) = %d, want max %d", got, auditQueryMaxOffset)
|
||||
}
|
||||
}
|
||||
|
||||
func TestQueryAuditHandlerAdminOnly(t *testing.T) {
|
||||
wh, _, _ := auditTestHub(t)
|
||||
viewer, tok := auditTestClient(wh, "viewer")
|
||||
@@ -265,7 +85,7 @@ func TestQueryAuditHandlerReturnsEvents(t *testing.T) {
|
||||
var names []string
|
||||
for _, e := range events {
|
||||
if m, ok := e.(map[string]any); ok {
|
||||
names = append(names, auditStringField(m, "event"))
|
||||
names = append(names, auditquery.StringField(m, "event"))
|
||||
}
|
||||
}
|
||||
joined := strings.Join(names, ",")
|
||||
|
||||
+32
-4
@@ -36,14 +36,23 @@ type Server struct {
|
||||
allowedOrigins []string // for WS Origin allowlist; empty = same-origin only
|
||||
loginIPLimit *wsauth.RateLimiter
|
||||
loginUserLimit *wsauth.RateLimiter
|
||||
trustForwardedFor bool // honor X-Forwarded-For (behind trusted proxy only)
|
||||
basePath string // web UI mount prefix (e.g. "/remoter"); "" = domain root
|
||||
brandName string // white-label title; "" = "SimpleRemoter" (official branding)
|
||||
sso SSODetector // nil = SSO disabled
|
||||
trustForwardedFor bool // honor X-Forwarded-For (behind trusted proxy only)
|
||||
basePath string // web UI mount prefix (e.g. "/remoter"); "" = domain root
|
||||
brandName string // white-label title; "" = "SimpleRemoter" (official branding)
|
||||
sso SSODetector // nil = SSO disabled
|
||||
mcp mcpEndpoint // nil = no /mcp route
|
||||
sweepDone chan struct{} // closes to stop the login-limiter sweeper
|
||||
sweepStopOnce sync.Once
|
||||
}
|
||||
|
||||
// mcpEndpoint is the part of *mcp.Server the web server mounts. Expressed as
|
||||
// an interface so web does not depend on the mcp package (the endpoint owns
|
||||
// its own auth and protocol; web only routes to it).
|
||||
type mcpEndpoint interface {
|
||||
Handle(http.ResponseWriter, *http.Request)
|
||||
Enabled() bool
|
||||
}
|
||||
|
||||
// Config tunes the server's exposed-on-public-HTTPS hardening knobs.
|
||||
// All fields are optional; zero values pick reasonable defaults.
|
||||
type Config struct {
|
||||
@@ -109,6 +118,15 @@ func (s *Server) WithConfig(cfg Config) *Server {
|
||||
return s
|
||||
}
|
||||
|
||||
// WithMCP attaches the MCP endpoint under /mcp (basePath-aware via mount).
|
||||
// When the endpoint reports itself disabled (no bearer token) the route is not
|
||||
// registered and /mcp 404s, matching "no token = feature off". Safe to call
|
||||
// before Start.
|
||||
func (s *Server) WithMCP(m mcpEndpoint) *Server {
|
||||
s.mcp = m
|
||||
return s
|
||||
}
|
||||
|
||||
// Start launches the server in a goroutine and returns immediately.
|
||||
// If port is 0, returns nil without starting anything.
|
||||
func (s *Server) Start() error {
|
||||
@@ -129,6 +147,16 @@ func (s *Server) Start() error {
|
||||
mux.HandleFunc("/api/devices", s.requireBearer(s.handleDevices))
|
||||
mux.HandleFunc("/sso", s.handleSSO)
|
||||
mux.HandleFunc("/ws", s.ws.serve)
|
||||
// MCP is its own protocol with its own static bearer token; it does not go
|
||||
// through requireBearer (that validates browser sessions). Mounted inside
|
||||
// the mux so basePath stripping applies like every other route.
|
||||
if s.mcp != nil {
|
||||
if s.mcp.Enabled() {
|
||||
mux.HandleFunc("/mcp", s.mcp.Handle)
|
||||
} else {
|
||||
s.log.Info("MCP endpoint disabled: YAMA_MCP_TOKEN not set")
|
||||
}
|
||||
}
|
||||
mux.HandleFunc("/static/xterm.js", staticHandler(xtermJS, "application/javascript; charset=utf-8"))
|
||||
mux.HandleFunc("/static/xterm.css", staticHandler(xtermCSS, "text/css; charset=utf-8"))
|
||||
mux.HandleFunc("/static/xterm-fit.js", staticHandler(xtermFitJS, "application/javascript; charset=utf-8"))
|
||||
|
||||
+2
-2
@@ -265,7 +265,7 @@ $auditFiltered = Rpc '' $null 'get_audit_log' @{ type = 'zzz-no-such-type'; limi
|
||||
Check 'get_audit_log 过滤未命中返回 0 条' ($auditFiltered.error -eq $null -and @($auditFiltered.result.structuredContent.entries).Count -eq 0)
|
||||
|
||||
$status = Rpc '' $null 'get_server_status' @{}
|
||||
$st = $status.result.structuredContent.status
|
||||
$st = $status.result.structuredContent
|
||||
Check 'get_server_status 正常返回' ($status.error -eq $null -and $null -ne $st)
|
||||
$basePort = 6544
|
||||
if ($Base -match ':(\d+)(/|$)') { $basePort = [int]$Matches[1] }
|
||||
@@ -806,7 +806,7 @@ if (-not $longCall) {
|
||||
([int]$jr.error.code -eq -32800)) $body
|
||||
|
||||
# 交叉核对:get_server_status 的 sessions.pending 应回到 0,主机能再次正常调用
|
||||
$st2 = (Rpc '' $null 'get_server_status' @{}).result.structuredContent.status
|
||||
$st2 = (Rpc '' $null 'get_server_status' @{}).result.structuredContent
|
||||
Check '取消后 get_server_status 无挂起(sessions.pending=0)' `
|
||||
([int]$st2.sessions.pending -eq 0) ("pending=" + $st2.sessions.pending)
|
||||
if (HasTool 'list_processes') {
|
||||
|
||||
+32
-12
@@ -14,7 +14,8 @@ inputSchema、outputSchema,以及运行时不可见的开关元信息(`gate`
|
||||
| `mcp/tools.json` | 工具清单本体(生成产物,勿手工编辑) |
|
||||
| `tools/mcp_tools/dump_tools.py` | 从运行中的服务端抓 `tools/list` |
|
||||
| `tools/mcp_tools/make_tools_json.py` | 把抓取结果转成 `tools.json`(含 gate / platforms 表) |
|
||||
| `tools/mcp_tools/verify_tools.py` | 校验 `tools.json` 与服务端是否一致 |
|
||||
| `tools/mcp_tools/verify_tools.py` | 校验 `tools.json` 与服务端是否一致(含 Go 端 `--subset`) |
|
||||
| `tools/mcp_tools/gen_go_tools.py` | 从 `tools.json` 抽取 Go 端 9 个工具,生成 `server/go/mcp/tools_minimal.json` |
|
||||
| `tools/mcp_tools/check_platform_table.py` | 校验 `tools.json` 的 `platforms` 与 C++ `kToolPlatforms` 一致 |
|
||||
|
||||
## 更新流程
|
||||
@@ -87,14 +88,17 @@ python tools/mcp_tools/verify_tools.py --live mcp/tools.json
|
||||
| 命令分支 | `client/`、`linux/main.cpp`、`macos/main.mm`、`android/app/src/main/cpp/main.cpp` |
|
||||
| 能力位 | `common/commands.h` 的 `LOGIN_INFOR::DefaultCaps()`;Linux 另在 `linux/main.cpp:RefreshLoginCaps` 追加 `SCREEN_PREVIEW` |
|
||||
|
||||
当前分布(61 个工具):
|
||||
当前分布(54 个工具):
|
||||
|
||||
| platforms | 数量 | 典型工具 |
|
||||
|---|---|---|
|
||||
| `win+lnx+mac+apk` | 10 | 只读写服务端本地数据:`list_online_hosts` / `get_audit_log` / `mcp_*` |
|
||||
| `win+lnx+mac` | 6 | 进程列表、文件列取、日志、V2 文件传输、`copy_files_c2c` |
|
||||
| `win+lnx` | 12 | `remote_*` 全族、`get_screenshot`、`get_activity_history`、`exec_command` / `terminal_*` / `kill_process` |
|
||||
| `win` | 33 | 服务 / 注册表 / 键日志 / 文件写 / **`list_windows`** / `get_foreground_window` / `host_*` / `chat_*` / `power_action` |
|
||||
| `win+lnx+mac+apk` | 9 | 只读写服务端本地数据:`list_hosts` / `get_host_detail` / `get_client_log` / `get_audit_log` / `get_server_status` / `mcp_*` / `host_set_remark` / `host_set_watch_level` |
|
||||
| `win+lnx+apk` | 11 | `remote_*` 全族、`exec_command` / `terminal_*`、`get_screenshot`、`get_activity_history` |
|
||||
| `win+lnx+mac` | 6 | 进程列表、文件列取 / V2 文件传输(含 `read_file`)、`copy_files_c2c` |
|
||||
| `win+lnx` | 2 | `http_probe`、`kill_process` |
|
||||
| `win+apk` | 6 | `remote_block_input`、`uninstall_host`、`chat_*` 全族 |
|
||||
| `win` | 19 | 服务 / 注册表 / 键日志 / 文件搜索与写入 / **`list_windows`** / `get_foreground_window` / `host_inspect` / `host_control_*` / `operate_window` / 网络连接 / `power_action` |
|
||||
| `apk` | 1 | `remote_lock_screen` |
|
||||
|
||||
**注意 `exec_command` / `terminal_*` / `kill_process` 不在 `win+lnx+mac` 组**:
|
||||
macOS 客户端其实有对应实现(`macos/main.mm:753` 的 `ShellworkingThread` 跑 PTY,
|
||||
@@ -106,8 +110,9 @@ macOS 客户端其实有对应实现(`macos/main.mm:753` 的 `ShellworkingThre
|
||||
`SystemManager.h:38` 和 macOS 的 `SystemManager.mm:39` 都有 `COMMAND_WSLIST`
|
||||
的 `case` 分支,看起来是支持的。但 `BuildListWindows` 把命令发在**主连接**上
|
||||
(`McpServer.cpp:2931`),而这两个平台的主循环只处理 `COMMAND_SYSTEM`
|
||||
(起 SystemManager 子连接),`WSLIST` 在子连接里才被处理——走不到。实测 Linux
|
||||
上直接超时 `-32001`。那两个 `case` 是给 SystemDlg 窗口管理用的,不是 MCP 这条路径。
|
||||
(起 SystemManager 子连接),`WSLIST` 在子连接里才被处理——走不到。关掉平台门禁
|
||||
(`McpPlatformGuard=0`)时实测 Linux 上直接超时 `-32001`;默认门禁开启时,这张表
|
||||
会先拦下并返回 `-32005`。那两个 `case` 是给 SystemDlg 窗口管理用的,不是 MCP 这条路径。
|
||||
Windows 是在主循环里处理的(`client/KernelManager.cpp:1491`),所以正常。
|
||||
|
||||
### 平台优先级(产品定位)
|
||||
@@ -191,11 +196,26 @@ python tools/mcp_tools/check_platform_table.py
|
||||
|
||||
## 与 Go 服务端的关系
|
||||
|
||||
`impl` 字段就是给 Go 端裁剪用的:标 `mfc` 的工具表示 Go 端还没有对应能力。
|
||||
Go 端补齐某个工具的底层命令后,把它改成 `both`。
|
||||
Go 最小服务端(`server/go`,设计见 `docs/Mcp_Go_Minimal_Design.md`)实现 9 个工具。
|
||||
它的 `tools/list` **不是手写的**:`gen_go_tools.py` 从 `tools.json` 原样抽取这 9 个工具
|
||||
生成 `server/go/mcp/tools_minimal.json`,再由 `//go:embed` 编进二进制。
|
||||
|
||||
注意 Go 端目前只有 5 类客户端命令(`SCREEN_SPY` / `NEXT` / `SCREEN_CONTROL` /
|
||||
`BYE` / `SHELL`),所以短期内 `impl: both` 的工具不会多。
|
||||
改完 `tools.json` 之后:
|
||||
|
||||
```bash
|
||||
# 重新生成嵌入副本(--check 只检查是否为最新,CI 友好)
|
||||
python tools/mcp_tools/gen_go_tools.py
|
||||
python tools/mcp_tools/gen_go_tools.py --check
|
||||
|
||||
# 抓 Go 端线上 tools/list,与 tools.json 逐字段比对
|
||||
# 读写模式恰好 9 个;YAMA_MCP_READONLY=1 时恰好 7 个(隐藏 terminal_*)
|
||||
python tools/mcp_tools/verify_tools.py --subset mcp/tools.json <token> <port>
|
||||
python tools/mcp_tools/verify_tools.py --subset mcp/tools.json <token> <port> --readonly
|
||||
```
|
||||
|
||||
`--subset` 与 `--live` 的差别:前者**名字集合必须恰好等于** 9(或 7),多一个少一个
|
||||
都失败;后者只报双方差异。`impl` 字段的 `mfc` / `go` / `both` 目前仍是人工维护的
|
||||
元信息,脚本不据此推断。
|
||||
|
||||
## 前置条件
|
||||
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate server/go/mcp/tools_minimal.json from mcp/tools.json.
|
||||
|
||||
The Go server embeds its tools/list payload, so the nine tools it exposes must
|
||||
be a byte-for-byte copy of the canonical schemas. This script extracts them
|
||||
without hand-editing, preserving tools.json order, and keeps only the four
|
||||
fields MCP publishes: name / description / inputSchema / outputSchema.
|
||||
|
||||
Usage:
|
||||
python tools/mcp_tools/gen_go_tools.py # rewrite the embedded file
|
||||
python tools/mcp_tools/gen_go_tools.py --check # exit 1 if it is stale
|
||||
|
||||
Run from anywhere; paths are resolved relative to this file.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# The nine tools of the Go minimal server (design §3.1). Order in the embedded
|
||||
# file follows mcp/tools.json, not this list.
|
||||
MINIMAL_TOOLS = (
|
||||
"list_hosts",
|
||||
"get_host_detail",
|
||||
"get_screenshot",
|
||||
"list_files",
|
||||
"get_audit_log",
|
||||
"get_server_status",
|
||||
"terminal_exec",
|
||||
"terminal_close",
|
||||
"read_file",
|
||||
)
|
||||
|
||||
OUTPUT_FIELDS = ("name", "description", "inputSchema", "outputSchema")
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
TOOLS_JSON = REPO_ROOT / "mcp" / "tools.json"
|
||||
OUTPUT_JSON = REPO_ROOT / "server" / "go" / "mcp" / "tools_minimal.json"
|
||||
|
||||
|
||||
def render() -> str:
|
||||
with TOOLS_JSON.open(encoding="utf-8") as f:
|
||||
doc = json.load(f)
|
||||
tools = doc["tools"] if isinstance(doc, dict) else doc
|
||||
|
||||
by_name = {}
|
||||
for tool in tools:
|
||||
name = tool.get("name")
|
||||
if name in by_name:
|
||||
raise SystemExit(f"duplicate tool name in {TOOLS_JSON}: {name}")
|
||||
by_name[name] = tool
|
||||
|
||||
missing = [n for n in MINIMAL_TOOLS if n not in by_name]
|
||||
if missing:
|
||||
raise SystemExit(f"tools missing from {TOOLS_JSON}: {', '.join(missing)}")
|
||||
|
||||
minimal = []
|
||||
for tool in tools:
|
||||
if tool["name"] not in MINIMAL_TOOLS:
|
||||
continue
|
||||
minimal.append({field: tool[field] for field in OUTPUT_FIELDS})
|
||||
if len(minimal) != len(MINIMAL_TOOLS):
|
||||
raise SystemExit(
|
||||
f"expected {len(MINIMAL_TOOLS)} tools, got {len(minimal)}"
|
||||
)
|
||||
return json.dumps(minimal, ensure_ascii=False, indent=2) + "\n"
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument(
|
||||
"--check",
|
||||
action="store_true",
|
||||
help="do not write; exit 1 when tools_minimal.json is out of date",
|
||||
)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
want = render()
|
||||
if args.check:
|
||||
try:
|
||||
current = OUTPUT_JSON.read_text(encoding="utf-8")
|
||||
except FileNotFoundError:
|
||||
print(f"FAIL {OUTPUT_JSON} is missing", file=sys.stderr)
|
||||
return 1
|
||||
if current != want:
|
||||
print(
|
||||
f"FAIL {OUTPUT_JSON} is stale; run gen_go_tools.py",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 1
|
||||
print(f"PASS {OUTPUT_JSON} matches mcp/tools.json")
|
||||
return 0
|
||||
|
||||
OUTPUT_JSON.parent.mkdir(parents=True, exist_ok=True)
|
||||
OUTPUT_JSON.write_text(want, encoding="utf-8", newline="\n")
|
||||
print(f"wrote {OUTPUT_JSON} ({len(MINIMAL_TOOLS)} tools)")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
@@ -118,9 +118,10 @@ GATE = {
|
||||
|
||||
# platforms: 该工具涉及的任一主机都必须落在此集合内。
|
||||
#
|
||||
# 判定依据是**服务端实际放行**,不是客户端有没有实现。两者在 macOS 上会分叉:
|
||||
# exec_command / terminal_* / kill_process 的客户端实现是有的,但服务端刻意拦着
|
||||
# (McpServer.cpp:3652「macOS 本轮不开放」、6870),所以标 win/lnx(终端族另有 apk)。
|
||||
# 判定依据是**服务端实际放行**,不是客户端有没有实现。两者可能在 macOS 上分叉,
|
||||
# 2026-11-14 起不再分叉:exec_command / terminal_* / kill_process 的 macOS 实现接上了
|
||||
# 能力位(CLIENT_CAP_TERMINAL / CLIENT_CAP_PROCESS),服务端按能力位放行——老构建收到
|
||||
# 这些工具仍返回 -32005,但那是「客户端太旧」而不是平台被拦,故平台表标 mac。
|
||||
# Android 同理:COMMAND_SHELL 只有声明 CLIENT_CAP_TERMINAL 的新版 APK 才处理,
|
||||
# 老 APK 由工具内部按能力位返回 -32005。
|
||||
#
|
||||
@@ -128,12 +129,13 @@ GATE = {
|
||||
# 全平台 —— 只读写服务端本地数据,与客户端平台无关
|
||||
# win/lnx/mac —— client/、linux/、macos/ 都有该命令的处理分支,且服务端不拦
|
||||
# win/lnx —— 远程控制只实现于 Windows/Linux(McpServer.cpp:2728);
|
||||
# 以及 macOS 客户端有实现但服务端未开放的 kill_process
|
||||
# 仅 win —— 服务/注册表/键日志/活动历史/文件写/host_* /power_action
|
||||
# 以及 http_probe(macOS 终端可用,但探测命令用了 GNU 专有的 base64 -w)
|
||||
# 仅 win —— 服务/注册表/键日志/文件写/host_* /power_action
|
||||
# (power_action 实际走 TOKEN_MACHINE_MANAGE,不是通用电源命令)
|
||||
#
|
||||
# 支持面是产品定位的阶梯:win 100% > lnx 46% > mac 28% ≈ apk 16%。
|
||||
# Windows 是唯一全量支持的平台,check_platform_table.py 会把这条做成不变式。
|
||||
# 支持面是产品定位的阶梯:win 100% > lnx 46% > apk 16%(mac 2026-11-14 起进入补全阶段,
|
||||
# 已覆盖终端、进程、截屏、活动历史、文件传输)。Windows 是唯一全量支持的平台,
|
||||
# check_platform_table.py 会把这条做成不变式。
|
||||
#
|
||||
# apk 现状:COMMAND_SYSTEM 与 COMMAND_SHELL 在 android/.../main.cpp 明确标注 not
|
||||
# implemented,故除服务端本地类之外,只有少量按需补过分支的能力:运行日志
|
||||
@@ -170,19 +172,22 @@ PLATFORMS = {
|
||||
# 实测 Linux 直接超时 -32001。别被 SystemManager 里的 case 骗到,那是 SystemDlg 用的。
|
||||
"list_windows": _WIN,
|
||||
|
||||
# macOS 客户端有 PTY 实现(macos/main.mm:753 起 ShellworkingThread),但服务端
|
||||
# 本轮刻意不开放(McpServer.cpp:3652 注释「macOS 本轮不开放」),故实际不可用。
|
||||
# Android 新版复用 common/PTYHandler.h,声明 CLIENT_CAP_TERMINAL 后服务端才放行。
|
||||
"terminal_open": _WLA,
|
||||
"terminal_exec": _WLA,
|
||||
"terminal_close": _WLA,
|
||||
"exec_command": _WLA,
|
||||
# macOS 客户端一直是完整 PTY(macos/main.mm 的 ShellworkingThread),2026-11-14 起
|
||||
# 声明 CLIENT_CAP_TERMINAL,服务端按能力位放行(老构建仍返回 -32005)。
|
||||
# Android 新版复用 common/PTYHandler.h,同样声明 CLIENT_CAP_TERMINAL 后服务端才放行。
|
||||
"terminal_open": _APK,
|
||||
"terminal_exec": _APK,
|
||||
"terminal_close": _APK,
|
||||
"exec_command": _APK,
|
||||
|
||||
# http_probe 走终端通道:macOS 终端未开放;Android 的 toybox 不保证有 curl/base64
|
||||
# http_probe 走终端通道:macOS 终端已开放,但 POSIX 探测命令用了 GNU 专有的
|
||||
# `base64 -w`(BSD base64 没有该开关),换成两平台通用写法前仍只标 win/lnx;
|
||||
# Android 的 toybox 不保证有 curl/base64
|
||||
"http_probe": _WL,
|
||||
|
||||
# macOS 客户端有 COMMAND_KILLPROCESS 分支,但服务端同样拦着(McpServer.cpp:6870)
|
||||
"kill_process": _WL,
|
||||
# macOS 客户端有 COMMAND_KILLPROCESS(SystemManager,SIGKILL),2026-11-14 起
|
||||
# 声明 CLIENT_CAP_PROCESS 后服务端放行;老构建按能力位提前拒绝。
|
||||
"kill_process": _TRIO,
|
||||
|
||||
# 需要 CLIENT_CAP_V2;三个桌面平台的 DefaultCaps() 都含 V2
|
||||
"download_file": _TRIO,
|
||||
@@ -200,15 +205,16 @@ PLATFORMS = {
|
||||
"remote_lock_screen": _APKONLY,
|
||||
|
||||
# 需要 CLIENT_CAP_SCREEN_PREVIEW:Windows 恒有,Linux 仅在探测到 X11 桌面时声明,
|
||||
# macOS 仅在登录时已授予录屏权限时声明(CGDisplayCreateImage → BGRX),
|
||||
# Android 仅在无障碍服务在跑时声明(takeScreenshot,只支持 mode=screen)
|
||||
"get_screenshot": _WLA,
|
||||
"get_screenshot": _APK,
|
||||
|
||||
# ---- 仅 Windows ----
|
||||
"list_services": _WIN,
|
||||
"control_service": _WIN,
|
||||
"list_registry": _WIN,
|
||||
"get_keylog": _WIN,
|
||||
"get_activity_history": _WLA, # Windows 前台窗口;Linux 桌面/无桌面均有实现(linux/main.cpp);APK 复用同一采样机
|
||||
"get_activity_history": _APK, # Windows 前台窗口;Linux 桌面/无桌面均有实现(linux/main.cpp);macOS 用 CGWindowList 采前台窗口(macos/ActivityHistory.mm);APK 复用同一采样机
|
||||
"get_foreground_window": _WIN, # 窗口信息 RPC:CLIENT_CAP_WINDOW_INFO,仅 Windows 客户端声明
|
||||
"search_file": _WIN,
|
||||
"delete_path": _WIN,
|
||||
|
||||
+123
-18
@@ -1,6 +1,6 @@
|
||||
"""校验 tools.json 与 MCP 服务端的 tools/list 是否一致。
|
||||
|
||||
两种模式:
|
||||
三种模式:
|
||||
python verify_tools.py --offline mcp/tools.json tools_raw.json
|
||||
对比 tools.json 与已保存的黄金样本(不联网)
|
||||
|
||||
@@ -9,6 +9,12 @@
|
||||
token 省略时依次取环境变量 YAMA_MCP_TOKEN、注册表 McpToken;
|
||||
port 省略时自动探测 6545(明文后端)/ 6544(TLS 前端)
|
||||
|
||||
python verify_tools.py --subset mcp/tools.json [token] [port] [--readonly]
|
||||
校验 Go 服务端(server/go)的 MCP 端点:名字集合必须恰好是它实现的那
|
||||
9 个工具(只读模式 7 个),且 description / inputSchema / outputSchema
|
||||
与 tools.json 里的同名工具逐字段一致。Go 端把 tools_minimal.json 内嵌
|
||||
进二进制,这一模式检查的就是线上真正发布的字节。
|
||||
|
||||
比对内容:name / description / inputSchema / outputSchema,逐字段深度比较,
|
||||
外加工具顺序。gate / write / manage / impl 是 tools.json 独有的元信息,不参与比对;
|
||||
例外是 gate == "!machine" 的降级工具——它们只在 McpMachine=0 时出现,不进本次比对。
|
||||
@@ -19,6 +25,24 @@ import os
|
||||
import ssl
|
||||
import sys
|
||||
|
||||
# Go 最小服务端实现的 9 个工具(docs/Mcp_Go_Minimal_Design.md §3.1)。
|
||||
# tools/list 恰好是这些,多一个少一个都算失败。
|
||||
GO_MINIMAL_TOOLS = (
|
||||
"list_hosts",
|
||||
"get_host_detail",
|
||||
"get_screenshot",
|
||||
"list_files",
|
||||
"get_audit_log",
|
||||
"get_server_status",
|
||||
"terminal_exec",
|
||||
"terminal_close",
|
||||
"read_file",
|
||||
)
|
||||
# YAMA_MCP_READONLY=1 时 Go 端隐藏的写工具(terminal_* 会创建/关闭会话)。
|
||||
GO_READONLY_HIDDEN = ("terminal_exec", "terminal_close")
|
||||
|
||||
FIELDS = ("description", "inputSchema", "outputSchema")
|
||||
|
||||
|
||||
def normalize(obj):
|
||||
"""规范化:键排序后序列化,消除 JSON object 的键序差异。"""
|
||||
@@ -91,11 +115,107 @@ def fetch_live(token, port=None):
|
||||
sys.exit(f"连接失败 -> {last}")
|
||||
|
||||
|
||||
def report_field_diffs(live_by_name, golden_by_name, names):
|
||||
"""逐字段比较同名工具,返回差异处数;一个工具最多报一处。"""
|
||||
diffs = 0
|
||||
for name in names:
|
||||
a, b = live_by_name[name], golden_by_name[name]
|
||||
for f in FIELDS:
|
||||
va, vb = normalize(a.get(f)), normalize(b.get(f))
|
||||
if va != vb:
|
||||
diffs += 1
|
||||
print(f"!! {name}.{f} 不一致")
|
||||
for i, (ca, cb) in enumerate(zip(va, vb)):
|
||||
if ca != cb:
|
||||
print(f" @{i}")
|
||||
print(f" 服务端: ...{va[max(0,i-60):i+80]}...")
|
||||
print(f" json : ...{vb[max(0,i-60):i+80]}...")
|
||||
break
|
||||
else:
|
||||
print(f" 长度不同: {len(va)} vs {len(vb)}")
|
||||
break
|
||||
return diffs
|
||||
|
||||
|
||||
def verify_subset(path, token, port, readonly):
|
||||
"""Go 最小服务端:名字集合恰好是 GO_MINIMAL_TOOLS,schema 与 tools.json 一致。"""
|
||||
expected = [n for n in GO_MINIMAL_TOOLS
|
||||
if not (readonly and n in GO_READONLY_HIDDEN)]
|
||||
tools_live, live_stats = fetch_live(token, port)
|
||||
print(f"tools.json: {path}")
|
||||
print(f"模式: {'只读(隐藏 ' + ' / '.join(GO_READONLY_HIDDEN) + ')' if readonly else '读写'}")
|
||||
print(f"期望: {len(expected)} 个工具 / 服务端: {len(tools_live)} 个")
|
||||
|
||||
live_names = [t["name"] for t in tools_live]
|
||||
expected_set, live_set = set(expected), set(live_names)
|
||||
diffs = 0
|
||||
extra = sorted(live_set - expected_set)
|
||||
missing = [n for n in expected if n not in live_set]
|
||||
if extra:
|
||||
diffs += len(extra)
|
||||
print(f"!! 服务端多出: {extra}")
|
||||
if missing:
|
||||
diffs += len(missing)
|
||||
print(f"!! 服务端缺少: {missing}")
|
||||
dupes = sorted({n for n in live_names if live_names.count(n) > 1})
|
||||
if dupes:
|
||||
diffs += len(dupes)
|
||||
print(f"!! 服务端重复: {dupes}")
|
||||
|
||||
# 顺序一致性:tools/list 的数组顺序会影响模型的选择倾向
|
||||
if not extra and not missing and not dupes:
|
||||
order = [n for n in live_names if n in expected_set]
|
||||
if order != expected:
|
||||
diffs += 1
|
||||
print("!! 工具顺序与 tools.json 不一致")
|
||||
for i, (x, y) in enumerate(zip(order, expected)):
|
||||
if x != y:
|
||||
print(f" 首个差异 @{i}: 服务端={x} 期望={y}")
|
||||
break
|
||||
else:
|
||||
print("工具顺序: 一致")
|
||||
|
||||
doc = json.load(open(path, encoding="utf-8"))
|
||||
tools_json = doc["tools"] if isinstance(doc, dict) else doc
|
||||
golden_by_name = {t["name"]: t for t in tools_json}
|
||||
live_by_name = {t["name"]: t for t in tools_live}
|
||||
|
||||
comparable = []
|
||||
for name in expected:
|
||||
if name not in golden_by_name:
|
||||
diffs += 1
|
||||
print(f"!! tools.json 缺少工具 {name}")
|
||||
elif name in live_by_name:
|
||||
comparable.append(name)
|
||||
diffs += report_field_diffs(live_by_name, golden_by_name, comparable)
|
||||
|
||||
print(f" 体积: 响应 {live_stats['response_bytes']} B / tools 数组 "
|
||||
f"{live_stats['tools_array_bytes']} B")
|
||||
if diffs == 0:
|
||||
print(f"\nPASS: Go 服务端 {len(expected)} 个工具与 tools.json 完全一致")
|
||||
return 0
|
||||
print(f"\nFAIL: {diffs} 处差异")
|
||||
return 1
|
||||
|
||||
|
||||
def main():
|
||||
args = sys.argv[1:]
|
||||
if not args:
|
||||
sys.exit(__doc__)
|
||||
|
||||
if args[0] == "--subset":
|
||||
argv = [a for a in args[1:]]
|
||||
readonly = "--readonly" in argv
|
||||
argv = [a for a in argv if a != "--readonly"]
|
||||
if not argv:
|
||||
sys.exit("用法: python verify_tools.py --subset <tools.json> [token] [port] [--readonly]")
|
||||
path = argv[0]
|
||||
token = resolve_token(argv[1] if len(argv) > 1 else "")
|
||||
port = int(argv[2]) if len(argv) > 2 else None
|
||||
if not token:
|
||||
sys.exit("未找到 McpToken(参数 / YAMA_MCP_TOKEN / 注册表 均无)")
|
||||
return verify_subset(path, token, port, readonly)
|
||||
|
||||
if args[0] == "--offline":
|
||||
if len(args) < 3:
|
||||
sys.exit("用法: python verify_tools.py --offline <tools.json> <黄金样本.json>")
|
||||
@@ -142,24 +262,9 @@ def main():
|
||||
if only_json:
|
||||
print(f"!! 仅 json 有: {only_json}")
|
||||
|
||||
FIELDS = ("description", "inputSchema", "outputSchema")
|
||||
diffs = 0
|
||||
for name in sorted(set(live_by_name) & set(json_by_name)):
|
||||
a, b = live_by_name[name], json_by_name[name]
|
||||
for f in FIELDS:
|
||||
va, vb = normalize(a.get(f)), normalize(b.get(f))
|
||||
if va != vb:
|
||||
diffs += 1
|
||||
print(f"!! {name}.{f} 不一致")
|
||||
for i, (ca, cb) in enumerate(zip(va, vb)):
|
||||
if ca != cb:
|
||||
print(f" @{i}")
|
||||
print(f" 服务端: ...{va[max(0,i-60):i+80]}...")
|
||||
print(f" json : ...{vb[max(0,i-60):i+80]}...")
|
||||
break
|
||||
else:
|
||||
print(f" 长度不同: {len(va)} vs {len(vb)}")
|
||||
break # 一个工具报一次即可
|
||||
FIELDS_SHARED = sorted(set(live_by_name) & set(json_by_name))
|
||||
diffs += report_field_diffs(live_by_name, json_by_name, FIELDS_SHARED)
|
||||
|
||||
# 顺序一致性:tools/list 的数组顺序会影响模型的选择倾向
|
||||
order_live = [t["name"] for t in tools_live]
|
||||
|
||||
Reference in new issue
Block a user