Feat(client): complete the macOS feature set (phase 0 and 1)
Phase 0 makes implementations that already existed reachable. macOS now declares TERMINAL, SCREEN_CLIPBOARD, PROCESS and C2C_RECV_ACK; PROCESS is a new bit and Linux declares it too. SystemManager was dead code -- its constructor took a second argument and it did not derive IOCPManager, so the sub-connection skeleton could never instantiate it -- and now matches the createHandler/OnReceive contract, so COMMAND_SYSTEM really spawns a sub-connection (proc_listpids, SIGKILL). DataProcess always gets a NULL user, so main.mm keeps a g_pMainClient handle and the V2 C2C receiver finally answers TOKEN_C2C_RECV_RESULT. The server asks for SupportsTerminal() on MAC for exec_command / terminal_* and for SupportsProcess() for kill_process, so an old build gets "client is too old" instead of a command nobody answers; kToolPlatforms and mcp/tools.json follow. http_probe stays win/lnx: the terminal works on macOS, but the probe uses GNU-only base64 -w. Phase 1 is POSIX parity. ScreenPreview captures through CGDisplayCreateImage, scales and ships BGRX for the server to encode, and the capability is only declared when preflight or a real capture says the display is readable. ActivityHistory samples the frontmost layer-0 window once a second and prints the same records as Windows and Linux. COMMAND_SCREEN_KEYFRAME_REQ is now consumed by Linux (x264 IDR) and macOS (VideoToolbox force keyframe): the receive thread raises a flag, the capture thread -- which owns the encoder -- consumes it and puts it back if the frame never went out. The macOS quality level persists in NSUserDefaults because main.mm rewrites config.conf. Linux client and Debug x64 server rebuild green; check_platform_table PASS. Not built or run on a Mac. Co-Authored-By: deepseek-flash
This commit is contained in:
1 parent
c2b59f5d4a
commit
06b93f7bdb
19 files changed
+890
-121
No files matched your search
@@ -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
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
+156
-4
@@ -36,6 +36,8 @@
|
||||
#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"
|
||||
@@ -61,6 +63,11 @@ 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)
|
||||
|
||||
// 远程地址:当前为写死状态,如需调试,请按实际情况修改
|
||||
@@ -686,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 锁,
|
||||
@@ -963,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*/)
|
||||
@@ -984,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);
|
||||
@@ -1023,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)
|
||||
@@ -1043,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);
|
||||
@@ -1071,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);
|
||||
}
|
||||
@@ -1229,6 +1362,10 @@ int main(int argc, const char* argv[])
|
||||
loadConfig();
|
||||
Mprintf("Config loaded from %s\n", g_configPath.c_str());
|
||||
|
||||
// 历史活动采样:进程一启动就开始攒(服务端随时可能来查),
|
||||
// 与 Linux 端在登录前 Start 的时机一致。
|
||||
MacActivityHistory::Instance().Start();
|
||||
|
||||
// 传输方式由信任锚文件决定(服务端右键「TLS 传输」才会写入 ~/.config/ghost/yama-ca.pem)。
|
||||
// 启动时打一行,排查「首次连接为什么/为什么不加密」不用去猜。
|
||||
if (TlsLoadError()) {
|
||||
@@ -1294,6 +1431,9 @@ int main(int argc, const char* argv[])
|
||||
// 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);
|
||||
@@ -1329,6 +1469,8 @@ int main(int argc, const char* argv[])
|
||||
ClientAuth::OnNewConnection();
|
||||
// 本条连接可能是热切换信任锚后重建的:TLS 标志按当前状态重算,再发登录。
|
||||
RefreshLoginTls(logInfo);
|
||||
// 录屏授权可能刚补齐(看守线程会重启进程,但这一次登录也要报对能力位)
|
||||
RefreshLoginCaps(logInfo);
|
||||
ClientObject->SendLoginInfo(logInfo.Speed(clock() - c));
|
||||
|
||||
// 心跳保活循环:定时发送心跳包,服务端回复后动态更新 RTT
|
||||
@@ -1336,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");
|
||||
}
|
||||
@@ -1399,6 +1542,15 @@ int main(int argc, const char* argv[])
|
||||
|
||||
Mprintf("Shutting down...\n");
|
||||
|
||||
// 先断开在飞线程对主连接的引用:抓屏/历史活动线程是 detach 出来的,
|
||||
// ClientObject 出作用域时它们可能还在跑。g_bExit 已置位能挡住绝大多数,
|
||||
// 清空指针是最后一道保险(先判 g_bExit 再解引用)。
|
||||
g_pMainClient = nullptr;
|
||||
|
||||
// 先收采样线程再关日志:采样循环本身不写日志,但停在静态析构里
|
||||
// 会撞上正在拆除的 CoreFoundation 对象,不如走正常退出路径收干净。
|
||||
MacActivityHistory::Instance().Stop();
|
||||
|
||||
// Release power assertions
|
||||
if (sleepAssertionID) {
|
||||
IOPMAssertionRelease(sleepAssertionID);
|
||||
|
||||
Reference in new issue
Block a user