2 Commits
Author SHA1 Message Date
yuanyuanxianganddeepseek-flash 2e34e49186 Fix: Keep the captured monitor stable across restarts
GDI and DXGI each kept their own static monitor index, and DXGI
committed the index before its initialization had succeeded. When a
quality change restarted capture and DXGI fell back to GDI, the next
DXGI attempt read the failed attempt's index and jumped to the other
monitor. Both backends now share one process-wide index with separate
peek and commit steps, and the commit only happens after the backend
is actually up.

Manual switching is made a one-shot request: InitScreenSpy consumes
the flag and RestartScreen only sets it, so an adaptive restart that
lands in the middle of a switch no longer drops the request or
re-applies it on every later rebuild. Window capture no longer
touches the index at all, so leaving window mode returns to the
monitor that was on screen.

Also: restart capture on a bitrate change only when the target level
is still H.264 (switching to RGB565/DIFF never uses the bitrate), and
bound the DXGI output fallback so a session without any enumerable
output cannot spin forever in InitDXGI.

Co-Authored-By: deepseek-flash
2026-11-08 20:44:49 +01:00
yuanyuanxianganddeepseek-flash d8048979e3 Feature: Report activity history on Linux clients
Implement COMMAND_QUERY_ACTIVITY -> TOKEN_REPORT_ACTIVITY with two backends
picked at startup. With a desktop, a sampler thread reads the foreground
window every second and books dwell time like the Windows client: under
five seconds is dropped, five idle minutes close the window, the last 500
records stay newest first, each line being "[YYYY-MM-DD HH:MM:SS] [title]
duration". It uses its own ActivityChecker because an Xlib connection
cannot be shared with the heartbeat thread, and it is stopped before main's
locals go away.

A reachable X server is not enough: the window backend is only chosen when
the root window carries _NET_SUPPORTING_WM_CHECK, so Xvfb or a bare X
without an EWMH window manager falls back to the headless backend instead
of sampling a window id that never appears.

