5 Commits
Author SHA1 Message Date
yuanyuanxianganddeepseek-flash ae46b7b53b Test: add a release-gate E2E smoke script
Basic functions were only ever exercised by hand before a release, and a
regression that killed the client when opening video management stayed in
the field for a month. The new script starts an isolated Debug server
(Bin\settings.ini, port 6543), brings a test client online (the built-in
Run Test client by default, x64\Debug\ghost.exe with -ExternalClient),
selects the host and fires the real toolbar command IDs one by one.

Every command must open a new #32770 dialog within a per-feature timeout,
and the server/client processes are checked for liveness after each step,
so a crash like the webcam one fails loudly instead of waiting to be
noticed. Results are PASS/FAIL/WARN/SKIP: WARN is a message box (its text
is included), SKIP marks missing prerequisites (no microphone, no admin
rights, no camera).

MCP/Web ports held by the running Release instance are temporarily turned
off in settings.ini and the file is restored unconditionally afterwards;
the Release instance is never touched. Verified end to end in both client
modes on the development machine.

Co-Authored-By: deepseek-flash
2026-11-21 16:44:47 +01:00
yuanyuanxianganddeepseek-flash 94cb4584c8 Fix(client): keep webcam capture alive across driver quirks
Opening video management killed the client on some hosts: the DirectShow
sample callback memcpy'd into a null bitmap buffer.

IMediaControl::Run legitimately returns S_FALSE while the state change
completes asynchronously; the graph is already running and frames are
delivered. Open passed that S_FALSE to its caller, which compared against
S_OK (introduced in 8d4c118) and took the "camera failed to open" abort
path while the graph kept running; ConstructBI never allocated the buffers
and the first callback wrote to address 0.

Open now returns S_OK only when the graph is running (S_FALSE normalised)
and a failure code otherwise. BufferCB drops a frame with S_OK when the
buffer is not ready or the driver hands over more bytes than negotiated,
so the start-up race or a resolution change can neither corrupt the heap
nor stop the stream. ConstructBI validates the dimensions and allocates the
full BITMAPINFO that SendBitMapInfor copies.

Also accept FORMAT_VideoInfo2 (many built-in cameras report it, and the
cast to VIDEOINFOHEADER read garbage dimensions) and fix BindVideoFilter's
comma-expression loop that called BindToStorage with a dangling IMoniker
once enumeration ran out.

Debug and Release x64 clients build; the host that reproducibly crashed
now works.

Co-Authored-By: deepseek-flash
2026-11-21 16:44:42 +01:00
yuanyuanxianganddeepseek-flash 798456032e Fix(server): size status bar panes from measured text
The FRP/runtime/expiry panes kept fixed 250/180/180 pixel widths while the
text is drawn with a system font that changes with language, display
scaling and accessibility text size. Where the font is larger the expiry
text is cut inside the pane: "到期: 2026-12-31 (41天)" shows the date but
drops the remaining days, and the wider English "Expires: 2026-12-31 (41d)"
stays cut on another machine.

Measure each pane's text as wide characters (the status bar control is
Unicode internally; ANSI measurement is up to 10% narrower for CJK) against
several candidate fonts - the pane's own font, SYSTEM_FONT, DEFAULT_GUI_FONT,
lfStatusFont and lfMessageFont - and take the widest. Widths never drop below
the previously proven 250/180/180, so 100% scaling layouts are unchanged, and
the expiry pane gets an extra 20px with a 220px floor for the longer English
string.

A new LayoutStatusPanes() applies the widths in one place and, when their sum
exceeds the bar, hides panes in priority order (runtime -> FRP -> MCP -> TLS)
so the last pane cannot be clipped at the window edge. OnSize, the periodic
refresh and the FRP auto-proxy start/stop all go through it now.

Verified with Release x64 builds; visual confirmation on the affected
machines is still pending.

Co-Authored-By: deepseek-flash
2026-11-21 12:31:38 +01:00
yuanyuanxianganddeepseek-flash de9e9a7369 Feature(client): support host transfer in the macOS client
Mirror the Android semantics: move the main link to the assigned master
immediately, persist the record in config so it survives restarts, return
to the original master on expiry or early return, and revert after the new
master stays unreachable for 60s. Share requests are answered as
unsupported, and the capability matrix is updated accordingly.

A target counts as unusable when the connection is refused or when it is
accepted but never passes MasterSettings (a foreign service on that port,
or a master built with another key). The latter used to be retried forever,
stranding the host until expiry; both shapes now count toward the revert
gate and reset only once a connection verifies. Early return clears the
persisted record at once, so a crash before the main loop restores the
original master cannot resurrect the transfer on restart.

Endpoints from the command or the record are bounds-checked before being
written into CONNECT_ADDRESS (strcpy_s is strcpy on POSIX), config access
is serialized across the receive and main threads, the new validTo is
published before the pending target so expiry cannot undo a fresh
transfer, and a stale early-return flag is cleared when a new transfer
applies or one is reverted.

The Linux client was rebuilt with the shared header changes; the macOS
side is not compiled here and still needs a build on a Mac.

Co-Authored-By: deepseek-flash
2026-11-21 10:15:35 +01:00
yuanyuanxianganddeepseek-flash 913b74097b Improve: ship release builds without debug info and symbols
linux/CMakeLists.txt forced -g into the global flags regardless of build
type, so even a Release build carried full DWARF: 7.7MB of the 10.3MB
binary was .debug_* material the client never uses at runtime.

Drop the forced -g and default CMAKE_BUILD_TYPE to Release, stripping the
symbol table at link time (-s) so only Debug builds keep symbols. Do the
same for macOS with ld64's -Wl,-x on Release, which drops the 8.3k local
symbols while keeping external ones and the signature ld appends.

linux/ghost drops from 10.3MB to 2.5MB (UPX on top: 0.87MB). Rebuilt
under WSL and verified with readelf: no .debug_*/.symtab/.strtab, BuildID
kept. The macOS change is not verified here; it needs a build on the Mac.

Co-Authored-By: deepseek-flash
2026-11-20 17:40:00 +01:00
16 changed files with 1163 additions and 102 deletions

No files matched your search

