Compare commits
5
Commits
b743de6747
...
v1.4.3
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
db4543ad54 | ||
|
|
06b93f7bdb | ||
|
|
c2b59f5d4a | ||
|
|
4456467c50 | ||
|
|
a25e89b220 |
No files matched your search
@@ -32,6 +32,8 @@
|
||||
> 本软件**仅供教育目的及授权使用场景**:组织内远程 IT 管理、经授权的渗透测试与安全研究、个人设备管理与技术学习。
|
||||
>
|
||||
> **未经授权访问计算机系统属违法行为。** 使用者须对遵守所有适用法律承担全部责任。开发者对任何滥用行为概不负责。
|
||||
>
|
||||
> **二次开发红线:** 如使用大模型协助对本项目进行二次开发,不得破解本项目,也不得替换本项目的私有库以达到绕过授权的目的。一经发现,授权服务器将对其**永久拉黑**。
|
||||
|
||||
---
|
||||
|
||||
@@ -378,6 +380,38 @@ nohup ./server_linux_amd64 --port 6543 --http-port 9001 > yama.log 2>&1 &
|
||||
|
||||
## 更新日志
|
||||
|
||||
### v1.4.3 (2026.11.14)
|
||||
|
||||
**MCP 工具面收敛 & Go 极简 MCP & Android / macOS 能力补齐 & TLS 开箱即用**
|
||||
|
||||
**新功能:**
|
||||
- **MCP 工具收敛 60 → 54**:`host_list_*` 十个只读工具合并为 `host_inspect(aspects[])`、三个主机列表合并为 `list_hosts`、窗口与服务控制各只留一个名字;加上本次新增的 5 个工具,清单最终为 54 项(全部开关打开时 `tools/list` 列出 49 项),响应体从 193 KB 降到 169 KB(-12.6%)。旧名保留为可调用别名;`McpMachine` 开启时降级的 `list_processes` / `list_windows` / `list_services` 不再列出
|
||||
- **MCP 新工具**:`http_probe`(仅私网 IP 的 HTTP 检查,不跟随重定向、正文 64 KB、校验证书)、`read_file`(按行读远端文本,BOM / UTF-8 / GBK 自动识别,负 offset 从尾部读,回整文件 SHA-256)、`get_foreground_window` 与窗口信息 RPC(179/180,`expect_hwnd` / `require_foreground`)、`uninstall_host`、`remote_lock_screen`
|
||||
- **MCP 原生捕获**:`get_screenshot` 支持区域 / 窗口 / 单显示器 1:1 捕获(`CLIENT_CAP_SCREEN_REGION`,返回源矩形与缩放),`remote_open` 可只推目标窗口或区域,`remote_mouse` 支持窗口相对坐标
|
||||
- **Go 极简 MCP**:无状态 `POST /mcp` + Bearer 鉴权,9 个工具(只读 7 个),每设备锁与全局并发闸门、每次调用写审计;终端 256 KiB 环形缓冲,`list_files` / `read_file` 走文件管理子连接,`get_screenshot` 走主连接预览 RPC
|
||||
- **Android 客户端补齐**:屏幕预览(API 30+ 无障碍抓屏)、活动历史、运行日志上报、TLS 热切换(OpenSSL 3.5.0 静态链接)、主控推送 APK 升级、远程交谈 / 终端 / 剪贴板 / 锁屏 / 隐私遮罩 / 卸载、语音监听,并让远控调优命令真正生效(此前硬编码 Good 使自适应质量永远无法启动)
|
||||
- **macOS 客户端阶段 0 / 1**:TLS 传输、运行日志上报、授权后自动重启、终端与进程管理能力位、屏幕预览、活动历史、关键帧请求
|
||||
- **TLS 开箱即用**:未配置证书时首次需要即自签(RSA-2048,十年),可在对话框导出 PEM,也可内嵌进生成的客户端与下发的 DLL,首连即 TLS
|
||||
- **Linux 客户端**:分享到另一主控(fork 子实例)、转移到另一主控(到期自动恢复)、活动历史(有桌面走 X11,无桌面汇总登录与 shell 历史)、记住全屏与远端光标
|
||||
- **Windows 远控**:多显示器改抓整个虚拟桌面、采集监视器索引跨重启稳定、自适应质量新增吞吐判据与防振荡、调优开关改为按客户端保存、注入按键在断连 / 切后台时释放
|
||||
- **主控与 Web**:高级菜单「运行测试程序」(载荷在主控进程内加载,带防误伤标记)、文件管理器传输历史落盘、特性限制与真实菜单对齐(57/19/46 项)、Web 控制台设备列表分组过滤、状态栏 TLS / MCP 状态
|
||||
|
||||
**改进:**
|
||||
- MCP 契约与实现对齐:条件必填改 `allOf` / `if` / `then`,`outputSchema` 与实际返回一致,说明文本逐条对过代码
|
||||
- 只交文本块的 MCP 客户端也能看到主机 ID 与列表行;`list_files` 改为列全目录再分页,路径统一 GBK
|
||||
- 终端会话语义:可隐式开会话、超时保留并轮询、`terminal_close` 显式回收、忙时提示占用者、取消可按 id / session_id 定位
|
||||
- 危险操作确认框列出目标主机且默认「否」;「高速 / 极速」更名为「高画质 / 流畅」;Ctrl+F 改为即输即筛
|
||||
- 中文进程名显示、配置读取创建空注册表子键、试用口令覆盖等一批细节修正
|
||||
|
||||
**Bug 修复:**
|
||||
- 两个能让远程对端打死服务端的路径:httplib `Content-Length: -1` 无鉴权死循环 DoS、畸形 JPEG 触发 libjpeg `exit()`
|
||||
- 远控音频偶发永久静音(环形缓冲跨线程无锁、格式包丢失、Modern Standby 恢复、端点变更)
|
||||
- 质量切换跳到另一台显示器、从 RGB565 / DIFF 切回 H.264 冻结最长 10 秒;慢帧下自适应质量永远弃权
|
||||
- Web 远端画面在分辨率 / 质量变化后黑屏;Web 终端心跳重连后按键全部丢失
|
||||
- 远程桌面窗口缩放后不重绘;浮动工具栏质量菜单一打开就收回;注入按键卡住修饰键
|
||||
- macOS 子连接线程泄漏(六周后达 2048 线程);HELL 头编码固定导致约三分之一 Release 客户端登不上 Go fallback
|
||||
- 特性限制在 32 位主控上丢失 bit 32 以上的 40 项;运行时长跨时区恒显示 0;登录保留区越界
|
||||
|
||||
### v1.4.2 (2026.10.31)
|
||||
|
||||
**MCP 运维套件 & WebSocket 传输 & 抓屏健壮性**
|
||||
|
||||
@@ -32,6 +32,8 @@
|
||||
> This software is intended **solely for educational purposes and authorized use cases**: remote IT administration within your own organization, authorized penetration testing and security research, personal device management, and technical learning.
|
||||
>
|
||||
> **Unauthorized access to computer systems is illegal.** Users are fully responsible for compliance with all applicable laws. The developers assume no liability for misuse.
|
||||
>
|
||||
> **Secondary development:** if you use a large language model to assist with secondary development of this project, you must not crack the software or replace this project's private libraries to bypass authorization. Violations are detected and the authorization server **permanently blacklists** the offender.
|
||||
|
||||
---
|
||||
|
||||
@@ -378,6 +380,38 @@ Valid : 2026-02-01 to 2028-02-01
|
||||
|
||||
## Changelog
|
||||
|
||||
### v1.4.3 (2026.11.14)
|
||||
|
||||
**MCP tool consolidation & Go minimal MCP & Android / macOS parity & TLS out of the box**
|
||||
|
||||
**New features:**
|
||||
- **MCP tools 60 to 54**: the ten read-only `host_list_*` tools merged into `host_inspect(aspects[])`, the three host lists into `list_hosts`, and each window / service pair behind one name; together with the five tools added in this release the manifest settles at 54 entries (49 in `tools/list` with every switch on) and the response shrinks from 193 KB to 169 KB (-12.6%). The old names remain callable aliases, and the degraded `list_processes` / `list_windows` / `list_services` are no longer listed while `McpMachine` is on
|
||||
- **New MCP tools**: `http_probe` (private-network HTTP checks only, no redirects, 64 KB body cap, certificate verification), `read_file` (line-based remote text reads with BOM / UTF-8 / GBK detection, negative offset from the end, whole-file SHA-256), `get_foreground_window` plus a window-info RPC (179/180, `expect_hwnd` / `require_foreground`), `uninstall_host`, `remote_lock_screen`
|
||||
- **Native capture**: `get_screenshot` captures a region, a window or a single monitor at 1:1 (`CLIENT_CAP_SCREEN_REGION`, returning the source rect and scale); `remote_open` can stream only the target window or region; `remote_mouse` accepts window-relative coordinates
|
||||
- **Go minimal MCP**: a stateless `POST /mcp` with bearer auth, nine tools (seven read-only), per-device locks, a global concurrency gate and one audit record per call; 256 KiB terminal ring, `list_files` / `read_file` over the file-manager sub-connection, `get_screenshot` over the main-connection preview RPC
|
||||
- **Android client**: screen preview (accessibility capture on API 30+), activity history, runtime log reporting, TLS hot-switching (OpenSSL 3.5.0 statically linked), master-pushed APK updates, remote chat / terminal / clipboard / lock screen / privacy overlay / uninstall, voice monitoring, and remote-desktop tuning commands that actually take effect (a hardcoded "Good" had stopped adaptive quality from ever starting)
|
||||
- **macOS client, phases 0 and 1**: TLS transport, runtime log reporting, automatic restart once permissions are granted, terminal and process-management capability bits, screen preview, activity history, keyframe requests
|
||||
- **TLS out of the box**: with no certificate configured the server self-signs one (RSA-2048, ten years) the first time it is needed, can export it as PEM, and can embed it in generated clients and delivered DLLs so the first connection is already TLS
|
||||
- **Linux client**: share to another master (forked child instances), transfer to another master (restored on expiry), activity history (X11 sampling with a headless login/shell-history fallback), remembered fullscreen and remote-cursor state
|
||||
- **Windows remote desktop**: multi-monitor capture of the whole virtual desktop, a capture monitor index that survives restarts, a throughput criterion and anti-oscillation for adaptive quality, tuning flags saved per client, injected keys released on blur and disconnect
|
||||
- **Master and web console**: "Run test program" in the Advanced menu (the in-memory client payload loaded inside the master process, guarded by a magic), file-manager transfer history persisted, feature limits aligned with the real menus (57/19/46 items), a group filter in the web device list, TLS and MCP panes in the status bar
|
||||
|
||||
**Improvements:**
|
||||
- MCP contracts now match the handlers: conditional required arguments use `allOf` / `if` / `then`, `outputSchema` matches the returned shape, and the instructions were checked line by line against the code
|
||||
- Text-only MCP clients now see host ids and listing rows; `list_files` lists the whole directory before paging and paths are GBK in both directions
|
||||
- Terminal semantics: a session can be opened or reused implicitly, a timed-out command keeps its session and can be polled, `terminal_close` reclaims explicitly, busy errors name the holder, and cancels can be addressed by id or session_id
|
||||
- Destructive confirmations list the target hosts and default to No; "High speed / Ultra speed" became "High quality / Smooth"; Ctrl+F filters as you type
|
||||
- Chinese process names, registry reads creating empty subkeys, and trial-code replacement, among other refinements
|
||||
|
||||
**Bug fixes:**
|
||||
- Two paths by which a remote peer could terminate the server: the unauthenticated `Content-Length: -1` DoS in httplib and a malformed JPEG reaching libjpeg's `exit()`
|
||||
- Remote desktop audio could go permanently silent (unlocked ring buffer shared across threads, a dropped format packet, Modern Standby resume, endpoint changes)
|
||||
- A quality switch jumped to another monitor, switching back to H.264 froze the view for up to ten seconds, and slow frames made the adaptive controller abstain forever
|
||||
- The web remote view went black after a resolution or quality change, and a web terminal lost every keystroke after a heartbeat reconnect
|
||||
- The remote desktop did not repaint after a window resize; the floating toolbar's quality menu retracted as soon as it opened; injected keys left modifiers stuck
|
||||
- macOS leaked one receive thread per sub-connection (2048 threads after six weeks); a fixed HELL header encoding kept about a third of Release clients off the Go fallback server
|
||||
- Feature limits lost the 40 items above bit 31 on 32-bit builds; uptime read 0 across time zones; the login reserved list could overflow
|
||||
|
||||
### v1.4.2 (2026.10.31)
|
||||
|
||||
**MCP operations suite & WebSocket transport & capture robustness**
|
||||
|
||||
@@ -32,6 +32,8 @@
|
||||
> 本軟體**僅供教育目的及授權使用情境**:組織內遠端 IT 管理、經授權的滲透測試與安全研究、個人裝置管理與技術學習。
|
||||
>
|
||||
> **未經授權存取電腦系統屬違法行為。** 使用者須對遵守所有適用法律承擔全部責任。開發者對任何濫用行為概不負責。
|
||||
>
|
||||
> **二次開發紅線:** 如使用大模型協助對本專案進行二次開發,不得破解本專案,也不得替換本專案的私有函式庫以達到繞過授權的目的。一經發現,授權伺服器將對其**永久列入黑名單**。
|
||||
|
||||
---
|
||||
|
||||
@@ -378,6 +380,38 @@ nohup ./server_linux_amd64 --port 6543 --http-port 9001 > yama.log 2>&1 &
|
||||
|
||||
## 更新日誌
|
||||
|
||||
### v1.4.3 (2026.11.14)
|
||||
|
||||
**MCP 工具面收斂 & Go 極簡 MCP & Android / macOS 能力補齊 & TLS 開箱即用**
|
||||
|
||||
**新功能:**
|
||||
- **MCP 工具收斂 60 → 54**:`host_list_*` 十個唯讀工具合併為 `host_inspect(aspects[])`、三個主機列表合併為 `list_hosts`、視窗與服務控制各只留一個名字;加上本次新增的 5 個工具,清單最終為 54 項(全部開關開啟時 `tools/list` 列出 49 項),回應從 193 KB 降到 169 KB(-12.6%)。舊名保留為可呼叫別名;`McpMachine` 開啟時降級的 `list_processes` / `list_windows` / `list_services` 不再列出
|
||||
- **MCP 新工具**:`http_probe`(僅私網 IP 的 HTTP 檢查,不跟隨重新導向、內文 64 KB、校驗憑證)、`read_file`(逐行讀取遠端文字,BOM / UTF-8 / GBK 自動辨識,負 offset 從尾端讀,回傳整個檔案 SHA-256)、`get_foreground_window` 與視窗資訊 RPC(179/180,`expect_hwnd` / `require_foreground`)、`uninstall_host`、`remote_lock_screen`
|
||||
- **MCP 原生擷取**:`get_screenshot` 支援區域 / 視窗 / 單一螢幕 1:1 擷取(`CLIENT_CAP_SCREEN_REGION`,回傳來源矩形與縮放),`remote_open` 可只推送目標視窗或區域,`remote_mouse` 支援視窗相對座標
|
||||
- **Go 極簡 MCP**:無狀態 `POST /mcp` + Bearer 驗證,9 個工具(唯讀 7 個),每裝置鎖與全域並行閘門、每次呼叫寫稽核;終端 256 KiB 環形緩衝,`list_files` / `read_file` 走檔案管理子連線,`get_screenshot` 走主連線預覽 RPC
|
||||
- **Android 用戶端補齊**:螢幕預覽(API 30+ 無障礙擷取)、活動歷史、執行日誌上報、TLS 熱切換(OpenSSL 3.5.0 靜態連結)、主控推送 APK 升級、遠端交談 / 終端 / 剪貼簿 / 鎖屏 / 隱私遮罩 / 卸載、語音監聽,並讓遠控調校命令真正生效(先前硬編碼 Good 使自適應品質永遠無法啟動)
|
||||
- **macOS 用戶端階段 0 / 1**:TLS 傳輸、執行日誌上報、授權後自動重啟、終端與行程管理能力位、螢幕預覽、活動歷史、關鍵幀請求
|
||||
- **TLS 開箱即用**:未設定憑證時首次需要即自簽(RSA-2048,十年),可在對話框匯出 PEM,也可內嵌進產生的用戶端與下發的 DLL,首連即 TLS
|
||||
- **Linux 用戶端**:分享到另一主控(fork 子實例)、轉移到另一主控(到期自動還原)、活動歷史(有桌面走 X11,無桌面彙整登入與 shell 歷史)、記住全螢幕與遠端游標
|
||||
- **Windows 遠控**:多螢幕改抓整個虛擬桌面、擷取監視器索引跨重啟穩定、自適應品質新增吞吐判據與防振盪、調校開關改為依用戶端儲存、注入按鍵在斷線 / 切換背景時釋放
|
||||
- **主控與 Web**:進階選單「執行測試程式」(載荷在主控行程內載入,帶防誤傷標記)、檔案管理員傳輸歷史落地、功能限制與真實選單對齊(57/19/46 項)、Web 控制台裝置列表分組過濾、狀態列 TLS / MCP 狀態
|
||||
|
||||
**改進:**
|
||||
- MCP 契約與實作對齊:條件必填改 `allOf` / `if` / `then`,`outputSchema` 與實際回傳一致,說明文字逐條對過程式碼
|
||||
- 只交文字區塊的 MCP 用戶端也能看到主機 ID 與列表列;`list_files` 改為列全目錄再分頁,路徑統一 GBK
|
||||
- 終端工作階段語意:可隱式開工作階段、逾時保留並輪詢、`terminal_close` 顯式回收、忙碌時提示佔用者、取消可依 id / session_id 定位
|
||||
- 危險操作確認框列出目標主機且預設「否」;「高速 / 極速」更名為「高畫質 / 流暢」;Ctrl+F 改為即輸即篩
|
||||
- 中文行程名稱顯示、設定讀取建立空登錄子機碼、試用口令覆蓋等一批細節修正
|
||||
|
||||
**Bug 修復:**
|
||||
- 兩個能讓遠端對端打死伺服端的路徑:httplib `Content-Length: -1` 無驗證死迴圈 DoS、畸形 JPEG 觸發 libjpeg `exit()`
|
||||
- 遠控音訊偶發永久靜音(環形緩衝跨執行緒無鎖、格式封包遺失、Modern Standby 還原、端點變更)
|
||||
- 品質切換跳到另一台螢幕、從 RGB565 / DIFF 切回 H.264 凍結最長 10 秒;慢幀下自適應品質永遠棄權
|
||||
- Web 遠端畫面在解析度 / 品質變化後黑屏;Web 終端心跳重連後按鍵全部遺失
|
||||
- 遠端桌面視窗縮放後不重繪;浮動工具列品質選單一打開就收回;注入按鍵卡住修飾鍵
|
||||
- macOS 子連線執行緒洩漏(六週後達 2048 執行緒);HELL 標頭編碼固定導致約三分之一 Release 用戶端登不上 Go fallback
|
||||
- 功能限制在 32 位元主控上遺失 bit 32 以上的 40 項;執行時間跨時區恆顯示 0;登入保留區越界
|
||||
|
||||
### v1.4.2 (2026.10.31)
|
||||
|
||||
**MCP 維運套件 & WebSocket 傳輸 & 擷取畫面健壯性**
|
||||
|
||||
@@ -785,7 +785,11 @@ BOOL IOCPClient::ConnectServer(const char* szServerIP, unsigned short uPort)
|
||||
// the TCP stream and prevent any complete command from being delivered.
|
||||
// SAFE_CLOSE_HANDLE and CloseHandle are no-ops on Android, so the value
|
||||
// is never dereferenced as a kernel handle.
|
||||
m_hWorkThread = reinterpret_cast<HANDLE>(static_cast<uintptr_t>(id));
|
||||
// POSIX 下这个值只当「线程已存在」的非空标志用,从不反向解引用。
|
||||
// 不能用 static_cast<uintptr_t>(id):macOS 的 pthread_t 是
|
||||
// _opaque_pthread_t*(Linux/Android 是整型),指针经整型中转是非法的。
|
||||
// reinterpret_cast 对两种形态都成立(整型→指针 / 指针→指针)。
|
||||
m_hWorkThread = reinterpret_cast<HANDLE>(id);
|
||||
} else {
|
||||
// pthread_create 直接返回错误码(不经 errno):EAGAIN(35)/EPERM(1) 基本就是
|
||||
// 进程/用户的线程数到顶。这条路径原本完全静默——连接看起来「成功」了,
|
||||
|
||||
@@ -49,7 +49,9 @@ BOOL IOCPUDPClient::ConnectServer(const char* szServerIP, unsigned short uPort)
|
||||
if (ret == 0) {
|
||||
m_bWorkThread = S_RUN;
|
||||
m_bIsRunning = TRUE;
|
||||
m_hWorkThread = reinterpret_cast<HANDLE>(static_cast<uintptr_t>(id));
|
||||
// 同 IOCPClient:macOS 的 pthread_t 是 _opaque_pthread_t*,不能经
|
||||
// static_cast<uintptr_t> 中转,reinterpret_cast 对整型/指针两种实现都成立。
|
||||
m_hWorkThread = reinterpret_cast<HANDLE>(id);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
+2
-2
@@ -103,7 +103,7 @@ IDR_WAVE WAVE "Res\\msg.wav"
|
||||
//
|
||||
|
||||
VS_VERSION_INFO VERSIONINFO
|
||||
FILEVERSION 1,0,4,2
|
||||
FILEVERSION 1,0,4,3
|
||||
PRODUCTVERSION 1,0,0,1
|
||||
FILEFLAGSMASK 0x3fL
|
||||
#ifdef _DEBUG
|
||||
@@ -121,7 +121,7 @@ BEGIN
|
||||
BEGIN
|
||||
VALUE "CompanyName", "FUCK THE UNIVERSE"
|
||||
VALUE "FileDescription", "A GHOST"
|
||||
VALUE "FileVersion", "1.0.4.2"
|
||||
VALUE "FileVersion", "1.0.4.3"
|
||||
VALUE "InternalName", "ServerDll.dll"
|
||||
VALUE "LegalCopyright", "Copyright (C) 2019-2026"
|
||||
VALUE "OriginalFilename", "ServerDll.dll"
|
||||
|
||||
Binary file not shown.
@@ -169,9 +169,9 @@ public:
|
||||
|
||||
// 处理 V2 文件数据包
|
||||
// 返回: 0=成功, >0=错误码
|
||||
// reply:主连接(Linux 传 g_pMainClient)。非空时,C2C 传输的最后一个条目处理完会回一包
|
||||
// 落盘结果(TOKEN_C2C_SEND_RESULT),服务端据此把 receiver_ack 变成真实值;
|
||||
// 传 nullptr(macOS 目前没有全局主连接)则保持旧行为,不发回执。
|
||||
// reply:主连接(Linux/macOS 传 g_pMainClient)。非空时,C2C 传输的最后一个条目
|
||||
// 处理完会回一包落盘结果(TOKEN_C2C_RECV_RESULT),服务端据此把 receiver_ack
|
||||
// 变成真实值;传 nullptr 则保持旧行为,不发回执。
|
||||
static int RecvFileChunkV2(const uint8_t* buf, size_t len, uint64_t myClientID,
|
||||
IOCPClient* reply = nullptr)
|
||||
{
|
||||
|
||||
+19
-4
@@ -138,19 +138,20 @@ inline int isValid_10s()
|
||||
// 无此位 = 老客户端,按系统 ANSI(默认 CP936)解读
|
||||
#define CLIENT_CAP_SCREEN_PREVIEW 0x0004 // 支持屏幕预览(双击在线主机时弹缩略图)
|
||||
#define CLIENT_CAP_C2C_PATHS 0x0008 // 支持按路径清单向另一客户端发送文件(COMMAND_C2C_SEND_FILES,仅 Windows)
|
||||
#define CLIENT_CAP_C2C_RECV_ACK 0x0010 // 作为 C2C 目标端时,落盘完成后回执(TOKEN_C2C_RECV_RESULT,目前仅 Linux)
|
||||
#define CLIENT_CAP_C2C_RECV_ACK 0x0010 // 作为 C2C 目标端时,落盘完成后回执(TOKEN_C2C_RECV_RESULT,Linux/macOS)
|
||||
#define CLIENT_CAP_PROTO_SWITCH 0x0020 // 支持服务端远程切换传输协议(COMMAND_SET_PROTO,仅 Windows)
|
||||
#define CLIENT_CAP_EMBEDDED_ANCHOR 0x0040 // 当前靠「生成时内嵌的 TLS 信任锚」在加密(按运行时状态置位,不是能力声明)
|
||||
#define CLIENT_CAP_VIRTUAL_DESKTOP 0x0080 // 支持按 COMMAND_SCREEN_SPY 参数 buffer[11](wire 索引 12)强制抓取整个虚拟桌面(多显示器远程控制)
|
||||
#define CLIENT_CAP_WINDOW_INFO 0x0100 // 支持 COMMAND_MCP_WINDOW_INFO(带矩形/前后台/最小化状态的窗口列表)与窗口激活(CMD_WINDOW_ACTIVATE_FLAG)
|
||||
#define CLIENT_CAP_SCREEN_REGION 0x0200 // 支持 COMMAND_SCREEN_PREVIEW_REQ 扩展(区域/窗口/显示器原生分辨率截图)
|
||||
#define CLIENT_CAP_APK_UPDATE 0x0400 // 支持接收 COMMAND_UPDATE 下发的 APK 并走系统安装器(仅 Android)
|
||||
#define CLIENT_CAP_SCREEN_CLIPBOARD 0x0800 // 屏幕子连接处理 COMMAND_SCREEN_SET_CLIPBOARD,并把 VK_V 映射成 ACTION_PASTE(仅新版 Android)
|
||||
#define CLIENT_CAP_SCREEN_CLIPBOARD 0x0800 // 屏幕子连接处理 COMMAND_SCREEN_SET_CLIPBOARD,并把 VK_V 映射成 ACTION_PASTE(新版 Android 与 macOS;Linux 只在屏幕子连接里实现了剪贴板,未声明)
|
||||
#define CLIENT_CAP_LOCK_SCREEN 0x1000 // 屏幕子连接处理 COMMAND_SCREEN_CTRL_ALT_DEL(Android 映射为锁屏 GLOBAL_ACTION_LOCK_SCREEN)
|
||||
#define CLIENT_CAP_UNINSTALL 0x2000 // 主连接处理 TOKEN_UNINSTALL(Android 拉起系统卸载确认框;Windows 客户端一直支持但不声明)
|
||||
#define CLIENT_CAP_REMOTE_CHAT 0x4000 // 主连接处理 COMMAND_CHAT(远程交谈子连接;Windows 一直支持但不声明,目前只有新版 Android 声明)
|
||||
#define CLIENT_CAP_TERMINAL 0x8000 // 主连接处理 COMMAND_SHELL(PTY 终端子连接:exec_command / terminal_*;Linux 一直支持但不声明,目前只有新版 Android 声明)
|
||||
#define CLIENT_CAP_TERMINAL 0x8000 // 主连接处理 COMMAND_SHELL(PTY 终端子连接:exec_command / terminal_*;Linux 一直支持但不声明,新版 Android 与 macOS 声明)
|
||||
#define CLIENT_CAP_PRIVACY_OVERLAY 0x10000 // 屏幕子连接处理 COMMAND_SCREEN_BLOCK_INPUT / COMMAND_SCREEN_BLANK(Android 用无障碍全屏 overlay 实现;Windows 一直支持锁定键鼠但不声明这个位)
|
||||
#define CLIENT_CAP_PROCESS 0x20000 // 主连接处理 COMMAND_SYSTEM(系统子连接:COMMAND_PSLIST / COMMAND_KILLPROCESS;Linux/macOS 声明,Windows 一直支持但不声明)
|
||||
|
||||
#define TALK_DLG_MAXLEN 1024 // 最大输入字符长度
|
||||
|
||||
@@ -1337,8 +1338,10 @@ typedef struct LOGIN_INFOR {
|
||||
caps |= CLIENT_CAP_SCREEN_REGION;
|
||||
#elif defined(__linux__) && !defined(__ANDROID__)
|
||||
// Linux 客户端作为 C2C 目标端时会回执落盘结果(common/FileTransferV2.h)。
|
||||
// macOS 暂未接线(无全局主连接句柄),不声明——服务端就不会为它空等回执。
|
||||
caps |= CLIENT_CAP_C2C_RECV_ACK;
|
||||
// COMMAND_SYSTEM → SystemManager(/proc 枚举 + kill)。一直有实现,声明出来是为了
|
||||
// 让「这台主机能不能杀进程」有据可查,不必再靠平台名推断。
|
||||
caps |= CLIENT_CAP_PROCESS;
|
||||
#elif defined(__ANDROID__)
|
||||
// 收到服务端下发的 APK 后写盘并拉起系统安装器。老 APK 没有这个分支,
|
||||
// 服务端据此提示「先手动装一次新版」,而不是发一个对方会静默丢弃的包。
|
||||
@@ -1358,6 +1361,18 @@ typedef struct LOGIN_INFOR {
|
||||
// 远程终端(COMMAND_SHELL → PTY 子连接):老 APK 里 COMMAND_SHELL 是空实现,
|
||||
// 服务端据此提前拒绝 exec_command / terminal_*,而不是等子连接超时。
|
||||
caps |= CLIENT_CAP_TERMINAL;
|
||||
#elif defined(__APPLE__)
|
||||
// 终端(COMMAND_SHELL → PTY 子连接)在 macOS 一直是完整实现(zsh/bash 交互 +
|
||||
// resize),以前只是没声明,服务端据此把 exec_command / terminal_* 当作不支持。
|
||||
caps |= CLIENT_CAP_TERMINAL;
|
||||
// 屏幕子连接已处理 COMMAND_SCREEN_SET_CLIPBOARD / GET_CLIPBOARD。
|
||||
caps |= CLIENT_CAP_SCREEN_CLIPBOARD;
|
||||
// COMMAND_SYSTEM → SystemManager(proc_listpids 枚举 + SIGKILL)。老 macOS 构建
|
||||
// 收到 COMMAND_SYSTEM 只打一行日志,服务端据此提前拒绝 kill_process。
|
||||
caps |= CLIENT_CAP_PROCESS;
|
||||
// 作为 C2C 目标端落盘后回执(TOKEN_C2C_RECV_RESULT),走主连接全局句柄。
|
||||
caps |= CLIENT_CAP_C2C_RECV_ACK;
|
||||
// SCREEN_PREVIEW 依赖录屏授权,由 main.mm 在登录前按运行时状态追加(同 Linux)。
|
||||
#endif
|
||||
return caps;
|
||||
}
|
||||
|
||||
+30
-11
@@ -17,7 +17,8 @@
|
||||
#endif
|
||||
|
||||
#include <iostream>
|
||||
#include <cstdio> // fprintf:macOS 非 ObjC 翻译单元的 Mprintf 走 stderr
|
||||
#include <cstdio> // fputs/fflush/stderr:macOS 的 mirrorStderr 把每行日志同步写 stderr
|
||||
#include <cstring> // strrchr:getFileName 不依赖调用方先包含 <string.h>
|
||||
#include <fstream>
|
||||
#include <mutex>
|
||||
#include <queue>
|
||||
@@ -78,6 +79,20 @@ public:
|
||||
snprintf(buf, sizeof(buf), "%d", (int)getpid());
|
||||
instance.pid = buf;
|
||||
instance.enable = false;
|
||||
#elif defined(__APPLE__)
|
||||
// macOS:只保留内存 ring + stderr,不另建日志文件。
|
||||
// - ring 是服务端「运行日志」菜单的数据源:COMMAND_QUERY_LOG →
|
||||
// TOKEN_REPORT_LOG,见 common/ClientLogHandler.h;
|
||||
// - stderr 已被 macos/main.mm 重定向到 /tmp/ghost.log(daemon 与 App
|
||||
// bundle 两种启动方式都做),那是现场唯一日志文件,再往
|
||||
// ~/.config/ghost 写一份只会让两边对不上。
|
||||
// 此前 macOS 的 Mprintf 是 NSLog/fprintf,从不经过 Logger,ring 永远是
|
||||
// 空的 —— 服务端点「运行日志」打开后一个字都没有,就是这个原因。
|
||||
char buf[16] = {};
|
||||
snprintf(buf, sizeof(buf), "%d", (int)getpid());
|
||||
instance.pid = buf;
|
||||
instance.enable = false;
|
||||
instance.mirrorStderr = true;
|
||||
#else // Linux
|
||||
char buf[16] = {};
|
||||
snprintf(buf, sizeof(buf), "%d", (int)getpid());
|
||||
@@ -167,6 +182,14 @@ public:
|
||||
logEntry.pop_back();
|
||||
logEntry += '\n';
|
||||
|
||||
// macOS:把同一行镜像到 stderr,也就是 /tmp/ghost.log。ring 只留最近
|
||||
// kMemLogMax 条,而现场排查往往要往前翻,两边保持完全相同的文本(含前缀和
|
||||
// 时间戳),对照时不必换算。
|
||||
if (mirrorStderr) {
|
||||
fputs(logEntry.c_str(), stderr);
|
||||
fflush(stderr);
|
||||
}
|
||||
|
||||
// Always record to in-memory ring buffer regardless of enable flag.
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_memMutex);
|
||||
@@ -263,6 +286,7 @@ private:
|
||||
}
|
||||
std::string logFileName; // 日志文件名
|
||||
bool enable; // 是否启用
|
||||
bool mirrorStderr = false; // macOS:每行同时镜像到 stderr(/tmp/ghost.log)
|
||||
bool threadRun; // 日志线程状态
|
||||
std::queue<std::string> logQueue; // 日志队列
|
||||
std::mutex queueMutex; // 队列互斥锁
|
||||
@@ -384,19 +408,14 @@ inline const char* getFileName(const char* path)
|
||||
#elif defined(_WIN32)
|
||||
#define Mprintf(format, ...) Logger::getInstance().log(getFileName((__FILE__)), __LINE__, (format), __VA_ARGS__)
|
||||
#elif defined(__APPLE__)
|
||||
// macOS: 使用 NSLog 输出到系统日志(可通过 Console.app 查看)
|
||||
// macOS:与 Linux 一样写 Logger —— 内存 ring 供服务端「运行日志」菜单取回
|
||||
// (COMMAND_QUERY_LOG → TOKEN_REPORT_LOG),Logger 初始化时置 mirrorStderr,
|
||||
// 同一行再落到 stderr,也就是 /tmp/ghost.log。不要改回 NSLog/fprintf:那样
|
||||
// ring 永远为空,菜单打开后没有任何内容。
|
||||
#ifdef Mprintf
|
||||
#undef Mprintf
|
||||
#endif
|
||||
#ifdef __OBJC__
|
||||
#define Mprintf(format, ...) NSLog(@"%@", [NSString stringWithFormat:@(format), ##__VA_ARGS__])
|
||||
#else
|
||||
// 非 ObjC 翻译单元(IOCPClient/FileManager/TlsChannel 等)没有 NSLog,只能写流。
|
||||
// 必须写 stderr:macos/main.mm 把 stderr 重定向到 /tmp/ghost.log(daemon 与 App bundle
|
||||
// 两种启动方式都做,App bundle 还设了 CFLOG_FORCE_STDERR 让 NSLog 也落到同一文件);
|
||||
// stdout 在 App bundle / login item 启动时没人接收,写过去的日志会直接丢掉。
|
||||
#define Mprintf(format, ...) fprintf(stderr, format, ##__VA_ARGS__)
|
||||
#endif
|
||||
#define Mprintf(format, ...) Logger::getInstance().log(getFileName(__FILE__), __LINE__, format, ##__VA_ARGS__)
|
||||
#elif defined(__ANDROID__)
|
||||
#include <android/log.h>
|
||||
#include <cstdarg>
|
||||
|
||||
@@ -951,6 +951,17 @@ schema 里写明这一点;同时根键分支补上 `path: ""`,让两个分
|
||||
`MessageHandle` 的 `TOKEN_REPORT_LOG` 分支取走首包后会 `CancelIO` 关掉这条连接,回在
|
||||
主连接上就是把主连接关掉(客户端当场掉线)。
|
||||
|
||||
macOS 还有第二层问题,只影响日志内容,2026-11-14 修:处理器虽然接上了,但 `Logger` 的
|
||||
ring 只能被 `Mprintf` 写入,而 macOS 的 `Mprintf` 当时直接走 `NSLog`/`fprintf(stderr)`,
|
||||
从不经过 `Logger`——ring 恒为空,菜单和 `get_client_log` 拿到的都是空快照。现在 macOS 的
|
||||
`Mprintf`(由 `common/logger.h` 定义)与 Linux 一样写 `Logger`(ring;`enable=false` 不另
|
||||
建日志文件),再由 `Logger` 把同一行镜像到 stderr(即 `/tmp/ghost.log`),同一条 Mprintf
|
||||
在文件与菜单里的文本、前缀、时间戳完全一致;ring 只留最近 1000 行,更早的内容只在文件
|
||||
里。`macos/main.mm` 里原先用 `NSLog` 的启动/配置/权限等生命周期行也一并改成 `Mprintf`,
|
||||
否则菜单里看不到现场最常翻的那几行;`ScreenHandler`/`H264Encoder`/`InputHandler` 等 ObjC
|
||||
模块的 `NSLog` 不动,它们和两条直接 `write(2)` 的启动横幅仍只出现在 `/tmp/ghost.log`。
|
||||
MFC 的「运行日志」对话框与 MCP 的 `get_client_log` 走同一条链路,两端同时可用。
|
||||
|
||||
### 18.4 验证与未覆盖
|
||||
|
||||
- 服务端 21:17:21 构建 + 两端客户端重编后实测:`ids` 批量(`get_host_detail` /
|
||||
@@ -1282,3 +1293,62 @@ region 同样要求新 Windows 客户端(桌面尾块是 `CLIENT_CAP_WINDOW_IN
|
||||
客户端),返回 `-32005`;默认整屏目标行为与字节流完全不变。
|
||||
- window/region 目标各自多一次窗口信息 RPC;region 目标还要多等一次
|
||||
`TOKEN_BITMAPINFO` 到达(通常几十毫秒)。
|
||||
|
||||
## 24. 增补(2026-11-14:macOS 客户端能力补齐,阶段 0 + 1)
|
||||
|
||||
macOS 客户端此前有大量「实现了但服务端不认」的功能,断点有三层,缺任何一层都表现为
|
||||
「工具直接 `-32005`」或「发下去以后等超时」:
|
||||
|
||||
1. 客户端**没接线**(`COMMAND_SYSTEM` 只打一行日志,`SystemManager` 的签名也不满足
|
||||
子连接骨架,从未被实例化);
|
||||
2. 接上了但**没声明能力位**(终端、剪贴板、C2C 回执早就在跑,`moduleVersion` 里却一个位都没有);
|
||||
3. 声明了能力位,但服务端**仍按平台表一律拒绝** `MAC`。
|
||||
|
||||
本批把三层一起补齐。
|
||||
|
||||
### 24.1 阶段 0:让已有实现可达
|
||||
|
||||
- **能力位**(`common/commands.h`):新增 `CLIENT_CAP_PROCESS=0x20000`;macOS 的
|
||||
`DefaultCaps()` 声明 `TERMINAL` / `SCREEN_CLIPBOARD` / `PROCESS` / `C2C_RECV_ACK`,
|
||||
Linux 也补声明 `PROCESS`(`SystemManager` 一直在跑,只是没声明)。
|
||||
Windows 一直支持进程管理与终端但从不声明,调用方按平台区分,行为不变。
|
||||
- **`SystemManager`**(`macos/SystemManager.*`):改成派生 `IOCPManager`、构造只收
|
||||
`IOCPClient*`,满足 `common/sub_conn_thread.h` 的 `createHandler` / `OnReceive` 契约;
|
||||
`main.mm` 的 `COMMAND_SYSTEM` 现在真的起子连接(`proc_listpids` 枚举 + `SIGKILL`)。
|
||||
- **C2C 落盘回执**:`DataProcess` 的 `user` 恒为 NULL,因此在 `main.mm` 增加
|
||||
`g_pMainClient`(同 `linux/main.cpp`),作为 V2 接收端回 `TOKEN_C2C_RECV_RESULT`。
|
||||
`download_file` / `upload_file` / `copy_files_c2c` 的 macOS 目标端 `receiver_ack`
|
||||
由恒 `false` 变为真实回执。
|
||||
- **服务端放行**(`McpServer.cpp`):`exec_command` / `terminal_*` 对 `MAC` 要求
|
||||
`SupportsTerminal()`,`kill_process` 要求 `SupportsProcess()`,老 macOS 构建返回
|
||||
`-32005` 并提示升级,而不是发一条没人接的命令后假报 ok;`kToolPlatforms` 同步。
|
||||
- `http_probe` **仍只放行 Windows/Linux**:macOS 终端已可用,但 POSIX 探测命令用了
|
||||
GNU 专有的 `base64 -w`,BSD base64 没有该开关,等换成两平台通用写法再放开。
|
||||
|
||||
### 24.2 阶段 1:POSIX 对齐
|
||||
|
||||
- **屏幕预览**(`macos/ScreenPreview.*`):`CGDisplayCreateImage` → 等比缩放 →
|
||||
`SCREEN_PREVIEW_FMT_BGRX`,与服务端统一编码 JPEG 的 Linux 路径一致(macOS 不做
|
||||
JPEG 编码)。`CLIENT_CAP_SCREEN_PREVIEW` 只在**登录时已授予录屏权限**时声明
|
||||
(`RefreshLoginCaps`,每次重连重判),否则 `get_screenshot` 会一直等超时。
|
||||
- **历史活动**(`macos/ActivityHistory.*`):每秒采一次前台窗口
|
||||
(`CGWindowListCopyWindowInfo`,第一个 `layer 0` 窗口;窗口标题需录屏授权,没有权限
|
||||
时退化为应用名),输出格式与 Windows/Linux 完全一致;`COMMAND_QUERY_ACTIVITY`
|
||||
在主连接一次性快照回 `TOKEN_REPORT_ACTIVITY`,单飞行。
|
||||
- **强制关键帧**:Web 屏幕墙恢复时服务端发 `COMMAND_SCREEN_KEYFRAME_REQ`。
|
||||
Windows 一直支持;本次让 Linux(x264 `X264_TYPE_IDR`)与 macOS(VideoToolbox
|
||||
`kVTEncodeFrameOptionKey_ForceKeyFrame`)也消费它——接收线程只置标志,采集线程在
|
||||
下一帧 `exchange`,编码器实例仍归采集线程独占。抓帧失败时把请求放回去,下一帧再试。
|
||||
Android 仍未实现,属后续项。
|
||||
- **质量等级持久化**(`macos/ScreenHandler.mm`):`CMD_QUALITY_LEVEL` 的 persist 位
|
||||
以前是 `(void)persist` 的 TODO,现在写入 `NSUserDefaults`(键 `GhostQualityLevel`),
|
||||
启动时读回并套用。**不写** `~/.config/ghost/config.conf`:那份配置由 `main.mm`
|
||||
用内存 map 整体重写,单独追加键会被下一次写盘冲掉。
|
||||
- `kToolPlatforms`:`get_screenshot` / `get_activity_history` 增加 `kPlatMac`。
|
||||
|
||||
### 24.3 兼容与代价
|
||||
|
||||
- 老 macOS 构建:终端/进程类工具返回「client is too old ... upgrade」,不再假报成功。
|
||||
- `remote_open` 仍拒绝 `MAC`(屏幕/注入链路的 macOS 实机验证还没做),本批不动。
|
||||
- `mcp/tools.json` 是生成物(`tools/mcp_tools/`),平台表变更后要用跑起来的服务端
|
||||
重新生成。
|
||||
+30
-3
@@ -556,6 +556,13 @@ public:
|
||||
}
|
||||
break;
|
||||
|
||||
case COMMAND_SCREEN_KEYFRAME_REQ:
|
||||
// Web 屏幕墙恢复/新加入者请求:下一帧强制 IDR。只置标志,
|
||||
// 编码器实例归采集线程所有(COMMAND_SCREEN_KEYFRAME_REQ 与 CMD_QUALITY_LEVEL
|
||||
// 一样在屏幕子连接的接收线程上处理)。
|
||||
m_keyframeRequested.store(true);
|
||||
break;
|
||||
|
||||
case COMMAND_SCREEN_SET_CLIPBOARD:
|
||||
// 服务端设置剪贴板: [cmd:1][text:N]
|
||||
if (size > 1) {
|
||||
@@ -967,6 +974,9 @@ private:
|
||||
LinuxConfig m_config; // 配置持久化 (~/.config/ghost/config.conf)
|
||||
std::atomic<int> m_bFullScreen; // 全屏偏好(主控端下发,随 ScreenSettings 上报)
|
||||
std::atomic<int> m_bRemoteCursor; // 远程光标偏好(同上)
|
||||
// Web 端请求下一帧强制 IDR(COMMAND_SCREEN_KEYFRAME_REQ)。接收线程置位、
|
||||
// 采集线程消费:编码器实例只在采集线程里创建/销毁,接收线程不能直接碰。
|
||||
std::atomic<bool> m_keyframeRequested{false};
|
||||
|
||||
// H264 编码器
|
||||
std::unique_ptr<X264Encoder> m_h264Encoder;
|
||||
@@ -1068,6 +1078,18 @@ private:
|
||||
// 发送 H264 编码帧
|
||||
void SendH264Frame(bool forceKeyframe = false)
|
||||
{
|
||||
// 强制 IDR 请求在调用点已经 exchange 掉,只有真的把这一帧编出来才算消费成功。
|
||||
// 中途任何提前返回(抓屏失败 / 没连接 / 编码器开不起来 / 编码失败)都把它还回去,
|
||||
// 否则 Web 端要等编码器下一次自然 IDR(最长一个 GOP)才能解出画面。
|
||||
struct RearmOnFailure {
|
||||
std::atomic<bool>& flag;
|
||||
bool force;
|
||||
bool consumed;
|
||||
RearmOnFailure(std::atomic<bool>& f, bool force_)
|
||||
: flag(f), force(force_), consumed(false) {}
|
||||
~RearmOnFailure() { if (force && !consumed) flag.store(true); }
|
||||
} rearm(m_keyframeRequested, forceKeyframe);
|
||||
|
||||
if (!CaptureScreen(m_currFrame)) return;
|
||||
if (!m_client) return;
|
||||
|
||||
@@ -1096,7 +1118,7 @@ private:
|
||||
int result = m_h264Encoder->encode(
|
||||
m_currFrame.data(), 32, m_bmpHeader.biWidth * 4,
|
||||
m_bmpHeader.biWidth, m_bmpHeader.biHeight,
|
||||
&encodedData, &encodedSize, 1);
|
||||
&encodedData, &encodedSize, 1, forceKeyframe);
|
||||
|
||||
if (result != 0 || !encodedData || encodedSize == 0) {
|
||||
return;
|
||||
@@ -1117,6 +1139,7 @@ private:
|
||||
|
||||
memcpy(&packet[headerSize], encodedData, encodedSize);
|
||||
m_client->Send2Server((char*)packet.data(), packet.size());
|
||||
rearm.consumed = true;
|
||||
}
|
||||
|
||||
// 差异比较算法(支持 DIFF/RGB565/GRAY)
|
||||
@@ -1333,10 +1356,13 @@ private:
|
||||
if (algo != currentAlgo) {
|
||||
currentAlgo = algo;
|
||||
if (algo == ALGORITHM_H264) {
|
||||
// 切换到 H264,发送关键帧
|
||||
// 切换到 H264,发送关键帧;这一帧本身就是关键帧,
|
||||
// 挂起的强制 IDR 请求顺手清掉,别下一帧再打一次。
|
||||
m_keyframeRequested.store(false);
|
||||
SendH264Frame(true);
|
||||
} else {
|
||||
// 切换离开 H264,关闭编码器并发送完整帧
|
||||
m_keyframeRequested.store(false); // 关键帧请求对非 H264 无意义
|
||||
if (m_h264Encoder) {
|
||||
m_h264Encoder->close();
|
||||
m_h264Encoder.reset();
|
||||
@@ -1346,7 +1372,8 @@ private:
|
||||
} else {
|
||||
// 正常帧
|
||||
if (algo == ALGORITHM_H264) {
|
||||
SendH264Frame(false);
|
||||
// 服务端的强制 IDR 请求在这里消费:下一帧就是关键帧。
|
||||
SendH264Frame(m_keyframeRequested.exchange(false));
|
||||
} else {
|
||||
SendDiffFrame();
|
||||
}
|
||||
|
||||
+6
-1
@@ -165,12 +165,13 @@ public:
|
||||
* @param outData Output: pointer to encoded H264 data
|
||||
* @param outSize Output: size of encoded data
|
||||
* @param direction 1 = normal, -1 = vertical flip
|
||||
* @param forceKeyframe true = 本帧强制 IDR(服务端 COMMAND_SCREEN_KEYFRAME_REQ)
|
||||
* @return 0 on success, negative on error
|
||||
*/
|
||||
int encode(uint8_t* bgra, uint8_t bpp, uint32_t stride,
|
||||
uint32_t width, uint32_t height,
|
||||
uint8_t** outData, uint32_t* outSize,
|
||||
int direction = 1)
|
||||
int direction = 1, bool forceKeyframe = false)
|
||||
{
|
||||
if (!m_encoder || !m_picIn || !fn_x264_encoder_encode) {
|
||||
return -1;
|
||||
@@ -197,9 +198,13 @@ public:
|
||||
}
|
||||
|
||||
// Encode
|
||||
// Web 端新加入/恢复时服务端会发 COMMAND_SCREEN_KEYFRAME_REQ:把本帧标成 IDR,
|
||||
// 参考链立即重建,不必等 keyint_max(15 秒)后的下一个关键帧。
|
||||
m_picIn->i_type = forceKeyframe ? X264_TYPE_IDR : X264_TYPE_AUTO;
|
||||
x264_nal_t* pNal = nullptr;
|
||||
int iNal = 0;
|
||||
int encodeSize = fn_x264_encoder_encode(m_encoder, &pNal, &iNal, m_picIn, m_picOut);
|
||||
m_picIn->i_type = X264_TYPE_AUTO; // 只对这一帧有效
|
||||
|
||||
if (encodeSize < 0) {
|
||||
return -4;
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
#pragma once
|
||||
// macOS 客户端的「历史活动」采样器(服务端 COMMAND_QUERY_ACTIVITY → TOKEN_REPORT_ACTIVITY)。
|
||||
//
|
||||
// 后台每秒采样一次前台窗口(CGWindowListCopyWindowInfo 取最前面的 layer 0 窗口),
|
||||
// 输出格式与 Windows/Linux 端完全一致,服务端 CActivityDialog 与 MCP
|
||||
// get_activity_history 都只按行切分纯文本,不需要改:
|
||||
// [2026-11-14 10:00:00] [Safari - GitHub] 12s
|
||||
// 停留不足 5 秒的一闪而过不记录;同一条记录里的窗口标题会跟着更新
|
||||
// (浏览器切标签页标题常变,但窗口没换,仍算同一段停留)。
|
||||
//
|
||||
// 与 Windows/Linux 一样各平台独立实现:Linux 那份要 X11,macOS 这份要 CGWindowList +
|
||||
// NSWorkspace,共用的只有输出格式。
|
||||
#include <atomic>
|
||||
#include <deque>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
class MacActivityHistory
|
||||
{
|
||||
public:
|
||||
static MacActivityHistory& Instance();
|
||||
|
||||
// 启动后台采样线程(幂等)。应当在进程启动后尽早调用,历史从那一刻开始攒;
|
||||
// 查询时才启动的话,第一次查到的永远是空表。
|
||||
void Start();
|
||||
|
||||
// 进程退出时收线程;可以再次 Start(与 Linux 端一样保留这个能力)
|
||||
void Stop();
|
||||
|
||||
// 最新在前,每行一条;进行中的窗口(驻留已达阈值)排在最前
|
||||
std::string Dump() const;
|
||||
|
||||
// 还没有够 5 秒的记录时的说明,避免对话框全空
|
||||
static std::string EmptyText();
|
||||
|
||||
private:
|
||||
MacActivityHistory() = default;
|
||||
~MacActivityHistory() { Stop(); }
|
||||
MacActivityHistory(const MacActivityHistory&) = delete;
|
||||
MacActivityHistory& operator=(const MacActivityHistory&) = delete;
|
||||
|
||||
void Loop();
|
||||
|
||||
private:
|
||||
mutable std::mutex m_mutex;
|
||||
std::deque<std::string> m_records; // 已完成记录,最新在前
|
||||
std::string m_curTitle;
|
||||
std::string m_curStartTime;
|
||||
int m_curDwellSec = 0;
|
||||
|
||||
std::atomic<bool> m_running{ false };
|
||||
std::atomic<bool> m_started{ false };
|
||||
std::thread m_thread;
|
||||
};
|
||||
@@ -0,0 +1,233 @@
|
||||
#import "ActivityHistory.h"
|
||||
|
||||
#import <CoreGraphics/CoreGraphics.h>
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <unistd.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <ctime>
|
||||
|
||||
#include "../common/logger.h" // Mprintf(Start 失败要留痕)
|
||||
|
||||
// 与 Windows 端 client/ActivityHistory.h、Linux 端 linux/LinuxActivityHistory.h 一致
|
||||
#ifndef ACTIVITY_MIN_DWELL_SEC
|
||||
#define ACTIVITY_MIN_DWELL_SEC 5 // 一闪而过阈值(秒):驻留低于此值不记录
|
||||
#endif
|
||||
#ifndef ACTIVITY_HISTORY_MAX
|
||||
#define ACTIVITY_HISTORY_MAX 500 // 内存保留的最大记录条数
|
||||
#endif
|
||||
|
||||
namespace {
|
||||
|
||||
struct ProbeResult
|
||||
{
|
||||
uint64_t id = 0; // 窗口号(CGWindowNumber),0 表示空闲/无窗口
|
||||
std::string title;
|
||||
};
|
||||
|
||||
std::string CFStrToUtf8(CFStringRef s)
|
||||
{
|
||||
if (!s) return std::string();
|
||||
char buf[1024] = {};
|
||||
if (!CFStringGetCString(s, buf, sizeof(buf), kCFStringEncodingUTF8)) return std::string();
|
||||
return std::string(buf);
|
||||
}
|
||||
|
||||
// 按字节截断可能切在多字节字符中间,而服务端要按 UTF-8 转 GBK(对话框)或
|
||||
// 塞进 JSON(MCP),半截字符会变成乱码/非法 JSON。返回可以安全截断的位置。
|
||||
// 与 linux/LinuxActivityHistory.h 的 Utf8Boundary 同实现。
|
||||
size_t Utf8Boundary(const std::string& s)
|
||||
{
|
||||
const size_t n = s.size();
|
||||
size_t i = n;
|
||||
while (i > 0 && n - i < 3 && ((unsigned char)s[i - 1] & 0xC0) == 0x80) --i;
|
||||
if (i == 0) return n;
|
||||
const unsigned char c = (unsigned char)s[i - 1];
|
||||
size_t need = 1;
|
||||
if ((c & 0x80) == 0) need = 1;
|
||||
else if ((c & 0xE0) == 0xC0) need = 2;
|
||||
else if ((c & 0xF0) == 0xE0) need = 3;
|
||||
else if ((c & 0xF8) == 0xF0) need = 4;
|
||||
return (n - (i - 1) >= need) ? n : i - 1;
|
||||
}
|
||||
|
||||
// 控制字符换成空格(换行会破坏「每行一条」),可选截断
|
||||
std::string CleanLine(const std::string& s, size_t maxLen = 512)
|
||||
{
|
||||
std::string out;
|
||||
out.reserve(std::min(s.size(), maxLen));
|
||||
bool cut = false;
|
||||
for (char c : s) {
|
||||
unsigned char uc = (unsigned char)c;
|
||||
out += (uc < 0x20 || uc == 0x7f) ? ' ' : c;
|
||||
if (out.size() >= maxLen) { cut = true; break; }
|
||||
}
|
||||
if (cut) out.resize(Utf8Boundary(out));
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string FormatTimeStamp(std::time_t t)
|
||||
{
|
||||
std::tm tm{};
|
||||
localtime_r(&t, &tm);
|
||||
char buf[64];
|
||||
snprintf(buf, sizeof(buf), "%04d-%02d-%02d %02d:%02d:%02d",
|
||||
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
|
||||
tm.tm_hour, tm.tm_min, tm.tm_sec);
|
||||
return buf;
|
||||
}
|
||||
|
||||
// 时长格式化:Ns / Nm / NmNs / NhNm(与 Windows/Linux 端一致)
|
||||
std::string FormatDuration(int sec)
|
||||
{
|
||||
if (sec < 0) sec = 0;
|
||||
if (sec < 60) return std::to_string(sec) + "s";
|
||||
if (sec < 3600) {
|
||||
int m = sec / 60, s = sec % 60;
|
||||
return s ? std::to_string(m) + "m" + std::to_string(s) + "s"
|
||||
: std::to_string(m) + "m";
|
||||
}
|
||||
int h = sec / 3600, m = (sec % 3600) / 60;
|
||||
return std::to_string(h) + "h" + std::to_string(m) + "m";
|
||||
}
|
||||
|
||||
std::string FormatWindowRecord(const std::string& startTime, const std::string& title, int dwellSec)
|
||||
{
|
||||
return "[" + startTime + "] [" + CleanLine(title) + "] " + FormatDuration(dwellSec);
|
||||
}
|
||||
|
||||
// 前台窗口探测。CGWindowListCopyWindowInfo 按「从前往后」返回屏幕上的窗口,
|
||||
// 第一个 layer==0 的普通窗口就是当前最前面的那个;窗口标题(kCGWindowName)
|
||||
// 只有录到屏权限时才可见,没有权限时退化为只报应用名。
|
||||
ProbeResult ProbeFrontWindow()
|
||||
{
|
||||
ProbeResult r;
|
||||
|
||||
CFArrayRef list = CGWindowListCopyWindowInfo(
|
||||
kCGWindowListOptionOnScreenOnly | kCGWindowListExcludeDesktopElements,
|
||||
kCGNullWindowID);
|
||||
if (list == nullptr) return r;
|
||||
|
||||
const CFIndex count = CFArrayGetCount(list);
|
||||
for (CFIndex i = 0; i < count; ++i) {
|
||||
CFDictionaryRef window = (CFDictionaryRef)CFArrayGetValueAtIndex(list, i);
|
||||
|
||||
// 菜单栏/停靠栏/悬浮层都不是「用户在用的窗口」
|
||||
int layer = 0;
|
||||
CFNumberRef layerRef = (CFNumberRef)CFDictionaryGetValue(window, kCGWindowLayer);
|
||||
if (layerRef) CFNumberGetValue(layerRef, kCFNumberIntType, &layer);
|
||||
if (layer != 0) continue;
|
||||
|
||||
// 跳过本进程自己的窗口(客户端没有界面,但保险)
|
||||
int ownerPid = 0;
|
||||
CFNumberRef pidRef = (CFNumberRef)CFDictionaryGetValue(window, kCGWindowOwnerPID);
|
||||
if (pidRef) CFNumberGetValue(pidRef, kCFNumberIntType, &ownerPid);
|
||||
if (ownerPid == (int)getpid()) continue;
|
||||
|
||||
std::string owner = CFStrToUtf8((CFStringRef)CFDictionaryGetValue(window, kCGWindowOwnerName));
|
||||
if (owner.empty()) continue; // 无主的系统杂项窗口
|
||||
|
||||
std::string name = CFStrToUtf8((CFStringRef)CFDictionaryGetValue(window, kCGWindowName));
|
||||
|
||||
uint64_t number = 0;
|
||||
CFNumberRef numRef = (CFNumberRef)CFDictionaryGetValue(window, kCGWindowNumber);
|
||||
if (numRef) CFNumberGetValue(numRef, kCFNumberSInt64Type, &number);
|
||||
|
||||
r.id = number ? number : 1;
|
||||
r.title = name.empty() ? owner : owner + " - " + name;
|
||||
break;
|
||||
}
|
||||
|
||||
CFRelease(list);
|
||||
return r;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
MacActivityHistory& MacActivityHistory::Instance()
|
||||
{
|
||||
static MacActivityHistory inst;
|
||||
return inst;
|
||||
}
|
||||
|
||||
std::string MacActivityHistory::EmptyText()
|
||||
{
|
||||
return "[来源] 桌面窗口活动:暂无记录(没有停留超过 5 秒的活动窗口)\n";
|
||||
}
|
||||
|
||||
void MacActivityHistory::Start()
|
||||
{
|
||||
bool expected = false;
|
||||
if (!m_started.compare_exchange_strong(expected, true)) return;
|
||||
m_running = true;
|
||||
try {
|
||||
m_thread = std::thread(&MacActivityHistory::Loop, this);
|
||||
} catch (const std::exception& e) {
|
||||
// 采样是附加功能:线程起不来就降级成「没有历史活动」,别让异常穿过 main
|
||||
// (main.mm 里是裸调用,逃出去就是 std::terminate)。复位后允许再次 Start。
|
||||
m_running = false;
|
||||
m_started.store(false);
|
||||
Mprintf("*** ActivityHistory: failed to start sampler: %s ***\n", e.what());
|
||||
}
|
||||
}
|
||||
|
||||
void MacActivityHistory::Stop()
|
||||
{
|
||||
m_running = false;
|
||||
if (m_thread.joinable()) m_thread.join();
|
||||
m_started.store(false);
|
||||
}
|
||||
|
||||
std::string MacActivityHistory::Dump() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
std::string out;
|
||||
if (!m_curTitle.empty() && m_curDwellSec >= ACTIVITY_MIN_DWELL_SEC)
|
||||
out += FormatWindowRecord(m_curStartTime, m_curTitle, m_curDwellSec) + "\n";
|
||||
for (const auto& rec : m_records)
|
||||
out += rec + "\n";
|
||||
return out;
|
||||
}
|
||||
|
||||
void MacActivityHistory::Loop()
|
||||
{
|
||||
uint64_t lastId = 0;
|
||||
std::string lastTitle, startTime;
|
||||
int dwellSec = 0;
|
||||
|
||||
while (m_running) {
|
||||
ProbeResult p = ProbeFrontWindow();
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
if (p.id == 0 || p.title.empty()) {
|
||||
// 空闲/锁屏/无窗口:结账上一个窗口
|
||||
if (lastId != 0 && dwellSec >= ACTIVITY_MIN_DWELL_SEC)
|
||||
m_records.push_front(FormatWindowRecord(startTime, lastTitle, dwellSec));
|
||||
lastId = 0;
|
||||
lastTitle.clear();
|
||||
dwellSec = 0;
|
||||
} else if (p.id == lastId) {
|
||||
// 同一窗口:标题变了也连续累计(浏览器标签切换标题常变)
|
||||
++dwellSec;
|
||||
lastTitle = p.title;
|
||||
} else {
|
||||
if (lastId != 0 && dwellSec >= ACTIVITY_MIN_DWELL_SEC)
|
||||
m_records.push_front(FormatWindowRecord(startTime, lastTitle, dwellSec));
|
||||
lastId = p.id;
|
||||
lastTitle = p.title;
|
||||
startTime = FormatTimeStamp(std::time(nullptr));
|
||||
dwellSec = 1;
|
||||
}
|
||||
|
||||
while (m_records.size() > ACTIVITY_HISTORY_MAX)
|
||||
m_records.pop_back();
|
||||
|
||||
m_curTitle = lastTitle;
|
||||
m_curStartTime = startTime;
|
||||
m_curDwellSec = dwellSec;
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::seconds(1));
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,8 @@ set(SOURCES
|
||||
../client/TlsChannelLinux.cpp
|
||||
../client/sign_shim_unix.cpp
|
||||
ScreenHandler.mm
|
||||
ScreenPreview.mm
|
||||
ActivityHistory.mm
|
||||
InputHandler.mm
|
||||
SystemManager.mm
|
||||
Permissions.mm
|
||||
|
||||
@@ -10,6 +10,12 @@ public:
|
||||
// Returns true if granted, false otherwise
|
||||
static bool checkScreenCapture();
|
||||
|
||||
// 只查授权状态、不真的抓屏(macOS 10.15+,更早的版本恒为 true)。
|
||||
// 授权看守线程用它轮询:checkScreenCapture() 每调一次就抓一整帧(视网膜屏
|
||||
// 20+ MB),而这里只需要「用户刚在设置里勾上了」这个状态位。它在二进制重签名
|
||||
// 后可能报假阴性 —— 正因如此,启动时的那次检查仍用 checkScreenCapture()。
|
||||
static bool checkScreenCapturePreflight();
|
||||
|
||||
// Request screen recording permission (shows system dialog, macOS 10.15+)
|
||||
static void requestScreenCapture();
|
||||
|
||||
|
||||
@@ -34,6 +34,13 @@ bool Permissions::checkScreenCapture() {
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Permissions::checkScreenCapturePreflight() {
|
||||
if (@available(macOS 10.15, *)) {
|
||||
return CGPreflightScreenCaptureAccess();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void Permissions::requestScreenCapture() {
|
||||
if (@available(macOS 10.15, *)) {
|
||||
// Trigger system permission dialog
|
||||
|
||||
@@ -47,10 +47,59 @@ TLS Transport:
|
||||
If the log says "trust anchor exists but failed to load", the client refuses
|
||||
to connect (fail-closed) until the anchor is fixed or removed.
|
||||
|
||||
Client Log:
|
||||
The controller's host right-click menu ("运行日志") sends COMMAND_QUERY_LOG;
|
||||
the client opens a sub-connection and reports its in-memory log ring
|
||||
(Logger, last 1000 lines) as TOKEN_REPORT_LOG. On macOS Mprintf (as defined
|
||||
by common/logger.h) writes that ring, and Logger mirrors the same line to
|
||||
stderr, so one Mprintf line reads identically in the dialog and in
|
||||
/tmp/ghost.log (same prefix and timestamp); content older than the
|
||||
1000-entry ring exists only in the file. main.mm logs startup, config,
|
||||
permissions, TLS, WS, connection and exit through Mprintf, so those lines
|
||||
are all visible in the dialog. The ObjC helper modules (ScreenHandler /
|
||||
H264Encoder / InputHandler / Permissions) still use NSLog, and the two
|
||||
"=== ghost ... started ===" banners are raw write(2) calls; all of those
|
||||
appear only in /tmp/ghost.log. Mprintf lines also no longer go to Apple's
|
||||
Unified Logging (NSLog in the helpers still does). The MCP tool
|
||||
get_client_log reads that same ring.
|
||||
|
||||
Verify: open "运行日志" for the Mac host; the dialog should show startup
|
||||
lines such as "=== macOS Ghost Client ===", "Config loaded from ...",
|
||||
the permission results, "[TLS] transport on first connect: ...", plus
|
||||
command and heartbeat entries.
|
||||
|
||||
Note: the POSIX client reports a snapshot once per connection (the Windows
|
||||
client keeps pushing increments every 3s). Closing and reopening "运行日志"
|
||||
takes a fresh snapshot.
|
||||
|
||||
Permissions Required:
|
||||
1. Screen Recording - System Settings > Privacy & Security > Screen Recording
|
||||
2. Accessibility - System Settings > Privacy & Security > Accessibility
|
||||
|
||||
Both are TCC grants, and macOS applies them per process: a grant made while
|
||||
the app is running only takes effect after it restarts. install.sh also resets
|
||||
both (tccutil reset) and re-signs the bundle ad-hoc on every install, and a
|
||||
rebuilt binary has a new cdhash, so the old records would not match anyway --
|
||||
expect to re-grant after each update.
|
||||
|
||||
When a permission is missing at startup the client requests both, and starts
|
||||
a watcher that polls CGPreflightScreenCaptureAccess / AXIsProcessTrusted --
|
||||
only for the permission that was actually missing; one that already passed
|
||||
the real capture check is not re-judged by preflight (it can report false
|
||||
negatives after re-signing). Once everything reads granted, the main loop
|
||||
disconnects and launches a fresh process ("Auto-restart: launching a fresh
|
||||
process ..."), so the new process starts with the grants in place: the old
|
||||
"grant one, kill, reopen" round trip twice becomes "tick both boxes and let
|
||||
it restart". The new process logs "(started by the auto-restart after
|
||||
permissions were granted)" at startup, and that line is what the 运行日志
|
||||
dialog shows, because the in-memory ring dies with the old process; the
|
||||
Auto-restart line itself stays in /tmp/ghost.log only. The watcher gives up
|
||||
after 15 minutes, and the auto-restart happens at most once per launch
|
||||
(guarded by GHOST_AUTO_RELAUNCHED), so if something still reports missing,
|
||||
restart manually as before. The restart disconnects first, so the controller
|
||||
sees a clean disconnect and reconnect, but any remote session in progress
|
||||
(screen, terminal, file transfer) is dropped when it happens.
|
||||
|
||||
Features:
|
||||
[x] Screen capture (CGDisplayCreateImage)
|
||||
[x] H264 video encoding (VideoToolbox)
|
||||
|
||||
@@ -128,6 +128,9 @@ private:
|
||||
std::atomic<uint8_t> m_algorithm;
|
||||
std::atomic<int> m_maxFPS;
|
||||
int8_t m_qualityLevel;
|
||||
// Web 端请求下一帧强制 IDR(COMMAND_SCREEN_KEYFRAME_REQ)。只由接收线程置位、
|
||||
// 采集线程消费:编码器实例只在采集线程里创建/销毁,接收线程不能直接碰。
|
||||
std::atomic<bool> m_keyframeRequested{false};
|
||||
|
||||
// Pending resolution change (set by applyQualityLevel, consumed by captureLoop)
|
||||
std::atomic<bool> m_dimensionsChanged{false};
|
||||
|
||||
+52
-3
@@ -17,6 +17,22 @@
|
||||
// Global client ID (calculated in main.mm)
|
||||
extern uint64_t g_myClientID;
|
||||
|
||||
// 质量等级持久化:服务端下发 CMD_QUALITY_LEVEL 时带 persist 位,就是「下次开机还这样」。
|
||||
// 存 NSUserDefaults 而不是 ~/.config/ghost/config.conf——后者由 main.mm 用内存 map 整体
|
||||
// 重写(分组变更会触发),单独往同一个文件写键会被下一次写盘冲掉。
|
||||
static NSString* const kQualityLevelKey = @"GhostQualityLevel";
|
||||
|
||||
// 读上次保存的等级。范围外的值(-2 关闭 / -1 自适应 / 越界)保留原值返回,
|
||||
// 由 applyQualityLevel 决定怎么处理:只有 [0, QUALITY_COUNT) 才会套用配置表。
|
||||
static int8_t loadPersistedQualityLevel()
|
||||
{
|
||||
NSNumber* saved = [[NSUserDefaults standardUserDefaults] objectForKey:kQualityLevelKey];
|
||||
if (!saved) return (int8_t)QUALITY_GOOD;
|
||||
int level = [saved intValue];
|
||||
if (level < QUALITY_DISABLED || level >= QUALITY_COUNT) return (int8_t)QUALITY_GOOD;
|
||||
return (int8_t)level;
|
||||
}
|
||||
|
||||
ScreenHandler::ScreenHandler(IOCPClient* client)
|
||||
: m_client(client)
|
||||
, m_clientID(0)
|
||||
@@ -45,6 +61,10 @@ ScreenHandler::ScreenHandler(IOCPClient* client)
|
||||
// Cache color space (avoid per-frame creation)
|
||||
m_colorSpace = CGColorSpaceCreateDeviceRGB();
|
||||
|
||||
// 上次保存的质量等级(服务端下发的 CMD_QUALITY_LEVEL 带 persist 位时写入)。
|
||||
// 放在构造末尾按普通调用应用一次:此时 m_width==0,尺寸相关分支天然不触发。
|
||||
applyQualityLevel(loadPersistedQualityLevel(), false);
|
||||
|
||||
// Initialize input handler for mouse/keyboard control
|
||||
m_inputHandler = std::make_unique<InputHandler>();
|
||||
if (m_inputHandler->init()) {
|
||||
@@ -498,6 +518,12 @@ void ScreenHandler::OnReceive(uint8_t* data, ULONG size)
|
||||
}
|
||||
break;
|
||||
|
||||
case COMMAND_SCREEN_KEYFRAME_REQ:
|
||||
// Web 屏幕墙恢复/新加入者请求:下一帧强制 IDR,立即重建参考链。
|
||||
// 这里只置标志,由采集线程在下一帧消费(见 sendH264Frame 的调用点)。
|
||||
m_keyframeRequested.store(true);
|
||||
break;
|
||||
|
||||
case COMMAND_SCREEN_SET_CLIPBOARD:
|
||||
// 服务端设置剪贴板: [cmd:1][text:N]
|
||||
if (size > 1) {
|
||||
@@ -626,8 +652,13 @@ void ScreenHandler::applyQualityLevel(int8_t level, bool persist)
|
||||
{
|
||||
m_qualityLevel = level;
|
||||
|
||||
// TODO: persist to config file if needed
|
||||
(void)persist;
|
||||
// 持久化(服务端 CMD_QUALITY_LEVEL 的第 3 字节)。下次启动构造时读回并应用,
|
||||
// 与 Linux 端把 QualityLevel 写进 config 的语义一致。
|
||||
if (persist) {
|
||||
[[NSUserDefaults standardUserDefaults] setInteger:(NSInteger)level forKey:kQualityLevelKey];
|
||||
[[NSUserDefaults standardUserDefaults] synchronize];
|
||||
NSLog(@">>> Quality saved: level=%d", (int)level);
|
||||
}
|
||||
|
||||
if (level == QUALITY_DISABLED) {
|
||||
// Disabled mode: keep current settings
|
||||
@@ -834,6 +865,18 @@ void ScreenHandler::sendDiffFrame()
|
||||
|
||||
void ScreenHandler::sendH264Frame(bool keyframe)
|
||||
{
|
||||
// 强制 IDR 请求在调用点已经 exchange 掉,只有真的把这一帧编出来才算消费成功。
|
||||
// 中途任何提前返回(抓屏失败 / 没连接 / 编码器开不起来 / 编码失败)都把它还回去,
|
||||
// 否则 Web 端要等编码器下一次自然 IDR(最长一个 GOP)才能解出画面。
|
||||
struct RearmOnFailure {
|
||||
std::atomic<bool>& flag;
|
||||
bool force;
|
||||
bool consumed;
|
||||
RearmOnFailure(std::atomic<bool>& f, bool force_)
|
||||
: flag(f), force(force_), consumed(false) {}
|
||||
~RearmOnFailure() { if (force && !consumed) flag.store(true); }
|
||||
} rearm(m_keyframeRequested, keyframe);
|
||||
|
||||
if (!captureScreen(m_currFrame)) return;
|
||||
if (!m_client) return;
|
||||
|
||||
@@ -900,6 +943,7 @@ void ScreenHandler::sendH264Frame(bool keyframe)
|
||||
memcpy(&packet[headerSize], encodedData, encodedSize);
|
||||
|
||||
m_client->Send2Server((char*)packet.data(), packet.size());
|
||||
rearm.consumed = true;
|
||||
}
|
||||
|
||||
uint32_t ScreenHandler::compareBitmap(const uint8_t* curr, const uint8_t* prev,
|
||||
@@ -1214,8 +1258,12 @@ void ScreenHandler::captureLoop()
|
||||
currentAlgo = algo;
|
||||
|
||||
if (algo == ALGORITHM_H264) {
|
||||
// 这一帧本身就是关键帧:挂起的强制 IDR 请求顺手清掉,别下一帧再打一次
|
||||
m_keyframeRequested.store(false);
|
||||
sendH264Frame(true); // First H264 frame is keyframe
|
||||
} else {
|
||||
// 非 H264 时关键帧请求没有意义,顺手清掉,免得切回 H264 时白打一次 IDR
|
||||
m_keyframeRequested.store(false);
|
||||
if (m_h264Encoder) {
|
||||
m_h264Encoder->close();
|
||||
m_h264Encoder.reset();
|
||||
@@ -1224,7 +1272,8 @@ void ScreenHandler::captureLoop()
|
||||
}
|
||||
} else {
|
||||
if (algo == ALGORITHM_H264) {
|
||||
sendH264Frame(false);
|
||||
// 服务端的强制 IDR 请求在这里消费:下一帧就是关键帧。
|
||||
sendH264Frame(m_keyframeRequested.exchange(false));
|
||||
} else {
|
||||
sendDiffFrame();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
#pragma once
|
||||
// 屏幕预览(COMMAND_SCREEN_PREVIEW_REQ)—— macOS 端一次性抓屏
|
||||
//
|
||||
// 与 linux/ScreenPreview.h、Windows 端 client/ScreenPreview.h 对应:服务端双击在线主机
|
||||
// 时索取一张缩略图。macOS 没有可依赖的 JPEG 编码库(ImageIO 能编,但走的是另一套
|
||||
// 颜色/尺寸语义,与 Windows 的 GDI+ 输出不一致),所以这里只做 抓屏 → 等比缩放 →
|
||||
// BGRA 原始像素,由服务端在 IO 线程统一编码成 JPEG(下游只认 JPEG 一种格式)。
|
||||
#include <vector>
|
||||
|
||||
class ScreenPreview
|
||||
{
|
||||
public:
|
||||
// 本机当前能否截图:有主显示器且已授予录屏权限。
|
||||
// 服务端按 CLIENT_CAP_SCREEN_PREVIEW 决定要不要下发预览请求,能力位就取自它。
|
||||
static bool IsAvailable();
|
||||
|
||||
// 抓主屏并等比缩放到 maxWidth 以内(不放大、高不超过 1080),返回 ScreenPreviewStatus。
|
||||
// out 为自上而下逐行、每像素 B,G,R,X 四字节(X=0xFF),无行首填充。
|
||||
static int Capture(int maxWidth, std::vector<unsigned char>& out, int& outW, int& outH);
|
||||
};
|
||||
@@ -0,0 +1,101 @@
|
||||
#import "ScreenPreview.h"
|
||||
#import "Permissions.h"
|
||||
#import <CoreGraphics/CoreGraphics.h>
|
||||
|
||||
#include "../common/commands.h" // ScreenPreviewStatus / SCREEN_PREVIEW_FMT_BGRX
|
||||
|
||||
#include <cstddef>
|
||||
|
||||
namespace {
|
||||
|
||||
// 目标尺寸:与 Linux/Windows 端同一套规则——等比缩到 maxWidth 以内(不放大),
|
||||
// 高度再压到 1080(竖屏/超宽屏的原始像素包会大到没意义),宽高取偶数。
|
||||
bool ComputeTargetSize(int sw, int sh, int maxWidth, int& tw, int& th)
|
||||
{
|
||||
if (sw <= 0 || sh <= 0) return false;
|
||||
tw = sw;
|
||||
th = sh;
|
||||
if (tw > maxWidth) {
|
||||
th = (int)((long long)sh * maxWidth / sw);
|
||||
tw = maxWidth;
|
||||
}
|
||||
if (th > 1080) {
|
||||
tw = (int)((long long)tw * 1080 / th);
|
||||
th = 1080;
|
||||
}
|
||||
tw &= ~1;
|
||||
th &= ~1;
|
||||
if (tw < 2) tw = 2;
|
||||
if (th < 2) th = 2;
|
||||
if (tw > sw) tw = sw;
|
||||
if (th > sh) th = sh;
|
||||
return tw > 0 && th > 0;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool ScreenPreview::IsAvailable()
|
||||
{
|
||||
// 没有录屏授权时 CGDisplayCreateImage 仍然会返回一张图(macOS 15 起是壁纸 +
|
||||
// 窗口占位),看起来"成功"却什么都看不到,所以不能只靠试抓一次。
|
||||
if (CGMainDisplayID() == 0) return false;
|
||||
// 预检只读 TCC 状态位,ad-hoc 重签之后可能假阴性;启动时的授权判定因此用的是
|
||||
// 真抓一帧(Permissions::checkScreenCapture)。这里两者取或:宁可多发几次注定
|
||||
// 失败的预览请求,也不要出现「远程能看屏、get_screenshot 却一直 -32005」。
|
||||
return Permissions::checkScreenCapturePreflight() || Permissions::checkScreenCapture();
|
||||
}
|
||||
|
||||
int ScreenPreview::Capture(int maxWidth, std::vector<unsigned char>& out, int& outW, int& outH)
|
||||
{
|
||||
outW = 0;
|
||||
outH = 0;
|
||||
out.clear();
|
||||
|
||||
// 与 Linux 端一致:上限防滥用,下限防止 1 像素宽的退化请求
|
||||
if (maxWidth < 64) maxWidth = 64;
|
||||
if (maxWidth > 1920) maxWidth = 1920;
|
||||
|
||||
const CGDirectDisplayID display = CGMainDisplayID();
|
||||
if (display == 0) return SCREEN_PREVIEW_NOT_SUPPORTED;
|
||||
|
||||
const int sw = (int)CGDisplayPixelsWide(display);
|
||||
const int sh = (int)CGDisplayPixelsHigh(display);
|
||||
int tw = 0, th = 0;
|
||||
if (!ComputeTargetSize(sw, sh, maxWidth, tw, th)) return SCREEN_PREVIEW_CAPTURE_FAILED;
|
||||
|
||||
// CGDisplayCreateImage 从 macOS 14 起标记废弃(官方推荐 ScreenCaptureKit 的异步
|
||||
// SCScreenshotManager),但没有删除;一次几十毫秒的抓图用异步 API 要额外起 run loop,
|
||||
// 不划算。这里显式压掉废弃告警,并在构建机升级到真正移除该 API 时再换实现。
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
|
||||
CGImageRef image = CGDisplayCreateImage(display);
|
||||
#pragma clang diagnostic pop
|
||||
if (image == nullptr) return SCREEN_PREVIEW_CAPTURE_FAILED;
|
||||
|
||||
// kCGImageAlphaNoneSkipFirst + 32Little 在内存里就是 B,G,R,X 的字节序,与协议里
|
||||
// SCREEN_PREVIEW_FMT_BGRX 的定义一致;缩放交给 CoreGraphics 在绘制时完成。
|
||||
const size_t stride = (size_t)tw * 4;
|
||||
out.resize(stride * (size_t)th);
|
||||
CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB();
|
||||
CGContextRef ctx = CGBitmapContextCreate(out.data(), (size_t)tw, (size_t)th, 8, stride, cs,
|
||||
kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Little);
|
||||
CGColorSpaceRelease(cs);
|
||||
if (ctx == nullptr) {
|
||||
CGImageRelease(image);
|
||||
out.clear();
|
||||
return SCREEN_PREVIEW_CAPTURE_FAILED;
|
||||
}
|
||||
|
||||
CGContextSetInterpolationQuality(ctx, kCGInterpolationMedium);
|
||||
CGContextSetShouldAntialias(ctx, false);
|
||||
CGContextDrawImage(ctx, CGRectMake(0, 0, tw, th), image);
|
||||
CGContextRelease(ctx);
|
||||
CGImageRelease(image);
|
||||
|
||||
// Alpha 字节协议要求 0xFF;kCGImageAlphaNoneSkipFirst 不会写它
|
||||
for (size_t i = 3; i < out.size(); i += 4) out[i] = 0xFF;
|
||||
|
||||
outW = tw;
|
||||
outH = th;
|
||||
return SCREEN_PREVIEW_OK;
|
||||
}
|
||||
+28
-21
@@ -1,40 +1,47 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <sys/types.h>
|
||||
|
||||
// Forward declaration
|
||||
class IOCPClient;
|
||||
// IOCPManager / IOCPClient / PBYTE / ULONG 来自这里;本类必须派生 IOCPManager,
|
||||
// 见下方注释。Mprintf 由 common/logger.h 提供(本类的日志要进「运行日志」的 ring)。
|
||||
#include "../client/IOCPClient.h"
|
||||
#include "../common/logger.h"
|
||||
|
||||
class SystemManager {
|
||||
// ============== macOS 进程管理 ==============
|
||||
// 与 Linux 端(linux/SystemManager.h)同一套 wire 格式:主连接收到 COMMAND_SYSTEM 后,
|
||||
// 客户端另起一条「系统子连接」,本类只在这条子连接上收发:
|
||||
// COMMAND_PSLIST → TOKEN_PSLIST
|
||||
// COMMAND_KILLPROCESS → kill(2) 后补发一次 TOKEN_PSLIST
|
||||
// COMMAND_WSLIST → TOKEN_WSLIST
|
||||
//
|
||||
// 两个约束都是子连接骨架(common/sub_conn_thread.h)定死的:
|
||||
// 1. 必须派生 IOCPManager —— 骨架装的回调是 IOCPManager::DataProcess,它把 user
|
||||
// 强转成 IOCPManager* 再调虚函数 OnReceive;普通类装上去会直接崩。
|
||||
// 2. 构造函数必须只收 IOCPClient* —— 骨架的 createHandler 契约是
|
||||
// std::unique_ptr<T>(IOCPClient*)。
|
||||
// 这也解释了它以前为什么是死代码:签名对不上骨架,一直没被实例化,
|
||||
// main.mm 的 COMMAND_SYSTEM 只打了一行日志。
|
||||
class SystemManager : public IOCPManager
|
||||
{
|
||||
public:
|
||||
SystemManager(IOCPClient* client, uint64_t clientID);
|
||||
~SystemManager();
|
||||
explicit SystemManager(IOCPClient* client);
|
||||
~SystemManager() override {}
|
||||
|
||||
// Handle commands from server
|
||||
void onReceive(const uint8_t* data, size_t size);
|
||||
virtual VOID OnReceive(PBYTE szBuffer, ULONG ulLength) override;
|
||||
|
||||
private:
|
||||
// Send process list to server
|
||||
// 发送完整进程列表(构造时立即发一次,服务端据此判定子连接就绪)
|
||||
void sendProcessList();
|
||||
|
||||
// Kill processes by PID
|
||||
// 终止进程:载荷是若干个 4 字节 PID(与 Windows/Linux 一致)
|
||||
void killProcesses(const uint8_t* data, size_t size);
|
||||
|
||||
// Send window list (limited on macOS without accessibility)
|
||||
// 窗口列表:macOS 只能给「有可见窗口的应用」的伪句柄(PID)+ 应用名
|
||||
void sendWindowsList();
|
||||
|
||||
// Get process name by PID
|
||||
static std::string getProcessName(pid_t pid);
|
||||
|
||||
// Get process executable path by PID
|
||||
static std::string getProcessPath(pid_t pid);
|
||||
|
||||
// Get all running PIDs
|
||||
static std::vector<pid_t> getAllPids();
|
||||
|
||||
private:
|
||||
IOCPClient* m_client;
|
||||
uint64_t m_clientID;
|
||||
};
|
||||
+30
-32
@@ -4,34 +4,30 @@
|
||||
#import <sys/sysctl.h>
|
||||
#import <libproc.h>
|
||||
#import <signal.h>
|
||||
#import <unistd.h>
|
||||
#include <cstring> // memcpy / strlen / memset
|
||||
#include <unistd.h>
|
||||
|
||||
SystemManager::SystemManager(IOCPClient* client, uint64_t clientID)
|
||||
SystemManager::SystemManager(IOCPClient* client)
|
||||
: m_client(client)
|
||||
, m_clientID(clientID)
|
||||
{
|
||||
// Send initial process list on connection
|
||||
// 与 Windows/Linux 端一致:构造时立即发送进程列表。服务端把这条首包当作
|
||||
// 「系统子连接已就绪」,kill_process / list_processes 都在等它。
|
||||
sendProcessList();
|
||||
}
|
||||
|
||||
SystemManager::~SystemManager()
|
||||
void SystemManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
{
|
||||
}
|
||||
if (!szBuffer || ulLength == 0) return;
|
||||
|
||||
void SystemManager::onReceive(const uint8_t* data, size_t size)
|
||||
{
|
||||
if (!data || size == 0) return;
|
||||
|
||||
switch (data[0]) {
|
||||
switch (szBuffer[0]) {
|
||||
case COMMAND_PSLIST:
|
||||
sendProcessList();
|
||||
break;
|
||||
|
||||
case COMMAND_KILLPROCESS:
|
||||
if (size > 1) {
|
||||
killProcesses(data + 1, size - 1);
|
||||
if (ulLength > 1) {
|
||||
killProcesses(szBuffer + 1, ulLength - 1);
|
||||
// Refresh list after kill
|
||||
usleep(100000); // 100ms wait
|
||||
sendProcessList();
|
||||
}
|
||||
break;
|
||||
@@ -41,12 +37,12 @@ void SystemManager::onReceive(const uint8_t* data, size_t size)
|
||||
break;
|
||||
|
||||
default:
|
||||
NSLog(@"SystemManager: Unknown command: %d", (int)data[0]);
|
||||
Mprintf("[SystemManager] Unknown sub-command: %d\n", (int)szBuffer[0]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<pid_t> SystemManager::getAllPids()
|
||||
static std::vector<pid_t> getAllPids()
|
||||
{
|
||||
std::vector<pid_t> pids;
|
||||
|
||||
@@ -54,8 +50,8 @@ std::vector<pid_t> SystemManager::getAllPids()
|
||||
int count = proc_listpids(PROC_ALL_PIDS, 0, NULL, 0);
|
||||
if (count <= 0) return pids;
|
||||
|
||||
// Allocate buffer for PIDs
|
||||
std::vector<pid_t> buffer(count * 2); // Extra space for new processes
|
||||
// Allocate buffer for PIDs (double the size: processes may spawn in between)
|
||||
std::vector<pid_t> buffer(count * 2);
|
||||
count = proc_listpids(PROC_ALL_PIDS, 0, buffer.data(), (int)(buffer.size() * sizeof(pid_t)));
|
||||
if (count <= 0) return pids;
|
||||
|
||||
@@ -69,7 +65,7 @@ std::vector<pid_t> SystemManager::getAllPids()
|
||||
return pids;
|
||||
}
|
||||
|
||||
std::string SystemManager::getProcessName(pid_t pid)
|
||||
static std::string getProcessName(pid_t pid)
|
||||
{
|
||||
char name[PROC_PIDPATHINFO_MAXSIZE];
|
||||
memset(name, 0, sizeof(name));
|
||||
@@ -82,7 +78,7 @@ std::string SystemManager::getProcessName(pid_t pid)
|
||||
return "";
|
||||
}
|
||||
|
||||
std::string SystemManager::getProcessPath(pid_t pid)
|
||||
static std::string getProcessPath(pid_t pid)
|
||||
{
|
||||
char path[PROC_PIDPATHINFO_MAXSIZE];
|
||||
memset(path, 0, sizeof(path));
|
||||
@@ -112,6 +108,7 @@ void SystemManager::sendProcessList()
|
||||
#endif
|
||||
|
||||
std::vector<pid_t> pids = getAllPids();
|
||||
size_t sent = 0;
|
||||
|
||||
for (pid_t pid : pids) {
|
||||
if (pid <= 0) continue;
|
||||
@@ -139,29 +136,31 @@ void SystemManager::sendProcessList()
|
||||
// Write fullPath (null-terminated)
|
||||
buf.insert(buf.end(), path.begin(), path.end());
|
||||
buf.push_back(0);
|
||||
++sent;
|
||||
}
|
||||
|
||||
m_client->Send2Server((char*)buf.data(), buf.size());
|
||||
NSLog(@"SystemManager SendProcessList: %zu bytes, %zu processes",
|
||||
buf.size(), pids.size());
|
||||
m_client->Send2Server((char*)buf.data(), (ULONG)buf.size());
|
||||
Mprintf("[SystemManager] SendProcessList: %zu bytes, %zu processes\n", buf.size(), sent);
|
||||
}
|
||||
|
||||
void SystemManager::killProcesses(const uint8_t* data, size_t size)
|
||||
{
|
||||
// Each PID is 4 bytes (DWORD)
|
||||
// Each PID is 4 bytes (DWORD),与 Windows/Linux 端一致
|
||||
for (size_t i = 0; i + sizeof(uint32_t) <= size; i += sizeof(uint32_t)) {
|
||||
uint32_t dwPid = *(uint32_t*)(data + i);
|
||||
uint32_t dwPid;
|
||||
memcpy(&dwPid, data + i, sizeof(dwPid));
|
||||
pid_t pid = (pid_t)dwPid;
|
||||
|
||||
// Don't allow killing kernel/launchd
|
||||
// Don't allow killing kernel/launchd(launchd 的 pid 是 1)
|
||||
if (pid <= 1) continue;
|
||||
|
||||
// Don't allow killing ourselves
|
||||
if (pid == getpid()) continue;
|
||||
|
||||
int ret = kill(pid, SIGKILL);
|
||||
NSLog(@"SystemManager kill(%d, SIGKILL) = %d", (int)pid, ret);
|
||||
Mprintf("[SystemManager] kill(%d, SIGKILL) = %d\n", (int)pid, ret);
|
||||
}
|
||||
usleep(100000); // 100ms 等待进程退出,之后的列表才不会还把死进程列出来
|
||||
}
|
||||
|
||||
void SystemManager::sendWindowsList()
|
||||
@@ -171,7 +170,8 @@ void SystemManager::sendWindowsList()
|
||||
std::vector<uint8_t> buf;
|
||||
buf.push_back(TOKEN_WSLIST);
|
||||
|
||||
// Get list of running applications
|
||||
// macOS 没有 HWND。这里列「有可见窗口的应用」,句柄位置放 PID 充当伪句柄,
|
||||
// 与 Windows 的 TOKEN_WSLIST 同构(uint64 句柄 + NUL 结尾标题)。
|
||||
NSArray<NSRunningApplication*>* apps = [[NSWorkspace sharedWorkspace] runningApplications];
|
||||
|
||||
for (NSRunningApplication* app in apps) {
|
||||
@@ -185,17 +185,15 @@ void SystemManager::sendWindowsList()
|
||||
|
||||
pid_t pid = app.processIdentifier;
|
||||
|
||||
// Write window handle (use PID as pseudo-handle)
|
||||
uint64_t hwnd = (uint64_t)pid;
|
||||
const uint8_t* p = (const uint8_t*)&hwnd;
|
||||
buf.insert(buf.end(), p, p + sizeof(uint64_t));
|
||||
|
||||
// Write window title (null-terminated)
|
||||
const char* utf8Name = [name UTF8String];
|
||||
buf.insert(buf.end(), utf8Name, utf8Name + strlen(utf8Name));
|
||||
buf.push_back(0);
|
||||
}
|
||||
|
||||
m_client->Send2Server((char*)buf.data(), buf.size());
|
||||
NSLog(@"SystemManager SendWindowsList: %zu bytes", buf.size());
|
||||
m_client->Send2Server((char*)buf.data(), (ULONG)buf.size());
|
||||
Mprintf("[SystemManager] SendWindowsList: %zu bytes\n", buf.size());
|
||||
}
|
||||
+2
-1
@@ -110,7 +110,8 @@ echo "2. 授权以下权限 (在系统设置中勾选 GhostClient):"
|
||||
echo " - 屏幕录制: 允许捕获屏幕画面"
|
||||
echo " - 辅助功能: 允许控制鼠标键盘"
|
||||
echo ""
|
||||
echo "3. 授权后重启应用:"
|
||||
echo "3. 两个都授权后应用会自己重启一次(日志里是 Auto-restart: launching ...),"
|
||||
echo " 一般不用手动操作。若 15 分钟内没等到,手动重启:"
|
||||
echo ""
|
||||
echo " pkill -f GhostClient && open /Applications/GhostClient.app"
|
||||
echo ""
|
||||
|
||||
+397
-31
@@ -7,6 +7,10 @@
|
||||
#import <signal.h>
|
||||
#import <unistd.h>
|
||||
#import <fcntl.h>
|
||||
#import <errno.h>
|
||||
#import <limits.h>
|
||||
#import <pthread.h>
|
||||
#import <sys/wait.h>
|
||||
#import <IOKit/IOKitLib.h>
|
||||
#import <IOKit/pwr_mgt/IOPMLib.h>
|
||||
#import <fstream>
|
||||
@@ -32,12 +36,19 @@
|
||||
#import "ScreenHandler.h"
|
||||
#import "InputHandler.h"
|
||||
#import "SystemManager.h"
|
||||
#import "ScreenPreview.h"
|
||||
#import "ActivityHistory.h"
|
||||
#import "../common/PTYHandler.h"
|
||||
#import "../common/FileManager.h"
|
||||
#import "../common/FileTransferV2.h"
|
||||
#import "../common/logger.h"
|
||||
#import "ClipboardHandler.h"
|
||||
|
||||
// 本文件的运行期日志一律用 Mprintf:它既进内存 ring —— 服务端「运行日志」菜单与
|
||||
// MCP 的 get_client_log 就取这一份 —— 又由 Logger 镜像到 stderr(/tmp/ghost.log)。
|
||||
// NSLog 只会落在文件里、不进 ring,所以启动/配置/权限这些现场最常翻的行不要用
|
||||
// NSLog。(ScreenHandler/H264/InputHandler 等 ObjC 模块里的 NSLog 保持原样。)
|
||||
|
||||
// Global state
|
||||
static std::atomic<bool> g_running(true);
|
||||
static std::atomic<bool> g_needResendLogin(false); // 分组变更后需要重发登录信息
|
||||
@@ -45,10 +56,18 @@ static std::atomic<bool> g_needResendLogin(false); // 分组变更后需要重
|
||||
// DataProcess 跑在接收线程上,直接关 socket 会和主线程的发送竞争,所以只置标志,
|
||||
// 由主心跳循环择机 Disconnect 并重连(与 linux/main.cpp 的 g_needReconnect 同语义)。
|
||||
static std::atomic<bool> g_needReconnect(false);
|
||||
// 权限补齐后要求重启进程(见文件下方的「授权后自动重启」)。只看守线程置位,主循环
|
||||
// 见到它先断开主连接再重启,避免新进程起来时旧连接还挂在服务端。
|
||||
static std::atomic<bool> g_autoRestartPending(false);
|
||||
|
||||
// Client ID (calculated from system info, used by ScreenHandler)
|
||||
uint64_t g_myClientID = 0;
|
||||
|
||||
// 主连接句柄。DataProcess 的 user 参数恒为 NULL,而 V2 C2C 落盘回执
|
||||
// (TOKEN_C2C_RECV_RESULT)要发在主连接上,所以留一个全局指针(同 linux/main.cpp)。
|
||||
// Send2Server 内部持锁,可在工作线程调用;用之前一律先判 IsConnected()。
|
||||
static IOCPClient* g_pMainClient = nullptr;
|
||||
|
||||
// 服务端身份校验全局状态已抽到 common/client_auth_state.h(namespace ClientAuth)
|
||||
|
||||
// 远程地址:当前为写死状态,如需调试,请按实际情况修改
|
||||
@@ -116,14 +135,14 @@ static void saveConfig()
|
||||
|
||||
std::ofstream file(g_configPath, std::ios::trunc);
|
||||
if (!file.is_open()) {
|
||||
NSLog(@"Failed to save config to %s", g_configPath.c_str());
|
||||
Mprintf("Failed to save config to %s\n", g_configPath.c_str());
|
||||
return;
|
||||
}
|
||||
|
||||
for (const auto& kv : g_configData) {
|
||||
file << kv.first << "=" << kv.second << "\n";
|
||||
}
|
||||
NSLog(@"Config saved to %s", g_configPath.c_str());
|
||||
Mprintf("Config saved to %s\n", g_configPath.c_str());
|
||||
}
|
||||
|
||||
// Get config string value
|
||||
@@ -144,7 +163,7 @@ static void setConfigStr(const std::string& key, const std::string& value)
|
||||
static void saveGroupName(const std::string& groupName)
|
||||
{
|
||||
setConfigStr("group_name", groupName);
|
||||
NSLog(@"Group name saved: %s", groupName.c_str());
|
||||
Mprintf("Group name saved: %s\n", groupName.c_str());
|
||||
}
|
||||
|
||||
// Load group name from config file
|
||||
@@ -489,7 +508,7 @@ static std::string getInstallTime()
|
||||
installTime = [NSString stringWithUTF8String:currentTime.c_str()];
|
||||
[defaults setObject:installTime forKey:@"ghost_install_time"];
|
||||
[defaults synchronize];
|
||||
NSLog(@"First run - recorded install time: %@", installTime);
|
||||
Mprintf("First run - recorded install time: %s\n", [installTime UTF8String]);
|
||||
}
|
||||
|
||||
return std::string([installTime UTF8String]);
|
||||
@@ -608,8 +627,8 @@ static void fillLoginInfo(LOGIN_INFOR& info)
|
||||
std::string normPath = normalizeExePathLower(exePath);
|
||||
std::string idInput = machineId + "|" + normPath;
|
||||
g_myClientID = XXH64(idInput.c_str(), idInput.length(), 0);
|
||||
NSLog(@"ClientID(v2): %llu (machineId=%s, path=%s)",
|
||||
g_myClientID, machineId.c_str(), normPath.c_str());
|
||||
Mprintf("ClientID(v2): %llu (machineId=%s, path=%s)\n",
|
||||
g_myClientID, machineId.c_str(), normPath.c_str());
|
||||
} else {
|
||||
// 老算法兜底
|
||||
char cpuStr[32];
|
||||
@@ -620,7 +639,7 @@ static void fillLoginInfo(LOGIN_INFOR& info)
|
||||
cpuStr + "|" +
|
||||
exePath;
|
||||
g_myClientID = XXH64(idInput.c_str(), idInput.length(), 0);
|
||||
NSLog(@"ClientID(v1 fallback): %llu (IOPlatformUUID 读取失败)", g_myClientID);
|
||||
Mprintf("ClientID(v1 fallback): %llu (IOPlatformUUID 读取失败)\n", g_myClientID);
|
||||
}
|
||||
info.AddReserved(std::to_string(g_myClientID).c_str());
|
||||
|
||||
@@ -637,8 +656,8 @@ static void fillLoginInfo(LOGIN_INFOR& info)
|
||||
// 服务端签名输入:与服务端 AddList 处签名格式一致(startTime + "|" + clientID)
|
||||
ClientAuth::g_loginMsg = std::string(info.szStartTime) + "|" + std::to_string(g_myClientID);
|
||||
|
||||
NSLog(@"LOGIN_INFOR filled: OS=%s, Host=%s, CPU=%dMHz, PubIP=%s, ClientID=%llu",
|
||||
osVer.c_str(), hostname.c_str(), info.dwCPUMHz, pubIP.c_str(), g_myClientID);
|
||||
Mprintf("LOGIN_INFOR filled: OS=%s, Host=%s, CPU=%dMHz, PubIP=%s, ClientID=%llu\n",
|
||||
osVer.c_str(), hostname.c_str(), info.dwCPUMHz, pubIP.c_str(), g_myClientID);
|
||||
}
|
||||
|
||||
// [[19] RES_TLS] 是「当前」传输状态的快照,服务端在线列表的 TLS 列就取这个值。
|
||||
@@ -674,6 +693,18 @@ static void RefreshLoginTls(LOGIN_INFOR& info)
|
||||
info.szReserved[sizeof(info.szReserved) - 1] = '\0';
|
||||
}
|
||||
|
||||
// 能力位(moduleVersion 的 "-%04X" 后缀)里唯一依赖运行环境的是屏幕预览:
|
||||
// 只有本机已授予录屏权限时才声明,否则服务端会一直要缩略图、每次都要等超时降级。
|
||||
// 与 RefreshLoginTls 一样只在主线程登录前调用,每次重连都会重新判断。
|
||||
static void RefreshLoginCaps(LOGIN_INFOR& info)
|
||||
{
|
||||
unsigned int caps = LOGIN_INFOR::DefaultCaps();
|
||||
if (ScreenPreview::IsAvailable()) {
|
||||
caps |= CLIENT_CAP_SCREEN_PREVIEW;
|
||||
}
|
||||
info.SetCaps(caps);
|
||||
}
|
||||
|
||||
// ============== Signal Handling ==============
|
||||
|
||||
// 注意:signal handler 内不能调 NSLog/Mprintf(NSLog 走 Foundation 锁,
|
||||
@@ -696,6 +727,10 @@ static void setupSignals()
|
||||
}
|
||||
|
||||
// 经典 Unix 双 fork 守护进程
|
||||
//
|
||||
// 必须早于任何 Mprintf:Logger 单例在首次 Mprintf 时创建并启动刷盘线程,fork 之后
|
||||
// 子进程里那条线程并不存在(这里 enable=false 不刷盘,ring 与 stderr 镜像照常,
|
||||
// 但别把第一条 Mprintf 挪到本函数之前)。
|
||||
static void daemonize()
|
||||
{
|
||||
// macOS 10.12+ NSLog 默认只写 os_log(Unified Logging),非 TTY 时不写 stderr。
|
||||
@@ -741,6 +776,163 @@ static void daemonize()
|
||||
}
|
||||
}
|
||||
|
||||
// ============== 授权后自动重启 ==============
|
||||
//
|
||||
// macOS 的 TCC 授权对每个进程只算一次:屏幕录制由 WindowServer 按进程缓存,无障碍
|
||||
// 的输入注入也是按进程判定的。用户在「系统设置」里勾上之后,当前进程仍然拿不到,
|
||||
// 必须重新启动;install.sh 每次安装又会 tccutil reset 并重新 ad-hoc 签名(binary
|
||||
// 一变 cdhash 就变,旧记录本来也对不上),所以每次更新都要重新授权。
|
||||
//
|
||||
// 这里把「勾选 → 手动杀掉 → 重新打开」压成「勾两下,应用自己重启一次」:启动时只要
|
||||
// 缺任一权限,就起一个看守线程轮询;补齐后置 g_autoRestartPending,由主循环断开主连接
|
||||
// 再拉起一个**新进程**(RelaunchSelf,不是原地 execv),新进程就是带着授权起来的。
|
||||
//
|
||||
// 为什么用新进程而不是原地 execv:
|
||||
// · TCC 按进程判定,新 pid / 新 audit token 一定重新评估,不赌 exec 会不会刷新缓存;
|
||||
// · 子进程在 exec 前关掉 3 以上的所有 fd,旧的主连接/子连接 socket 不会被带进新
|
||||
// 镜像 —— 否则服务端会一直把一条已经没人读的连接当成在线主机,新登录被排进
|
||||
// standby,要等心跳超时才顶上来。
|
||||
//
|
||||
// 轮询用 CGPreflightScreenCaptureAccess(Permissions::checkScreenCapturePreflight),
|
||||
// 不用 checkScreenCapture():后者每次真的抓一整帧(视网膜屏 20+ MB),而这里要的只是
|
||||
// 「用户刚勾上」这个状态位。而且只对启动时**确实缺**的那一项轮询:启动时已经用真抓一帧
|
||||
// 证明可用的录屏权限不再看 preflight —— 它重签名后会假阴性(见 Permissions.mm),
|
||||
// 真拿它当门槛会让「录屏本来就好、只差无障碍」的场景永远等不到重启。
|
||||
//
|
||||
// 防重启循环:exec 前置 GHOST_AUTO_RELAUNCHED=1,新进程看到它就不再起看守线程,
|
||||
// 每次启动最多自动重启一次。
|
||||
static char** g_relaunchArgv = nullptr;
|
||||
static bool g_permNeedScreen = false; // 启动时确实缺录屏权限(起线程前置好)
|
||||
static bool g_permNeedAx = false;
|
||||
|
||||
static bool RelaunchSelf()
|
||||
{
|
||||
std::string selfPath = getExecutablePath();
|
||||
if (selfPath.empty()) {
|
||||
Mprintf("Auto-restart skipped: cannot resolve the executable path\n");
|
||||
return false;
|
||||
}
|
||||
char resolved[PATH_MAX] = {};
|
||||
const char* exe = realpath(selfPath.c_str(), resolved) ? resolved : selfPath.c_str();
|
||||
|
||||
setenv("GHOST_AUTO_RELAUNCHED", "1", 1);
|
||||
Mprintf("Auto-restart: launching a fresh process (%s)\n", exe);
|
||||
fflush(NULL);
|
||||
|
||||
pid_t pid = fork();
|
||||
if (pid < 0) {
|
||||
Mprintf("Auto-restart failed: fork() errno=%d\n", errno);
|
||||
unsetenv("GHOST_AUTO_RELAUNCHED");
|
||||
return false;
|
||||
}
|
||||
if (pid == 0) {
|
||||
// 子进程:多线程进程 fork 之后只能调用 async-signal-safe 的函数。
|
||||
// 关掉父进程除 0/1/2 外的所有 fd(旧连接 socket 都在其中),新镜像会自己
|
||||
// 重新打开 /tmp/ghost.log。exec 失败以 127 退出,让父进程知道要留下来。
|
||||
long maxfd = sysconf(_SC_OPEN_MAX);
|
||||
if (maxfd < 0 || maxfd > 65536) maxfd = 65536;
|
||||
for (long fd = 3; fd < maxfd; ++fd) close((int)fd);
|
||||
execv(exe, g_relaunchArgv);
|
||||
_exit(127);
|
||||
}
|
||||
|
||||
// 父进程:等子进程交出结果。成功的子进程不会退出;daemon 模式下 exec 后的镜像会
|
||||
// 以 0 退出、把守护进程交给它再 fork 出来的孙进程。失败的样子有好几种,一律当失败
|
||||
// 并保留当前进程 —— 不能因为换进程失败把客户端弄丢:
|
||||
// · execv 失败(127);
|
||||
// · AMFI 因签名不符 SIGKILL(install.sh 的注释里就写了这个场景:服务端 patch 过
|
||||
// 地址的 binary 必须先重签,没签的那份一 exec 就被内核杀掉);
|
||||
// · dyld 装载失败 / 静态初始化期崩溃(SIGABRT 等);
|
||||
// · daemonize() 的 fork 失败(exit(1))。
|
||||
// 交接 1 秒之后才发生的崩溃看不到,这是换进程本身的上限。
|
||||
int status = 0;
|
||||
bool handoffFailed = false;
|
||||
for (int i = 0; i < 200; ++i) {
|
||||
pid_t r = waitpid(pid, &status, WNOHANG);
|
||||
if (r == pid) {
|
||||
handoffFailed = WIFSIGNALED(status) || (WIFEXITED(status) && WEXITSTATUS(status) != 0);
|
||||
break;
|
||||
}
|
||||
Sleep(5);
|
||||
}
|
||||
|
||||
// 交接的这 1 秒里如果收到了停止请求(信号、Activity Monitor 里退出、服务端
|
||||
// COMMAND_BYE),新进程并不知道这件事,会把刚退出的客户端又拉起来。收掉子进程,
|
||||
// 让退出照常完成。
|
||||
if (!g_running) {
|
||||
Mprintf("Auto-restart cancelled: shutdown was requested while starting the new process\n");
|
||||
if (kill(pid, SIGTERM) == 0) {
|
||||
bool reaped = false;
|
||||
for (int i = 0; i < 200 && !reaped; ++i) {
|
||||
int st = 0;
|
||||
if (waitpid(pid, &st, WNOHANG) == pid) reaped = true;
|
||||
else Sleep(5);
|
||||
}
|
||||
if (!reaped) {
|
||||
kill(pid, SIGKILL);
|
||||
waitpid(pid, NULL, 0);
|
||||
}
|
||||
}
|
||||
unsetenv("GHOST_AUTO_RELAUNCHED");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (handoffFailed) {
|
||||
if (WIFEXITED(status) && WEXITSTATUS(status) == 127) {
|
||||
Mprintf("Auto-restart failed: the new process could not exec %s\n", exe);
|
||||
} else if (WIFSIGNALED(status)) {
|
||||
Mprintf("Auto-restart failed: the new process was killed by signal %d during startup\n",
|
||||
WTERMSIG(status));
|
||||
} else {
|
||||
Mprintf("Auto-restart failed: the new process exited with %d during startup\n",
|
||||
WEXITSTATUS(status));
|
||||
}
|
||||
unsetenv("GHOST_AUTO_RELAUNCHED");
|
||||
return false;
|
||||
}
|
||||
|
||||
Mprintf("Auto-restart: handing over to the new process\n");
|
||||
_exit(0);
|
||||
return false; // 不可达
|
||||
}
|
||||
|
||||
// 看守线程:等启动时缺的权限补齐,然后请主循环重启(重启本身在主线程里做)。
|
||||
static void* PermissionWatcherThread(void* /*param*/)
|
||||
{
|
||||
const bool needScreen = g_permNeedScreen;
|
||||
const bool needAx = g_permNeedAx;
|
||||
|
||||
if (needScreen && needAx) {
|
||||
Mprintf("Permission watcher: waiting for screen recording and accessibility...\n");
|
||||
} else if (needScreen) {
|
||||
Mprintf("Permission watcher: waiting for screen recording...\n");
|
||||
} else {
|
||||
Mprintf("Permission watcher: waiting for accessibility...\n");
|
||||
}
|
||||
|
||||
const int kMaxWaitSec = 15 * 60;
|
||||
for (int waited = 0; g_running && !g_autoRestartPending && waited < kMaxWaitSec; ++waited) {
|
||||
const bool screenOk = !needScreen || Permissions::checkScreenCapturePreflight();
|
||||
const bool axOk = !needAx || Permissions::checkAccessibility();
|
||||
if (screenOk && axOk) {
|
||||
Mprintf("Permissions are granted; asking the main loop to restart\n");
|
||||
g_autoRestartPending = true;
|
||||
return NULL;
|
||||
}
|
||||
if (waited % 30 == 0) {
|
||||
Mprintf("Permission watcher: still waiting (%ds): screen=%s, accessibility=%s\n",
|
||||
waited, screenOk ? "granted" : "missing", axOk ? "granted" : "missing");
|
||||
}
|
||||
Sleep(1000);
|
||||
}
|
||||
|
||||
if (g_running && !g_autoRestartPending) {
|
||||
Mprintf("Permission watcher: gave up after %ds; restart the app once permissions are granted\n",
|
||||
kMaxWaitSec);
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// ============== Main Entry Point ==============
|
||||
// RttEstimator + g_rttEstimator + g_heartbeatInterval 已抽到 common/rtt_estimator.h
|
||||
|
||||
@@ -790,6 +982,19 @@ void* FileManagerworkingThread(void* /*param*/)
|
||||
return NULL;
|
||||
}
|
||||
|
||||
void* SystemManagerworkingThread(void* /*param*/)
|
||||
{
|
||||
// 进程/窗口子连接。SystemManager 的构造函数会把首包 TOKEN_PSLIST 发出去,
|
||||
// 服务端据此判定「系统子连接就绪」(kill_process 的确认包也靠它)。
|
||||
RunSubConnThread<SystemManager>(
|
||||
"SystemManagerworkingThread",
|
||||
[](IOCPClient* c) { return std::unique_ptr<SystemManager>(new SystemManager(c)); },
|
||||
[](IOCPClient* c, SystemManager*) {
|
||||
Mprintf(">>> SystemManagerworkingThread [%p] initialized\n", c);
|
||||
});
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// 日志上报(对应 Windows 端 CClientLogManager):子连接建立即发首包全量。
|
||||
// 服务端取走首包后会关掉这条子连接,发完等连接断开即可。
|
||||
void* ClientLogworkingThread(void* /*param*/)
|
||||
@@ -811,7 +1016,9 @@ void* ClientLogworkingThread(void* /*param*/)
|
||||
// std::system_error,异常会穿过 DataProcess 落到 OnServerReceiving 的 catch(...),
|
||||
// 客户端日志里只剩一行笼统的 "[ERROR] OnServerReceiving catch an error":
|
||||
// 「点了终端/桌面/文件毫无反应,而且连一条收到命令的日志都没有」正是这样产生的
|
||||
// ——坏的三个功能恰好全都 spawn 线程,好的 SYSTEM/WSLIST 恰好都不 spawn。
|
||||
// ——坏的三个功能恰好全都 spawn 线程,好的 SYSTEM(当时只打日志)/WSLIST 恰好都不 spawn。
|
||||
// 后来 COMMAND_SYSTEM 也接上了子连接(SystemManagerworkingThread),这条历史注释保留
|
||||
// 是为了说明「线程创建失败会让功能看起来毫无反应」这个坑。
|
||||
static void SpawnSubConnWorker(const char* name, void* (*entry)(void*))
|
||||
{
|
||||
Mprintf("** Received '%s' command, spawning worker ***\n", name);
|
||||
@@ -850,6 +1057,73 @@ static void ApplyTlsAnchorChange(void* user)
|
||||
user, after ? "TLS" : "plaintext");
|
||||
}
|
||||
|
||||
// ============== 屏幕预览(COMMAND_SCREEN_PREVIEW_REQ) ==============
|
||||
// 同一时刻只跑一个抓屏任务:列表缩略图是周期性刷新,服务端还可能重发/并发请求,
|
||||
// 多余的直接丢弃,让服务端超时后按「预览不可用」降级(与 Linux 端限流一致)。
|
||||
static std::atomic<int> g_previewInFlight(0);
|
||||
|
||||
static void ScreenPreviewThread(ScreenPreviewReq req)
|
||||
{
|
||||
// 抓屏/缩放全程可能在几十毫秒量级,跑在独立线程里,不阻塞接收线程
|
||||
struct InFlightGuard {
|
||||
~InFlightGuard() { g_previewInFlight.fetch_sub(1); }
|
||||
} guard;
|
||||
|
||||
std::vector<unsigned char> pixels;
|
||||
int w = 0, h = 0;
|
||||
int st = ScreenPreview::Capture(req.maxWidth, pixels, w, h);
|
||||
bool ok = (st == SCREEN_PREVIEW_OK) && !pixels.empty();
|
||||
if (!ok) pixels.clear();
|
||||
|
||||
uint32_t bytes = ok ? (uint32_t)pixels.size() : 0;
|
||||
std::vector<char> pkt(sizeof(ScreenPreviewRspHeader) + bytes);
|
||||
ScreenPreviewRspHeader* hdr = (ScreenPreviewRspHeader*)pkt.data();
|
||||
memset(hdr, 0, sizeof(*hdr));
|
||||
hdr->token = TOKEN_SCREEN_PREVIEW_RSP;
|
||||
hdr->reqId = req.reqId;
|
||||
hdr->status = (uint8_t)st;
|
||||
// 成功时发原始 BGRA,由服务端统一编码成 JPEG(macOS 没有与 Windows GDI+ 输出
|
||||
// 一致的 JPEG 路径);失败时 format 无意义,填 JPEG 保持包头合法
|
||||
hdr->format = ok ? SCREEN_PREVIEW_FMT_BGRX : SCREEN_PREVIEW_FMT_JPEG;
|
||||
hdr->width = (uint16_t)w;
|
||||
hdr->height = (uint16_t)h;
|
||||
hdr->bytes = bytes;
|
||||
if (ok) {
|
||||
memcpy(pkt.data() + sizeof(*hdr), pixels.data(), pixels.size());
|
||||
}
|
||||
|
||||
// Send2Server 内部持锁,可在工作线程调用;进程退出/断线时不再回包
|
||||
if (g_bExit == S_CLIENT_NORMAL && g_pMainClient && g_pMainClient->IsConnected()) {
|
||||
g_pMainClient->Send2Server(pkt.data(), (int)pkt.size());
|
||||
}
|
||||
if (!ok) {
|
||||
Mprintf("** Screen preview capture failed: status=%d ***\n", st);
|
||||
}
|
||||
}
|
||||
|
||||
// ============== 历史活动(COMMAND_QUERY_ACTIVITY → TOKEN_REPORT_ACTIVITY) ==============
|
||||
// 与 Windows/Linux 一致:主连接一次性快照,不开子连接(服务端 TOKEN_REPORT_ACTIVITY
|
||||
// 分支不 CancelIO)。快照要拿锁、拼字符串,放线程里,别堵接收线程。
|
||||
// 同时在飞的报表最多一份:连点/多个 MCP 调用把同一份快照叠起来没有任何意义。
|
||||
static std::atomic<int> g_activityReportsInFlight(0);
|
||||
|
||||
static void ActivityReportThread()
|
||||
{
|
||||
std::string text = MacActivityHistory::Instance().Dump();
|
||||
if (text.empty())
|
||||
text = MacActivityHistory::EmptyText();
|
||||
|
||||
std::vector<BYTE> pkt(1 + text.size());
|
||||
pkt[0] = TOKEN_REPORT_ACTIVITY;
|
||||
if (!text.empty())
|
||||
memcpy(pkt.data() + 1, text.data(), text.size());
|
||||
bool sent = false;
|
||||
if (g_bExit == S_CLIENT_NORMAL && g_pMainClient && g_pMainClient->IsConnected())
|
||||
sent = g_pMainClient->Send2Server((char*)pkt.data(), (ULONG)pkt.size()) != FALSE;
|
||||
Mprintf("[Activity] report %zu bytes%s\n", text.size(), sent ? "" : " FAILED");
|
||||
g_activityReportsInFlight.fetch_sub(1, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
|
||||
{
|
||||
if (szBuffer == nullptr || ulLength == 0)
|
||||
@@ -870,13 +1144,45 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
|
||||
} else if (szBuffer[0] == COMMAND_SCREEN_SPY) {
|
||||
SpawnSubConnWorker("SCREEN_SPY", ScreenworkingThread);
|
||||
} else if (szBuffer[0] == COMMAND_SYSTEM) {
|
||||
Mprintf("** [%p] Received 'SYSTEM' command ***\n", user);
|
||||
// 系统子连接:进程列表、杀进程、窗口列表都在子连接上收发(同 Windows/Linux)
|
||||
SpawnSubConnWorker("SYSTEM", SystemManagerworkingThread);
|
||||
} else if (szBuffer[0] == COMMAND_LIST_DRIVE) {
|
||||
SpawnSubConnWorker("LIST_DRIVE", FileManagerworkingThread);
|
||||
} else if (szBuffer[0] == COMMAND_QUERY_LOG) {
|
||||
// 与 Windows 端一致:回日志必须开子连接(服务端取走首包后 CancelIO 关的是
|
||||
// 子连接;若回在主连接上,被关掉的就是主连接本身)。
|
||||
SpawnSubConnWorker("QUERY_LOG", ClientLogworkingThread);
|
||||
} else if (szBuffer[0] == COMMAND_QUERY_ACTIVITY) {
|
||||
// 历史活动:主连接一次性快照。已经有报表在飞就丢掉这一次
|
||||
// (服务端每主机单飞行,连点也只是重复请求)
|
||||
if (g_activityReportsInFlight.fetch_add(1) >= 1) {
|
||||
g_activityReportsInFlight.fetch_sub(1);
|
||||
return TRUE;
|
||||
}
|
||||
Mprintf("** [%p] Received 'QUERY_ACTIVITY' command ***\n", user);
|
||||
try {
|
||||
std::thread(ActivityReportThread).detach();
|
||||
} catch (const std::exception& e) {
|
||||
// 线程起不来要把在途计数还回去,否则之后的历史活动请求全被当成「忙」丢掉
|
||||
g_activityReportsInFlight.fetch_sub(1);
|
||||
Mprintf("** Activity report thread failed: %s ***\n", e.what());
|
||||
}
|
||||
} else if (szBuffer[0] == COMMAND_SCREEN_PREVIEW_REQ) {
|
||||
if (ulLength < sizeof(ScreenPreviewReq)) return TRUE;
|
||||
ScreenPreviewReq req;
|
||||
memcpy(&req, szBuffer, sizeof(req));
|
||||
// 抓屏可能耗几十毫秒,必须离开接收线程;超额请求直接丢弃(服务端会超时降级)
|
||||
if (g_previewInFlight.fetch_add(1) >= 1) {
|
||||
g_previewInFlight.fetch_sub(1);
|
||||
return TRUE;
|
||||
}
|
||||
try {
|
||||
std::thread(ScreenPreviewThread, req).detach();
|
||||
} catch (const std::exception& e) {
|
||||
// 线程起不来时必须把在途计数还回去,否则后面所有预览请求都会被当成「忙」丢掉
|
||||
g_previewInFlight.fetch_sub(1);
|
||||
Mprintf("** Screen preview thread failed: %s ***\n", e.what());
|
||||
}
|
||||
} else if (szBuffer[0] == COMMAND_C2C_PREPARE) {
|
||||
// C2C 准备接收通知
|
||||
FileTransferV2::HandleC2CPrepare(szBuffer, ulLength, nullptr);
|
||||
@@ -898,8 +1204,8 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
|
||||
}
|
||||
}
|
||||
} else if (szBuffer[0] == COMMAND_SEND_FILE_V2 || szBuffer[0] == COMMAND_FILE_COMPLETE_V2) {
|
||||
// V2 文件接收
|
||||
int result = FileTransferV2::RecvFileChunkV2(szBuffer, ulLength, g_myClientID);
|
||||
// V2 文件接收;g_pMainClient 用于 C2C 落盘回执(DataProcess 的 user 恒为 NULL)
|
||||
int result = FileTransferV2::RecvFileChunkV2(szBuffer, ulLength, g_myClientID, g_pMainClient);
|
||||
if (result != 0) {
|
||||
Mprintf("** [%p] V2 File recv error: %d ***\n", user, result);
|
||||
}
|
||||
@@ -992,6 +1298,9 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
|
||||
// -d 后台守护进程模式
|
||||
int main(int argc, const char* argv[])
|
||||
{
|
||||
// 自动重启要按原样重放命令行(比如带 -d),argv 在进程生命周期内一直有效
|
||||
g_relaunchArgv = const_cast<char**>(argv);
|
||||
|
||||
// 解析 -d 参数
|
||||
bool daemon_mode = (argc > 1 && strcmp(argv[1], "-d") == 0);
|
||||
|
||||
@@ -1014,14 +1323,20 @@ int main(int argc, const char* argv[])
|
||||
}
|
||||
|
||||
@autoreleasepool {
|
||||
NSLog(@"=== macOS Ghost Client%s ===", daemon_mode ? " (daemon)" : "");
|
||||
Mprintf("=== macOS Ghost Client%s ===\n", daemon_mode ? " (daemon)" : "");
|
||||
// 上一代进程补齐权限后把我们拉起来的。这行进内存 ring,主控端「运行日志」能
|
||||
// 看到;触发重启的那行 "Auto-restart: ..." 只留在 /tmp/ghost.log 里(ring 随
|
||||
// 旧进程一起没了)。
|
||||
if (getenv("GHOST_AUTO_RELAUNCHED")) {
|
||||
Mprintf("(started by the auto-restart after permissions were granted)\n");
|
||||
}
|
||||
|
||||
// ============== Power Management: Keep System Awake ==============
|
||||
// 1. Disable App Nap - prevent macOS from suspending this process
|
||||
id<NSObject> powerActivity = [[NSProcessInfo processInfo]
|
||||
beginActivityWithOptions:(NSActivityUserInitiated | NSActivityIdleSystemSleepDisabled)
|
||||
reason:@"Remote control client must maintain persistent connection"];
|
||||
NSLog(@"App Nap disabled, activity token acquired");
|
||||
Mprintf("App Nap disabled, activity token acquired\n");
|
||||
|
||||
// 2. Prevent system idle sleep using IOKit power assertion
|
||||
IOPMAssertionID sleepAssertionID = 0;
|
||||
@@ -1032,9 +1347,9 @@ int main(int argc, const char* argv[])
|
||||
&sleepAssertionID
|
||||
);
|
||||
if (result == kIOReturnSuccess) {
|
||||
NSLog(@"Power assertion created: system idle sleep disabled (ID: %u)", sleepAssertionID);
|
||||
Mprintf("Power assertion created: system idle sleep disabled (ID: %u)\n", sleepAssertionID);
|
||||
} else {
|
||||
NSLog(@"Warning: Failed to create power assertion (error: 0x%x)", result);
|
||||
Mprintf("Warning: Failed to create power assertion (error: 0x%x)\n", result);
|
||||
}
|
||||
|
||||
// 3. Display sleep: managed by ScreenHandler - only prevents display sleep
|
||||
@@ -1045,7 +1360,11 @@ int main(int argc, const char* argv[])
|
||||
|
||||
// Load configuration file (~/.config/ghost/config.conf)
|
||||
loadConfig();
|
||||
NSLog(@"Config loaded from %s", g_configPath.c_str());
|
||||
Mprintf("Config loaded from %s\n", g_configPath.c_str());
|
||||
|
||||
// 历史活动采样:进程一启动就开始攒(服务端随时可能来查),
|
||||
// 与 Linux 端在登录前 Start 的时机一致。
|
||||
MacActivityHistory::Instance().Start();
|
||||
|
||||
// 传输方式由信任锚文件决定(服务端右键「TLS 传输」才会写入 ~/.config/ghost/yama-ca.pem)。
|
||||
// 启动时打一行,排查「首次连接为什么/为什么不加密」不用去猜。
|
||||
@@ -1057,14 +1376,14 @@ int main(int argc, const char* argv[])
|
||||
}
|
||||
|
||||
// Check permissions
|
||||
NSLog(@"Checking permissions...");
|
||||
Mprintf("Checking permissions...\n");
|
||||
|
||||
bool hasScreenCapture = Permissions::checkScreenCapture();
|
||||
if (hasScreenCapture) {
|
||||
NSLog(@"Screen capture permission: OK");
|
||||
Mprintf("Screen capture permission: OK\n");
|
||||
} else {
|
||||
NSLog(@"Screen capture permission not granted.");
|
||||
NSLog(@"Please grant permission in System Preferences > Privacy & Security > Screen Recording");
|
||||
Mprintf("Screen capture permission not granted.\n");
|
||||
Mprintf("Please grant permission in System Preferences > Privacy & Security > Screen Recording\n");
|
||||
// Request permission (triggers system dialog on first run)
|
||||
Permissions::requestScreenCapture();
|
||||
// Only open settings if this appears to be a re-run without permission
|
||||
@@ -1076,25 +1395,45 @@ int main(int argc, const char* argv[])
|
||||
|
||||
bool hasAccessibility = Permissions::checkAccessibility();
|
||||
if (hasAccessibility) {
|
||||
NSLog(@"Accessibility permission: OK");
|
||||
Mprintf("Accessibility permission: OK\n");
|
||||
} else {
|
||||
NSLog(@"Accessibility permission not granted.");
|
||||
NSLog(@"Please grant permission in System Preferences > Privacy & Security > Accessibility");
|
||||
Mprintf("Accessibility permission not granted.\n");
|
||||
Mprintf("Please grant permission in System Preferences > Privacy & Security > Accessibility\n");
|
||||
Permissions::requestAccessibility();
|
||||
}
|
||||
|
||||
// 缺权限时起看守线程:用户在系统设置里勾选后自动重启一次,省掉手动杀掉重开。
|
||||
// 上面的 request* 已经把两个系统提示都弹了,这里只负责「授权完成 → 应用重启」。
|
||||
if (!hasScreenCapture || !hasAccessibility) {
|
||||
if (getenv("GHOST_AUTO_RELAUNCHED")) {
|
||||
Mprintf("Auto-restart already used once this launch; restart manually after granting permissions\n");
|
||||
} else {
|
||||
g_permNeedScreen = !hasScreenCapture;
|
||||
g_permNeedAx = !hasAccessibility;
|
||||
pthread_t tid;
|
||||
if (pthread_create(&tid, nullptr, PermissionWatcherThread, nullptr) == 0) {
|
||||
pthread_detach(tid);
|
||||
} else {
|
||||
Mprintf("Warning: failed to start the permission watcher\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// FDA check is unreliable (no official API), just log a warning
|
||||
if (!Permissions::checkFullDiskAccess()) {
|
||||
NSLog(@"Full Disk Access: not detected (may be false negative).");
|
||||
NSLog(@"If file access issues occur, grant FDA in System Preferences > Privacy & Security > Full Disk Access");
|
||||
Mprintf("Full Disk Access: not detected (may be false negative).\n");
|
||||
Mprintf("If file access issues occur, grant FDA in System Preferences > Privacy & Security > Full Disk Access\n");
|
||||
// Don't auto-open settings since detection is unreliable
|
||||
} else {
|
||||
NSLog(@"Full Disk Access: OK");
|
||||
Mprintf("Full Disk Access: OK\n");
|
||||
}
|
||||
|
||||
// Create client
|
||||
auto ClientObject = std::make_unique<IOCPClient>(g_bExit, false);
|
||||
ClientObject->setManagerCallBack(NULL, DataProcess, NULL);
|
||||
// C2C 落盘回执要在主连接上回包,但 DataProcess 拿到的 user 恒为 NULL,
|
||||
// 只能靠全局句柄(同 linux/main.cpp)。重连复用同一个对象,因此只在这里赋一次。
|
||||
g_pMainClient = ClientObject.get();
|
||||
// 同 Linux:不传 conn 就取不到注入的 CONNECT_ADDRESS,协议必须显式喂进去,
|
||||
// 否则配成 WS/WSS 也只会静默按明文 TCP 直连。
|
||||
ClientObject->SetDefaultProto((int)(unsigned char)g_SETTINGS.protoType);
|
||||
@@ -1104,11 +1443,18 @@ int main(int argc, const char* argv[])
|
||||
}
|
||||
|
||||
// Main event loop
|
||||
NSLog(@"Starting main loop...");
|
||||
Mprintf("Starting main loop...\n");
|
||||
LOGIN_INFOR logInfo;
|
||||
fillLoginInfo(logInfo);
|
||||
|
||||
while (g_running) {
|
||||
// 权限补齐后重启:放在循环最前面,连着的和没连上的都只走这一个出口。
|
||||
if (g_autoRestartPending) {
|
||||
Mprintf("Restarting to apply newly granted permissions\n");
|
||||
if (RelaunchSelf()) break; // 成功则不返回(父进程直接退出)
|
||||
Mprintf("Auto-restart failed; continuing with the current process\n");
|
||||
g_autoRestartPending = false;
|
||||
}
|
||||
clock_t c = clock();
|
||||
if (!ClientObject->ConnectServer(g_SETTINGS.ServerIP(), g_SETTINGS.ServerPort())) {
|
||||
Sleep(5000);
|
||||
@@ -1123,6 +1469,8 @@ int main(int argc, const char* argv[])
|
||||
ClientAuth::OnNewConnection();
|
||||
// 本条连接可能是热切换信任锚后重建的:TLS 标志按当前状态重算,再发登录。
|
||||
RefreshLoginTls(logInfo);
|
||||
// 录屏授权可能刚补齐(看守线程会重启进程,但这一次登录也要报对能力位)
|
||||
RefreshLoginCaps(logInfo);
|
||||
ClientObject->SendLoginInfo(logInfo.Speed(clock() - c));
|
||||
|
||||
// 心跳保活循环:定时发送心跳包,服务端回复后动态更新 RTT
|
||||
@@ -1130,6 +1478,7 @@ int main(int argc, const char* argv[])
|
||||
// 检查是否需要重发登录信息(分组变更后)
|
||||
if (g_needResendLogin.exchange(false)) {
|
||||
fillLoginInfo(logInfo);
|
||||
RefreshLoginCaps(logInfo);
|
||||
ClientObject->SendLoginInfo(logInfo);
|
||||
Mprintf(">> Resent login info after group change\n");
|
||||
}
|
||||
@@ -1139,10 +1488,18 @@ int main(int argc, const char* argv[])
|
||||
for (int i = 0; i < interval; ++i) {
|
||||
if (g_needReconnect.load(std::memory_order_relaxed))
|
||||
break;
|
||||
if (g_autoRestartPending)
|
||||
break;
|
||||
if (!ClientObject->IsRunning() || !ClientObject->IsConnected() || g_bExit != S_CLIENT_NORMAL)
|
||||
break;
|
||||
Sleep(1000);
|
||||
}
|
||||
// 权限补齐:先正常断开主连接,再回外层重启 —— 服务端立刻看到断开,
|
||||
// 新进程登录时不会和一条「还挂着」的旧连接撞车。
|
||||
if (g_autoRestartPending) {
|
||||
ClientObject->Disconnect();
|
||||
break;
|
||||
}
|
||||
// 信任锚热切换(COMMAND_TLS_ENABLE/DISABLE)会置这个标志:
|
||||
// 断开后由外层循环按新的传输方式重连。
|
||||
if (g_needReconnect.exchange(false)) {
|
||||
@@ -1183,12 +1540,21 @@ int main(int argc, const char* argv[])
|
||||
Mprintf(">>> Exit normally (g_bExit=%d)\n", (int)g_bExit);
|
||||
}
|
||||
|
||||
NSLog(@"Shutting down...");
|
||||
Mprintf("Shutting down...\n");
|
||||
|
||||
// 先断开在飞线程对主连接的引用:抓屏/历史活动线程是 detach 出来的,
|
||||
// ClientObject 出作用域时它们可能还在跑。g_bExit 已置位能挡住绝大多数,
|
||||
// 清空指针是最后一道保险(先判 g_bExit 再解引用)。
|
||||
g_pMainClient = nullptr;
|
||||
|
||||
// 先收采样线程再关日志:采样循环本身不写日志,但停在静态析构里
|
||||
// 会撞上正在拆除的 CoreFoundation 对象,不如走正常退出路径收干净。
|
||||
MacActivityHistory::Instance().Stop();
|
||||
|
||||
// Release power assertions
|
||||
if (sleepAssertionID) {
|
||||
IOPMAssertionRelease(sleepAssertionID);
|
||||
NSLog(@"Released sleep assertion");
|
||||
Mprintf("Released sleep assertion\n");
|
||||
}
|
||||
// Display assertion is managed by ScreenHandler (released in stop())
|
||||
// powerActivity is automatically released when exiting @autoreleasepool
|
||||
|
||||
+12
-5
@@ -363,11 +363,12 @@
|
||||
},
|
||||
{
|
||||
"name": "get_activity_history",
|
||||
"description": "获取指定在线主机的历史活动记录。Windows 与有桌面的 Linux 客户端返回前台窗口驻留记录,每行一条「[时间] [标题] 时长」;Android 客户端返回前台应用驻留记录(标题为「应用名 (包名)」,需开启无障碍服务);无桌面的 Linux 客户端返回登录记录与 shell 命令历史,每行带「[登录]」或「[命令]」标签(首行为「[来源]」说明)。主连接 RPC。结果按 limit/offset 分页(默认 100 条、上限 1000),新在前:offset=0 就是最近 limit 条,想看更早的再往后翻。total 为本机现有记录总数,hasMore 表示还有更早的记录;窗口后端只保留最近 500 条,所以 total 最多约 501(含进行中的当前窗口)。",
|
||||
"description": "获取指定在线主机的历史活动记录。Windows、有桌面的 Linux 与 macOS 客户端返回前台窗口驻留记录,每行一条「[时间] [标题] 时长」(macOS 无录屏授权时标题退化为应用名);Android 客户端返回前台应用驻留记录(标题为「应用名 (包名)」,需开启无障碍服务);无桌面的 Linux 客户端返回登录记录与 shell 命令历史,每行带「[登录]」或「[命令]」标签(首行为「[来源]」说明)。主连接 RPC。结果按 limit/offset 分页(默认 100 条、上限 1000),新在前:offset=0 就是最近 limit 条,想看更早的再往后翻。total 为本机现有记录总数,hasMore 表示还有更早的记录;窗口后端只保留最近 500 条,所以 total 最多约 501(含进行中的当前窗口)。",
|
||||
"gate": null,
|
||||
"platforms": [
|
||||
"win",
|
||||
"lnx",
|
||||
"mac",
|
||||
"apk"
|
||||
],
|
||||
"impl": "mfc",
|
||||
@@ -506,11 +507,12 @@
|
||||
},
|
||||
{
|
||||
"name": "get_screenshot",
|
||||
"description": "截取指定在线主机的一帧画面,返回 base64 编码的 JPEG 图片:图片在 content 的 image 块(data 为 base64,mimeType=image/jpeg);structuredContent.image 只有 mimeType/width/height/bytes 元数据,不含图片数据。支持 Windows 与带 X11 桌面的 Linux 客户端(能力位 CLIENT_CAP_SCREEN_PREVIEW),主连接 RPC、一次性返回。Android 客户端用无障碍服务 takeScreenshot 抓屏(Android 11+ 且开启无障碍服务,此时登录会声明该能力位;只支持 mode=screen)。mode 可选 screen(默认,整虚拟桌面)/region(指定矩形)/window(指定 hwnd)/monitor(指定显示器);后三种默认按源尺寸 1:1 原生分辨率抓取(适合 OCR/视觉读字),需要较新的 Windows 客户端(CLIENT_CAP_SCREEN_REGION,否则 -32005),结果在 structuredContent.capture 里回报实际源矩形与缩放比例。",
|
||||
"description": "截取指定在线主机的一帧画面,返回 base64 编码的 JPEG 图片:图片在 content 的 image 块(data 为 base64,mimeType=image/jpeg);structuredContent.image 只有 mimeType/width/height/bytes 元数据,不含图片数据。支持 Windows、带 X11 桌面的 Linux 与 macOS(登录时已授予录屏权限)客户端(能力位 CLIENT_CAP_SCREEN_PREVIEW),主连接 RPC、一次性返回。Android 客户端用无障碍服务 takeScreenshot 抓屏(Android 11+ 且开启无障碍服务,此时登录会声明该能力位;只支持 mode=screen)。mode 可选 screen(默认,整虚拟桌面)/region(指定矩形)/window(指定 hwnd)/monitor(指定显示器);后三种默认按源尺寸 1:1 原生分辨率抓取(适合 OCR/视觉读字),需要较新的 Windows 客户端(CLIENT_CAP_SCREEN_REGION,否则 -32005),结果在 structuredContent.capture 里回报实际源矩形与缩放比例。",
|
||||
"gate": null,
|
||||
"platforms": [
|
||||
"win",
|
||||
"lnx",
|
||||
"mac",
|
||||
"apk"
|
||||
],
|
||||
"impl": "mfc",
|
||||
@@ -1513,6 +1515,7 @@
|
||||
"platforms": [
|
||||
"win",
|
||||
"lnx",
|
||||
"mac",
|
||||
"apk"
|
||||
],
|
||||
"impl": "mfc",
|
||||
@@ -1563,6 +1566,7 @@
|
||||
"platforms": [
|
||||
"win",
|
||||
"lnx",
|
||||
"mac",
|
||||
"apk"
|
||||
],
|
||||
"impl": "mfc",
|
||||
@@ -1612,6 +1616,7 @@
|
||||
"platforms": [
|
||||
"win",
|
||||
"lnx",
|
||||
"mac",
|
||||
"apk"
|
||||
],
|
||||
"impl": "mfc",
|
||||
@@ -1710,6 +1715,7 @@
|
||||
"platforms": [
|
||||
"win",
|
||||
"lnx",
|
||||
"mac",
|
||||
"apk"
|
||||
],
|
||||
"impl": "mfc",
|
||||
@@ -2588,7 +2594,7 @@
|
||||
},
|
||||
{
|
||||
"name": "upload_file",
|
||||
"description": "把主控本机文件或目录上传到指定在线主机的目录(V2 协议,主连接发送)。支持 Windows 与 Linux/macOS 主机;local_path 为主控本机绝对路径(文件或目录,目录递归上传);remote_dir 为远程保存目录(不存在自动创建),Windows 用 C:\\uploads 这类盘符路径,Linux/macOS 用 /home/user/uploads 这类绝对 POSIX 路径;overwrite=false 时跳过 remote_dir 下已存在的同名顶层项。返回 files[{path,size,sha256}] 与 total_bytes/skipped/receiver_ack;sha256 恒为空(发送端不计算)。receiver_ack=true 表示目标端已确认写入(Linux 客户端回执),false 表示目标端没有回执(Windows 目标、老客户端或 macOS),此时需要确证请用 list_files 复核。",
|
||||
"description": "把主控本机文件或目录上传到指定在线主机的目录(V2 协议,主连接发送)。支持 Windows 与 Linux/macOS 主机;local_path 为主控本机绝对路径(文件或目录,目录递归上传);remote_dir 为远程保存目录(不存在自动创建),Windows 用 C:\\uploads 这类盘符路径,Linux/macOS 用 /home/user/uploads 这类绝对 POSIX 路径;overwrite=false 时跳过 remote_dir 下已存在的同名顶层项。返回 files[{path,size,sha256}] 与 total_bytes/skipped/receiver_ack;sha256 恒为空(发送端不计算)。receiver_ack=true 表示目标端已确认写入(Linux/macOS 客户端回执),false 表示目标端没有回执(Windows 目标或老客户端),此时需要确证请用 list_files 复核。",
|
||||
"gate": "file_transfer",
|
||||
"write": true,
|
||||
"platforms": [
|
||||
@@ -2661,7 +2667,7 @@
|
||||
},
|
||||
{
|
||||
"name": "copy_files_c2c",
|
||||
"description": "在两个在线主机之间直接拷贝文件(V2 C2C:源主机自己发、目标主机自己收,服务端只中继,不在主控落盘)。源主机必须是 Windows;目标主机可以是 Windows 或 Linux/macOS。paths 为源主机绝对路径(文件或目录,目录递归、保留相对目录结构);dst_dir 为目标主机保存目录(不存在自动创建),Windows 目标用 D:\\Incoming 这类绝对路径,Linux/macOS 目标用 /home/user/incoming 这类绝对 POSIX 路径。overwrite 默认 false:目标目录已存在同名顶层项时跳过并计入 skipped(目标端是无条件覆盖写,不跳过就会每次全量重发);预检本身失败(目标主机忙/超时/拒绝访问)不报错,退回全发并置 skip_check_failed=true。返回 transfer_id/file_count/total_bytes/skipped/skip_check_failed/receiver_ack:receiver_ack=true 表示目标端已确认写入(Linux 客户端回执),false 表示目标端没有回执(Windows 目标、老客户端或 macOS),此时需要确证请用 list_files 复核。",
|
||||
"description": "在两个在线主机之间直接拷贝文件(V2 C2C:源主机自己发、目标主机自己收,服务端只中继,不在主控落盘)。源主机必须是 Windows;目标主机可以是 Windows 或 Linux/macOS。paths 为源主机绝对路径(文件或目录,目录递归、保留相对目录结构);dst_dir 为目标主机保存目录(不存在自动创建),Windows 目标用 D:\\Incoming 这类绝对路径,Linux/macOS 目标用 /home/user/incoming 这类绝对 POSIX 路径。overwrite 默认 false:目标目录已存在同名顶层项时跳过并计入 skipped(目标端是无条件覆盖写,不跳过就会每次全量重发);预检本身失败(目标主机忙/超时/拒绝访问)不报错,退回全发并置 skip_check_failed=true。返回 transfer_id/file_count/total_bytes/skipped/skip_check_failed/receiver_ack:receiver_ack=true 表示目标端已确认写入(Linux/macOS 客户端回执),false 表示目标端没有回执(Windows 目标或老客户端),此时需要确证请用 list_files 复核。",
|
||||
"gate": "file_transfer",
|
||||
"write": true,
|
||||
"platforms": [
|
||||
@@ -2758,7 +2764,8 @@
|
||||
"write": true,
|
||||
"platforms": [
|
||||
"win",
|
||||
"lnx"
|
||||
"lnx",
|
||||
"mac"
|
||||
],
|
||||
"impl": "mfc",
|
||||
"inputSchema": {
|
||||
|
||||
Binary file not shown.
@@ -590,6 +590,7 @@
|
||||
<Image Include="res\Bitmap\Refresh.bmp" />
|
||||
<Image Include="res\Bitmap\remove.bmp" />
|
||||
<Image Include="res\Bitmap\RequestAuth.bmp" />
|
||||
<Image Include="res\Bitmap\RunTest.bmp" />
|
||||
<Image Include="res\Bitmap\Settings.bmp" />
|
||||
<Image Include="res\Bitmap\Share.bmp" />
|
||||
<Image Include="res\Bitmap\Show.bmp" />
|
||||
|
||||
@@ -377,5 +377,6 @@
|
||||
<Image Include="res\Bitmap\FileSpeed.bmp" />
|
||||
<Image Include="res\Bitmap\Disclaimer.bmp" />
|
||||
<Image Include="res\Bitmap\CopyName.bmp" />
|
||||
<Image Include="res\Bitmap\RunTest.bmp" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -2242,7 +2242,7 @@ std::string BuildToolsListResult(const Json::Value& id) {
|
||||
{
|
||||
Json::Value tool(Json::objectValue);
|
||||
tool["name"] = "get_activity_history";
|
||||
tool["description"] = u8"获取指定在线主机的历史活动记录。Windows 与有桌面的 Linux 客户端返回前台窗口驻留记录,每行一条「[时间] [标题] 时长」;Android 客户端返回前台应用驻留记录(标题为「应用名 (包名)」,需开启无障碍服务);无桌面的 Linux 客户端返回登录记录与 shell 命令历史,每行带「[登录]」或「[命令]」标签(首行为「[来源]」说明)。主连接 RPC。结果按 limit/offset 分页(默认 100 条、上限 1000),新在前:offset=0 就是最近 limit 条,想看更早的再往后翻。total 为本机现有记录总数,hasMore 表示还有更早的记录;窗口后端只保留最近 500 条,所以 total 最多约 501(含进行中的当前窗口)。";
|
||||
tool["description"] = u8"获取指定在线主机的历史活动记录。Windows、有桌面的 Linux 与 macOS 客户端返回前台窗口驻留记录,每行一条「[时间] [标题] 时长」(macOS 无录屏授权时标题退化为应用名);Android 客户端返回前台应用驻留记录(标题为「应用名 (包名)」,需开启无障碍服务);无桌面的 Linux 客户端返回登录记录与 shell 命令历史,每行带「[登录]」或「[命令]」标签(首行为「[来源]」说明)。主连接 RPC。结果按 limit/offset 分页(默认 100 条、上限 1000),新在前:offset=0 就是最近 limit 条,想看更早的再往后翻。total 为本机现有记录总数,hasMore 表示还有更早的记录;窗口后端只保留最近 500 条,所以 total 最多约 501(含进行中的当前窗口)。";
|
||||
|
||||
tool["inputSchema"] = BuildPagedHostListInputSchema(); // { id | ids } + limit/offset
|
||||
tool["outputSchema"] = BuildActivityHistoryOutputSchema();
|
||||
@@ -2254,7 +2254,7 @@ std::string BuildToolsListResult(const Json::Value& id) {
|
||||
{
|
||||
Json::Value tool(Json::objectValue);
|
||||
tool["name"] = "get_screenshot";
|
||||
tool["description"] = u8"截取指定在线主机的一帧画面,返回 base64 编码的 JPEG 图片:图片在 content 的 image 块(data 为 base64,mimeType=image/jpeg);structuredContent.image 只有 mimeType/width/height/bytes 元数据,不含图片数据。支持 Windows 与带 X11 桌面的 Linux 客户端(能力位 CLIENT_CAP_SCREEN_PREVIEW),主连接 RPC、一次性返回。Android 客户端用无障碍服务 takeScreenshot 抓屏(Android 11+ 且开启无障碍服务,此时登录会声明该能力位;只支持 mode=screen)。mode 可选 screen(默认,整虚拟桌面)/region(指定矩形)/window(指定 hwnd)/monitor(指定显示器);后三种默认按源尺寸 1:1 原生分辨率抓取(适合 OCR/视觉读字),需要较新的 Windows 客户端(CLIENT_CAP_SCREEN_REGION,否则 -32005),结果在 structuredContent.capture 里回报实际源矩形与缩放比例。";
|
||||
tool["description"] = u8"截取指定在线主机的一帧画面,返回 base64 编码的 JPEG 图片:图片在 content 的 image 块(data 为 base64,mimeType=image/jpeg);structuredContent.image 只有 mimeType/width/height/bytes 元数据,不含图片数据。支持 Windows、带 X11 桌面的 Linux 与 macOS(登录时已授予录屏权限)客户端(能力位 CLIENT_CAP_SCREEN_PREVIEW),主连接 RPC、一次性返回。Android 客户端用无障碍服务 takeScreenshot 抓屏(Android 11+ 且开启无障碍服务,此时登录会声明该能力位;只支持 mode=screen)。mode 可选 screen(默认,整虚拟桌面)/region(指定矩形)/window(指定 hwnd)/monitor(指定显示器);后三种默认按源尺寸 1:1 原生分辨率抓取(适合 OCR/视觉读字),需要较新的 Windows 客户端(CLIENT_CAP_SCREEN_REGION,否则 -32005),结果在 structuredContent.capture 里回报实际源矩形与缩放比例。";
|
||||
|
||||
tool["inputSchema"] = BuildGetScreenshotInputSchema(); // { id } 必填 + max_width 可选
|
||||
tool["outputSchema"] = BuildScreenshotOutputSchema();
|
||||
@@ -2676,7 +2676,7 @@ std::string BuildToolsListResult(const Json::Value& id) {
|
||||
if (CMcpServer::Instance().IsFileTransferEnabled() && !CMcpServer::Instance().IsReadonly()) {
|
||||
Json::Value tool(Json::objectValue);
|
||||
tool["name"] = "upload_file";
|
||||
tool["description"] = u8"把主控本机文件或目录上传到指定在线主机的目录(V2 协议,主连接发送)。支持 Windows 与 Linux/macOS 主机;local_path 为主控本机绝对路径(文件或目录,目录递归上传);remote_dir 为远程保存目录(不存在自动创建),Windows 用 C:\\uploads 这类盘符路径,Linux/macOS 用 /home/user/uploads 这类绝对 POSIX 路径;overwrite=false 时跳过 remote_dir 下已存在的同名顶层项。返回 files[{path,size,sha256}] 与 total_bytes/skipped/receiver_ack;sha256 恒为空(发送端不计算)。receiver_ack=true 表示目标端已确认写入(Linux 客户端回执),false 表示目标端没有回执(Windows 目标、老客户端或 macOS),此时需要确证请用 list_files 复核。";
|
||||
tool["description"] = u8"把主控本机文件或目录上传到指定在线主机的目录(V2 协议,主连接发送)。支持 Windows 与 Linux/macOS 主机;local_path 为主控本机绝对路径(文件或目录,目录递归上传);remote_dir 为远程保存目录(不存在自动创建),Windows 用 C:\\uploads 这类盘符路径,Linux/macOS 用 /home/user/uploads 这类绝对 POSIX 路径;overwrite=false 时跳过 remote_dir 下已存在的同名顶层项。返回 files[{path,size,sha256}] 与 total_bytes/skipped/receiver_ack;sha256 恒为空(发送端不计算)。receiver_ack=true 表示目标端已确认写入(Linux/macOS 客户端回执),false 表示目标端没有回执(Windows 目标或老客户端),此时需要确证请用 list_files 复核。";
|
||||
tool["inputSchema"] = BuildUploadFileInputSchema();
|
||||
tool["outputSchema"] = BuildUploadFileOutputSchema();
|
||||
tools.append(tool);
|
||||
@@ -2688,7 +2688,7 @@ std::string BuildToolsListResult(const Json::Value& id) {
|
||||
if (CMcpServer::Instance().IsFileTransferEnabled() && !CMcpServer::Instance().IsReadonly()) {
|
||||
Json::Value tool(Json::objectValue);
|
||||
tool["name"] = "copy_files_c2c";
|
||||
tool["description"] = u8"在两个在线主机之间直接拷贝文件(V2 C2C:源主机自己发、目标主机自己收,服务端只中继,不在主控落盘)。源主机必须是 Windows;目标主机可以是 Windows 或 Linux/macOS。paths 为源主机绝对路径(文件或目录,目录递归、保留相对目录结构);dst_dir 为目标主机保存目录(不存在自动创建),Windows 目标用 D:\\Incoming 这类绝对路径,Linux/macOS 目标用 /home/user/incoming 这类绝对 POSIX 路径。overwrite 默认 false:目标目录已存在同名顶层项时跳过并计入 skipped(目标端是无条件覆盖写,不跳过就会每次全量重发);预检本身失败(目标主机忙/超时/拒绝访问)不报错,退回全发并置 skip_check_failed=true。返回 transfer_id/file_count/total_bytes/skipped/skip_check_failed/receiver_ack:receiver_ack=true 表示目标端已确认写入(Linux 客户端回执),false 表示目标端没有回执(Windows 目标、老客户端或 macOS),此时需要确证请用 list_files 复核。";
|
||||
tool["description"] = u8"在两个在线主机之间直接拷贝文件(V2 C2C:源主机自己发、目标主机自己收,服务端只中继,不在主控落盘)。源主机必须是 Windows;目标主机可以是 Windows 或 Linux/macOS。paths 为源主机绝对路径(文件或目录,目录递归、保留相对目录结构);dst_dir 为目标主机保存目录(不存在自动创建),Windows 目标用 D:\\Incoming 这类绝对路径,Linux/macOS 目标用 /home/user/incoming 这类绝对 POSIX 路径。overwrite 默认 false:目标目录已存在同名顶层项时跳过并计入 skipped(目标端是无条件覆盖写,不跳过就会每次全量重发);预检本身失败(目标主机忙/超时/拒绝访问)不报错,退回全发并置 skip_check_failed=true。返回 transfer_id/file_count/total_bytes/skipped/skip_check_failed/receiver_ack:receiver_ack=true 表示目标端已确认写入(Linux/macOS 客户端回执),false 表示目标端没有回执(Windows 目标或老客户端),此时需要确证请用 list_files 复核。";
|
||||
tool["inputSchema"] = BuildCopyFilesC2CInputSchema();
|
||||
tool["outputSchema"] = BuildCopyFilesC2COutputSchema();
|
||||
tools.append(tool);
|
||||
@@ -4197,11 +4197,15 @@ std::string BuildExecCommand(const Json::Value& id, const Json::Value& args, CMy
|
||||
if (!ctx)
|
||||
return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId));
|
||||
|
||||
// Linux/Android 客户端同样走 PTY + POSIX 哨兵;macOS 本轮不开放。
|
||||
// Linux/Android 客户端同样走 PTY + POSIX 哨兵;macOS 客户端也有完整 PTY
|
||||
// (common/PTYHandler.h,zsh/bash 交互),是否可用改由 CLIENT_CAP_TERMINAL 判定:
|
||||
// 老 macOS 构建收到 COMMAND_SHELL 只打一行 unimplemented,发下去只会拖到超时。
|
||||
CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
|
||||
const bool posix = (clientType == "LNX" || clientType == "APK");
|
||||
if (clientType == "MAC")
|
||||
return BuildError(id, -32005, "exec_command is only supported on Windows, Linux and Android hosts");
|
||||
const bool posix = (clientType == "LNX" || clientType == "APK" || clientType == "MAC");
|
||||
if (clientType == "MAC" && !ctx->SupportsTerminal())
|
||||
return BuildError(id, -32005,
|
||||
"macOS client is too old for exec_command: "
|
||||
"it does not declare CLIENT_CAP_TERMINAL; upgrade the client first");
|
||||
// 老 APK 的 COMMAND_SHELL 是空实现,发下去只会拖到超时;按能力位提前拒绝。
|
||||
if (clientType == "APK" && !ctx->SupportsTerminal())
|
||||
return BuildError(id, -32005,
|
||||
@@ -4854,8 +4858,10 @@ static bool ResolveTerminalSessionHost(const Json::Value& id, const Json::Value&
|
||||
}
|
||||
|
||||
CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
|
||||
if (clientType == "MAC") {
|
||||
errJson = BuildError(id, -32005, "Persistent terminal is only supported on Windows, Linux and Android hosts");
|
||||
if (clientType == "MAC" && !ctx->SupportsTerminal()) {
|
||||
errJson = BuildError(id, -32005,
|
||||
"macOS client is too old for the persistent terminal: "
|
||||
"it does not declare CLIENT_CAP_TERMINAL; upgrade the client first");
|
||||
return false;
|
||||
}
|
||||
if (clientType == "APK" && !ctx->SupportsTerminal()) {
|
||||
@@ -5196,7 +5202,8 @@ std::string BuildTerminalExec(const Json::Value& id, const Json::Value& args, CM
|
||||
if (!ResolveTerminalSessionHost(id, args, parent, devId, ctx, errJson))
|
||||
return errJson;
|
||||
const bool posix = (ctx->GetAdditionalData(RES_CLIENT_TYPE) == "LNX" ||
|
||||
ctx->GetAdditionalData(RES_CLIENT_TYPE) == "APK");
|
||||
ctx->GetAdditionalData(RES_CLIENT_TYPE) == "APK" ||
|
||||
ctx->GetAdditionalData(RES_CLIENT_TYPE) == "MAC");
|
||||
|
||||
// command 省略 = 轮询模式(P0-2);session_id 可省略(P0-1:带 command 时自动建/复用默认会话)。
|
||||
std::string command = Trim(GetStringArg(args, "command"));
|
||||
@@ -9803,8 +9810,14 @@ std::string BuildKillProcess(const Json::Value& id, const Json::Value& args, CMy
|
||||
return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId));
|
||||
|
||||
CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
|
||||
if (clientType == "MAC" || clientType == "APK")
|
||||
return BuildError(id, -32005, "kill_process is only supported on Windows and Linux hosts");
|
||||
// macOS 客户端有 COMMAND_SYSTEM → SystemManager(proc_listpids + SIGKILL)分支,
|
||||
// 但没有对应能力位的老构建收到 COMMAND_SYSTEM 只打一行日志 → 刷新永远等不到,故按位拒绝。
|
||||
if (clientType == "MAC" && !ctx->SupportsProcess())
|
||||
return BuildError(id, -32005,
|
||||
"macOS client is too old for kill_process: "
|
||||
"it does not declare CLIENT_CAP_PROCESS; upgrade the client first");
|
||||
if (clientType == "APK")
|
||||
return BuildError(id, -32005, "kill_process is only supported on Windows, Linux and macOS hosts");
|
||||
|
||||
CMcpServer& mcp = CMcpServer::Instance();
|
||||
if (mcp.IsReadonly())
|
||||
@@ -11988,7 +12001,9 @@ const ToolPlatform kToolPlatforms[] = {
|
||||
{ "upload_file", kPlatWin|kPlatLnx|kPlatMac },
|
||||
// ---- win+lnx(+apk) ---- 远程控制全族 + 需 SCREEN_PREVIEW 的截屏 + macOS 未开放项
|
||||
// Android 用无障碍 takeScreenshot(API 30+,需开无障碍服务),只支持 mode=screen
|
||||
{ "get_screenshot", kPlatWin|kPlatLnx|kPlatApk },
|
||||
// macOS 走 macos/ScreenPreview.mm(CGDisplayCreateImage,声明 CLIENT_CAP_SCREEN_PREVIEW
|
||||
// 的前提是登录时已授予录屏权限),与 Linux 一样回 BGRX 由服务端编码
|
||||
{ "get_screenshot", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
|
||||
// 窗口信息 RPC 只在 Windows 客户端实现(CLIENT_CAP_WINDOW_INFO)
|
||||
{ "get_foreground_window", kPlatWin },
|
||||
// Android 客户端把注入翻译成触摸手势 / 全局动作(android/.../ControlService.kt),
|
||||
@@ -12000,17 +12015,21 @@ const ToolPlatform kToolPlatforms[] = {
|
||||
{ "remote_clipboard", kPlatWin|kPlatLnx|kPlatApk },
|
||||
// COMMAND_SCREEN_CTRL_ALT_DEL:只有 Android 客户端实现(映射为系统锁屏)
|
||||
{ "remote_lock_screen", kPlatApk },
|
||||
// macOS 客户端有 PTY 实现(macos/main.mm:753),但服务端刻意不开放
|
||||
// (McpServer.cpp:3652「macOS 本轮不开放」),故实际不可用;
|
||||
// Android 新版复用 common/PTYHandler.h(/system/bin/sh),声明 CLIENT_CAP_TERMINAL
|
||||
{ "exec_command", kPlatWin|kPlatLnx|kPlatApk },
|
||||
{ "terminal_open", kPlatWin|kPlatLnx|kPlatApk },
|
||||
{ "terminal_exec", kPlatWin|kPlatLnx|kPlatApk },
|
||||
{ "terminal_close", kPlatWin|kPlatLnx|kPlatApk },
|
||||
// macOS 客户端有 COMMAND_KILLPROCESS 分支,服务端同样拦着(McpServer.cpp:6870)
|
||||
{ "kill_process", kPlatWin|kPlatLnx },
|
||||
// http_probe 要走终端通道(Windows 用 PowerShell、Linux 用 curl);macOS 终端未开放,
|
||||
// Android 的 toybox 不保证有 curl/base64,故只标 win/lnx(工具内部对 MAC/APK 返回 -32005)。
|
||||
// macOS 客户端同样是完整 PTY(common/PTYHandler.h,zsh/bash),新版声明
|
||||
// CLIENT_CAP_TERMINAL;老 macOS 构建收到 COMMAND_SHELL 只打一行 unimplemented,
|
||||
// 工具内部按能力位提前拒绝(McpServer.cpp 的 SupportsTerminal 判定)。
|
||||
// Android 新版复用 common/PTYHandler.h(/system/bin/sh),同样声明 CLIENT_CAP_TERMINAL
|
||||
{ "exec_command", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
|
||||
{ "terminal_open", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
|
||||
{ "terminal_exec", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
|
||||
{ "terminal_close", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
|
||||
// macOS 客户端有 COMMAND_SYSTEM → SystemManager(proc_listpids + SIGKILL),
|
||||
// 新版声明 CLIENT_CAP_PROCESS;老构建按能力位提前拒绝。
|
||||
{ "kill_process", kPlatWin|kPlatLnx|kPlatMac },
|
||||
// http_probe 要走终端通道(Windows 用 PowerShell、Linux 用 curl)。
|
||||
// macOS 终端已开放,但这里的 POSIX 命令用了 `base64 -w`(GNU 专有),BSD base64
|
||||
// 没有这个开关,头和体都会解不出来——等换成两平台通用的折行写法再放行。
|
||||
// Android 的 toybox 不保证有 curl/base64,故仍只标 win/lnx。
|
||||
{ "http_probe", kPlatWin|kPlatLnx },
|
||||
// ---- win ---- 服务 / 注册表 / 键日志 / 文件写 / host_* / chat_* / power_action
|
||||
// list_windows 单列:BuildListWindows 把 COMMAND_WSLIST 发在**主连接**上
|
||||
@@ -12023,7 +12042,8 @@ const ToolPlatform kToolPlatforms[] = {
|
||||
// Linux 客户端已实现 COMMAND_QUERY_ACTIVITY → TOKEN_REPORT_ACTIVITY(linux/LinuxActivityHistory.h,
|
||||
// 有桌面走 X11 窗口采样,无桌面走 last + shell 历史),Android 复用同一套采样机、
|
||||
// 前台应用由无障碍服务提供,与 Windows 同为主连接 RPC
|
||||
{ "get_activity_history", kPlatWin|kPlatLnx|kPlatApk },
|
||||
// macOS 是 macos/ActivityHistory.mm(CGWindowList 前台窗口采样,同样主连接一次性快照)
|
||||
{ "get_activity_history", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
|
||||
{ "list_services", kPlatWin },
|
||||
{ "get_keylog", kPlatWin },
|
||||
{ "list_registry", kPlatWin },
|
||||
|
||||
@@ -46,7 +46,7 @@
|
||||
|
||||
// 程序版本号 [建议格式: X.Y.Z]
|
||||
// 影响:关于对话框、标题栏
|
||||
#define BRAND_VERSION "1.4.2"
|
||||
#define BRAND_VERSION "1.4.3"
|
||||
|
||||
// 启动画面名称 [建议大写,更有 Logo 感]
|
||||
// 影响:启动画面 Logo 文字(大号艺术字体渲染)
|
||||
|
||||
@@ -171,6 +171,16 @@ public:
|
||||
return (strtoul(caps.GetString(), nullptr, 16) & CLIENT_CAP_TERMINAL) != 0;
|
||||
}
|
||||
|
||||
// 检查客户端是否处理 COMMAND_SYSTEM(系统子连接:COMMAND_PSLIST / COMMAND_KILLPROCESS)。
|
||||
// Linux/macOS 声明;Windows 客户端一直有这条分支但不声明,调用方按平台区分。
|
||||
// 没有这一位的主机(如老 macOS 构建)收到 COMMAND_SYSTEM 只打一行日志,
|
||||
// 服务端据此提前拒绝 kill_process,而不是发下去后等刷新超时、再报一个假的 ok。
|
||||
bool SupportsProcess() const {
|
||||
CString caps = GetClientData(ONLINELIST_CAPABILITIES);
|
||||
if (caps.IsEmpty()) return false;
|
||||
return (strtoul(caps.GetString(), nullptr, 16) & CLIENT_CAP_PROCESS) != 0;
|
||||
}
|
||||
|
||||
// 检查客户端是否处理 COMMAND_SCREEN_BLOCK_INPUT / COMMAND_SCREEN_BLANK(Android 用
|
||||
// 无障碍全屏 overlay 实现:输入锁 = 透明 overlay 吃掉触摸,黑屏 = 黑色 overlay)。
|
||||
// Windows 客户端一直支持键鼠锁定但不声明这个位,调用方按平台区分;老 APK 收到两个
|
||||
|
||||
@@ -118,9 +118,10 @@ GATE = {
|
||||
|
||||
# platforms: 该工具涉及的任一主机都必须落在此集合内。
|
||||
#
|
||||
# 判定依据是**服务端实际放行**,不是客户端有没有实现。两者在 macOS 上会分叉:
|
||||
# exec_command / terminal_* / kill_process 的客户端实现是有的,但服务端刻意拦着
|
||||
# (McpServer.cpp:3652「macOS 本轮不开放」、6870),所以标 win/lnx(终端族另有 apk)。
|
||||
# 判定依据是**服务端实际放行**,不是客户端有没有实现。两者可能在 macOS 上分叉,
|
||||
# 2026-11-14 起不再分叉:exec_command / terminal_* / kill_process 的 macOS 实现接上了
|
||||
# 能力位(CLIENT_CAP_TERMINAL / CLIENT_CAP_PROCESS),服务端按能力位放行——老构建收到
|
||||
# 这些工具仍返回 -32005,但那是「客户端太旧」而不是平台被拦,故平台表标 mac。
|
||||
# Android 同理:COMMAND_SHELL 只有声明 CLIENT_CAP_TERMINAL 的新版 APK 才处理,
|
||||
# 老 APK 由工具内部按能力位返回 -32005。
|
||||
#
|
||||
@@ -128,12 +129,13 @@ GATE = {
|
||||
# 全平台 —— 只读写服务端本地数据,与客户端平台无关
|
||||
# win/lnx/mac —— client/、linux/、macos/ 都有该命令的处理分支,且服务端不拦
|
||||
# win/lnx —— 远程控制只实现于 Windows/Linux(McpServer.cpp:2728);
|
||||
# 以及 macOS 客户端有实现但服务端未开放的 kill_process
|
||||
# 仅 win —— 服务/注册表/键日志/活动历史/文件写/host_* /power_action
|
||||
# 以及 http_probe(macOS 终端可用,但探测命令用了 GNU 专有的 base64 -w)
|
||||
# 仅 win —— 服务/注册表/键日志/文件写/host_* /power_action
|
||||
# (power_action 实际走 TOKEN_MACHINE_MANAGE,不是通用电源命令)
|
||||
#
|
||||
# 支持面是产品定位的阶梯:win 100% > lnx 46% > mac 28% ≈ apk 16%。
|
||||
# Windows 是唯一全量支持的平台,check_platform_table.py 会把这条做成不变式。
|
||||
# 支持面是产品定位的阶梯:win 100% > lnx 46% > apk 16%(mac 2026-11-14 起进入补全阶段,
|
||||
# 已覆盖终端、进程、截屏、活动历史、文件传输)。Windows 是唯一全量支持的平台,
|
||||
# check_platform_table.py 会把这条做成不变式。
|
||||
#
|
||||
# apk 现状:COMMAND_SYSTEM 与 COMMAND_SHELL 在 android/.../main.cpp 明确标注 not
|
||||
# implemented,故除服务端本地类之外,只有少量按需补过分支的能力:运行日志
|
||||
@@ -170,19 +172,22 @@ PLATFORMS = {
|
||||
# 实测 Linux 直接超时 -32001。别被 SystemManager 里的 case 骗到,那是 SystemDlg 用的。
|
||||
"list_windows": _WIN,
|
||||
|
||||
# macOS 客户端有 PTY 实现(macos/main.mm:753 起 ShellworkingThread),但服务端
|
||||
# 本轮刻意不开放(McpServer.cpp:3652 注释「macOS 本轮不开放」),故实际不可用。
|
||||
# Android 新版复用 common/PTYHandler.h,声明 CLIENT_CAP_TERMINAL 后服务端才放行。
|
||||
"terminal_open": _WLA,
|
||||
"terminal_exec": _WLA,
|
||||
"terminal_close": _WLA,
|
||||
"exec_command": _WLA,
|
||||
# macOS 客户端一直是完整 PTY(macos/main.mm 的 ShellworkingThread),2026-11-14 起
|
||||
# 声明 CLIENT_CAP_TERMINAL,服务端按能力位放行(老构建仍返回 -32005)。
|
||||
# Android 新版复用 common/PTYHandler.h,同样声明 CLIENT_CAP_TERMINAL 后服务端才放行。
|
||||
"terminal_open": _APK,
|
||||
"terminal_exec": _APK,
|
||||
"terminal_close": _APK,
|
||||
"exec_command": _APK,
|
||||
|
||||
# http_probe 走终端通道:macOS 终端未开放;Android 的 toybox 不保证有 curl/base64
|
||||
# http_probe 走终端通道:macOS 终端已开放,但 POSIX 探测命令用了 GNU 专有的
|
||||
# `base64 -w`(BSD base64 没有该开关),换成两平台通用写法前仍只标 win/lnx;
|
||||
# Android 的 toybox 不保证有 curl/base64
|
||||
"http_probe": _WL,
|
||||
|
||||
# macOS 客户端有 COMMAND_KILLPROCESS 分支,但服务端同样拦着(McpServer.cpp:6870)
|
||||
"kill_process": _WL,
|
||||
# macOS 客户端有 COMMAND_KILLPROCESS(SystemManager,SIGKILL),2026-11-14 起
|
||||
# 声明 CLIENT_CAP_PROCESS 后服务端放行;老构建按能力位提前拒绝。
|
||||
"kill_process": _TRIO,
|
||||
|
||||
# 需要 CLIENT_CAP_V2;三个桌面平台的 DefaultCaps() 都含 V2
|
||||
"download_file": _TRIO,
|
||||
@@ -200,15 +205,16 @@ PLATFORMS = {
|
||||
"remote_lock_screen": _APKONLY,
|
||||
|
||||
# 需要 CLIENT_CAP_SCREEN_PREVIEW:Windows 恒有,Linux 仅在探测到 X11 桌面时声明,
|
||||
# macOS 仅在登录时已授予录屏权限时声明(CGDisplayCreateImage → BGRX),
|
||||
# Android 仅在无障碍服务在跑时声明(takeScreenshot,只支持 mode=screen)
|
||||
"get_screenshot": _WLA,
|
||||
"get_screenshot": _APK,
|
||||
|
||||
# ---- 仅 Windows ----
|
||||
"list_services": _WIN,
|
||||
"control_service": _WIN,
|
||||
"list_registry": _WIN,
|
||||
"get_keylog": _WIN,
|
||||
"get_activity_history": _WLA, # Windows 前台窗口;Linux 桌面/无桌面均有实现(linux/main.cpp);APK 复用同一采样机
|
||||
"get_activity_history": _APK, # Windows 前台窗口;Linux 桌面/无桌面均有实现(linux/main.cpp);macOS 用 CGWindowList 采前台窗口(macos/ActivityHistory.mm);APK 复用同一采样机
|
||||
"get_foreground_window": _WIN, # 窗口信息 RPC:CLIENT_CAP_WINDOW_INFO,仅 Windows 客户端声明
|
||||
"search_file": _WIN,
|
||||
"delete_path": _WIN,
|
||||
|
||||
Reference in new issue
Block a user