Without a desktop the answer is computed on demand: logins from
"last -n 100 -F" plus bash/zsh history of root and /home/*, tagged [登录] or
[命令] after a [来源] header. Both halves are merged and sorted by
timestamp; three fifths of the budget goes to logins and reboot records are
capped at ten, since a WSL or container writes one reboot per start.
activity_commands=0 drops the command half.

A single detached thread builds and sends it, only while the main link is up.

The MCP gate now admits Linux for get_activity_history and documents both
shapes. test/unit/linux covers the parsers, ordering and UTF-8 truncation;
15 cases pass.

Co-Authored-By: deepseek-flash
2026-11-08 15:22:09 +01:00
11 changed files with 1017 additions and 41 deletions

No files matched your search

+17 -8
View File
@@ -168,6 +168,15 @@ public:
int m_nScreenCount; // 屏幕数量
BOOL m_bEnableMultiScreen;// 多显示器支持
// ===== 屏索引(GDI 与 DXGI 共用同一份)=====
// 0 = 所有显示器拼成的虚拟桌面,k>=1 = 第 k 块显示器(DXGI 下对应输出 k-1)。
// 选屏(Peek)和确认(Commit)必须分开:DXGI 初始化失败会回退 GDI,失败的尝试
// 若推进了索引,回退后第一次重建就会跳到另一块屏上(现场表现:调个质量档就换屏)。
static int& MonitorCur() { static int v = 0; return v; } // 当前正在显示的屏
static int& MonitorNext() { static int v = 0; return v; } // 下一次"切换显示器"要去的屏
static void CommitMonitorIndex(int idx) { MonitorCur() = idx; MonitorNext() = idx + 1; }
int m_nMonitorIndex = 0; // 本次构造选中的屏;后端初始化成功后由它提交
// 滚动检测相关
CScrollDetector* m_pScrollDetector; // 滚动检测器
bool m_bEnableScrollDetect; // 是否启用滚动检测
@@ -230,17 +239,16 @@ public:
m_BlockNum = 8;
m_ThreadPool = new ThreadPool(m_BlockNum);
auto monitors = GetAllMonitors();
// index = 下一次切屏要用的索引(沿用原语义:切屏时自增)
// current = 当前正在显示的索引。重建截屏对象(质量档位、分辨率、ROI、窗口捕获)
// 必须沿用它,不能用 index —— index 永远指向"下一块",比正在显示的那块
// 大 1,所以 switchScreen=false 时读 index 会跳到下一块屏幕上。
static int index = 0;
static int current = 0;
// 屏索引全进程只有一份(MonitorCur/MonitorNext),GDI 与 DXGI 共用。
// 这里只“取”不“提交”:重建截屏对象时(质量档位、分辨率、ROI、窗口捕获)
// 必须沿用当前屏(switchScreen=false),只有"切换显示器"才前进一格。
// 提交留给真正建成的后端——DXGI 构造完才知道初始化成不成功,而失败要回退
// GDI,此时索引不能已经前进过。
m_nScreenCount = monitors.size();
m_bEnableMultiScreen = all;
if (all && !monitors.empty()) {
int idx = (switchScreen ? index++ : current) % (monitors.size()+1);
current = idx;
int idx = (switchScreen ? MonitorNext() : MonitorCur()) % (int)(monitors.size()+1);
m_nMonitorIndex = idx;
if (idx == 0) {
m_iScreenX = GetSystemMetrics(SM_XVIRTUALSCREEN);
m_iScreenY = GetSystemMetrics(SM_YVIRTUALSCREEN);
@@ -254,6 +262,7 @@ public:
m_ulFullHeight = rt.bottom - rt.top;
}
} else {
m_nMonitorIndex = 0; // 单屏模式不参与屏索引
//::GetSystemMetrics(SM_CXSCREEN/SM_CYSCREEN)获取屏幕大小不准
//例如当屏幕显示比例为125%时,获取到的屏幕大小需要乘以1.25才对
DEVMODE devmode;
+31 -13
View File
@@ -97,6 +97,8 @@ public:
CreateDXGIFactory1(__uuidof(IDXGIFactory1), (void**)&pFactory);
if (!pFactory) return;
// 输出回落标记:索引在当前适配器上不存在时回到主输出重试一次
bool forceFirstOutput = false;
do {
// 3. 获取设备
static UINT idx = 0;
@@ -105,25 +107,31 @@ public:
if (!dxgiAdapter)break;
// 4. 获取 DXGI 输出(屏幕)
// screen = 下一次切屏要用的输出索引(沿用原语义:切屏时自增)
// current = 当前正在用的输出。重建截屏对象(质量/分辨率变化)必须沿用它:
// 读 screen 会跳到下一个输出,多显示器下表现为"调个质量就换屏",
// 单显示器下 EnumOutputs(1) 不存在,会让 DXGI 初始化失败降级成 GDI。
static UINT screen = 0;
static UINT current = 0;
UINT outIndex = switchScreen ? screen++ : current;
// 屏索引与 GDI 共用一份(ScreenCapture::MonitorCur):0=虚拟桌面(DXGI 抓不了,
// 落到主输出),k>=1 表示第 k 块显示器,映射到输出 k-1。重建截屏对象
// (质量/分辨率变化)沿用当前屏,只有"切换显示器"才前进一格。
// 这里只取不提交:失败会回退 GDI,提交在初始化成功之后(见 break 前)。
UINT outIndex = 0;
if (all && !forceFirstOutput) {
const int n = m_nScreenCount + 1;
const int sel = (switchScreen ? MonitorNext() : MonitorCur()) % n;
outIndex = sel >= 1 ? (UINT)(sel - 1) : 0u;
}
HRESULT r = dxgiAdapter->EnumOutputs(outIndex, &dxgiOutput);
if (r == DXGI_ERROR_NOT_FOUND && all) {
// 索引在当前适配器上不存在(拔掉外接屏等):回到主输出再试,
// 避免拿一个无效索引去遍历适配器,最后降级成 GDI。
screen = 0;
current = 0;
if (r == DXGI_ERROR_NOT_FOUND && all && !forceFirstOutput) {
// 索引在当前适配器上不存在(拔掉外接屏、显示器挂在另一块显卡上等):
// 回到主输出再试一次,避免拿一个无效索引去遍历适配器,最后降级成 GDI。
// 只回落一次:若连主输出都枚举不到(无显示器的会话),必须落到下面
// 的 break 去回退 GDI,否则会在「切适配器 → 再枚举 → 又 NOT_FOUND」
// 之间空转,把抓屏线程挂死。
Mprintf("[DXGI] output %u not found on adapter %u, retry with primary output\n",
outIndex, (unsigned)idx);
forceFirstOutput = true;
idx ++;
dxgiAdapter->Release();
dxgiAdapter = nullptr;
continue;
}
current = outIndex;
if (!dxgiOutput)break;
// 4.1 获取屏幕位置(多显示器支持)
@@ -209,6 +217,13 @@ public:
desc.Usage = D3D11_USAGE_STAGING;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
d3dDevice->CreateTexture2D(&desc, NULL, &cpuTexture);
// IsInitSucceed() 判的就是 cpuTexture;建不出来就别再往下分配十几 MB
// 缓冲、也别提交屏索引——直接 break,由 InitScreenSpy 回退 GDI,
// GDI 会从同一份“未提交”的索引重建,两条路径仍然落在同一块屏上。
if (!cpuTexture) {
Mprintf("[DXGI] CreateTexture2D failed, fall back to GDI\n");
break;
}
// 9. 初始化 BITMAPINFO
m_BitmapInfor_Full = ConstructBitmapInfo(32, m_ulFullWidth, m_ulFullHeight);
@@ -257,6 +272,9 @@ public:
m_BitmapInfor_Send->bmiHeader.biHeight = h;
m_BitmapInfor_Send->bmiHeader.biSizeImage = w * h * 4;
}
// 初始化到这里才算成功,此时才能提交屏索引:中途失败(DuplicateOutput 等)
// 会回退 GDI,如果把失败尝试的索引提交了,回退后第一次重建就会换屏。
if (all && m_nScreenCount > 0) CommitMonitorIndex((int)outIndex + 1);
Mprintf("[DXGI] out=%u mode=%ux%u surf=%ux%u fmt=%d rot=%d -> send=%dx%d\n",
outIndex, duplDesc.ModeDesc.Width, duplDesc.ModeDesc.Height,
m_surfW, m_surfH, (int)realFmt, (int)m_rotation,
+18 -4
View File
@@ -216,7 +216,10 @@ bool CScreenManager::RestartScreen(BOOL switchScreen)
// 3. 重新启动工作线程(InitScreenSpy 会创建新对象)
m_bIsWorking = TRUE;
m_SendFirst = FALSE;
m_SwitchScreen = switchScreen;
// 只有请求切换时才置位,普通重建(质量档/分辨率/ROI/换窗口)不清除:
// 切屏请求要挂起到某次重建真正提交了屏索引为止。否则「切屏后紧跟一个质量档
// 调整」会把请求覆盖成 false,截屏对象建好前被顶掉,切换就静默丢了。
if (switchScreen) m_SwitchScreen = TRUE;
m_hWorkThread = __CreateThread(NULL, 0, WorkThreadProc, this, 0, NULL);
return true;
}
@@ -506,7 +509,12 @@ void CScreenManager::InitScreenSpy()
BYTE* user = (BYTE*)m_ptrUser;
BOOL all = FALSE;
RECT rect = m_ROI;
// 「切换显示器」是一次性请求:取用即清除。之后的自适应重启(质量档、分辨率、
// ROI、换窗口)一律 switchScreen=false,沿用当前屏。不清除的话,工作线程里
// 因窗口尺寸变化触发的原地重建(WorkThreadProc 直接调本函数,不经过
// RestartScreen)会把旧请求再消费一次,每重建一次就换一块屏。
BOOL switchScreen = m_SwitchScreen;
m_SwitchScreen = FALSE;
if (!(user == NULL || ((int)user) == 1)) {
UserParam* param = (UserParam*)user;
if (param && param->length>0) {
@@ -543,7 +551,10 @@ void CScreenManager::InitScreenSpy()
}
// 保存屏幕类型,服务端用于判断是否显示虚拟桌面相关菜单
m_ScreenSettings.ScreenType = DXGI;
Mprintf("CScreenManager: Type %d Algorithm: %d (QualityLevel=%d)\n", DXGI, int(algo), level);
// switch 是本次重建是否要换屏,all 是客户端是否支持多显示器;屏索引变化会打印
// 在各后端自己的日志里(CScreenSpy 的 monitor= / DXGI 的 out=)。
Mprintf("CScreenManager: Type %d Algorithm: %d (QualityLevel=%d) switch=%d all=%d\n",
DXGI, int(algo), level, (int)switchScreen, (int)all);
if (DXGI == USING_VIRTUAL) {
m_virtual = TRUE;
HDESK hDesk = SelectDesktop((char*)m_DesktopID.c_str());
@@ -1138,10 +1149,13 @@ VOID CScreenManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
m_ScreenSettings.MaxFPS = profile.maxFPS;
bool needRestart = false;
if (m_ScreenSpyObject) {
// 如果当前是 H264 且码率变化,需要重启以重新创建编码器
// 码率变化要重建编码器,但只在「目标档位仍是 H264」时才有意义:
// 换到 RGB565/DIFF 的档位根本不用码率(profile.bitRate=0),
// 为一次 3000→0 重启截屏纯属白丢一个 IDR(还连带重建抓屏对象)。
bool isH264 = (m_ScreenSpyObject->GetAlgorithm() == ALGORITHM_H264);
bool staysH264 = (profile.algorithm == ALGORITHM_H264);
bool bitRateChanged = m_ScreenSpyObject->SetBitRate(profile.bitRate);
if (isH264 && bitRateChanged) {
if (isH264 && staysH264 && bitRateChanged) {
needRestart = true;
}
m_ScreenSpyObject->SetAlgorithm(profile.algorithm);
+2
View File
@@ -71,6 +71,8 @@ public:
RECT m_ROI = {0};
HWND m_hTargetWnd = NULL; // 窗口捕获目标(NULL=全屏)
bool m_bDynamicForeground = false; // true=每帧自动跟踪前景窗口(HWND sentinel=-1触发)
// 挂起的「切换显示器」请求:InitScreenSpy 取用一次即清除,只有 SwitchScreen()
// 会把它重新置位。为 TRUE 时下一次建截屏对象前进一格屏索引,否则沿用当前屏。
BOOL m_SwitchScreen = TRUE;
BOOL SendClientClipboard(BOOL fast);
VOID UpdateClientClipboard(char *szBuffer, ULONG ulLength);
+9 -2
View File
@@ -20,6 +20,13 @@ CScreenSpy::CScreenSpy(ULONG ulbiBitCount, BYTE algo, BOOL vDesk, int gop, BOOL
m_bDynamicForeground = dynamicFg;
m_GOP = gop;
// GDI 构造本身没有失败路径,到这里就确认当前屏。DXGI 初始化失败回退到 GDI 时
// 也走这里:两条路径必须落到同一块屏上,否则下一次重建会换屏。
// 窗口捕获(含动态前景)不参与屏索引:下面的窗口矩形会覆盖基类的显示器几何,
// 此时若提交,一次窗口重建就会把索引往前推一格,取消窗口捕获后画面就换屏了。
if (!hwnd && !m_bDynamicForeground && m_bEnableMultiScreen && m_nScreenCount > 0)
CommitMonitorIndex(m_nMonitorIndex);
// 窗口捕获模式:用 DWM 真实边界覆盖基类的全屏尺寸,并缓存阴影偏移量
if (hwnd) {
RECT wndRc = {}, frameRc = {};
@@ -49,8 +56,8 @@ CScreenSpy::CScreenSpy(ULONG ulbiBitCount, BYTE algo, BOOL vDesk, int gop, BOOL
m_BitmapInfor_Send = new BITMAPINFO(*m_BitmapInfor_Full);
m_nInstructionSet = cfg.GetInt("settings", "CpuSpeedup", 0);
Mprintf("CScreenSpy: strategy=%d, maxWidth=%d, fullWidth=%d, algo=%d\n",
strategy, maxWidth, m_BitmapInfor_Send->bmiHeader.biWidth, m_bAlgorithm);
Mprintf("CScreenSpy: strategy=%d, maxWidth=%d, fullWidth=%d, algo=%d, monitor=%d\n",
strategy, maxWidth, m_BitmapInfor_Send->bmiHeader.biWidth, m_bAlgorithm, m_nMonitorIndex);
if (strategy == 1) {
// strategy=1: 用户明确选择原始分辨率
+562
View File
@@ -0,0 +1,562 @@
#pragma once
// Linux 客户端的「历史活动」(服务端 COMMAND_QUERY_ACTIVITY → TOKEN_REPORT_ACTIVITY)。
//
// 双后端:
// 窗口后端:有可用桌面(X11 + EWMH)时,后台每秒采样前台窗口,输出格式与 Windows
// 端 client/ActivityHistory.cpp 完全一致:[时间] [窗口标题] 时长
// 无头后端:没有桌面时(服务器/容器/daemon 启动时 DISPLAY 不可用),查询时现算
// 「登录记录 + shell 命令历史」,每行带 [登录] / [命令] 标签,首行标明来源
//
// 服务端 CActivityDialog 与 MCP get_activity_history 都只按行切分纯文本,不需要改。
// 纯解析函数放在这里(不依赖 X11),单元测试见 test/unit/linux/ActivityHistoryTest.cpp。
#include <string>
#include <vector>
#include <deque>
#include <mutex>
#include <thread>
#include <atomic>
#include <chrono>
#include <functional>
#include <ctime>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#ifndef _WIN32
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
// 与 Windows 端 client/ActivityHistory.h 保持一致
#ifndef ACTIVITY_MIN_DWELL_SEC
#define ACTIVITY_MIN_DWELL_SEC 5 // 一闪而过阈值(秒):驻留低于此值不记录
#endif
#ifndef ACTIVITY_IDLE_BREAK_SEC
#define ACTIVITY_IDLE_BREAK_SEC 300 // 空闲打断阈值(秒):与 Windows 端一致
#endif
#ifndef ACTIVITY_HISTORY_MAX
#define ACTIVITY_HISTORY_MAX 500 // 内存保留的最大记录条数
#endif
namespace LinuxActivity {
// 采样线程从 X11 拿到的一条观测:id==0 表示空闲/无窗口/取不到标题
struct ProbeResult
{
unsigned long winId = 0;
std::string title;
};
inline std::tm LocalTimeOf(std::time_t t)
{
std::tm tm{};
#ifdef _WIN32
localtime_s(&tm, &t);
#else
localtime_r(&t, &tm);
#endif
return tm;
}
inline std::string FormatTimeStamp(std::time_t t)
{
std::tm tm = LocalTimeOf(t);
char buf[80]; // 64 够放下极限值,多留一点让 -Wformat-truncation 闭嘴
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;
}
inline std::string NowStr()
{
return FormatTimeStamp(std::time(nullptr));
}
// 时长格式化:Ns / Nm / NmNs / NhNm(与 Windows 端一致)
inline 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";
}
// UTF-8 尾字节修正:按字节截断可能切在多字节字符中间,而服务端要按 UTF-8
// 转 GBK(对话框)或塞进 JSON(MCP),半截字符会变成乱码/非法 JSON。
// 返回可以安全截断的位置。
inline 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;
}
// 控制字符换成空格(换行会破坏「每行一条」),可选截断
inline 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;
}
inline std::string FormatWindowRecord(const std::string& startTime, const std::string& title, int dwellSec)
{
return "[" + startTime + "] [" + CleanLine(title) + "] " + FormatDuration(dwellSec);
}
inline std::string FormatCommandRecord(std::time_t ts, const std::string& user, const std::string& cmd)
{
std::string t = ts > 0 ? FormatTimeStamp(ts) : std::string("时间未知");
return "[" + t + "] [命令] " + user + ": " + cmd;
}
inline std::vector<std::string> SplitWs(const std::string& s)
{
std::vector<std::string> out;
size_t i = 0;
while (i < s.size()) {
while (i < s.size() && (s[i] == ' ' || s[i] == '\t' || s[i] == '\r')) ++i;
size_t start = i;
while (i < s.size() && s[i] != ' ' && s[i] != '\t' && s[i] != '\r') ++i;
if (i > start) out.push_back(s.substr(start, i - start));
}
return out;
}
// bash / zsh 历史文本解析。
// bash 设了 HISTTIMEFORMAT 时按 "#<epoch>" + 命令成对写;
// zsh 开 EXTENDED_HISTORY 时写成 ": <epoch>:<elapsed>;命令"。
// 其余按普通行处理(时间未知)。
inline std::vector<std::string> ParseShellHistoryText(const std::string& text,
const std::string& user,
size_t maxLines)
{
std::vector<std::string> out;
std::time_t pending = 0;
size_t i = 0;
while (i < text.size()) {
size_t nl = text.find('\n', i);
std::string line = text.substr(i, nl == std::string::npos ? std::string::npos : nl - i);
i = (nl == std::string::npos) ? text.size() : nl + 1;
if (!line.empty() && line.back() == '\r') line.pop_back();
if (line.empty()) continue;
// "#1699560000" —— 只认纯数字,避免把真实的 "#注释" 当成时间戳
if (line[0] == '#' && line.size() > 1 && line.size() <= 13 &&
std::all_of(line.begin() + 1, line.end(),
[](unsigned char c) { return c >= '0' && c <= '9'; })) {
try { pending = (std::time_t)std::stoll(line.substr(1)); } catch (...) { pending = 0; }
continue;
}
std::time_t ts = pending;
pending = 0;
if (line.size() > 2 && line[0] == ':' && line[1] == ' ') {
size_t semi = line.find(';');
if (semi != std::string::npos) {
std::string meta = line.substr(2, semi - 2);
size_t colon = meta.find(':');
// 只认 ": <epoch>:<elapsed>;" 这一种形状。bash 里 ": ${PATH:=/usr/bin}; ls"
// 这种命令行同样以 ": " 开头、也带 ';',不能当成 zsh 元数据截掉。
const std::string tsPart = meta.substr(0, colon);
const bool zshMeta = colon != std::string::npos && !tsPart.empty() &&
std::all_of(tsPart.begin(), tsPart.end(),
[](unsigned char c) { return c >= '0' && c <= '9'; });
if (zshMeta) {
try { ts = (std::time_t)std::stoll(tsPart); } catch (...) { ts = 0; }
line = line.substr(semi + 1);
if (line.empty()) continue;
}
}
}
out.push_back(FormatCommandRecord(ts, user, CleanLine(line)));
}
if (out.size() > maxLines)
out.erase(out.begin(), out.end() - (long)maxLines);
return out;
}
inline int MonthNumber(const std::string& m)
{
static const char* kMonths[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
for (int i = 0; i < 12; ++i)
if (m == kMonths[i]) return i + 1;
return 0;
}
// `last -F`(LC_ALL=C)的输出解析。样例:
// root pts/0 203.0.113.7 Fri Nov 7 22:10:33 2026 - ... (00:49)
// reboot system boot 6.8.0-45 Fri Nov 7 22:10:20 2026 - ...
// root tty1 Sat Nov 8 09:00:00 2026 still logged in
// 本地登录没有 host 字段,靠「星期」在字段里的位置判断:
// [user][tty][host][Mon..Sun][Mon月][日][HH:MM:SS][年] 远程登录
// [user][tty][Mon..Sun][月][日][HH:MM:SS][年] 本地登录
// [reboot][system][boot][内核][Mon..Sun][月][日][...] 重启
inline int WeekdayIndex(const std::string& s)
{
static const char* kDays[] = { "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" };
for (int i = 0; i < 7; ++i)
if (s == kDays[i]) return i;
return -1;
}
inline std::vector<std::string> ParseLastOutput(const std::string& text, size_t maxLines)
{
std::vector<std::string> out;
size_t i = 0;
while (i < text.size() && out.size() < maxLines) {
size_t nl = text.find('\n', i);
std::string line = text.substr(i, nl == std::string::npos ? std::string::npos : nl - i);
i = (nl == std::string::npos) ? text.size() : nl + 1;
if (!line.empty() && line.back() == '\r') line.pop_back();
if (line.empty()) continue;
// 文件尾部的说明行不是记录
if (line.compare(0, 12, "wtmp begins ") == 0) continue;
std::vector<std::string> f = SplitWs(line);
if (f.size() < 4) continue;
// 定位「星期」,月份紧跟在它后面;找不到星期的行按未知时间原样保留
size_t wi = 0;
for (; wi < f.size(); ++wi) {
if (WeekdayIndex(f[wi]) >= 0) break;
}
int mon = (wi + 1 < f.size()) ? MonthNumber(f[wi + 1]) : 0;
if (wi >= f.size() || !mon || wi + 4 >= f.size()) {
out.push_back("[时间未知] [登录] " + CleanLine(line));
continue;
}
size_t mi = wi + 1; // 月份字段下标
const std::string& user = f[0];
std::string tty, host;
if (user == "reboot") {
host = (wi >= 4) ? f[3] : std::string(); // 内核版本
} else {
tty = f.size() > 1 ? f[1] : std::string();
host = (wi >= 3) ? f[2] : std::string();
}
int day = atoi(f[mi + 1].c_str());
int hour = 0, minute = 0, sec = 0;
int year = atoi(f[mi + 3].c_str());
std::string ts;
if (sscanf(f[mi + 2].c_str(), "%d:%d:%d", &hour, &minute, &sec) == 3 && year > 1970) {
char buf[80];
snprintf(buf, sizeof(buf), "%04d-%02d-%02d %02d:%02d:%02d",
year, mon, day, hour, minute, sec);
ts = buf;
}
std::string rec = "[" + (ts.empty() ? std::string("时间未知") : ts) + "] [登录] " + user;
if (user == "reboot") rec += " (system boot)";
if (!tty.empty()) rec += " " + tty;
if (!host.empty() && host != "-") rec += " from " + host;
out.push_back(rec);
}
return out;
}
// reboot 记录里除了时间几乎没别的信息,而无头/WSL 机器的 wtmp 常常堆着几十条
// (每次启动一条),会把真正的登录和命令全挤掉。这里只保留最近的几条。
constexpr size_t ACTIVITY_HEADLESS_MAX_REBOOTS = 10;
inline std::vector<std::string> LimitRebootSpam(const std::vector<std::string>& lines,
size_t maxReboots, size_t budget)
{
std::vector<std::string> kept;
kept.reserve(std::min(lines.size(), budget));
size_t reboots = 0;
for (const auto& l : lines) {
if (l.find("[登录] reboot ") != std::string::npos) {
if (++reboots > maxReboots) continue;
}
if (kept.size() >= budget) break;
kept.push_back(l);
}
return kept;
}
// 一条记录的时间戳键:"[2026-11-08 09:00:00] ..." → "2026-11-08 09:00:00",
// 认不出("[时间未知]")返回空串。
inline std::string RecordTimestampKey(const std::string& line)
{
if (line.size() < 21 || line[0] != '[') return std::string();
size_t close = line.find(']');
if (close == std::string::npos) return std::string();
std::string ts = line.substr(1, close - 1);
if (ts.size() != 19) return std::string();
return ts;
}
// 登录记录和命令历史是两批数据、各自新在前;服务端和 MCP 都按「offset=0 就是最近
// limit 条」分页,合并后必须真正按时间戳排一遍,否则最近的命令会被更早的登录挤到后面。
inline void SortNewestFirst(std::vector<std::string>& lines)
{
std::stable_sort(lines.begin(), lines.end(),
[](const std::string& a, const std::string& b) {
const std::string ka = RecordTimestampKey(a);
const std::string kb = RecordTimestampKey(b);
if (ka.empty() != kb.empty()) return !ka.empty(); // 有时间戳的在前
return ka > kb; // 同为空时两者等价,stable_sort 保持原顺序
});
}
// 窗口后端可用但没有记录时的说明(避免对话框全空)
inline std::string WindowBackendEmptyText()
{
return "[来源] 桌面窗口活动:暂无记录(没有停留超过 5 秒的活动窗口)\n";
}
#ifndef _WIN32
inline std::string RunCommandCapture(const std::string& cmd, size_t maxBytes = 256 * 1024)
{
std::string out;
FILE* p = popen(cmd.c_str(), "r");
if (!p) return out;
char buf[4096];
size_t n;
while ((n = fread(buf, 1, sizeof(buf), p)) > 0) {
out.append(buf, n);
if (out.size() >= maxBytes) break;
}
pclose(p);
return out;
}
// 只读文件尾部,避免把巨型历史文件整个读进来;从中间截断时丢掉半行
inline bool ReadFileTail(const std::string& path, size_t maxBytes, std::string& out)
{
out.clear();
FILE* f = fopen(path.c_str(), "rb");
if (!f) return false;
bool ok = false;
do {
if (fseek(f, 0, SEEK_END) != 0) break;
long len = ftell(f);
if (len < 0) break;
long start = ((size_t)len > maxBytes) ? len - (long)maxBytes : 0;
if (fseek(f, start, SEEK_SET) != 0) break;
char buf[8192];
size_t n;
while ((n = fread(buf, 1, sizeof(buf), f)) > 0) out.append(buf, n);
if (start > 0) {
size_t nl = out.find('\n');
if (nl == std::string::npos) out.clear();
else out.erase(0, nl + 1);
}
ok = true;
} while (0);
fclose(f);
return ok;
}
struct HistoryFile
{
std::string user;
std::string path;
std::time_t mtime;
};
// 客户端通常以 root 运行,但日常操作发生在普通用户 shell 里,两边都收
inline void CollectHistoryFiles(std::vector<HistoryFile>& files)
{
auto add = [&](const std::string& user, const std::string& path) {
struct stat st;
if (stat(path.c_str(), &st) != 0 || !S_ISREG(st.st_mode)) return;
files.push_back(HistoryFile{ user, path, st.st_mtime });
};
add("root", "/root/.bash_history");
add("root", "/root/.zsh_history");
DIR* d = opendir("/home");
if (!d) return;
while (struct dirent* e = readdir(d)) {
if (e->d_name[0] == '.') continue;
std::string base = std::string("/home/") + e->d_name;
add(e->d_name, base + "/.bash_history");
add(e->d_name, base + "/.zsh_history");
}
closedir(d);
}
// 无头后端:登录记录(last)+ shell 命令历史,每行一条,首行标注来源。
// includeCommands=false 时只返回登录记录(配置项 activity_commands=0)。
// maxLines 是总行数上限:登录记录先占,剩下的额度给命令。
inline std::string BuildHeadlessDump(bool includeCommands, size_t maxLines = 200)
{
// 登录记录最多占 60%(至少 10 行),余量一定留给命令历史:
// reboot 行虽然先算进来,但下面会被 LimitRebootSpam 削掉大半,不预留额度的话
// 无头机上很可能一条命令都看不到。
const size_t loginBudget = includeCommands
? std::min(maxLines, std::max<size_t>(10, maxLines * 3 / 5))
: maxLines;
std::vector<std::string> logins = LimitRebootSpam(
ParseLastOutput(RunCommandCapture("LC_ALL=C last -n 100 -F 2>/dev/null"), loginBudget),
ACTIVITY_HEADLESS_MAX_REBOOTS, loginBudget);
const size_t cmdBudget = includeCommands && maxLines > logins.size()
? maxLines - logins.size() : 0;
std::vector<std::string> cmds;
if (cmdBudget > 0) {
std::vector<HistoryFile> files;
CollectHistoryFiles(files);
// 最近改过的历史文件排在前面(大致对应当前活跃用户)
std::sort(files.begin(), files.end(),
[](const HistoryFile& a, const HistoryFile& b) { return a.mtime > b.mtime; });
for (const auto& f : files) {
std::string text;
if (!ReadFileTail(f.path, 256 * 1024, text)) continue;
std::vector<std::string> lines = ParseShellHistoryText(text, f.user, cmdBudget);
for (auto it = lines.rbegin(); it != lines.rend(); ++it)
cmds.push_back(*it); // 新在前,与 Windows 端一致
if (cmds.size() >= cmdBudget) break;
}
if (cmds.size() > cmdBudget) cmds.resize(cmdBudget);
}
std::vector<std::string> merged;
merged.reserve(logins.size() + cmds.size());
merged.insert(merged.end(), logins.begin(), logins.end());
merged.insert(merged.end(), cmds.begin(), cmds.end());
SortNewestFirst(merged);
std::string out = std::string("[来源] 无桌面环境:") +
(includeCommands ? "登录记录 + 命令历史" : "仅登录记录") + "\n";
if (merged.empty())
out += "[来源] 没有可用的登录/命令记录\n";
for (const auto& l : merged)
out += l + "\n";
return out;
}
#endif // !_WIN32
// ============== 窗口后端:后台采样线程(与 Windows 端 ActivityHistory 对齐)==============
class ActivityHistory
{
public:
static ActivityHistory& Instance()
{
static ActivityHistory inst;
return inst;
}
// probe 只能由采样线程调用(X11 连接不能跨线程共用,调用方要传自己的实例)
void Start(std::function<ProbeResult()> probe)
{
if (m_started.exchange(true)) return;
m_probe = std::move(probe);
m_running = true;
m_thread = std::thread(&ActivityHistory::Loop, this);
}
void Stop()
{
m_running = false;
if (m_thread.joinable())
m_thread.join();
}
// 最新在前;进行中的窗口(已驻留达阈值)排在最前
std::string 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& r : m_records)
out += r + "\n";
return out;
}
private:
ActivityHistory() = default;
~ActivityHistory() { Stop(); }
ActivityHistory(const ActivityHistory&) = delete;
ActivityHistory& operator=(const ActivityHistory&) = delete;
void Loop()
{
unsigned long lastId = 0;
std::string lastTitle, startTime;
int dwellSec = 0;
while (m_running) {
ProbeResult p = m_probe ? m_probe() : ProbeResult();
{
std::lock_guard<std::mutex> lock(m_mutex);
if (p.winId == 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.winId == lastId) {
// 同一窗口:标题变了也连续累计(浏览器标签切换标题常变)
++dwellSec;
lastTitle = p.title;
} else {
if (lastId != 0 && dwellSec >= ACTIVITY_MIN_DWELL_SEC)
m_records.push_front(FormatWindowRecord(startTime, lastTitle, dwellSec));
lastId = p.winId;
lastTitle = p.title;
startTime = NowStr();
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));
}
}
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::function<ProbeResult()> m_probe;
std::thread m_thread;
};
} // namespace LinuxActivity
+33
View File
@@ -23,6 +23,7 @@ SimpleRemoter 的 Linux 客户端,支持远程桌面、远程终端、文件
| 远程终端 | `PTYHandler` (main.cpp) | `ConPTYManager.cpp` | ✅ 完整 |
| 心跳/RTT | main.cpp | `KernelManager.cpp` | ✅ 完整 |
| 用户活动检测 | `ActivityChecker` | `ActivityWindow` | ✅ 完整 |
| 历史活动 | `LinuxActivityHistory.h` | `ActivityHistory.cpp` | ✅ 双后端(有桌面:X11 前台窗口驻留,格式与 Windows 一致;无桌面:`last` 登录记录 + bash/zsh 命令历史,`activity_commands=0` 可关闭命令采集) |
| 系统信息采集 | main.cpp | `LoginServer.cpp` | ✅ 完整 |
| 守护进程 | daemonize() | Windows 服务 | ✅ 完整 |
| 剪贴板同步 | `ClipboardHandler.h` | `ScreenManager.cpp` | ✅ 服务端↔Linux |
@@ -265,6 +266,37 @@ macOS 可直接复用。
所以分享到一台不在当前信任锚覆盖范围内的主控时,子进程会按 fail-closed 直接
握手失败、反复重连;要么先给这台主机装好包含该主控 CA 的信任锚,要么用明文分享。
## 历史活动
服务端「客户管理 → 历史活动」与 MCP `get_activity_history` 取的是同一次上报
(`COMMAND_QUERY_ACTIVITY` → `TOKEN_REPORT_ACTIVITY`)。客户端在**启动时**按有没有
桌面挑一个后端,之后不再切换:
| 后端 | 触发条件 | 内容 |
|------|---------|------|
| 窗口 | `DISPLAY` 可用且能连上 X 服务器 | 后台每秒采样前台窗口,格式与 Windows 客户端一致:`[YYYY-MM-DD HH:MM:SS] [窗口标题] 时长`。驻留不足 5 秒不记录,空闲 5 分钟算打断,内存保留最近 500 条,最新在前;重启客户端后重新累计 |
| 无头 | 没有 `DISPLAY` / 连不上 X(服务器、容器、systemd 服务) | 查询时现算:登录记录来自 `last -n 100 -F`,命令历史来自 root 和 `/home/*` 下的 `.bash_history`、`.zsh_history`,每行带 `[登录]` / `[命令]` 标签,首行 `[来源]` 说明 |
无头后端把额度按 6:4 分给登录记录和命令历史(登录至少 10 行),并且 `reboot`
记录最多保留 10 条——WSL/容器每启动一次就写一条 `reboot`,不设上限会把真正的
登录和命令全挤掉。
无头后端的登录记录和命令历史合并后按时间戳统一排序(新的在前,时间未知的排最后),
所以服务端/MCP 按 offset 分页时「offset=0」真的是最近的那些。
窗口后端有两个已知边界:
- **X 起来了但没有 EWMH 窗口管理器**(Xvfb、裸 X):`_NET_ACTIVE_WINDOW` 永远读不到。
启动时用根窗口上的 `_NET_SUPPORTING_WM_CHECK` 判一下,没有就直接按无头后端走。
- **没装 `libXss`**(很少见):拿不到空闲时间,一直按「在用」算,同一窗口会一路累加
时长,锁屏也不会打断。装了 `libxss1` 就正常。
命令历史的时间戳取决于 shell 配置:bash 需要 `HISTTIMEFORMAT`,zsh 需要
`EXTENDED_HISTORY`,否则只能拿到命令本身,显示为 `[时间未知]`。
**隐私开关**:在 `~/.config/ghost/config.conf` 里写 `activity_commands=0`,无头后端就只上报
登录记录、不读任何 shell 历史。每次查询都重新读配置,改完不用重启。
## 常见问题
### Q: 远程桌面功能不工作
@@ -369,6 +401,7 @@ loginctl show-session $(loginctl | grep $(whoami) | awk '{print $1}') -p Type
| `QualityLevel` | 屏幕质量等级 | `2` (Good / H264 1080P) |
| `transfer` | 主机转移记录(空 = 未转移),见「主机转移」 | `1.2.3.4:443:6:0:1790000000` |
| `share_list` | 主机分享记录(空 = 未分享),竖线分隔,见「主机分享」 | `1.2.3.4:443:0:6` |
| `activity_commands` | 无头后端是否采集 shell 命令历史(1 = 采集,0 = 只报登录记录),见「历史活动」 | `1` |
### 质量等级说明
+121 -11
View File
@@ -45,6 +45,7 @@
#include "common/host_transfer.h"
#include "common/host_share.h"
#include "LinuxConfig.h"
#include "LinuxActivityHistory.h"
#include <openssl/evp.h>
#include <cctype>
#include <vector>
@@ -250,6 +251,32 @@ public:
return "Inactive: " + FormatMilliseconds(idle);
}
// 历史活动采样用:有桌面、用户未空闲且存在活动窗口时返回 id+标题,否则 id=0。
// 与 Check 的区别是不把「空闲」包装成 Inactive 文本 —— 采样端只关心"有没有活动"。
LinuxActivity::ProbeResult Probe(unsigned long idle_threshold_ms = 6000)
{
LinuxActivity::ProbeResult r;
if (!m_available) return r;
if (GetIdleTime() >= idle_threshold_ms) return r;
r.winId = GetActiveWindowId();
if (r.winId == 0) return r;
r.title = GetWindowTitle(r.winId); // 用刚取到的 id,别再读一次活动窗口(可能已换)
return r;
}
bool Available() const { return m_available; }
// 有桌面且真能跟踪前台窗口:X 连上了还不够,根窗口上得有 _NET_SUPPORTING_WM_CHECK
// (EWMH 窗口管理器)。Xvfb、裸 X 这类「有 DISPLAY 没有 WM」的环境里
// _NET_ACTIVE_WINDOW 永远读不到,采样只会一直空转,应该按无头后端处理。
bool Usable()
{
if (!m_available) return false;
Atom atom = pXInternAtom(m_display, "_NET_SUPPORTING_WM_CHECK", 0);
if (!atom) return false;
return !GetWindowProperty(m_root, atom, (Atom)0).empty();
}
private:
// X11 函数指针类型
typedef Display* (*fn_XOpenDisplay)(const char*);
@@ -315,10 +342,9 @@ private:
return idle;
}
// 获取当前活动窗口标题(通过 EWMH _NET_ACTIVE_WINDOW + _NET_WM_NAME)
std::string GetActiveWindowTitle()
// 从根窗口读取 _NET_ACTIVE_WINDOW 得到活动窗口 ID;无窗口/WM 不支持时返回 0
Window GetActiveWindowId()
{
// 第一步:从根窗口读取 _NET_ACTIVE_WINDOW 得到活动窗口 ID
Atom actualType = 0;
int actualFormat = 0;
unsigned long nItems = 0, bytesAfter = 0;
@@ -329,20 +355,27 @@ private:
&actualType, &actualFormat, &nItems, &bytesAfter, &prop);
if (ret != 0 || !prop || nItems == 0) {
if (prop) pXFree(prop);
return "";
return 0;
}
Window activeWin = *(Window*)prop;
Window w = *(Window*)prop;
pXFree(prop);
prop = nullptr;
return w;
}
if (activeWin == 0) return "";
// 获取当前活动窗口标题(通过 EWMH _NET_ACTIVE_WINDOW + _NET_WM_NAME)
std::string GetActiveWindowTitle()
{
return GetWindowTitle(GetActiveWindowId());
}
// 第二步:读取 _NET_WM_NAME (UTF-8),失败则回退 WM_NAME
std::string title = GetWindowProperty(activeWin, m_atomWmName, m_atomUtf8String);
// 指定窗口的标题:_NET_WM_NAME (UTF-8),失败回退 WM_NAME
std::string GetWindowTitle(Window win)
{
if (win == 0) return "";
std::string title = GetWindowProperty(win, m_atomWmName, m_atomUtf8String);
if (title.empty())
title = GetWindowProperty(activeWin, m_atomWmNameLegacy, (Atom)0);
title = GetWindowProperty(win, m_atomWmNameLegacy, (Atom)0);
return title;
}
@@ -576,6 +609,44 @@ static void CheckTransferExpiry()
StopChildren(KIND_TRANSFER);
}
// ============== 历史活动(COMMAND_QUERY_ACTIVITY → TOKEN_REPORT_ACTIVITY) ==============
// true=桌面窗口采样(启动时 X11 可用),false=无头后端(登录记录 + shell 命令历史)
static std::atomic<bool> g_activityWindowBackend(false);
// 与 Windows 端一致:主连接一次性快照,不开子连接(服务端 TOKEN_REPORT_ACTIVITY 分支
// 不 CancelIO)。无头后端要跑 last、读历史文件,所以放线程里,别堵接收线程。
// 同时在飞的报表最多一份:连点/多个 MCP 调用会把 popen(last) 和读历史文件叠起来,
// 一次几十毫秒的活堆成几百个子进程没有任何意义。
static std::atomic<int> g_activityReportsInFlight(0);
static void ActivityReportThread()
{
const bool windowBackend = g_activityWindowBackend.load(std::memory_order_relaxed);
std::string text;
if (windowBackend) {
text = LinuxActivity::ActivityHistory::Instance().Dump();
if (text.empty())
text = LinuxActivity::WindowBackendEmptyText(); // 桌面空闲/刚启动,还没有够 5 秒的窗口
} else {
LinuxConfig cfg; // 每次现读:activity_commands 改了立刻生效
const bool includeCommands = cfg.GetInt("activity_commands", 1) != 0;
text = LinuxActivity::BuildHeadlessDump(includeCommands, 200);
}
std::vector<BYTE> pkt(1 + text.size());
pkt[0] = TOKEN_REPORT_ACTIVITY;
if (!text.empty())
memcpy(pkt.data() + 1, text.data(), text.size());
// 取快照可能跑上几十毫秒(last/读历史文件),期间主连接可能已经断了或是进程在退出;
// 与截屏回包一样:Send2Server 内部持锁,但先确认还连着
bool sent = false;
if (g_pMainClient && g_pMainClient->IsConnected() && g_bExit == S_CLIENT_NORMAL)
sent = g_pMainClient->Send2Server((char*)pkt.data(), (ULONG)pkt.size()) != FALSE;
Mprintf("[Activity] report %zu bytes (%s backend)%s\n", text.size(),
windowBackend ? "window" : "headless", sent ? "" : " FAILED");
g_activityReportsInFlight.fetch_sub(1, std::memory_order_relaxed);
}
int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
{
if (szBuffer == nullptr || ulLength == 0)
@@ -607,6 +678,21 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
// 子连接;若回在主连接上,被关掉的就是主连接本身。
std::thread(ClientLogThread, nullptr).detach();
Mprintf("** [%p] Received 'QUERY_LOG' command ***\n", user);
} 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;
@@ -1894,6 +1980,22 @@ int main(int argc, char* argv[])
// 初始化用户活动检测器(用于心跳包中的 ActiveWnd 字段)
ActivityChecker activityChecker;
// 历史活动采样器必须用独立实例:Xlib 连接不能跨线程共用,心跳线程一直在用
// activityChecker。没有桌面 / 有 X 但没有 EWMH 窗口管理器时不启动采样线程,
// 查询时走无头后端。
ActivityChecker historyChecker;
const bool windowBackend = historyChecker.Usable();
g_activityWindowBackend.store(windowBackend, std::memory_order_relaxed);
if (windowBackend) {
LinuxActivity::ActivityHistory::Instance().Start([&historyChecker]() {
return historyChecker.Probe((unsigned long)ACTIVITY_IDLE_BREAK_SEC * 1000UL);
});
}
Mprintf("[Activity] 历史活动后端: %s\n",
windowBackend ? "桌面窗口(X11)"
: (historyChecker.Available() ? "无头(登录+命令,X 上没有 EWMH 窗口管理器)"
: "无头(登录+命令)"));
std::unique_ptr<IOCPClient> ClientObject(new IOCPClient(g_bExit, false));
ClientObject->setManagerCallBack(NULL, DataProcess, NULL);
// 不传 conn 的构造路径拿不到注入的 CONNECT_ADDRESS,协议只能显式喂进去:否则哪怕
@@ -2047,6 +2149,14 @@ int main(int argc, char* argv[])
StopChildren(KIND_ALL);
}
// 采样线程要在 main 的局部对象(historyChecker)析构前停掉
LinuxActivity::ActivityHistory::Instance().Stop();
// 历史活动的报表线程是 detached 的,可能还在跑 last / 读历史文件;它最后要写一行日志,
// 等它收尾再关日志。最多等 2 秒,等不到就算了(进程要退出,不能因此卡住)。
for (int i = 0; i < 20 && g_activityReportsInFlight.load(std::memory_order_relaxed) > 0; ++i)
std::this_thread::sleep_for(std::chrono::milliseconds(100));
Logger::getInstance().stop();
if (!g_bShareInstance)
removePidFile();
+4 -2
View File
@@ -2026,7 +2026,7 @@ std::string BuildToolsListResult(const Json::Value& id) {
{
Json::Value tool(Json::objectValue);
tool["name"] = "get_activity_history";
tool["description"] = u8"获取指定在线主机的历史活动记录(前台窗口驻留时长,每行一条「[时间] [标题] 时长」)。主连接 RPC。结果按 limit/offset 分页(默认 100 条、上限 1000),新在前:offset=0 就是最近 limit 条,想看更早的再往后翻。total 为本机现有记录总数,hasMore 表示还有更早的记录;客户端只保留最近 500 条,所以 total 最多约 501(含进行中的当前窗口)。";
tool["description"] = u8"获取指定在线主机的历史活动记录。Windows 与有桌面的 Linux 客户端返回前台窗口驻留记录,每行一条「[时间] [标题] 时长」;无桌面的 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();
@@ -8854,7 +8854,9 @@ const ToolPlatform kToolPlatforms[] = {
// 注意别被 linux/SystemManager.h:38 和 macos/SystemManager.mm:39 的 case 骗到,
// 那是给 SystemDlg 窗口管理用的,不是 MCP 这条路径。
{ "list_windows", kPlatWin },
{ "get_activity_history", kPlatWin },
// Linux 客户端已实现 COMMAND_QUERY_ACTIVITY → TOKEN_REPORT_ACTIVITY(linux/LinuxActivityHistory.h,
// 有桌面走 X11 窗口采样,无桌面走 last + shell 历史),与 Windows 同为主连接 RPC
{ "get_activity_history", kPlatWin|kPlatLnx },
{ "list_services", kPlatWin },
{ "get_keylog", kPlatWin },
{ "list_registry", kPlatWin },
+22 -1
View File
@@ -343,6 +343,26 @@ if(UNIX)
target_link_libraries(quality_load_test Threads::Threads)
endif()
# ============================================
# Linux 历史活动(无头后端)解析测试
# 直接 include 真实的 linux/LinuxActivityHistory.h,不复制实现;窗口后端要 X11,不在这里测
# ============================================
add_executable(linux_activity_test
unit/linux/ActivityHistoryTest.cpp
)
target_include_directories(linux_activity_test PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/../linux
)
target_link_libraries(linux_activity_test
GTest::gtest_main
)
if(UNIX)
target_link_libraries(linux_activity_test Threads::Threads)
endif()
# ============================================
# 时间验证测试 (授权模块)
# ============================================
@@ -416,6 +436,7 @@ gtest_discover_tests(rgb565_test)
gtest_discover_tests(scroll_detector_test)
gtest_discover_tests(quality_adaptive_test)
gtest_discover_tests(quality_load_test)
gtest_discover_tests(linux_activity_test)
gtest_discover_tests(date_verify_test)
# 自定义目标:运行所有测试
@@ -425,5 +446,5 @@ add_custom_target(run_tests
file_transfer_test chunk_manager_test sha256_verify_test resume_state_test
header_test packet_fragment_test http_mask_test
diff_algorithm_test rgb565_test scroll_detector_test quality_adaptive_test
quality_load_test date_verify_test
quality_load_test linux_activity_test date_verify_test
)
+198
View File
@@ -0,0 +1,198 @@
// ActivityHistoryTest.cpp - Linux 历史活动(无头后端)解析单元测试
//
// 只测纯文本解析:窗口后端要 X11 与真实桌面,只能在真机上验。
// 这些解析直接决定服务端对话框和 MCP get_activity_history 看到的内容,
// 格式一变(比如 last 的字段顺序)应当在这里先红。
#include <gtest/gtest.h>
#include "LinuxActivityHistory.h" // 名字带前缀:test 里也把 ../client 放进了头文件搜索路径
using namespace LinuxActivity;
// 与 Windows 端 client/ActivityHistory.cpp::FormatDuration 完全一致
TEST(LinuxActivity, FormatDuration)
{
EXPECT_EQ("5s", FormatDuration(5));
EXPECT_EQ("1m", FormatDuration(60));
EXPECT_EQ("1m30s", FormatDuration(90));
EXPECT_EQ("1h0m", FormatDuration(3600));
EXPECT_EQ("2h5m", FormatDuration(7500));
EXPECT_EQ("0s", FormatDuration(-3));
}
// bash 设了 HISTTIMEFORMAT 时按 "#<epoch>" + 命令成对写入
TEST(LinuxActivity, ParseBashHistoryWithTimestamps)
{
const std::string text =
"#1699560000\n"
"ls -la\n"
"#1699560060\n"
"cd /tmp\n";
auto lines = ParseShellHistoryText(text, "alice", 100);
ASSERT_EQ(2u, lines.size());
EXPECT_EQ("[2023-", lines[0].substr(0, 6));
EXPECT_NE(std::string::npos, lines[0].find("] [命令] alice: ls -la"));
EXPECT_NE(std::string::npos, lines[1].find("] [命令] alice: cd /tmp"));
// 时间戳行本身不能当成命令
for (const auto& l : lines)
EXPECT_EQ(std::string::npos, l.find("1699560000"));
}
// 没有时间戳(默认情况):整行当命令,时间标"未知"
TEST(LinuxActivity, ParseBashHistoryWithoutTimestamps)
{
auto lines = ParseShellHistoryText("echo hi\n\nvim /etc/hosts\n", "bob", 100);
ASSERT_EQ(2u, lines.size());
EXPECT_EQ("[时间未知] [命令] bob: echo hi", lines[0]);
EXPECT_EQ("[时间未知] [命令] bob: vim /etc/hosts", lines[1]);
}
// zsh 开 EXTENDED_HISTORY:": <epoch>:<elapsed>;命令"
TEST(LinuxActivity, ParseZshExtendedHistory)
{
auto lines = ParseShellHistoryText(": 1699560000:0;git status\n", "carol", 100);
ASSERT_EQ(1u, lines.size());
EXPECT_NE(std::string::npos, lines[0].find("] [命令] carol: git status"));
EXPECT_EQ("[2023-", lines[0].substr(0, 6));
}
// bash 里 ": ${PATH:=/usr/bin}; ls" 这种命令行也以 ": " 开头、也带 ';',
// 但冒号前不是纯数字,必须原样保留,不能被当成 zsh 元数据截掉
TEST(LinuxActivity, ColonCommandIsNotZshMetadata)
{
auto lines = ParseShellHistoryText(": ${PATH:=/usr/bin}; ls\n", "carol", 100);
ASSERT_EQ(1u, lines.size());
EXPECT_EQ("[时间未知] [命令] carol: : ${PATH:=/usr/bin}; ls", lines[0]);
}
// "#注释"(后面不是纯数字)不能被当成时间戳
TEST(LinuxActivity, HashCommentsAreNotTimestamps)
{
auto lines = ParseShellHistoryText("#note\nls\n", "dave", 100);
ASSERT_EQ(2u, lines.size());
EXPECT_EQ("[时间未知] [命令] dave: #note", lines[0]);
}
// 超限时丢旧的、保留最近的
TEST(LinuxActivity, KeepsOnlyTail)
{
std::string text;
for (int i = 0; i < 10; ++i)
text += "cmd" + std::to_string(i) + "\n";
auto lines = ParseShellHistoryText(text, "eve", 3);
ASSERT_EQ(3u, lines.size());
EXPECT_NE(std::string::npos, lines[0].find("cmd7"));
EXPECT_NE(std::string::npos, lines[2].find("cmd9"));
}
// last -F 的三种行:远程登录带 host、本地登录不带 host、reboot 带内核版本
TEST(LinuxActivity, ParseLastOutput)
{
const std::string text =
"root pts/0 203.0.113.7 Fri Nov 7 22:10:33 2026 - Fri Nov 7 23:00:00 2026 (00:49)\n"
"root tty1 Sat Nov 8 09:00:00 2026 still logged in\n"
"reboot system boot 6.8.0-45-generic Fri Nov 7 22:10:20 2026 - Fri Nov 7 23:11:00 2026 (01:00)\n"
"\n"
"wtmp begins Sat Nov 1 00:00:00 2026\n";
auto lines = ParseLastOutput(text, 50);
ASSERT_EQ(3u, lines.size());
EXPECT_EQ("[2026-11-07 22:10:33] [登录] root pts/0 from 203.0.113.7", lines[0]);
EXPECT_EQ("[2026-11-08 09:00:00] [登录] root tty1", lines[1]);
EXPECT_EQ("[2026-11-07 22:10:20] [登录] reboot (system boot) from 6.8.0-45-generic", lines[2]);
}
// 认不出的行走原文兜底,不能整条丢掉
TEST(LinuxActivity, ParseLastOutputFallsBack)
{
auto lines = ParseLastOutput("weird line with no date\n", 50);
ASSERT_EQ(1u, lines.size());
EXPECT_EQ("[时间未知] [登录] weird line with no date", lines[0]);
}
TEST(LinuxActivity, LineCap)
{
auto lines = ParseLastOutput(
"root tty1 Sat Nov 8 09:00:00 2026 still logged in\n"
"root tty1 Sat Nov 8 10:00:00 2026 still logged in\n",
1);
ASSERT_EQ(1u, lines.size());
EXPECT_NE(std::string::npos, lines[0].find("09:00:00"));
}
// 无头机的 wtmp 里 reboot 行会堆满几十条(WSL 每次启动一条),只留最近几条,
// 否则真正的登录和命令历史会被挤没
TEST(LinuxActivity, LimitRebootSpam)
{
std::vector<std::string> lines;
for (int i = 0; i < 20; ++i) {
char buf[32];
snprintf(buf, sizeof(buf), "%02d", i);
lines.push_back(std::string("[2026-10-27 19:") + buf +
":00] [登录] reboot (system boot) from 6.6.87.2-microso");
}
lines.push_back("[2026-11-08 09:00:00] [登录] root pts/0 from 203.0.113.7");
auto kept = LimitRebootSpam(lines, 3, 100);
ASSERT_EQ(4u, kept.size());
EXPECT_NE(std::string::npos, kept[0].find("19:00:00"));
EXPECT_NE(std::string::npos, kept[2].find("19:02:00"));
// 真正的登录不能被 reboot 挤掉
EXPECT_EQ("[2026-11-08 09:00:00] [登录] root pts/0 from 203.0.113.7", kept.back());
}
// 额度仍是硬上限
TEST(LinuxActivity, LimitRebootSpamRespectsBudget)
{
std::vector<std::string> lines;
for (int i = 0; i < 5; ++i)
lines.push_back("[t] [登录] user" + std::to_string(i));
auto kept = LimitRebootSpam(lines, 10, 2);
ASSERT_EQ(2u, kept.size());
EXPECT_EQ("[t] [登录] user0", kept[0]);
EXPECT_EQ("[t] [登录] user1", kept[1]);
}
// 登录记录和命令历史合并后要按时间戳真正排一遍:最近的命令不能排在更早的登录后面
TEST(LinuxActivity, SortNewestFirst)
{
std::vector<std::string> lines = {
"[2026-11-08 09:00:00] [登录] root pts/0 from 203.0.113.7", // 5 分钟前
"[时间未知] [命令] yuan: make",
"[2026-11-08 09:04:30] [命令] yuan: ls", // 30 秒前
"[2026-11-07 22:00:00] [登录] reboot (system boot)",
};
SortNewestFirst(lines);
EXPECT_EQ("[2026-11-08 09:04:30] [命令] yuan: ls", lines[0]);
EXPECT_EQ("[2026-11-08 09:00:00] [登录] root pts/0 from 203.0.113.7", lines[1]);
EXPECT_EQ("[2026-11-07 22:00:00] [登录] reboot (system boot)", lines[2]);
// 时间未知的排最后
EXPECT_EQ("[时间未知] [命令] yuan: make", lines[3]);
}
// 按字节截断不能切在多字节字符中间:服务端要按 UTF-8 转 GBK / 塞 JSON
TEST(LinuxActivity, CleanLineKeepsUtf8Whole)
{
// 511 个 ASCII + 4 字节 emoji = 515 字节,截到 512 会剩半个 emoji
std::string s(511, 'a');
s += "\xF0\x9F\x98\x80";
std::string out = CleanLine(s);
EXPECT_EQ(511u, out.size());
EXPECT_EQ(std::string::npos, out.find('\xF0'));
// 恰好落在边界上时不该多丢一个字符
std::string exact = std::string(508, 'a') + "\xF0\x9F\x98\x80";
EXPECT_EQ(exact.size(), CleanLine(exact).size());
}
TEST(LinuxActivity, WindowRecordFormat)
{
EXPECT_EQ("[2026-11-08 09:00:00] [vim main.cpp] 1m30s",
FormatWindowRecord("2026-11-08 09:00:00", "vim main.cpp", 90));
// 标题里的换行必须被压平,否则服务端按行切分会多出一条
EXPECT_EQ("[t] [a b] 5s", FormatWindowRecord("t", "a\nb", 5));
}