+58 -32
View File
@@ -4,6 +4,7 @@
#include "stdafx.h"
#include "CaptureVideo.h"
#include <dvdmedia.h> // VIDEOINFOHEADER2:不少摄像头/驱动给的是 FORMAT_VideoInfo2
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
@@ -46,13 +47,14 @@ CCaptureVideo::~CCaptureVideo()
HRESULT CCaptureVideo::Open(int iDeviceID,int iPress)
{
Mprintf("CCaptureVideo call Open\n");
HRESULT hResult = S_FALSE;
HRESULT hResult = E_FAIL; // 默认失败:只有图真正跑起来才算成功
bool graphRunning = false;
do {
hResult = InitCaptureGraphBuilder();
if (FAILED(hResult))
break;
if (!BindVideoFilter(iDeviceID, &m_pBF)) {
hResult = S_FALSE;
hResult = E_FAIL; // 没有可用的 DirectShow 采集设备
break;
}
@@ -97,10 +99,29 @@ HRESULT CCaptureVideo::Open(int iDeviceID,int iPress)
//3 扑捉数据 FDO 一旦有数据就进行 回调函数调用 属于一个类
VIDEOINFOHEADER * vih = (VIDEOINFOHEADER*) mt.pbFormat;
// 只按 VIDEOINFOHEADER 解释 mt.pbFormat 不够:很多摄像头/驱动(尤其
// 笔记本内置摄像头)给出的格式是 FORMAT_VideoInfo2,两者头部布局不同,
// 直接强转会读出垃圾宽高,后面按它分配缓冲/逐帧 memcpy 就会崩。两种都认,
// 其它格式或非法尺寸一律当失败处理,让上层优雅退出而不是带病跑。
BITMAPINFOHEADER* bmi = NULL;
if (mt.formattype == FORMAT_VideoInfo && mt.pbFormat != NULL
&& mt.cbFormat >= sizeof(VIDEOINFOHEADER)) {
bmi = &((VIDEOINFOHEADER*)mt.pbFormat)->bmiHeader;
} else if (mt.formattype == FORMAT_VideoInfo2 && mt.pbFormat != NULL
&& mt.cbFormat >= sizeof(VIDEOINFOHEADER2)) {
bmi = &((VIDEOINFOHEADER2*)mt.pbFormat)->bmiHeader;
}
if (bmi == NULL || bmi->biWidth <= 0 || bmi->biHeight == 0
|| bmi->biWidth > 16384 || abs(bmi->biHeight) > 16384) {
Mprintf("CCaptureVideo: unsupported media type (formattype=%08lx cbFormat=%lu), abort\n",
(unsigned long)mt.formattype.Data1, (unsigned long)mt.cbFormat);
FreeMediaType(mt);
hResult = E_FAIL;
break;
}
//mCB 是个另外一个类 并且全局变量 有个回调
mCB.m_ulFullWidth = vih->bmiHeader.biWidth;
mCB.m_ulFullHeight = vih->bmiHeader.biHeight;
mCB.m_ulFullWidth = (ULONG)bmi->biWidth;
mCB.m_ulFullHeight = (ULONG)abs(bmi->biHeight);
FreeMediaType(mt);
@@ -120,11 +141,19 @@ HRESULT CCaptureVideo::Open(int iDeviceID,int iPress)
if(FAILED(hResult))
break;
// IMediaControl::Run 在「状态切换尚未完成、稍后异步完成」时会返回 S_FALSE,
// 这时图已经在跑、SampleGrabber 回调随时会到。以前把它原样返回给上层,
// 上层用 == S_OK 判断就误判成「摄像头没打开」并提前中止(8d4c118 引入),
// 而回调随后拿还没分配的 m_BitmapData_Full 做 memcpy —— 写地址 0 崩溃。
hResult = S_OK;
graphRunning = true;
} while (false);
Mprintf("CCaptureVideo Open %s\n", FAILED(hResult) ? "failed" : "succeed");
Mprintf("CCaptureVideo Open %s (hr=%08lX)\n",
graphRunning ? "succeed" : "failed", (unsigned long)hResult);
return hResult;
// 图没跑起来时一律返回失败码(S_FALSE 也是「成功」语义,会让上层误判)
return graphRunning ? S_OK : (FAILED(hResult) ? hResult : E_FAIL);
}
@@ -164,43 +193,40 @@ LPBITMAPINFO CCaptureVideo::GetBmpInfor()
BOOL CCaptureVideo::BindVideoFilter(int deviceId, IBaseFilter **pFilter)
{
if (deviceId < 0)
if (deviceId < 0 || pFilter == NULL)
return FALSE;// enumerate all video capture devices
*pFilter = NULL;
CComPtr<ICreateDevEnum> pCreateDevEnum;
HRESULT hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER,
IID_ICreateDevEnum, (void**)&pCreateDevEnum);
if (hr != NOERROR) {
if (hr != NOERROR)
return FALSE;
}
CComPtr<IEnumMoniker> pEm;
hr = pCreateDevEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory,&pEm, 0);
if (hr != NOERROR) {
hr = pCreateDevEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory, &pEm, 0);
if (hr != S_OK) // S_FALSE = 该类别下没有任何 DirectShow 设备
return FALSE;
}
pEm->Reset();
ULONG cFetched;
IMoniker *pM;
ULONG cFetched = 0;
IMoniker* pM = NULL;
int index = 0;
while(hr = pEm->Next(1, &pM, &cFetched), hr==S_OK, index <= deviceId) {
IPropertyBag *pBag;
//通过BindToStorage 可以访问该设备的标识集
hr = pM->BindToStorage(0, 0, IID_IPropertyBag, (void **)&pBag);
if(SUCCEEDED(hr)) {
VARIANT var;
var.vt = VT_BSTR;
hr = pBag->Read(L"FriendlyName", &var, NULL);
if (hr == NOERROR) {
if (index == deviceId) {
pM->BindToObject(0, 0, IID_IBaseFilter, (void**)pFilter);
}
SysFreeString(var.bstrVal);
}
pBag->Release(); //引用计数--
// 原实现写成逗号表达式 `while (hr = Next(...), hr == S_OK, index <= deviceId)`:
// 循环条件实际只看 index,枚举结束后还会继续用未初始化/已释放的 pM 调
// BindToStorage。机器上 VFW 能枚举到摄像头、DirectShow 却一个都没有时必崩。
while (pEm->Next(1, &pM, &cFetched) == S_OK && pM != NULL) {
if (index == deviceId) {
hr = pM->BindToObject(0, 0, IID_IBaseFilter, (void**)pFilter);
pM->Release();
return SUCCEEDED(hr) && *pFilter != NULL;
}
pM->Release();
index++;
pM = NULL;
++index;
}
return TRUE;
Mprintf("CCaptureVideo: no DirectShow video device #%d (enumerated %d)\n", deviceId, index);
return FALSE;
}
+21 -4
View File
@@ -123,10 +123,19 @@ public:
LPBITMAPINFO ConstructBI(ULONG ulbiBitCount)
{
int ColorNum = ulbiBitCount <= 8 ? 1 << ulbiBitCount : 0;
ULONG ulBitmapLength = sizeof(BITMAPINFOHEADER) + (ColorNum * sizeof(RGBQUAD)); //BITMAPINFOHEADER + 调色板的个数
// 宽高来自摄像头驱动,必须挡住 0/超大值:否则 biSizeImage 会溢出成小值,
// 之后每帧 memcpy 都变成堆越界——「换一台机器一开视频就崩」多半出在这里。
if (m_ulFullWidth == 0 || m_ulFullHeight == 0
|| m_ulFullWidth > 16384 || m_ulFullHeight > 16384)
return NULL;
m_BitmapInfor_Full = (BITMAPINFO *) new BYTE[ulBitmapLength];
// 分配「头部 + 完整 256 项调色板」:BITMAPINFO 本身只声明 bmiColors[1]
// (sizeof=44),而按 biBitCount 索引调色板的调用方会读到 44 字节之外。
// 当前只以 24bpp 调用(RGBQUAD 用不到),但按最大调色板预留 1KB 最省心,
// 也顺便修正了旧代码分配 40 字节、SendBitMapInfor 按 44 字节读取的越界。
const size_t biSize = sizeof(BITMAPINFOHEADER) + 256 * sizeof(RGBQUAD);
m_BitmapInfor_Full = (BITMAPINFO*) new BYTE[biSize];
ZeroMemory(m_BitmapInfor_Full, biSize);
BITMAPINFOHEADER* BitmapInforHeader = &(m_BitmapInfor_Full->bmiHeader);
@@ -192,8 +201,16 @@ public:
}
if (bStact==CMD_CAN_COPY) { //未初始化 发送的同差异的一样
// 驱动送来的帧可能比协商格式大(分辨率切换、格式回退、驱动自带填充):
// 不校验长度就 memcpy 会直接把堆写坏,表现就是进程当场崩溃。
// 注意必须返回 S_OK:BufferCB 返回错误可能让 SampleGrabber 停流,
// 那会让「图刚跑起来、缓冲区还没建好」时的第一帧把整条视频流掐死。
if (m_BitmapData_Full == NULL || m_dwSize == 0 || ulBufferSize <= 0
|| (unsigned long)ulBufferSize > m_dwSize) {
return S_OK; // 丢这一帧,保持数据流
}
//将图像数据拷贝的我们的内存
memcpy(m_BitmapData_Full,szBuffer,ulBufferSize); //位图
memcpy(m_BitmapData_Full,szBuffer,(size_t)ulBufferSize); //位图
InterlockedExchange((LPLONG)&bStact,CMD_CAN_SEND); //原子自增可以发送
return S_OK;
+19 -2
View File
@@ -36,6 +36,14 @@ DWORD CVideoManager::WorkThread(LPVOID lParam)
return 0x20261013;
}
// 摄像头打开成功但格式解析失败(VIDEOINFOHEADER2 之外的媒体类型、宽高非法等):
// 结束本次会话,绝不带着空缓冲区进采帧循环——那会在第一帧 memcpy 时崩掉。
if (This->m_CapVideo.GetBmpInfor() == NULL) {
Mprintf("CVideoManager: camera format unusable, abort session\n");
This->Destroy();
return 0x20261014;
}
static ULONGLONG dwLastScreen = GetTickCount64();
if (This->Initialize()) { //转到Initialize
@@ -100,10 +108,15 @@ void CVideoManager::Destroy()
void CVideoManager::SendBitMapInfor()
{
LPBITMAPINFO bi = m_CapVideo.GetBmpInfor();
if (bi == NULL) {
Mprintf("CVideoManager: no bitmap info, skip sending\n");
return;
}
const int dwBytesLength = 1 + sizeof(BITMAPINFO);
BYTE szBuffer[dwBytesLength + 3] = { 0 };
szBuffer[0] = TOKEN_WEBCAM_BITMAPINFO;
memcpy(szBuffer + 1, m_CapVideo.GetBmpInfor(), sizeof(BITMAPINFO));
memcpy(szBuffer + 1, bi, sizeof(BITMAPINFO));
HttpMask mask(DEFAULT_HOST, m_ClientObject->GetClientIPHeader());
m_ClientObject->Send2Server((char*)szBuffer, dwBytesLength, &mask);
}
@@ -187,9 +200,13 @@ BOOL CVideoManager::Initialize()
bRet= FALSE;
return bRet;
}
LPBITMAPINFO bi = m_CapVideo.GetBmpInfor();
if (bi == NULL) {
return FALSE;
}
m_pVideoCodec = new CVideoCodec;
//这里初始化,视频压缩 ,注意这里的压缩码 m_fccHandler(到构造函数中查看)
if (!m_pVideoCodec->InitCompressor(m_CapVideo.GetBmpInfor(), m_fccHandler)) {
if (!m_pVideoCodec->InitCompressor(bi, m_fccHandler)) {
delete m_pVideoCodec;
bRet=FALSE;
// 置NULL, 发送时判断是否为NULL来判断是否压缩
+7
View File
@@ -56,6 +56,13 @@ inline bool IsCommandAllowed(unsigned char cmd)
return g_settingsVerified.load(std::memory_order_acquire) || cmd == CMD_MASTERSETTING;
}
// 本连接是否已通过 MasterSettings 校验。转移主机用它判断「目标主控是否真的可用」:
// 连得上但校验一直不通过(对端不是主控,或不是本构建的主控)与连不上等价。
inline bool IsVerified()
{
return g_settingsVerified.load(std::memory_order_acquire);
}
// 处理 CMD_MASTERSETTING(payload = szBuffer + 1,payloadLen = ulLength - 1):
// 强制要求完整 MasterSettings(包含 Signature 字段);不完整 / 签名失败 → 不更新
// g_settingsVerified,让心跳循环 30s 超时自然把本次连接断开重连。
+11 -1
View File
@@ -43,10 +43,20 @@ inline bool ParseHeaderEnc(const std::string& s, int& out)
return true;
}
// 端点能安全写进 CONNECT_ADDRESS 的边界。非 Windows 上 strcpy_s/sprintf_s 就是无界的
// strcpy/sprintf(见 commands.h),地址超长会直接踩坏 szPort/iType 等后续字段,
// 所以来自命令或配置文件的端点必须先过这一关。
inline bool FitsConnAddress(const Endpoint& ep)
{
return !ep.ip.empty()
&& ep.ip.size() <= sizeof(((CONNECT_ADDRESS*)nullptr)->szServerIP) - 1
&& ep.port > 0 && ep.port <= 65535;
}
// 把端点写进连接参数。只在连接生命周期的持有线程调用(见文件头注释)。
inline void ApplyEndpoint(CONNECT_ADDRESS& conn, const Endpoint& ep)
{
if (ep.ip.empty() || ep.port <= 0)
if (!FitsConnAddress(ep))
return;
conn.SetServer(ep.ip.c_str(), ep.port);
if (ep.transport >= 0)
+6 -2
View File
@@ -17,6 +17,7 @@
namespace HostTransfer {
using HostEndpoint::Endpoint;
using HostEndpoint::FitsConnAddress;
using HostEndpoint::ParseTransport;
using HostEndpoint::ParseHeaderEnc;
using HostEndpoint::ApplyEndpoint;
@@ -28,7 +29,8 @@ struct Target {
long long validTo; // <= 0 表示无效
Target() : validTo(0) {}
bool Valid() const { return !ep.ip.empty() && ep.port > 0 && validTo > 0; }
// 端点容量由 FitsConnAddress 守住:记录里存的是外部输入,直接 ApplyTarget 会越界。
bool Valid() const { return FitsConnAddress(ep) && validTo > 0; }
bool Active(long long now) const { return Valid() && now <= validTo; }
};
@@ -54,7 +56,9 @@ inline bool ParseAssignCommand(const unsigned char* buf, unsigned long len,
Target t;
t.ep.ip = v[0];
t.ep.port = atoi(v[1].c_str());
if (t.ep.ip.empty() || t.ep.port <= 0 || t.ep.port > 65535)
// 长度/端口范围都要挡住:服务端只限制整条载荷不超过 250 字节,地址本身可以顶到
// CONNECT_ADDRESS::szServerIP[100] 之外,写进 g_SETTINGS 时就是堆栈/全局越界。
if (!FitsConnAddress(t.ep))
return false;
double days = atof(v[2].c_str());
+2 -2
View File
@@ -23,10 +23,10 @@
| 远程切换传输协议(TCP/WS/WSS) | ✓ | — | — | — |
| 客户端 ID 重建(克隆机撞 ID) | ✓ | — | — | — |
| 分享主机 / 取消分享 | ✓ | ✓ | — | — |
| 转移主机(到期自动复原) | ✓ | ✓ | — | ✓ |
| 转移主机(到期自动复原) | ✓ | ✓ | ✓ | ✓ |
说明:
- 分享/转移:Android 实现转移、不实现分享(收到分享命令会回“不支持”);macOS 两者均未实现。
- 分享/转移:Android 实现转移、不实现分享(收到分享命令会回“不支持”);macOS 同样只实现转移(收包即迁移主连接,记录存 `~/.config/ghost/config.conf` 的 `transfer` 键,连不上目标满 60 秒且连续失败 3 次后退回原主控),分享命令回“不支持”。
- **WebSocket/WSS 是“出包能力”,不是“运行时切换能力”**:四个平台的网络层(`IOCPClient` + `WsChannel.h`)都实现了 WS/WSS,生成客户端时把「协议」选为 WebSocket 或 WS+TLS 即可,客户端启动后按烘焙的 `protoType` 连接(需经反向代理入口;WSS 还需内嵌或在线下发的信任锚)。但运行时的「协议切换」菜单走 `COMMAND_SET_PROTO`,只有 Windows 客户端处理该命令并声明 `CLIENT_CAP_PROTO_SWITCH`;其他平台该菜单整组置灰,菜单里勾选 TCP 只是当前实际连接的传输,不代表客户端只能走 TCP。
- UDP/KCP/HTTP 伪装传输:只有 Windows 客户端有对应实现;Linux/macOS/Android 的网络层只处理 TCP/WS/WSS,出包时选其他协议不会生效。
- 并发上线(`RUNNING_PARALLEL`)只有 Windows 客户端实现;其他平台按单实例运行。
+9 -3
View File
@@ -35,9 +35,15 @@ set(SOURCES
add_executable(ghost ${SOURCES})
# 设置为可以调试
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g")
# 默认使用 Release:无调试信息、-O3,链接时剥离符号表(ghost 约 2.5MB);
# 需要 gdb 调试时用:cmake -DCMAKE_BUILD_TYPE=Debug . && make
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Release CACHE STRING "Build type" FORCE)
endif()
# 注意:这里不要再往 CMAKE_CXX_FLAGS 里塞 -g,否则 Release 也会带上 DWARF
# (ghost 会涨到 10MB 以上,其中 75% 是 .debug_* 段)。
target_link_options(ghost PRIVATE $<$<CONFIG:Release>:-s>)
# 链接 ZSTD 库
message(STATUS "链接库文件: ${CMAKE_SOURCE_DIR}/lib/libzstd.a")
+8
View File
@@ -140,6 +140,14 @@ make -j$(nproc)
编译成功后生成可执行文件 `ghost`。
默认按 Release 构建(`-O3`,链接时 `-s` 剥离符号表,产物约 2.5MB,不含调试信息)。
需要 gdb 调试或保留 DWARF 时改用:
```bash
cmake -DCMAKE_BUILD_TYPE=Debug . # -g(未优化)
cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo . # -O2 -g -DNDEBUG
```
## 使用方法
### 基本用法
+5
View File
@@ -124,6 +124,11 @@ target_compile_options(ghost PRIVATE
-fobjc-arc
)
# Release 链接时删掉 local 符号(对应 Linux 那边的 -s;ld64 用 -x)。
# 只删 non-global 符号,external 符号保留,dyld 绑定不受影响;签名由 ld 在链接
# 末尾完成,所以改符号表不会让签名失效。ghost 目前 ~19k 个符号里 8.3k 是 local。
target_link_options(ghost PRIVATE $<$<CONFIG:Release>:-Wl,-x>)
# Output directory
set_target_properties(ghost PROPERTIES
RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
+316 -7
View File
@@ -17,6 +17,7 @@
#import <thread>
#import <atomic>
#import <memory>
#import <mutex>
#import <string>
#import <map>
#import <vector>
@@ -29,6 +30,7 @@
#include "../common/xxhash.h"
#include "../common/rtt_estimator.h"
#include "../common/client_auth_state.h"
#include "../common/host_transfer.h" // 主机转移(COMMAND_ASSIGN_MASTER),与 Linux/Android 共用
#include "../common/posix_net_helpers.h"
#include "../common/sub_conn_thread.h"
#include "../common/ClientLogHandler.h"
@@ -82,6 +84,9 @@ State g_bExit = S_CLIENT_NORMAL;
static std::string g_configDir;
static std::string g_configPath;
static std::map<std::string, std::string> g_configData;
// 收包线程会写配置(分组变更、转移记录),主线程也会读/写(登录信息、到期清除),
// 而 g_configData 和整文件重写都不是线程安全的——所有访问都必须持有这把锁。
static std::mutex g_configMu;
// Initialize config paths
static void initConfigPaths()
@@ -112,6 +117,7 @@ static void mkdirRecursive(const std::string& path)
// Load all config from file
static void loadConfig()
{
std::lock_guard<std::mutex> lk(g_configMu);
initConfigPaths();
g_configData.clear();
@@ -127,8 +133,8 @@ static void loadConfig()
}
}
// Save all config to file
static void saveConfig()
// Save all config to file. 调用方必须持有 g_configMu(setConfigStr 已在锁内)。
static void saveConfigLocked()
{
initConfigPaths();
mkdirRecursive(g_configDir);
@@ -148,6 +154,7 @@ static void saveConfig()
// Get config string value
static std::string getConfigStr(const std::string& key, const std::string& def = "")
{
std::lock_guard<std::mutex> lk(g_configMu);
auto it = g_configData.find(key);
return it != g_configData.end() ? it->second : def;
}
@@ -155,8 +162,9 @@ static std::string getConfigStr(const std::string& key, const std::string& def =
// Set config string value
static void setConfigStr(const std::string& key, const std::string& value)
{
std::lock_guard<std::mutex> lk(g_configMu);
g_configData[key] = value;
saveConfig();
saveConfigLocked();
}
// Save group name to config file
@@ -172,6 +180,175 @@ static std::string loadGroupName()
return getConfigStr("group_name");
}
// ============== 主机转移(COMMAND_ASSIGN_MASTER + SHARE_TYPE_YAMA_FOREVER)==============
// 服务端「转移主机」下发的载荷是 host:port:days:shine[:transport],解析与记录编解码在
// common/host_transfer.h(与 Linux/Android 共用)。收包线程只记「待应用」,地址切换
// 放在主连接线程——CONNECT_ADDRESS 不参与跨线程同步(同 linux/main.cpp 与 Android)。
// 语义与 Android 对齐:主连接立即搬到新主控;目标持续一分钟连不上就退回原主控;
// 新主控也能把主机「提前归还」(把到期时刻设成当时)。
// 原主控只存在内存里(启动时的地址),绝不写回配置——恢复时读到的若还是转移目标,
// 就成了原地打转。
static HostTransfer::Endpoint g_transferOrig;
static std::atomic<long long> g_transferValidTo(0); // >0 = 转移中(到期时刻)
static std::atomic<bool> g_transferPending(false); // 接收线程已写好新目标,待主线程应用
static std::atomic<bool> g_transferEndEarly(false); // true = 新主控提前归还,不是到期
static std::mutex g_transferMu;
static HostTransfer::Target g_transferPendingTarget;
static int g_transferFailStreak = 0; // 仅主连接线程访问,无需原子
static long long g_transferFailAt = 0; // 本轮连续失败的起点(主连接线程)
// 回退判据:连续失败次数和已尝试时长**同时**满足才退回原主控。只看次数会被网络抖动
// 误伤:一次正常的转移会被无声撤销。计时从「本轮第一次失败」开始而不是从转移生效
// 开始——否则转移跑满一分钟后,任何几次瞬时连不上都会立刻把主机撤回去。
static const int kTransferRevertAttempts = 3;
static const long long kTransferRevertGraceSec = 60;
static std::string FormatUnixTimeHuman(long long epochSec)
{
const time_t t = (time_t)epochSec;
struct tm tmv;
if (!localtime_r(&t, &tmv))
return std::to_string(epochSec);
char buf[32] = { 0 };
if (strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", &tmv) == 0)
return std::to_string(epochSec);
const long off = tmv.tm_gmtoff;
const long absOff = off < 0 ? -off : off;
char zone[16] = { 0 };
snprintf(zone, sizeof(zone), "%c%02ld%02ld", off < 0 ? '-' : '+',
absOff / 3600, (absOff % 3600) / 60);
return std::string(buf) + " " + zone;
}
static std::string FormatDurationHuman(long long seconds)
{
if (seconds < 0) seconds = 0;
const long long h = seconds / 3600;
const long long m = (seconds % 3600) / 60;
const long long s = seconds % 60;
char buf[48] = { 0 };
if (h > 0) snprintf(buf, sizeof(buf), "%lldh %02lldm", h, m);
else if (m > 0) snprintf(buf, sizeof(buf), "%lldm %02llds", m, s);
else snprintf(buf, sizeof(buf), "%llds", s);
return buf;
}
// 主连接上的提示消息(服务端消息栏 + get_audit_log)。title/text 必须是纯 ASCII:
// 服务端按 ANSI(GBK) 解释这两个定长字段。
static void SendClientNotice(const char* title, const char* text)
{
if (g_bExit != S_CLIENT_NORMAL || !g_pMainClient || !g_pMainClient->IsConnected())
return;
ClientMsg msg(title, text);
g_pMainClient->Send2Server((char*)&msg, sizeof(msg));
}
static void SaveTransferRecord(const HostTransfer::Target& t)
{
setConfigStr("transfer", HostTransfer::EncodeRecord(t));
}
static void ClearTransferRecord()
{
setConfigStr("transfer", "");
}
static void RestoreOrigTarget()
{
HostTransfer::ApplyEndpoint(g_SETTINGS, g_transferOrig);
Mprintf("TRANSFER: restored to %s:%d\n",
g_transferOrig.ip.c_str(), g_transferOrig.port);
}
static bool TransferExpired()
{
const long long vt = g_transferValidTo.load(std::memory_order_relaxed);
return vt > 0 && (long long)time(nullptr) >= vt;
}
// 到期(或提前归还)就恢复原主控并清记录,返回是否真的复原了。
static bool HandleTransferExpiry()
{
if (!TransferExpired())
return false;
const bool early = g_transferEndEarly.exchange(false, std::memory_order_relaxed);
g_transferValidTo.store(0, std::memory_order_relaxed);
ClearTransferRecord();
RestoreOrigTarget();
Mprintf("TRANSFER: %s, back to original master\n",
early ? "ended early" : "expired");
return true;
}
// 把接收线程记下的目标落到连接参数。只在主连接线程调用:CONNECT_ADDRESS 没有跨线程
// 同步,ConnectServer 读的就是它。
static void ApplyPendingTransfer()
{
if (!g_transferPending.load(std::memory_order_acquire))
return;
HostTransfer::Target t;
{
std::lock_guard<std::mutex> lk(g_transferMu);
t = g_transferPendingTarget;
g_transferPending.store(false, std::memory_order_release);
}
HostTransfer::ApplyTarget(g_SETTINGS, t);
// 新转移生效:上一个「提前归还」若还没被 HandleTransferExpiry 消费,就作废了,
// 留着会让这次转移将来自然到期时被误报成“ended early”。
g_transferEndEarly.store(false, std::memory_order_relaxed);
g_transferFailStreak = 0;
g_transferFailAt = 0;
Mprintf("TRANSFER: applying %s:%d (transport=%d)\n",
t.ep.ip.c_str(), t.ep.port, t.ep.transport);
}
// 转移目标「不可用」的两种形态都算一次失败:连不上,以及连上了却始终通不过
// MasterSettings 校验(对端不是主控,或不是本构建的主控)。只看连不上的话,
// 一个「端口开着但不是主控」的地址会让主机一直空转,原主控那边已经看不到它了。
// 连续的失败次数和已尝试时长同时满足才退回原主控——只看次数会被网络抖动误伤。
static void NoteTransferFailure(const char* reason)
{
if (g_transferValidTo.load(std::memory_order_relaxed) <= 0)
return;
const long long now = (long long)time(nullptr);
if (g_transferFailStreak == 0)
g_transferFailAt = now; // 本轮第一次失败:60 秒窗口从这里开始
++g_transferFailStreak;
if (g_transferFailStreak < kTransferRevertAttempts
|| now - g_transferFailAt < kTransferRevertGraceSec)
return;
Mprintf("TRANSFER: target unusable for %s (%d tries, %s), reverting\n",
FormatDurationHuman(now - g_transferFailAt).c_str(), g_transferFailStreak, reason);
g_transferValidTo.store(0, std::memory_order_relaxed);
g_transferEndEarly.store(false, std::memory_order_relaxed);
g_transferFailStreak = 0;
g_transferFailAt = 0;
ClearTransferRecord();
RestoreOrigTarget();
}
// 启动时读记录:未过期就切到转移目标,过期/损坏就删掉。必须在建连之前调用——
// 同时记下此刻的连接参数作为「原主控」,之后才可能被转移目标覆盖。
static void LoadTransferRecord()
{
g_transferOrig = HostTransfer::CaptureEndpoint(g_SETTINGS);
HostTransfer::Target t;
if (!HostTransfer::DecodeRecord(getConfigStr("transfer"), t))
return;
const long long now = (long long)time(nullptr);
if (!t.Active(now)) {
Mprintf("TRANSFER: record expired at %s, removed\n",
FormatUnixTimeHuman(t.validTo).c_str());
ClearTransferRecord();
return;
}
g_transferValidTo.store(t.validTo, std::memory_order_relaxed);
HostTransfer::ApplyTarget(g_SETTINGS, t);
Mprintf("TRANSFER: active, target %s:%d, %s left\n",
t.ep.ip.c_str(), t.ep.port, FormatDurationHuman(t.validTo - now).c_str());
}
// ============== System Information Functions ==============
// Get macOS version string (e.g., "macOS 14.0 Sonoma")
@@ -1272,6 +1449,92 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
} else {
Mprintf("** [%p] TLS trust anchor removal: %s ***\n", user, err.c_str());
}
} else if (szBuffer[0] == COMMAND_SHARE || szBuffer[0] == COMMAND_SHARE_CANCEL) {
// 「分享主机」/「取消分享」:macOS 尚未实现。分享要在不改主连接的前提下再起
// 一条完整登录的连接,而登录校验状态、心跳、主连接句柄都是进程级单例,
// 第二条连接会把第一条顶掉(与 Android 的结论一致)。
// 服务端分享用的是 COMMAND_SHARE(assignFunction 用 ASSIGN + FOREVER 只发转移),
// 这里必须显式接住并回一条消息,否则主控那边以为下发成功了。
Mprintf("** [%p] SHARE not supported on macOS (%d), ignored ***\n",
user, (int)szBuffer[0]);
SendClientNotice("Share host", "macOS client does not support sharing a host");
return TRUE;
} else if (szBuffer[0] == COMMAND_ASSIGN_MASTER) {
// 「转移主机」:host:port:days:shine[:transport],解析见 common/host_transfer.h。
// 服务端只在这个命令上发 SHARE_TYPE_YAMA_FOREVER;类型不符(老版本或异常载荷)
// 一律不按转移处理。
if (ulLength < 3) {
Mprintf("** [%p] ASSIGN too short (%lu), ignored ***\n",
user, (unsigned long)ulLength);
return TRUE;
}
if (szBuffer[1] != SHARE_TYPE_YAMA_FOREVER) {
if (szBuffer[1] == SHARE_TYPE_YAMA) {
// 老服务端把「分享」发在同一个命令字节上(见 common/host_share.h:48)。
// 同样要回消息,否则主控那边以为这台主机的分享下发成功了。
Mprintf("** [%p] SHARE via ASSIGN (legacy), not supported on macOS ***\n", user);
SendClientNotice("Share host", "macOS client does not support sharing a host");
} else {
Mprintf("** [%p] ASSIGN type=%d not supported, ignored ***\n",
user, (int)szBuffer[1]);
}
return TRUE;
}
HostTransfer::Target t;
const long long now = (long long)time(nullptr);
if (!HostTransfer::ParseAssignCommand(szBuffer, ulLength, now, t)) {
// 载荷非法时什么都不做——绝不能把脏数据当成有效转移,否则一台上线中的
// 主机就被改到一个不存在的地址上去了。
Mprintf("** [%p] ASSIGN malformed payload, ignored ***\n", user);
return TRUE;
}
// 有效期内拒绝再次转移(与 Windows/Android 的 now <= valid_to 判断一致),
// 同时挡住「新主控再转一手」:主机此刻只连着新主控,它无权再改归属。
// 唯一例外:目标就是原主控——那是提前归还,把到期时刻设成「现在」,
// 走心跳循环里那条已经验证过的复原路径。
const bool toOriginal =
(t.ep.ip == g_transferOrig.ip && t.ep.port == g_transferOrig.port);
const long long active = g_transferValidTo.load(std::memory_order_relaxed);
if (now <= active) {
if (toOriginal) {
Mprintf("** [%p] ASSIGN back to original master, ending transfer early ***\n", user);
g_transferEndEarly.store(true, std::memory_order_relaxed);
g_transferValidTo.store(now, std::memory_order_relaxed);
// 记录立刻作废:主线程通常 1 秒内就会复原并再清一次,但若这期间进程
// 崩了/被杀,重启时旧记录(有效期还在)会把主机送回转移目标。
ClearTransferRecord();
SendClientNotice("Transfer host",
"Transfer ended early, returning to original master (validity ignored)");
return TRUE;
}
Mprintf("** [%p] ASSIGN ignored, already assigned until %s ***\n",
user, FormatUnixTimeHuman(active).c_str());
char msg[192];
snprintf(msg, sizeof(msg),
"Host is already transferred until %s (%s left), ignored",
FormatUnixTimeHuman(active).c_str(),
FormatDurationHuman(active - now).c_str());
SendClientNotice("Transfer host", msg);
return TRUE;
}
if (toOriginal) {
// 没在转移而目标就是原主控:无事可做,放行只会白白断线重连一次。
Mprintf("** [%p] ASSIGN target equals original master, ignored ***\n", user);
return TRUE;
}
// 先把新的到期时刻和记录落下来,最后才发布「待应用」。主线程看到 pending 就会
// 应用地址并紧接着检查到期,若 validTo 还是旧的(恰好已过期),就会把刚接受的
// 这次转移当成到期撤销掉。先挡住后续重复下发,再落盘。
g_transferValidTo.store(t.validTo, std::memory_order_relaxed);
SaveTransferRecord(t);
{
std::lock_guard<std::mutex> lk(g_transferMu);
g_transferPendingTarget = t;
g_transferPending.store(true, std::memory_order_release);
}
Mprintf("** [%p] ASSIGN to %s:%d for %s, moving the main link now ***\n",
user, t.ep.ip.c_str(), t.ep.port,
FormatDurationHuman(t.validTo - now).c_str());
} else {
Mprintf("** [%p] Received unimplemented command: %d ***\n", user, int(szBuffer[0]));
}
@@ -1346,6 +1609,10 @@ int main(int argc, const char* argv[])
loadConfig();
Mprintf("Config loaded from %s\n", g_configPath.c_str());
// 上次的「转移主机」还没到期就改连目标主控(原地址记在内存里,到期恢复)。
// 必须在建连之前:它决定本次启动要连哪台主控。
LoadTransferRecord();
// 历史活动采样:进程一启动就开始攒(服务端随时可能来查),
// 与 Linux 端在登录前 Start 的时机一致。
MacActivityHistory::Instance().Start();
@@ -1418,9 +1685,6 @@ int main(int argc, const char* argv[])
// 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);
if (g_SETTINGS.protoType == PROTO_WS || g_SETTINGS.protoType == PROTO_WSS) {
Mprintf("[WS] 按配置的传输协议连接: proto=%d(WSS 需要 TLS 支持,不支持的平台会 fail-closed)\n",
(int)(unsigned char)g_SETTINGS.protoType);
@@ -1439,8 +1703,19 @@ int main(int argc, const char* argv[])
Mprintf("Auto-restart failed; continuing with the current process\n");
g_autoRestartPending = false;
}
// 转移目标先落到连接参数;到期(或被新主控提前归还)则恢复原主控。
// 两者都只改地址/协议,真正的建连由本轮下面的 ConnectServer 完成。
ApplyPendingTransfer();
HandleTransferExpiry();
// 同 Linux:不传 conn 就取不到注入的 CONNECT_ADDRESS,协议必须显式喂进去,
// 否则配成 WS/WSS 也只会静默按明文 TCP 直连。每轮重喂还因为转移可能把目标
// 换成另一台主控,它的入口未必和原主控同构(原 WSS、对方直连设备端口时是 TCP)。
ClientObject->SetDefaultProto((int)(unsigned char)g_SETTINGS.protoType);
clock_t c = clock();
if (!ClientObject->ConnectServer(g_SETTINGS.ServerIP(), g_SETTINGS.ServerPort())) {
// 转移目标连不上:连续失败且已持续一分钟才退回原主控并清掉记录,
// 否则一个写错的地址会让这台主机彻底失联——原主控那边已经看不到它了。
NoteTransferFailure("unreachable");
Sleep(5000);
continue;
}
@@ -1476,6 +1751,10 @@ int main(int argc, const char* argv[])
break;
if (g_autoRestartPending)
break;
// 转移与到期复原按 1 秒粒度判断:0.001 天(86 秒)这种短转移等满
// 一个心跳周期才动就晚了。这里只 break,断开由循环外统一做。
if (g_transferPending.load(std::memory_order_acquire) || TransferExpired())
break;
if (!ClientObject->IsRunning() || !ClientObject->IsConnected() || g_bExit != S_CLIENT_NORMAL)
break;
Sleep(1000);
@@ -1486,6 +1765,19 @@ int main(int argc, const char* argv[])
ClientObject->Disconnect();
break;
}
// 转移主机:接收线程已写好新目标,先断开当前(原主控)连接,再由外层
// 循环换地址重连。地址必须在本线程、断开之后才改(见 ApplyPendingTransfer)。
if (g_transferPending.load(std::memory_order_acquire)) {
Mprintf("TRANSFER: leaving current master\n");
ClientObject->Disconnect();
break;
}
// 转移结束:恢复启动时记下的原主控。自然到期与新主控「提前归还」
// (它把到期时刻设成了当时,见 DataProcess 的 ASSIGN 分支)都走这里。
if (HandleTransferExpiry()) {
ClientObject->Disconnect();
break;
}
// 信任锚热切换(COMMAND_TLS_ENABLE/DISABLE)会置这个标志:
// 断开后由外层循环按新的传输方式重连。
if (g_needReconnect.exchange(false)) {
@@ -1497,7 +1789,8 @@ int main(int argc, const char* argv[])
break;
// 30 秒内未通过 MasterSettings 校验 → 断开本连接让外层重连,
// 永不退出进程(详见 ClientAuth::IsTimedOut 注释)。
// 永不退出进程(详见 ClientAuth::IsTimedOut 注释)。转移期间这类连接
// 记为一次失败(见下面心跳循环结束处),否则主机只能等到期才回原主控。
if (ClientAuth::IsTimedOut()) {
ClientObject->Disconnect();
break;
@@ -1516,6 +1809,22 @@ int main(int argc, const char* argv[])
memcpy(buf + 1, &hb, sizeof(Heartbeat));
ClientObject->Send2Server((char*)buf, sizeof(buf));
}
// 一条连接结束了,按「这条连接有没有通过 MasterSettings 校验」记账:
// · 校验通过 → 转移目标确实可用,失败计数清零(原实现只在建连成功时清零,
// 等于把「连得上但校验不过」的目标排除在回退判据之外);
// · 从未通过 → 目标「连得上但不是主控」:典型是端口上跑着别的服务
// (连上就被关掉,走不到 30 秒超时分支),或对端不认本构建。
// 正常退出/自动重启触发的断开不计(条件在后半段挡住);已经到期或提前归还
// 时 transfer 已结束,NoteTransferFailure 自己会返回。
if (g_running && g_bExit == S_CLIENT_NORMAL && !g_autoRestartPending) {
if (ClientAuth::IsVerified()) {
g_transferFailStreak = 0;
g_transferFailAt = 0; // 有可用连接:60 秒窗口整体重置
} else {
NoteTransferFailure("no master auth");
}
}
}
// 退出原因留痕:signal handler 不能直接打日志,在这里补一行。
+128 -49
View File
@@ -363,35 +363,70 @@ static UINT Indicators[] = {
IDR_STATUSBAR_EXPIRE
};
// 状态栏短标签分区(TLS/MCP)的宽度:按当前语言下两种取值的实际文本宽度取大者,
// 再留出左右边距。硬编码像素在不同语言/DPI 下容易被截断或浪费空间。
// 状态栏分区宽度:按当前语言/DPI 下的实际文本宽度加左右边距。硬编码像素在
// 125%/150% 缩放或换字体时会把文字截掉(「到期: ... (41天)」只剩日期就是这个原因)。
//
// 文本按宽字符测量:状态栏控件内部是 Unicode,ANSI 串会先按系统代码页转成宽字符再
// 绘制。中文串两种方式差可达 10%(本机 134 vs 153px),按 ANSI 测会偏窄。
static int MeasureStatusTextWide(HDC dc, const CString& text)
{
const int len = text.GetLength();
if (len <= 0)
return 0;
const int n = ::MultiByteToWideChar(CP_ACP, 0, text, len, nullptr, 0);
if (n <= 0)
return 0;
std::wstring w((size_t)n, L'\0');
::MultiByteToWideChar(CP_ACP, 0, text, len, &w[0], n);
SIZE sz = {};
::GetTextExtentPoint32W(dc, w.c_str(), n, &sz);
return (int)sz.cx;
}
// 难点是「控件到底用哪个字体画」。状态栏没有显式设过字体时,MFC 自己按 DC 默认字体
// (SYSTEM_FONT)计算分区宽度,而系统「状态栏字体」(lfStatusFont)往往更窄——本机
// 实测同一串文字 SYSTEM_FONT 134px、状态栏字体 109px。只按后者测就会把分区算窄、
// 把文字截掉,所以这里几种候选字体都测一遍取最大值。
static int CalcStatusPaneWidth(const CStatusBar& bar, const CString& text)
{
if (text.IsEmpty())
return 0;
CClientDC dc((CWnd*)&bar);
HGDIOBJ candidates[5] = {};
int count = 0;
if (CFont* pFont = bar.GetFont()) // 应用显式设过字体:控件就用它
candidates[count++] = (HGDIOBJ)pFont->GetSafeHandle();
candidates[count++] = ::GetStockObject(SYSTEM_FONT); // 无字体时的绘制/测量默认
candidates[count++] = ::GetStockObject(DEFAULT_GUI_FONT); // 另一种常见的默认
CFont statusFont, messageFont; // 系统字体表里的两种可能
NONCLIENTMETRICS ncm = {};
ncm.cbSize = sizeof(ncm);
if (::SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(ncm), &ncm, 0)) {
if (statusFont.CreateFontIndirect(&ncm.lfStatusFont))
candidates[count++] = (HGDIOBJ)statusFont.GetSafeHandle();
if (messageFont.CreateFontIndirect(&ncm.lfMessageFont))
candidates[count++] = (HGDIOBJ)messageFont.GetSafeHandle();
}
int width = 0;
for (int i = 0; i < count; ++i) {
HGDIOBJ old = dc.SelectObject(candidates[i]);
width = max(width, MeasureStatusTextWide(dc, text));
if (old != nullptr)
dc.SelectObject(old);
}
return width + 20;
}
// 状态栏短标签分区(TLS/MCP)的宽度:按当前语言下各取值的实际文本宽度取大者。
static int CalcStatusFlagPaneWidth(const CStatusBar& bar, const CString& a, const CString& b,
const CString& c = CString())
{
CClientDC dc((CWnd*)&bar);
CFont* pOld = nullptr;
CFont* pFont = bar.GetFont();
// 状态栏没有显式设过字体时,绘制用的是系统的「状态栏字体」(Segoe UI 9pt),
// 比 DEFAULT_GUI_FONT 宽约 8%:100% 缩放下靠边距还能兜住,缩放比更高就会截断,
// 所以这里直接按状态栏字体测量。
CFont statusFont;
if (pFont == nullptr) {
NONCLIENTMETRICS ncm = {};
ncm.cbSize = sizeof(ncm);
if (::SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(ncm), &ncm, 0)
&& statusFont.CreateFontIndirect(&ncm.lfStatusFont))
pFont = &statusFont;
}
if (pFont == nullptr)
pFont = CFont::FromHandle((HFONT)::GetStockObject(DEFAULT_GUI_FONT));
if (pFont != nullptr)
pOld = dc.SelectObject(pFont);
CSize szA = dc.GetTextExtent(a);
CSize szB = dc.GetTextExtent(b);
CSize szC = c.IsEmpty() ? CSize(0, 0) : dc.GetTextExtent(c);
if (pOld != nullptr)
dc.SelectObject(pOld);
return max(max(szA.cx, szB.cx), szC.cx) + 16;
return max(max(CalcStatusPaneWidth(bar, a), CalcStatusPaneWidth(bar, b)),
CalcStatusPaneWidth(bar, c));
}
std::string EventName()
@@ -3572,10 +3607,12 @@ void CMy2015RemoteDlg::StartFrpcAuto(const FrpAutoConfig& cfg)
// 设置状态栏显示的 FRP 地址 (IP:Port)
m_strFrpAddr.Format(_T("%hs:%d"), cfg.serverAddr.c_str(), cfg.remotePort);
// 直接更新状态栏 FRP 分区(不触发 OnSize 避免循环)
// 直接更新状态栏 FRP 分区(不触发 OnSize 避免循环)。宽度与 UpdateStatusBarStats
// 一致,按实际地址文本实测:硬编码 250px 在高缩放比机器上会截掉端口。
if (m_StatusBar.GetSafeHwnd()) {
m_StatusBar.SetPaneInfo(3, m_StatusBar.GetItemID(3), SBPS_NORMAL, 250);
m_nPaneFrpWidth = max(250, CalcStatusPaneWidth(m_StatusBar, m_strFrpAddr));
m_StatusBar.SetPaneText(3, m_strFrpAddr);
LayoutStatusPanes();
}
Mprintf("[FRP-Auto] 启动自动代理: %s:%d -> frps:%d\n",
@@ -3602,10 +3639,12 @@ void CMy2015RemoteDlg::StopFrpcAuto()
// 清除状态栏 FRP 地址
m_strFrpAddr.Empty();
// 直接更新状态栏 FRP 分区(不触发 OnSize 避免循环)
// 直接更新状态栏 FRP 分区(不触发 OnSize 避免循环)。宽度归零隐藏,下一次
// UpdateStatusBarStats 会按 FRPS/WAN/LAN 回退地址重新实测。
if (m_StatusBar.GetSafeHwnd()) {
m_StatusBar.SetPaneInfo(3, m_StatusBar.GetItemID(3), SBPS_NORMAL, 0);
m_nPaneFrpWidth = 0;
m_StatusBar.SetPaneText(3, _T(""));
LayoutStatusPanes();
}
Mprintf("[FRP-Auto] 已停止\n");
@@ -3944,20 +3983,9 @@ void CMy2015RemoteDlg::OnSize(UINT nType, int cx, int cy)
Rect.right=cx;
Rect.bottom=cy;
m_StatusBar.MoveWindow(Rect);
// 6个分区:消息(自动拉伸)、TLS、MCP、FRP地址(250px)、运行统计(180px)、到期时间(180px)
int paneExpire = m_strExpireDate.IsEmpty() ? 0 : 180; // 无到期信息时隐藏
// 优先显示上级 FRPC,其次显示本机 FRPS
int paneFrp = 250;
int paneRuntime = 180;
int paneTls = max(0, m_nPaneTlsWidth);
int paneMcp = max(0, m_nPaneMcpWidth);
int paneMsg = max(0, cx - paneTls - paneMcp - paneFrp - paneRuntime - paneExpire - 20);
m_StatusBar.SetPaneInfo(0, m_StatusBar.GetItemID(0), SBPS_STRETCH, paneMsg);
m_StatusBar.SetPaneInfo(1, m_StatusBar.GetItemID(1), SBPS_NORMAL, paneTls);
m_StatusBar.SetPaneInfo(2, m_StatusBar.GetItemID(2), SBPS_NORMAL, paneMcp);
m_StatusBar.SetPaneInfo(3, m_StatusBar.GetItemID(3), SBPS_NORMAL, paneFrp);
m_StatusBar.SetPaneInfo(4, m_StatusBar.GetItemID(4), SBPS_NORMAL, paneRuntime);
m_StatusBar.SetPaneInfo(5, m_StatusBar.GetItemID(5), SBPS_NORMAL, paneExpire);
// 6个分区:消息(自动拉伸)、TLS、MCP、FRP地址、运行统计、到期时间。
// 宽度由 UpdateStatusBarStats 按实测文本算好,这里只负责按当前窗口宽度摆位。
LayoutStatusPanes();
}
if(m_ToolBar.m_hWnd!=NULL) { //工具条
@@ -4240,9 +4268,7 @@ void CMy2015RemoteDlg::UpdateStatusBarStats()
m_nPaneTlsWidth = CalcStatusFlagPaneWidth(m_StatusBar, _TR("TLS: 有"), _TR("TLS: 无"),
_TR("TLS: 内置"));
m_nPaneMcpWidth = CalcStatusFlagPaneWidth(m_StatusBar, strMcp, strMcpWidest);
m_StatusBar.SetPaneInfo(1, m_StatusBar.GetItemID(1), SBPS_NORMAL, m_nPaneTlsWidth);
m_StatusBar.SetPaneText(1, strTls);
m_StatusBar.SetPaneInfo(2, m_StatusBar.GetItemID(2), SBPS_NORMAL, m_nPaneMcpWidth);
m_StatusBar.SetPaneText(2, strMcp);
// === 分区4:运行统计 ===
@@ -4326,12 +4352,21 @@ void CMy2015RemoteDlg::UpdateStatusBarStats()
strFrpDisplay.Format(_T("LAN %s:%d"), m_localPrivateIP.c_str(), THIS_CFG.Get1Int("settings", "ghost", ';', 6543));
}
}
// 根据是否有内容设置分区宽度
int paneFrpWidth = 250;
m_StatusBar.SetPaneInfo(3, m_StatusBar.GetItemID(3), SBPS_NORMAL, paneFrpWidth);
// 分区宽度按实际地址文本实测,但**不小于**改动前的固定宽度:250/180/180 在
// 100% 缩放下是验证过的,实测值只用于在高缩放比/大字体机器上把它们撑大。
m_nPaneFrpWidth = max(250, CalcStatusPaneWidth(m_StatusBar, strFrpDisplay));
m_StatusBar.SetPaneText(3, strFrpDisplay);
// === 分区4:运行统计 ===
// 宽度取「当前文本」与「可能出现的最长格式」的较大者:数字随时间增长时分区
// 不会每分钟跳一次,缩放比高的机器上也不会把 MTBF/运行时长截掉。
CString strRuntimeWidest =
_TR("运行:") + CString(_T(" 99999d 23h ")) + _TR("(无崩溃)");
m_nPaneRuntimeWidth = max(180,
max(CalcStatusPaneWidth(m_StatusBar, strRuntime),
CalcStatusPaneWidth(m_StatusBar, strRuntimeWidest)));
m_nPaneRuntimeWidth = max(m_nPaneRuntimeWidth,
CalcStatusPaneWidth(m_StatusBar, CString(_T("MTBF: 999d23h | 100.0%"))));
m_StatusBar.SetPaneText(4, strRuntime);
// === 分区5:到期时间 ===
@@ -4383,8 +4418,52 @@ void CMy2015RemoteDlg::UpdateStatusBarStats()
strDays.Format(_T("(%lld"), diffDays);
strExpire = _TR("到期:") + CString(_T(" ")) + strDate + _T(" ") + strDays + _TR("天") + _T(")");
}
// 宽度按文本实测,再多留一层富余:不同系统对英文字形("Expires:" 里的西文)
// 的字体回退和 GetTextExtent 有出入,多留 20px 总比截断好。下限 220 保证
// 「Expires: 2026-12-31 (41d)」这类比中文更长的串有足够空间。
m_nPaneExpireWidth = max(220, CalcStatusPaneWidth(m_StatusBar, strExpire) + 20);
m_StatusBar.SetPaneText(5, strExpire);
} else {
// 无授权信息:分区宽度归零(隐藏)
m_nPaneExpireWidth = 0;
}
// 各分区宽度都已按当前语言/DPI 算好,统一交给布局函数落位:窗口不够宽时
// 它会按优先级收掉低价值分区,保证「到期时间」不会被挤出右边缘。
LayoutStatusPanes();
}
// 按状态栏实际宽度布置分区。所有分区宽度之和(加上消息区下限)超过窗口时,按
// 运行统计 → FRP → MCP → TLS 的顺序隐藏,避免最后一个分区被窗口右边缘裁掉——
// 英文串比中文长、缩放比更高、窗口更窄,都会把总宽度顶上去,这里统一兜底。
void CMy2015RemoteDlg::LayoutStatusPanes()
{
if (!m_StatusBar.GetSafeHwnd())
return;
CRect rc;
m_StatusBar.GetClientRect(&rc);
int widths[6] = { 0, m_nPaneTlsWidth, m_nPaneMcpWidth, m_nPaneFrpWidth,
m_nPaneRuntimeWidth, m_nPaneExpireWidth };
static const int kDropOrder[] = { 4, 3, 2, 1 };
const int kMinMessageWidth = 120;
int fixedWidth = 0;
for (int i = 1; i <= 5; ++i)
fixedWidth += max(0, widths[i]);
for (int i = 0; i < (int)(sizeof(kDropOrder) / sizeof(kDropOrder[0]))
&& fixedWidth + kMinMessageWidth > rc.Width(); ++i) {
const int idx = kDropOrder[i];
fixedWidth -= max(0, widths[idx]);
widths[idx] = 0;
}
const int paneMsg = max(0, rc.Width() - fixedWidth - 20);
m_StatusBar.SetPaneInfo(0, m_StatusBar.GetItemID(0), SBPS_STRETCH, paneMsg);
for (int i = 1; i <= 5; ++i)
m_StatusBar.SetPaneInfo(i, m_StatusBar.GetItemID(i), SBPS_NORMAL, max(0, widths[i]));
}
void CMy2015RemoteDlg::DeletePopupWindow(BOOL bForce)
+4
View File
@@ -479,7 +479,11 @@ public:
CString m_strFrpAddr; // FRP 地址 (IP:Port),由上级提供
int m_nPaneTlsWidth = 60; // 状态栏 TLS 分区宽度(按当前语言实测文本宽度)
int m_nPaneMcpWidth = 60; // 状态栏 MCP 分区宽度(按当前语言实测文本宽度)
int m_nPaneFrpWidth = 250; // 状态栏 FRP 分区宽度(按当前文本实测)
int m_nPaneRuntimeWidth = 180; // 运行统计分区宽度(按最长可能文本实测)
int m_nPaneExpireWidth = 0; // 到期时间分区宽度(按当前文本实测;0 = 无授权/隐藏)
void UpdateStatusBarStats(); // 更新状态栏统计信息
void LayoutStatusPanes(); // 按窗口宽度布置状态栏分区(空间不足时按优先级隐藏)
CTrueColorToolBar m_ToolBar;
CGridDialog * m_gridDlg = NULL;
std::vector<DllInfo*> m_DllList;
+473
View File
@@ -0,0 +1,473 @@
# E2E-Smoke.ps1 - 发布前的基础功能端到端冒烟测试
#
# 做什么:
# 1. 启动 Debug 服务端(Bin\Yama_x64d.exe,读 Bin\settings.ini,默认端口 6543);
# 2. 起一个测试客户端:默认用服务端内置的「运行测试程序」(菜单 ID_TOOL_RUN_TEST),
# 加 -ExternalClient 则启动 x64\Debug\ghost.exe 127.0.0.1 6543;
# 3. 等它在在线列表(IDC_ONLINE=1001)上线并选中;
# 4. 按工具栏的命令 ID 逐个触发,断言每个命令在超时内弹出新的 #32770 对话框;
# 5. 每一步之后检查服务端/客户端进程是否还活着——像「点视频管理客户端崩溃」
# 这类回归会直接判失败;
# 6. 输出 PASS/FAIL 汇总表,任何一项失败则退出码为 1。
#
# 用法:
# powershell -File test\e2e\E2E-Smoke.ps1 # 全部功能
# powershell -File test\e2e\E2E-Smoke.ps1 -Only Video,File,Desktop
# powershell -File test\e2e\E2E-Smoke.ps1 -Build # 先重新编译 Debug 服务端/客户端
# powershell -File test\e2e\E2E-Smoke.ps1 -ExternalClient
# powershell -File test\e2e\E2E-Smoke.ps1 -RequireVideo # 有摄像头的机器上把视频弹窗设为必须
#
# 注意:
# - 不要同时运行两个 Debug 服务端;脚本开始前会检查 6543/6545/8080 是否被占用。
# - 正在运行的 Release 服务端(443/6544/9000)不受影响,脚本不会动它。
# - 所有中文输出都走 Unicode API / UTF-8 控制台,避免控制台代码页把标题显示成乱码。
param(
[string]$ServerExe = "",
[string]$ClientExe = "",
[switch]$ExternalClient,
[switch]$Build,
[int]$ServerTimeoutSec = 90,
[int]$ClientOnlineTimeoutSec = 60,
[int]$DefaultTimeoutSec = 15,
[string[]]$Only = @(),
[switch]$RequireVideo,
[switch]$KeepOpen
)
$ErrorActionPreference = 'Stop'
try { [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 } catch { }
$repo = Split-Path -Parent (Split-Path -Parent $PSScriptRoot) # test\e2e -> repo
if (-not $ServerExe) { $ServerExe = Join-Path $repo 'Bin\Yama_x64d.exe' }
if (-not $ClientExe) { $ClientExe = Join-Path $repo 'x64\Debug\ghost.exe' }
# ---------------------------------------------------------------- Win32 辅助
Add-Type -TypeDefinition @'
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
public static class E2E
{
public delegate bool EnumProc(IntPtr hWnd, IntPtr lParam);
[DllImport("user32.dll")] static extern bool EnumWindows(EnumProc cb, IntPtr l);
[DllImport("user32.dll")] static extern bool EnumChildWindows(IntPtr parent, EnumProc cb, IntPtr l);
[DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);
[DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern int GetClassName(IntPtr h, StringBuilder sb, int max);
[DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern int GetWindowText(IntPtr h, StringBuilder sb, int max);
[DllImport("user32.dll")] static extern bool IsWindowVisible(IntPtr h);
[DllImport("user32.dll")] public static extern bool IsWindow(IntPtr h);
[DllImport("user32.dll")] static extern IntPtr SendMessage(IntPtr h, uint m, IntPtr w, IntPtr l);
[DllImport("user32.dll")] public static extern bool PostMessage(IntPtr h, uint m, IntPtr w, IntPtr l);
[DllImport("user32.dll")] static extern int GetDlgCtrlID(IntPtr h);
[DllImport("user32.dll")] static extern IntPtr GetMenu(IntPtr h);
[DllImport("user32.dll")] static extern IntPtr GetWindow(IntPtr h, uint cmd);
public static string ClassName(IntPtr h)
{
var sb = new StringBuilder(256);
GetClassName(h, sb, sb.Capacity);
return sb.ToString();
}
public static string Text(IntPtr h)
{
var sb = new StringBuilder(2048);
GetWindowText(h, sb, sb.Capacity);
return sb.ToString();
}
public static bool HasMenu(IntPtr h) { return GetMenu(h) != IntPtr.Zero; }
// 某个进程的可视顶层对话框(#32770),排除主窗口本身。
public static IntPtr[] TopDialogs(uint pid, IntPtr exclude)
{
var list = new List<IntPtr>();
EnumWindows((h, l) =>
{
uint p; GetWindowThreadProcessId(h, out p);
if (p != pid || h == exclude) return true;
if (!IsWindowVisible(h)) return true;
if (ClassName(h) != "#32770") return true;
list.Add(h);
return true;
}, IntPtr.Zero);
return list.ToArray();
}
// 某个进程的所有可视顶层窗口(不限类名)。搜索栏这类不是 #32770 的自绘窗口
// 靠它判断「点击有反应」。
public static IntPtr[] TopWindows(uint pid, IntPtr exclude)
{
var list = new List<IntPtr>();
EnumWindows((h, l) =>
{
uint p; GetWindowThreadProcessId(h, out p);
if (p != pid || h == exclude) return true;
if (!IsWindowVisible(h)) return true;
list.Add(h);
return true;
}, IntPtr.Zero);
return list.ToArray();
}
[DllImport("winmm.dll")] public static extern int waveInGetNumDevs();
// 对话框里的静态文本/按钮文字,失败时用来判断是不是错误提示框。
public static string ChildTexts(IntPtr dlg)
{
var sb = new StringBuilder();
EnumChildWindows(dlg, (h, l) =>
{
string t = Text(h);
if (!string.IsNullOrWhiteSpace(t))
{
if (sb.Length > 0) sb.Append(" / ");
sb.Append(t.Trim());
}
return true;
}, IntPtr.Zero);
string s = sb.ToString();
if (s.Length > 300) s = s.Substring(0, 300) + "...";
return s;
}
public static IntPtr FindChild(IntPtr parent, string cls, int ctrlId)
{
IntPtr found = IntPtr.Zero;
EnumChildWindows(parent, (h, l) =>
{
if (ClassName(h) == cls && GetDlgCtrlID(h) == ctrlId) { found = h; return false; }
return true;
}, IntPtr.Zero);
return found;
}
public static int SendInt(IntPtr h, uint msg, int w, int l)
{
return (int)SendMessage(h, msg, (IntPtr)w, (IntPtr)l);
}
public static void PostCommand(IntPtr main, int id)
{
PostMessage(main, 0x0111 /*WM_COMMAND*/, (IntPtr)id, IntPtr.Zero);
}
public static void Click(IntPtr h, int x, int y)
{
IntPtr lp = (IntPtr)((y << 16) | (x & 0xFFFF));
PostMessage(h, 0x0201 /*WM_LBUTTONDOWN*/, (IntPtr)1, lp);
PostMessage(h, 0x0202 /*WM_LBUTTONUP*/, IntPtr.Zero, lp);
}
public static void Close(IntPtr h) { PostMessage(h, 0x0010 /*WM_CLOSE*/, IntPtr.Zero, IntPtr.Zero); }
}
'@
$WM_COMMAND = 0x0111
$LVM_GETITEMCOUNT = 0x1004
$LVM_GETITEMSTATE = 0x102C
$LVIS_SELECTED = 0x0002
function Wait-Until([scriptblock]$Condition, [int]$TimeoutSec, [int]$IntervalMs = 250) {
$deadline = (Get-Date).AddSeconds($TimeoutSec)
while ((Get-Date) -lt $deadline) {
try { if (& $Condition) { return $true } } catch { }
Start-Sleep -Milliseconds $IntervalMs
}
return $false
}
function Test-Alive($proc) {
if ($null -eq $proc) { return $false }
try { return -not $proc.HasExited } catch { return $false }
}
function Get-ListeningPorts {
try {
return @(Get-NetTCPConnection -State Listen -ErrorAction Stop |
Select-Object -ExpandProperty LocalPort)
} catch { return @() }
}
# ---------------------------------------------------------------- 阶段 1:准备
Write-Host "==> E2E smoke test" -ForegroundColor Cyan
Write-Host " server : $ServerExe"
Write-Host " client : $(if ($ExternalClient) { $ClientExe } else { 'in-process (Run Test)' })"
$running = @(Get-Process -Name 'Yama_x64d' -ErrorAction SilentlyContinue)
if ($running.Count -gt 0) {
throw "已有 Debug 服务端在运行(PID=$($running[0].Id))。请先关闭它,避免端口/实例冲突。"
}
if (-not (Test-Path $ServerExe)) { throw "找不到 Debug 服务端: $ServerExe(可加 -Build 先编译)" }
if ($ExternalClient -and -not (Test-Path $ClientExe)) { throw "找不到 Debug 客户端: $ClientExe" }
# 端口检查:6543 是客户端必须能连上的端口,被占用就直接失败。
# MCP/Web 端口(settings.ini 的 McpPort/WebSvrPort)如果已被别的实例占用(例如正在跑的
# Release 服务端也用 6545),临时在 settings.ini 里关掉它们,测试结束再恢复原文件。
$settingsPath = Join-Path (Split-Path $ServerExe) 'settings.ini'
$settingsBackup = $null
if (Test-Path $settingsPath) {
$settingsBackup = [System.IO.File]::ReadAllText($settingsPath, [System.Text.Encoding]::Default)
}
function Restore-Settings {
if ($script:settingsBackup -ne $null) {
[System.IO.File]::WriteAllText($script:settingsPath, $script:settingsBackup, [System.Text.Encoding]::Default)
}
}
function Set-IniValue([string]$text, [string]$key, [string]$value) {
$pattern = '(?m)^' + [regex]::Escape($key) + '=.*$'
if ($text -match $pattern) { return [regex]::Replace($text, $pattern, "$key=$value") }
return $text
}
$ports = Get-ListeningPorts
$udp = @()
try { $udp = @(Get-NetUDPEndpoint -ErrorAction Stop | Select-Object -ExpandProperty LocalPort) } catch { }
if (($ports -contains 6543) -or ($udp -contains 6543)) {
throw "端口 6543 已被占用,无法启动隔离的 Debug 测试实例。"
}
if ($settingsBackup -ne $null) {
$cfg = $settingsBackup
if (($ports -contains 6545) -or ($udp -contains 6545)) {
Write-Host " 6545 已被占用,本次测试临时关闭 Debug 实例的 MCP" -ForegroundColor DarkYellow
$cfg = Set-IniValue $cfg 'McpEnabled' '0'
}
if ($ports -contains 8080) {
Write-Host " 8080 已被占用,本次测试临时关闭 Debug 实例的 Web 控制台" -ForegroundColor DarkYellow
$cfg = Set-IniValue $cfg 'WebSvrPort' '0'
}
if ($cfg -ne $settingsBackup) {
[System.IO.File]::WriteAllText($settingsPath, $cfg, [System.Text.Encoding]::Default)
}
}
if ($Build) {
Write-Host "==> 编译 Debug 服务端/客户端 ..." -ForegroundColor Cyan
& powershell -NoProfile -File (Join-Path $repo 'build.ps1') -Config Debug -Platform x64 | Out-Null
& powershell -NoProfile -File (Join-Path $repo 'build.ps1') -Config Debug -Platform x64 -ClientOnly | Out-Null
if ($LASTEXITCODE -ne 0) { throw "编译失败(退出码 $LASTEXITCODE)" }
}
$server = $null
$client = $null
$results = New-Object System.Collections.ArrayList
function Add-Result($name, $status, $detail, $ms) {
[void]$results.Add([pscustomobject]@{ Feature = $name; Status = $status; Detail = $detail; Ms = $ms })
$color = switch ($status) {
'PASS' { 'Green' } 'FAIL' { 'Red' } 'WARN' { 'Yellow' } 'SKIP' { 'DarkYellow' } default { 'Gray' }
}
Write-Host (" {0,-5} {1,-14} {2}" -f $status, $name, $detail) -ForegroundColor $color
}
try {
# ------------------------------------------------------------ 阶段 2:启动服务端
Write-Host "==> 启动 Debug 服务端 ..." -ForegroundColor Cyan
$server = Start-Process -FilePath $ServerExe -WorkingDirectory (Split-Path $ServerExe) -PassThru
$main = [IntPtr]::Zero
$ok = Wait-Until {
$script:server.Refresh()
if ($script:server.HasExited) { return $false }
$h = $script:server.MainWindowHandle
if ($h -eq [IntPtr]::Zero) { return $false }
if (([E2E]::ClassName($h) -ne '#32770')) { return $false }
$script:main = $h
return $true
} $ServerTimeoutSec
if (-not $ok) { throw "Debug 服务端在 ${ServerTimeoutSec}s 内没有出现主窗口(是否弹了 UAC/登录框/端口错误框?)" }
$list = [IntPtr]::Zero
$ok = Wait-Until {
$script:list = [E2E]::FindChild($script:main, 'SysListView32', 1001)
return ($script:list -ne [IntPtr]::Zero)
} 30
if (-not $ok) { throw "找不到在线列表控件(IDC_ONLINE=1001)" }
# ------------------------------------------------------------ 阶段 3:客户端上线
if ($ExternalClient) {
Write-Host "==> 启动外部 Debug 客户端 ..." -ForegroundColor Cyan
$client = Start-Process -FilePath $ClientExe -ArgumentList @('127.0.0.1', '6543') `
-WorkingDirectory (Split-Path $ClientExe) -PassThru
} else {
Write-Host "==> 触发内置测试客户端(ID_TOOL_RUN_TEST)..." -ForegroundColor Cyan
[E2E]::PostCommand($main, 33106)
}
$count = 0
$ok = Wait-Until {
if ($script:server.HasExited) { throw '服务端进程已退出(客户端崩溃或被安全软件拦截)' }
if ($ExternalClient -and $script:client.HasExited) { throw '外部客户端进程已退出' }
$script:count = [E2E]::SendInt($script:list, $LVM_GETITEMCOUNT, 0, 0)
return ($script:count -ge 1)
} $ClientOnlineTimeoutSec
if (-not $ok) {
# 内置客户端失败时通常会弹一个消息框(例如内核 DLL 未就绪),把它的文字打出来。
$diag = @([E2E]::TopDialogs($server.Id, $main) | ForEach-Object { [E2E]::Text($_) } | Where-Object { $_ })
throw ("客户端 ${ClientOnlineTimeoutSec}s 内没有上线(在线列表 0 条)。弹窗: " + ($diag -join ' | '))
}
Write-Host " 在线主机: $count" -ForegroundColor Green
# 选中第一行;列表项需要先选中,工具栏命令才会对这台主机下发。
[E2E]::Click($list, 40, 40)
$selected = Wait-Until {
return ([E2E]::SendInt($script:list, $LVM_GETITEMSTATE, 0, $LVIS_SELECTED) -ne 0)
} 5
if (-not $selected) { throw "在线列表第 1 行没有被选中(点击坐标/列表布局可能变了)" }
# ------------------------------------------------------------ 阶段 4:逐项触发
# Id:工具栏/菜单命令 ID;Timeout:等弹窗的秒数;Expect:dialog / none
$features = @(
@{ Name = 'Terminal'; Id = 32776; Timeout = 20 },
@{ Name = 'Process'; Id = 32777; Timeout = 15 },
@{ Name = 'Window'; Id = 32778; Timeout = 15 },
@{ Name = 'Desktop'; Id = 32779; Timeout = 30 },
@{ Name = 'File'; Id = 32780; Timeout = 20 },
@{ Name = 'Audio'; Id = 32781; Timeout = 15; Requires = 'mic' },
@{ Name = 'Video'; Id = 32782; Timeout = 12; Optional = (-not $RequireVideo) },
@{ Name = 'Services'; Id = 32783; Timeout = 15; Requires = 'admin' },
@{ Name = 'Registry'; Id = 32784; Timeout = 15 },
@{ Name = 'Keylogger'; Id = 2117; Timeout = 15 },
@{ Name = 'Settings'; Id = 32794; Timeout = 10 },
@{ Name = 'BuildClient'; Id = 32786; Timeout = 15 },
@{ Name = 'Search'; Id = 32788; Timeout = 5; Expect = 'any' },
@{ Name = 'About'; Id = 32787; Timeout = 10 },
@{ Name = 'McpSettings'; Id = 33077; Timeout = 10 },
@{ Name = 'Connections'; Id = 33086; Timeout = 15 },
@{ Name = 'Talk'; Id = 33089; Timeout = 15 },
@{ Name = 'MachineManage'; Id = 32931; Timeout = 10 }
)
# powershell -File 会把 "A,B" 原样作为单个字符串传进来,这里统一拆开
$Only = @($Only | ForEach-Object { $_ -split '[,;\s]+' } | Where-Object { $_ })
if ($Only.Count -gt 0) {
$features = @($features | Where-Object { $Only -contains $_.Name })
if ($features.Count -eq 0) { throw " -Only 没有匹配到任何功能: $($Only -join ', ')" }
}
# 环境前提:没有录音设备时音频会话根本建立不起来;服务端未提权时服务枚举会失败。
# 这两种情况跳过而不是判 FAIL,避免冒烟脚本因为"机器没麦/没提权"天天红。
$hasMic = ([E2E]::waveInGetNumDevs() -gt 0)
$isAdmin = (New-Object Security.Principal.WindowsPrincipal(
[Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole(
[Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $hasMic) { Write-Host " 提示: 本机没有录音设备,Audio 将跳过" -ForegroundColor DarkYellow }
if (-not $isAdmin) { Write-Host " 提示: 服务端未提权,Services 将跳过(管理员身份运行脚本可覆盖)" -ForegroundColor DarkYellow }
foreach ($f in $features) {
if ($f.Requires -eq 'mic' -and -not $hasMic) {
Add-Result $f.Name 'SKIP' '本机没有录音设备(waveIn=0)' 0
continue
}
if ($f.Requires -eq 'admin' -and -not $isAdmin) {
Add-Result $f.Name 'SKIP' '服务端未以管理员运行,服务枚举不可用' 0
continue
}
# 每条命令前先关掉可能残留的对话框,保证快照干净
foreach ($h in @([E2E]::TopDialogs($server.Id, $main))) { [E2E]::Close($h) }
Start-Sleep -Milliseconds 300
if ($server.HasExited) { Add-Result $f.Name 'FAIL' '服务端进程已退出' 0; break }
if ($ExternalClient -and $client.HasExited) { Add-Result $f.Name 'FAIL' '客户端进程已退出' 0; break }
$expectAny = ($f.Expect -eq 'any')
$snapshot = {
if ($expectAny) { [E2E]::TopWindows($script:server.Id, $script:main) }
else { [E2E]::TopDialogs($script:server.Id, $script:main) }
}
$before = @(& $snapshot | ForEach-Object { $_.ToInt64() })
$sw = [System.Diagnostics.Stopwatch]::StartNew()
[E2E]::PostCommand($main, $f.Id)
$timeout = if ($f.Timeout) { $f.Timeout } else { $DefaultTimeoutSec }
$newDlg = [IntPtr]::Zero
$found = Wait-Until {
if ($script:server.HasExited) { return $true }
$cur = @(& $snapshot)
foreach ($h in $cur) {
if ($before -notcontains $h.ToInt64()) { $script:newDlg = $h; return $true }
}
return $false
} $timeout
$sw.Stop()
# 进程存活检查:进程内客户端模式下客户端崩溃会带走服务端
$crashed = $false
if ($server.HasExited) { $crashed = $true }
if ($ExternalClient -and $client.HasExited) { $crashed = $true }
if ($crashed) { Add-Result $f.Name 'FAIL' "进程已退出($($sw.ElapsedMilliseconds)ms)" $sw.ElapsedMilliseconds; break }
if ($f.Expect -eq 'none') {
if ($found -and $newDlg -ne [IntPtr]::Zero) {
$title = [E2E]::Text($newDlg)
Add-Result $f.Name 'FAIL' "不应弹窗,却弹出了「$title」" $sw.ElapsedMilliseconds
[E2E]::Close($newDlg)
} else {
Add-Result $f.Name 'PASS' '无弹窗,符合预期' $sw.ElapsedMilliseconds
}
continue
}
if ($found -and $newDlg -ne [IntPtr]::Zero) {
$title = [E2E]::Text($newDlg)
if (-not $title) { $title = '(无标题)' }
# 提示/错误框也算"弹了窗",但它不是功能对话框:单独标 WARN 并把文字带出来,
# 让报告里能直接看到「该功能不可用」之类的原因,而不是伪装成 PASS。
$suspicious = $title -match '(?i)^(notice|warning|error|提示|警告|错误|失败)$'
if ($suspicious) {
$child = [E2E]::ChildTexts($newDlg)
Add-Result $f.Name 'WARN' "弹出提示框「$title」: $child" $sw.ElapsedMilliseconds
} else {
Add-Result $f.Name 'PASS' "弹窗「$title」" $sw.ElapsedMilliseconds
}
[E2E]::Close($newDlg)
# 等窗口真正关掉,避免它挡住下一条命令
[void](Wait-Until { return -not [E2E]::IsWindow($newDlg) } 5)
} elseif ($f.Optional) {
Add-Result $f.Name 'SKIP' "超时未弹窗(${timeout}s);本项可选(视频需要摄像头)" $sw.ElapsedMilliseconds
} else {
Add-Result $f.Name 'FAIL' "超时 ${timeout}s 未弹出对话框(点击无反应?)" $sw.ElapsedMilliseconds
}
}
}
catch {
Write-Host "`n[ERROR] $($_.Exception.Message)" -ForegroundColor Red
foreach ($h in @([E2E]::TopDialogs($server.Id, $main) | Where-Object { $_ })) {
$t = [E2E]::Text($h); if ($t) { Write-Host " 弹窗: $t" -ForegroundColor Red }
}
Add-Result 'Startup' 'FAIL' $_.Exception.Message 0
}
finally {
if (-not $KeepOpen) {
Write-Host "==> 清理测试实例 ..." -ForegroundColor Cyan
try { if ($main -ne [IntPtr]::Zero) { [E2E]::Close($main) } } catch { }
Start-Sleep -Seconds 2
try { if (Test-Alive $server) { $server.Kill() } } catch { }
try { if ($ExternalClient -and (Test-Alive $client)) { $client.Kill() } } catch { }
# 服务端退出后会回写 settings.ini,恢复必须在进程结束之后
Start-Sleep -Milliseconds 300
Restore-Settings
} else {
Write-Host "==> -KeepOpen:测试实例保持运行(settings.ini 的临时修改请在关闭后手动恢复)" -ForegroundColor Yellow
}
}
# ---------------------------------------------------------------- 阶段 5:汇总
Write-Host ""
Write-Host "===== 结果汇总 =====" -ForegroundColor Cyan
$results | Format-Table Feature, Status, Detail, Ms -AutoSize | Out-String | Write-Host
$failed = @($results | Where-Object { $_.Status -eq 'FAIL' })
$warned = @($results | Where-Object { $_.Status -eq 'WARN' })
$skipped = @($results | Where-Object { $_.Status -eq 'SKIP' })
if ($warned.Count -gt 0) { Write-Host "WARN: $($warned.Count) 项(弹出了提示/错误框,请人工确认)" -ForegroundColor Yellow }
if ($skipped.Count -gt 0) { Write-Host "SKIP: $($skipped.Count) 项(环境不具备或可选功能)" -ForegroundColor DarkYellow }
if ($failed.Count -gt 0) {
Write-Host "FAILED: $($failed.Count) 项" -ForegroundColor Red
exit 1
}
Write-Host "ALL PASSED" -ForegroundColor Green
exit 0
+86
View File
@@ -0,0 +1,86 @@
# 发布前端到端冒烟测试(E2E-Smoke.ps1)
发布新版本前跑一遍,确认服务端 + 客户端的基础功能没有被改坏。
## 它做什么
1. 启动 **Debug 服务端** `Bin\Yama_x64d.exe`(读 `Bin\settings.ini`,客户端端口 6543);
2. 起测试客户端:
- 默认:服务端内置的「运行测试程序」(菜单命令 `ID_TOOL_RUN_TEST=33106`,进程内);
- `-ExternalClient`:启动 `x64\Debug\ghost.exe 127.0.0.1 6543`;
3. 等它出现在在线列表(控件 `IDC_ONLINE=1001`),选中第一行;
4. 按工具栏的真实命令 ID 逐个触发(见下表),断言每个命令在超时内弹出新的 `#32770` 对话框;
5. 每条命令后检查服务端/客户端进程是否还活着——像「点视频管理客户端崩溃」
这类回归会直接判 FAIL;
6. 输出 PASS/FAIL/WARN/SKIP 汇总表,有 FAIL 时退出码为 1。
## 用法
```bat
:: 全部功能(默认用内置测试客户端)
powershell -NoProfile -File test\e2e\E2E-Smoke.ps1
:: 先重新编译 Debug 服务端/客户端再测
powershell -NoProfile -File test\e2e\E2E-Smoke.ps1 -Build
:: 只测部分功能
powershell -NoProfile -File test\e2e\E2E-Smoke.ps1 -Only Terminal,Desktop,File,Video
:: 用独立的 Debug 客户端(能单独抓到客户端崩溃)
powershell -NoProfile -File test\e2e\E2E-Smoke.ps1 -ExternalClient
:: 有摄像头的机器上,把「视频管理弹窗」设为必须
powershell -NoProfile -File test\e2e\E2E-Smoke.ps1 -RequireVideo
:: 保留测试实例,人工点一遍
powershell -NoProfile -File test\e2e\E2E-Smoke.ps1 -KeepOpen
```
也可以直接双击 `run-e2e.cmd`(等价于全部功能)。
**以管理员身份运行**可覆盖「服务管理」(服务枚举需要提权);不提权时该项自动 SKIP。
## 覆盖的功能与命令 ID
| 功能 | 命令 ID | 依赖 |
|---|---|---|
| Terminal 终端管理 | 32776 | 客户端 |
| Process 进程管理 | 32777 | 客户端 |
| Window 窗口管理 | 32778 | 客户端 |
| Desktop 桌面管理 | 32779 | 客户端 |
| File 文件管理 | 32780 | 客户端 |
| Audio 语音管理 | 32781 | 客户端 + 录音设备 |
| Video 视频管理 | 32782 | 客户端 + 摄像头(默认可选) |
| Services 服务管理 | 32783 | 客户端 + 管理员权限 |
| Registry 注册表管理 | 32784 | 客户端 |
| Keylogger 键盘记录 | 2117 | 客户端 |
| Settings 参数设置 | 32794 | 无 |
| BuildClient 生成服务端 | 32786 | 无 |
| Search 搜索 | 32788 | 无(弹搜索栏) |
| About 帮助 | 32787 | 无 |
| McpSettings MCP | 33077 | 无 |
| Connections 连接管理 | 33086 | 客户端 |
| Talk 远程交谈 | 33089 | 客户端(会先弹确认框) |
| MachineManage 主机管理 | 32931 | 客户端 |
新增功能:在脚本的 `$features` 数组里加一行 `@{ Name='X'; Id=<命令ID>; Timeout=<秒> }` 即可。
## 结果怎么读
| 状态 | 含义 |
|---|---|
| PASS | 点击后弹出了功能对话框 |
| FAIL | 超时没有弹窗(点击无反应),或进程崩溃/退出 → 需要修 |
| WARN | 弹出了提示/错误框(标题为 Notice/提示/Error 等),报告里会带上框里的文字,需人工确认 |
| SKIP | 环境不具备(无麦克风 / 未提权 / 无摄像头 / 可选功能) |
## 注意事项
- 脚本只启动 **Debug** 实例;正在运行的 Release 服务端(443/6544 等)不受影响。
- 开始前要求 6543 空闲、没有其它 `Yama_x64d` 在跑。
- 如果 6545(MCP)/8080(Web)已被占用,脚本会临时在 `Bin\settings.ini` 里关掉对应监听,
测试结束**无条件恢复原文件**(包括异常退出/中断时)。
- 客户端在进程内模式下崩溃会带走服务端,同样会被判 FAIL。
- 视频管理:没有摄像头的机器无法弹窗,默认 SKIP;这类驱动相关的回归
(例如 `IMediaControl::Run` 返回 S_FALSE)请在有摄像头的机器上跑,
或加 `-RequireVideo` 让它变成硬性检查。
+10
View File
@@ -0,0 +1,10 @@
@echo off
:: 发布前端到端冒烟测试入口(等价于 E2E-Smoke.ps1 全部功能)
:: 需要覆盖「服务管理」时,请以管理员身份运行本脚本。
setlocal
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0E2E-Smoke.ps1" %*
set RC=%errorlevel%
echo.
echo ExitCode=%RC%
pause
exit /b %RC%