13 Commits
Author SHA1 Message Date
yuanyuanxianganddeepseek-flash cc0e4bbd7a Fix: Pass win keys down the hook chain while a chat is locked
During a locked chat the client installs a WH_KEYBOARD_LL hook that
swallows Alt+Tab, Alt+F4, Alt+Esc, Ctrl+Esc and the Win keys, so the person
sitting at the machine cannot get out of the lock. The hook returned 1
without calling CallNextHookEx. Low-level hooks run last installed first,
and this one is installed later than the server's hotkey forwarding hook,
so it sits in front of it: returning 1 ended the chain and the forwarding
hook never saw those keys. With YAMA running on the same machine as the
client, Win shortcuts stopped reaching the remote host for as long as the
lock was up.

The event is now passed down the chain before it is swallowed.
CallNextHookEx hands the event to the other hooks only, not to the system
or the shell, so the local shell is still blocked and the lock behaves
exactly as before, while the forwarding hook can see the key and act on
it.

Co-Authored-By: deepseek-flash
2026-10-25 02:40:30 +02:00
yuanyuanxianganddeepseek-flash 73aa2725b9 Fix: Pick an MSBuild instance that has ATL, not the first found
build.ps1 took the first MSBuild.exe matching a hardcoded glob under
%ProgramFiles% / %ProgramFiles(x86)%. On a machine that has both a
command-line build tools instance and an IDE, that is the build tools one.
It ships the v142 compiler, but ATL is a separate optional component there,
so the link step failed with LNK1104 on atls.lib while the same sources
built cleanly in the IDE whose instance carries ATL. The vswhere lookup
meant to cover installations on other drives never ran, because the glob
had already matched.

Candidates are now validated against VC\Tools\MSVC\*\atlmfc\lib\x86\atls.lib
before being accepted, every rejected instance is reported, and the vswhere
lookup enumerates all instances and applies the same check, so an
installation on another drive is found as well. When no instance carries
ATL the first candidate is still used, with a warning, which keeps the
previous behaviour and lets MSBuild emit the more specific error.

The script is also saved as UTF-8 with BOM: Windows PowerShell 5.1 reads a
BOM-less UTF-8 script as ANSI, which turns some Chinese comment characters
into a trailing backtick and swallows the following line.

This commit also carries the pending build script work: the Go server
builder, the -ClientOnly fast path, and the serverd / client debug presets
in build.cmd. Skills.md documents the two new presets.

Co-Authored-By: deepseek-flash
2026-10-25 02:38:46 +02:00
yuanyuanxianganddeepseek-flash 37d0297f07 Fix: Keep the keylogger thread pumping so the hook chain stays alive
The low-level keyboard hook callback runs only while the thread that
installed it pumps messages, but KeyLogger() gated PeekMessage on
IsConnected(). With offline recording enabled (kbrecord=Yes) and no
keyboard sub-connection, the hook stayed installed while its thread
never pumped, so every keystroke on the machine stalled against
LowLevelHooksTimeout (300 ms by default) and the hook was eventually
dropped by the system. Because the client installs its hook after YAMA
installs its own, the client's hook sits in front of YAMA's in the
chain, and the starved events broke the key pairs YAMA needs: Win
shortcuts and Ctrl+V forwarding stopped working while ordinary typing
was unaffected.

Pump messages unconditionally; this code is only reached while the hook
is installed, and the offline-record path installs it even without a
keyboard sub-connection.

Co-Authored-By: deepseek-flash
2026-10-25 02:22:17 +02:00
yuanyuanxianganddeepseek-flash 7160ea8f42 Fix: Stop the online-host list header from flickering
The list header is a child window of the list view, and
LVS_EX_DOUBLEBUFFER only covers the item area. The list view was created
without WS_CLIPCHILDREN, so every whole-list Invalidate or RedrawWindow
also erased the header with the class background brush before repainting
it. On top of that, AdjustColumnWidths ran on every WM_SIZE and issued an
unconditional SetColumnWidth per column, and each call repaints the
header. The result was an occasional one-frame blink of the header row:
irregular, low frequency, and confined to the header because the item
area is double-buffered.

Both lists now carry WS_CLIPCHILDREN, RDW_ALLCHILDREN was dropped from the
redraw calls that only need the list body (that flag forces child
repaints even when they are clipped), and column widths are only set when
they actually change.

The header still needs its background erase, but only for the strip to
the right of the last column: AdjustColumnWidths reserves 20px there and
the header's own paint stops at the last column, so that strip is colored
by WM_ERASEBKGND alone. Skipping the erase entirely left it black after a
minimize/restore cycle, when the window contents are discarded. The
header subclass now fills just that strip with COLOR_3DFACE and leaves the
column area untouched, which keeps the flicker fix, and the needRefresh
branch of OnSize forces an erase-redraw of the header so the strip is
repainted on minimize/restore and maximize/normalize.

Verified with a standalone probe that mirrors the list setup for the
header erase counts, and by rebuilding the app and checking the
minimize/restore case reported against the first version of this change.

Co-Authored-By: deepseek-flash
2026-10-24 15:45:49 +02:00
yuanyuanxianganddeepseek-flash 434812f87d Fix: Show the instant-message popup on packed clients
Clients packaged as SC_AES/sRDI shellcode run the payload image as raw
shellcode inside the loader stub, so the instant-message manager was
handed the stub's module handle. The stub's resource section carries no
IDD_DIALOG, and Windows rejects resource APIs on manually mapped images,
so DialogBoxParamA failed (error 1812 on Windows 11) and the bottom-right
popup never appeared after the operator sent a message.

The popup now falls back to an embedded compiled dialog template
generated from the IDD_DIALOG block in Script.rc and verified
byte-for-byte against the resource in the built ghost.exe. When the
resource lookup fails, the dialog is created with
DialogBoxIndirectParamA instead. Deployments where the resource lookup
already works keep the original path unchanged.

The incoming text is now terminated at the copied length. The server
sends the message body without a trailing NUL, so a message that filled
the 1024-byte buffer left SetDlgItemText reading past the end.

The title is now set with SetWindowTextW before the window is shown.
DialogBoxParamA converts the template's UTF-16 caption through the
system ANSI code page, so the Chinese title turned into "???" on 1252
systems (verified locally with a caption containing a character outside
CP936). The title follows the UI language: Chinese systems keep the
Chinese title, everything else shows "Message". The message body still
uses the ANSI path, preserving the existing per-ACP semantics.

Co-Authored-By: deepseek-flash
2026-10-23 12:22:44 +02:00
yuanyuanxianganddeepseek-flash c99a1c375e Feature: Add MCP tools for remote chat with the client user
Add chat_open, chat_send, chat_wait and chat_close to the MCP tool set,
behind a new McpChat switch that defaults to off and is independent of
the read-only switch. The tools reuse the existing client chat link: the
main connection sends COMMAND_CHAT, the client opens a sub-connection
with TOKEN_CONN_AUTH and TOKEN_CHAT_START, the server answers with
COMMAND_NEXT_CHAT, and both directions then carry raw CP936 text.

Sessions are per host and held in shared pointers under their own mutex,
so a waiting chat_wait survives a close or a dropped sub-connection, and
chat_send is serialised per session. Text is converted strictly between
UTF-8 and CP936: invalid UTF-8, characters GBK cannot represent (emoji,
accented letters) and messages over the client's 4000-byte buffer are
rejected with -32602 instead of being mangled. A one-second settle delay
after the sub-connection binds keeps the first message from reaching the
client before its chat window exists.

The routing hooks run before the host-management hooks in MessageHandle
and clear the route in OfflineProc before the context leaves the list. A
five-second tombstone absorbs a late TOKEN_CHAT_START after a timeout, so
a failed chat_open does not pop the MFC chat dialog. Idle sessions are
swept on every tool call, and audit entries record the session id and
byte counts only, never message bodies.

The settings dialog gains the chat checkbox and the translated labels
for all three languages, and the strict UTF-8 to CP936 helpers move from
McpMachine.cpp to McpInternal so both tool families can share them.

Co-Authored-By: deepseek-flash
2026-10-23 11:19:21 +02:00
yuanyuanxianganddeepseek-flash fff7c67af6 Fix: Make the remote chat dialog Unicode and loader-independent
Clients packaged as SC_AES/sRDI shellcode run the payload image as raw
shellcode inside the loader stub, so the chat manager was handed the
stub's module handle. The stub's resource section only carries a
manifest, and Windows resource APIs reject manually mapped images
outright, so creating IDD_CHAT failed and the chat thread exited before
the window ever existed.

The chat window now falls back to an embedded compiled dialog template
that is byte-identical to the IDD_CHAT resource, and the title-bar icon
is rebuilt directly from the module's own resource directory instead of
LoadIcon, bypassing the loader on both paths. The PE walking code checks
every offset against SizeOfImage and the resource directory size, so a
malformed or truncated image returns NULL instead of faulting.
Deployments where the resource lookup already works keep the original
code path unchanged.

The dialog is now created and driven with the wide-character API. The
client is still an MBCS build, but an ANSI dialog renders text with the
system code page, so GBK chat text turned into mojibake on German and
other non-936 systems. Incoming text is converted CP936 to UTF-16 and
outgoing text strictly back to CP936; characters GBK cannot represent
(emoji, accented letters) are refused with a visible notice instead of
silently becoming '?'. Static labels follow the system UI language, and
IDD_CHAT now uses the scalable MS Shell Dlg face so font linking can
supply CJK glyphs.

The window is now positioned explicitly as well. DS_CENTER in the
template put it at the work area origin on the three-monitor host: the
centred position came out negative there and Windows clamps out-of-range
creation coordinates to that origin. It is centred in the work area of
the monitor under the cursor instead, falling back to SPI_GETWORKAREA.

Teardown no longer leaves a hidden window behind either. The dialog
thread blocked in GetMessageW and never saw m_bRun cleared, while the
destructor waited for that thread before sending the message that would
have destroyed the window, so a close command that never arrived (the
sub-connection already gone, or WaitSendIdle timing out before CancelIO)
leaked the window, the dialog thread and the manager loop. The
destructor now destroys the window first, the loop checks m_bRun before
blocking, and it destroys the window itself if it exits first.

Co-Authored-By: deepseek-flash
2026-10-23 11:19:21 +02:00
yuanyuanxianganddeepseek-flash 3ae6298746 Fix: Align macOS mouse coordinates with the captured display
The macOS client derived its logical screen size from [NSScreen mainScreen]
while it captured CGMainDisplayID. In clamshell mode with an external display
the former can still report the disabled built-in panel (1470x956) while the
captured frame is 1280x1024, so every injected point was scaled by
logical/encode and drifted linearly with the distance from the top left
corner, independently on each axis. Take the logical size from
CGDisplayBounds of the captured display instead, and report the same bounds
in the login resolution.

For hosts that still run the old client, the remote desktop dialog gains a
per-host mouse calibration in its system menu. The factors are stored by
client ID together with the reported resolution and the captured frame size,
so they stop applying once the client is upgraded or a different display is
captured, and come back automatically when the original display returns.
When no calibration has been saved the dialog pre-fills the factors from
frame/reported, but only for macOS clients, because the other clients derive
their conversion from the captured display itself and a mismatching report
there would be misleading.

Co-Authored-By: deepseek-flash
2026-10-22 11:33:39 +02:00
yuanyuanxianganddeepseek-flash 38cd207f5d Feature: Add host management and connection management MCP tools
Expose the online-list TLS column through list_online_hosts, search_hosts
and get_host_detail. The value comes from the flag the client reports at
login, so old clients always read false.

Add list_network_connections and kill_network_connection on top of the
connection manager sub-connection protocol. The kill path matches the
original 110-byte record instead of rebuilding addresses, supports a dry
run, refuses UDP/IPv6 targets, and verifies that the quadruple really
disappeared instead of assuming success.

Add a host_* family backed by the machine manager protocol: ten read
tools covering every tab of the host management dialog, and four
recoverable write tools for process freeze/thaw, window restore/hide/
maximize/minimize, service start/stop/pause/continue/restart, and
scheduled task run/stop. Every write re-reads the snapshot before sending
and re-checks afterwards, reporting -32009 for stale targets rather than
acting blindly. The family is gated by McpMachine, the risky subset by
McpMachineDangerous, and writes additionally require read-only mode to
be off.

Route managed sub-connections from MessageHandle and OfflineProc, keep
the single-in-flight rule by sharing the pending table with a request
kind, and move the shared JSON/lock/encoding helpers into McpInternal so
both tool families use one implementation. Settings dialog, design docs
and en_US/zh_TW/de_DE translations are updated accordingly.

Co-Authored-By: deepseek-flash
2026-10-21 20:01:41 +02:00
yuanyuanxianganddeepseek-flash 6c8336b497 Fix: Repair task actions and harden machine management
Scheduled task actions never worked end to end: the server built task
packets with Unicode-style lengths in a MultiByte build, the client had
no dispatch for the run/stop/delete/create commands, and the directory
column was derived by replacing every occurrence of the task name, which
misplaced tasks whose name also appeared in a parent folder. Packets are
now assembled with narrow strings, the four commands are routed to
RunOrStopTask/DelTask/CreateTask, and the folder is taken from the task
path suffix only. The task list reply is trimmed to its real length
instead of sending the whole 32 KB scratch buffer.

On the client side, thawing a process resumed a single thread, the
inject output path was copied from a narrow string using a wide-character
length, and an empty window list dereferenced a NULL buffer. The service
list leaked its enumeration block and one service handle per skipped
entry, and the description was copied without a bound. Service start and
stop now validate every handle, initialize the status structure, and stop
synchronously before the start that follows a restart request, which
previously always failed because the service was still in STOP_PENDING.
Deleting a process used to test only the low byte of the PID and leaked
the process handle on early exits, and a failed path conversion kept the
previous process image name. The IE history timestamp wrote minutes and
seconds in the wrong order, the favorites reader queried and closed an
uninitialized registry key, software enumeration never closed its subkeys,
and the task scheduler objects were not released after use.

The network state list now frees the module, snapshot, and extended
tables on every exit path, uses HeapFree for tables allocated on the
process heap, and no longer calls an export that may be missing. Growth
failures everywhere keep the original buffer instead of overwriting the
pointer, the hosts reader rejects an invalid file size, and the COM task
walk releases definitions and folders.

Co-Authored-By: deepseek-flash
2026-10-20 21:48:13 +02:00
yuanyuanxianganddeepseek-flash c208b7368e Fix: Format net-state addresses as narrow strings on the client
The client is a MultiByte build, so the destination buffers are char[]
and _T("%s:%u") expands to an ANSI format that expects a char pointer.
The code nevertheless converted inet_ntoa() output to WCHAR* first, and
the ANSI %s stopped at the zero byte that follows the first wide
character. Every address therefore collapsed to its leading digit, so
192.168.0.55:443 was shown as 1 and 0.0.0.0:80 as 0 in the local and
remote address columns of the network connections tab.

Write the address and port straight into the char buffers with
sprintf_s in all four enumeration paths (legacy and Vista APIs, TCP and
UDP), and drop the now unused char2wchar_t helper.

Co-Authored-By: deepseek-flash
2026-10-20 21:24:47 +02:00
yuanyuanxianganddeepseek-flash 15a50db0a7 Fix: Keep IPv4 address bytes in network order for connection list
iphlpapi stores the address in network byte order inside the memory of
the DWORD, it is not a host-order integer. For 192.168.0.55 the DWORD
value on x86 is 0x3700A8C0 while its bytes are C0 A8 00 37, so shifting
the value by 24/16/8/0 produced 37 00 A8 C0 and the dialog rendered
"55.0.168.192" for both the local and remote address.

Copy the DWORD with memcpy instead, which preserves the memory layout
that inet_ntop and SetTcpEntry both expect. GetAddr4 is changed the
same way, otherwise a forced disconnect would rebuild a wrong address
and miss the target connection.

Co-Authored-By: deepseek-flash
2026-10-20 21:15:45 +02:00
yuanyuanxianganddeepseek-flash ca35e6e26f Feature: Add menu icons for the advanced and disclaimer entries
Add four 16x16 bitmaps and wire them through the existing m_bmOnline
table. The three entries under the "Advanced" menu had no icon at all,
and the disclaimer entry shared the help question mark with "what is
this", so the two were indistinguishable.

- desktop quality levels: a monitor with three ascending level bars in
  the screen
- screen preview levels: a thumbnail card with a sun, a folded corner
  and layered hills
- file transfer speed: a half-circle gauge with a red needle
- disclaimer: a document with a folded corner and an amber exclamation
  badge, so it no longer looks like the help entry

Grow the bitmap array to 75 entries and reserve resource IDs 412-415.

Co-Authored-By: deepseek-flash
2026-10-20 21:13:05 +02:00
51 changed files with 6496 additions and 449 deletions

No files matched your search

+2
View File
@@ -9,6 +9,8 @@
- build.cmd publish:编译YAMA.exe且通过upx压缩,所生成的可执行文件较小。
- buld.cmd server:只编译YAMA.exe,需保证所依赖的客户端程序已经编译。
- build.cmd go-server:编译 Go 服务端,可以选择带publish 参数进行upx压缩。
- build.cmd serverd:编译 Debug 版服务端(x64),输出 Bin\Yama_x64d.exe。
- build.cmd client:编译 Debug 版客户端(x64),输出 x64\Debug\ghost.exe。
## Go 服务端
+6 -1
View File
@@ -1,8 +1,10 @@
@echo off
:: SimpleRemoter Quick Build Script
:: Usage: build.cmd [release|debug] [x64|x86|all] [server|clean|publish|go-server]
:: Usage: build.cmd [release|debug] [x64|x86|all] [server|clean|publish|go-server|serverd|client]
:: go-server Build Go fallback server only -> Bin\YamaGo_x64.exe
:: go-server publish Same, plus UPX --best compression
:: serverd Debug server only (x64) -> Bin\Yama_x64d.exe
:: client Debug client (x64) -> x64\Debug\ghost.exe
setlocal enabledelayedexpansion
@@ -21,6 +23,9 @@ if /i "%~1"=="server" (set EXTRA_ARGS=!EXTRA_ARGS! -ServerOnly& shift& goto :par
if /i "%~1"=="clean" (set EXTRA_ARGS=!EXTRA_ARGS! -Clean& shift& goto :parse_args)
if /i "%~1"=="publish" (set EXTRA_ARGS=!EXTRA_ARGS! -Publish& shift& goto :parse_args)
if /i "%~1"=="go-server" (set EXTRA_ARGS=!EXTRA_ARGS! -GoServer& shift& goto :parse_args)
:: Debug presets: serverd = debug server x64 only, client = debug ghost x64 only
if /i "%~1"=="serverd" (set CONFIG=Debug& set PLATFORM=x64& set EXTRA_ARGS=!EXTRA_ARGS! -ServerOnly& shift& goto :parse_args)
if /i "%~1"=="client" (set CONFIG=Debug& set PLATFORM=x64& set EXTRA_ARGS=!EXTRA_ARGS! -ClientOnly& shift& goto :parse_args)
echo Unknown argument: %~1
shift
goto :parse_args
+103 -11
View File
@@ -1,9 +1,10 @@
# SimpleRemoter Build Script
# Usage: .\build.ps1 [-Config Release|Debug] [-Platform x64|x86|all] [-ServerOnly] [-Clean] [-Publish]
# SimpleRemoter Build Script
# Usage: .\build.ps1 [-Config Release|Debug] [-Platform x64|x86|all] [-ServerOnly] [-ClientOnly] [-Clean] [-Publish]
#
# Requirements:
# - Visual Studio 2019 or 2022
# - v142 toolset (MSVC v142 - VS 2019 C++ build tools)
# - ATL (C++ ATL for v142 build tools)
# - MFC libraries (C++ MFC for v142 build tools)
param(
@@ -14,6 +15,7 @@ param(
[string]$Platform = "x64",
[switch]$ServerOnly, # Only build main server (Yama), skip client projects
[switch]$ClientOnly, # Only build the client executable (ghost), skip server
[switch]$Clean, # Clean before build
[switch]$Publish, # Publish mode: rebuild all deps + x64 Release + UPX compress
[switch]$GoServer # Build Go fallback server (server/go) -> Bin/YamaGo_x64.exe
@@ -119,8 +121,27 @@ if ($GoServer) {
exit 0
}
# 判断某个 VS 安装是否带 ATL/MFC 组件。ATL 头文件用 #pragma comment(lib, "atls.lib")
# 自动链接,只装了编译工具(BuildTools)的实例常常没有这一块:编译能过、链接报
# LNK1104 无法打开 atls.lib。同机既装 BuildTools 又装 IDE 时,按路径取第一个会挑错。
function Test-VcAtlPresent {
param([string]$VsRoot)
if (-not $VsRoot) { return $false }
$atlLib = Join-Path $VsRoot "VC\Tools\MSVC\*\atlmfc\lib\x86\atls.lib"
return [bool](Get-ChildItem $atlLib -ErrorAction SilentlyContinue | Select-Object -First 1)
}
# 从 ...\MSBuild\Current\Bin\MSBuild.exe 反推 VS 安装根目录。
function Get-VsRootFromMsBuild {
param([string]$MsBuildPath)
$idx = $MsBuildPath.IndexOf("\MSBuild\", [System.StringComparison]::OrdinalIgnoreCase)
if ($idx -lt 0) { return $null }
return $MsBuildPath.Substring(0, $idx)
}
# Find MSBuild (VS2019 or VS2022, including Insiders/Preview)
# Order: Prefer installations with v142 toolset (VS2019) over VS2022 BuildTools
# Order: Prefer installations with v142 toolset (VS2019) over VS2022 BuildTools,
# and within that prefer instances that actually carry ATL/MFC.
$msBuildPaths = @(
# VS2019 Insiders/Preview (non-standard path) - has v142 + MFC
"${env:ProgramFiles}\Microsoft Visual Studio\18\*\MSBuild\Current\Bin\MSBuild.exe",
@@ -134,12 +155,17 @@ $msBuildPaths = @(
)
$msBuild = $null
$fallbackMsBuild = $null # 第一个找到的候选(可能不带 ATL),仅在没有带 ATL 的实例时兜底
foreach ($pattern in $msBuildPaths) {
$found = Get-ChildItem $pattern -ErrorAction SilentlyContinue | Select-Object -First 1
if ($found) {
$msBuild = $found.FullName
break
foreach ($found in @(Get-ChildItem $pattern -ErrorAction SilentlyContinue)) {
if (-not $fallbackMsBuild) { $fallbackMsBuild = $found.FullName }
if (Test-VcAtlPresent (Get-VsRootFromMsBuild $found.FullName)) {
$msBuild = $found.FullName
break
}
Write-Host "Skipping MSBuild without ATL/MFC: $($found.FullName)" -ForegroundColor DarkYellow
}
if ($msBuild) { break }
}
# 兜底:默认路径找不到(例如 VS 装在 D 盘)时,用 vswhere 反查。
@@ -147,19 +173,34 @@ foreach ($pattern in $msBuildPaths) {
if (-not $msBuild) {
$vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"
if (Test-Path $vswhere) {
$found = & $vswhere -latest -products * -requires Microsoft.Component.MSBuild `
-find "MSBuild\**\Bin\MSBuild.exe" 2>$null |
Select-Object -First 1
if ($found) { $msBuild = $found }
# 不能用 -requires Microsoft.VisualStudio.Component.VC.ATL 过滤组件 id:
# 各 VS 版本的 id 不一样(v142/v143/预览版),且预览实例可能根本查不到。
# 因此列出全部实例,再逐个用 atls.lib 落地校验(上面那条 glob 只看得到 C 盘,
# VS 装在 D 盘时只能靠这里找到)。
$hits = @(& $vswhere -products * -requires Microsoft.Component.MSBuild `
-find "MSBuild\**\Bin\MSBuild.exe" 2>$null)
foreach ($hit in $hits) {
if (-not $hit) { continue }
if (-not $fallbackMsBuild) { $fallbackMsBuild = $hit }
if (Test-VcAtlPresent (Get-VsRootFromMsBuild $hit)) { $msBuild = $hit; break }
}
}
}
# 一个带 ATL 的实例都没有:仍用兜底候选,让 MSBuild 报出更具体的错误。
if (-not $msBuild -and $fallbackMsBuild) {
Write-Host "WARNING: no VS instance with ATL/MFC found, using $fallbackMsBuild" -ForegroundColor Yellow
Write-Host " Install 'C++ ATL for v142 build tools' if linking fails on atls.lib." -ForegroundColor DarkGray
$msBuild = $fallbackMsBuild
}
if (-not $msBuild) {
Write-Host "ERROR: MSBuild not found." -ForegroundColor Red
Write-Host ""
Write-Host "Please install Visual Studio 2019 or 2022 with:" -ForegroundColor Yellow
Write-Host " - Desktop development with C++" -ForegroundColor White
Write-Host " - MSVC v142 - VS 2019 C++ x64/x86 build tools" -ForegroundColor White
Write-Host " - C++ ATL for v142 build tools" -ForegroundColor White
Write-Host " - C++ MFC for v142 build tools" -ForegroundColor White
exit 1
}
@@ -218,6 +259,9 @@ function Build-Project {
Write-Host "If you see 'v142 build tools cannot be found':" -ForegroundColor Yellow
Write-Host " Install 'MSVC v142 - VS 2019 C++ build tools' via VS Installer" -ForegroundColor White
Write-Host ""
Write-Host "If you see 'LNK1104: cannot open file atls.lib':" -ForegroundColor Yellow
Write-Host " Install 'C++ ATL for v142 build tools' via VS Installer" -ForegroundColor White
Write-Host ""
Write-Host "If you see 'MFC libraries are required':" -ForegroundColor Yellow
Write-Host " Install 'C++ MFC for v142 build tools' via VS Installer" -ForegroundColor White
exit 1
@@ -226,6 +270,54 @@ function Build-Project {
Write-Host "OK: $Project" -ForegroundColor Green
}
# Debug client fast path: build the client executable and stop.
# Only ghost is built — the other client projects (ServerDll, TestRun, TinyRun,
# SCLoader) exist to be embedded in the server and are irrelevant when the goal
# is debugging the client itself.
if ($ClientOnly) {
$clientProject = "ghost"
$clientPlatforms = if ($Platform -eq "all") { @("x86", "x64") } else { @($Platform) }
$startTime = Get-Date
Write-Host ""
Write-Host "========================================" -ForegroundColor Cyan
Write-Host " SimpleRemoter Client Build" -ForegroundColor Cyan
Write-Host " Config: $Config" -ForegroundColor Cyan
Write-Host " Platform: $Platform" -ForegroundColor Cyan
Write-Host " VS: $vsYear" -ForegroundColor Cyan
Write-Host " Clean: $Clean" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
foreach ($plat in $clientPlatforms) {
Build-Project -Project $clientProject -Configuration $Config -Platform $plat -ForceClean $Clean
}
$elapsed = (Get-Date) - $startTime
Write-Host ""
Write-Host "========================================" -ForegroundColor Green
Write-Host " Build Completed!" -ForegroundColor Green
Write-Host " Time: $($elapsed.TotalSeconds.ToString('F1')) seconds" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Green
Write-Host ""
Write-Host "Output files:" -ForegroundColor Cyan
# VS default OutDir for this project: $(SolutionDir)$(Platform)\$(Configuration)\
# x86 output lands in <root>\Debug, x64 in <root>\x64\Debug.
foreach ($plat in $clientPlatforms) {
$outDir = if ($plat -eq "x64") { Join-Path (Join-Path $rootDir "x64") $Config } else { Join-Path $rootDir $Config }
$clientOut = Join-Path $outDir "ghost.exe"
if (Test-Path $clientOut) {
$size = (Get-Item $clientOut).Length / 1MB
Write-Host " $clientOut ($($size.ToString('F2')) MB)" -ForegroundColor White
} else {
Write-Host " WARNING: expected output not found at $clientOut" -ForegroundColor Yellow
}
}
exit 0
}
# Determine platforms to build
$platforms = if ($Platform -eq "all") { @("x86", "x64") } else { @($Platform) }
+44
View File
@@ -0,0 +1,44 @@
// ChatDialogTemplate.h: IDD_CHAT 的编译后 DLGTEMPLATEEX(内嵌内存模板)
//
// 用途:加壳部署(EXE + SC_AES/sRDI)的客户端里,ChatManager 的 hInstance 是外壳进程
// 映像(GetModuleHandle(NULL)),其资源里只有清单、没有 IDD_CHAT;而载荷 EXE 以裸
// shellcode 在壳进程内运行,未注册进加载器,FindResource/LoadResource/CreateDialogParamW
// 一律取不到资源(实测 Win11 26200 返回 err=1812 / 59)。此时用下面的内存模板直接
// CreateDialogIndirectParamW 建窗,与部署形态无关。
//
// 数据来源:client/Script.rc 的 IDD_CHAT(DIALOGEX)。DLGTEMPLATEEX 的字符串字段
// 一律是 UTF-16,同一份字节既可用于 A 接口也可用于 W 接口;聊天窗口固定用 W 接口
// 创建成 Unicode 对话框,否则 MBCS 客户端在非中文系统(德语等)上会按系统代码页
// 渲染 GBK 字节,中文全部乱码。
//
// 重新生成(改动 Script.rc 的 IDD_CHAT 后必须同步):
// 1. rc /fo dlg.res dlg.rc (dlg.rc 只保留与 Script.rc 相同的 IDD_CHAT 块)
// 2. link /dll /noentry /machine:x64 /out:dlg.dll dlg.res
// 3. 从 dlg.dll 的 RT_DIALOG(5) → 106 → 任意语言 取数据块,按 16 字节一行导出。
// 当前块 240 字节:CAPTION "Remote Chat"、FONT 9 "MS Shell Dlg" charset 1、
// 控件 ID 1001/1002/1003/1004,与 Script.rc 完全一致。
#ifndef YAMA_CHAT_DIALOG_TEMPLATE_H
#define YAMA_CHAT_DIALOG_TEMPLATE_H
// DLGTEMPLATEEX 的 DWORD 字段要求模板指针 4 字节对齐;显式声明对齐,避免依赖
// 编译器把字节数组放在什么边界上。
__declspec(align(4)) static const unsigned char kChatDialogTemplate[] = {
0x01, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x08, 0xCA, 0x80,
0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0xEB, 0x00, 0x9B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x52, 0x00,
0x65, 0x00, 0x6D, 0x00, 0x6F, 0x00, 0x74, 0x00, 0x65, 0x00, 0x20, 0x00, 0x43, 0x00, 0x68, 0x00,
0x61, 0x00, 0x74, 0x00, 0x00, 0x00, 0x09, 0x00, 0x90, 0x01, 0x00, 0x01, 0x4D, 0x00, 0x53, 0x00,
0x20, 0x00, 0x53, 0x00, 0x68, 0x00, 0x65, 0x00, 0x6C, 0x00, 0x6C, 0x00, 0x20, 0x00, 0x44, 0x00,
0x6C, 0x00, 0x67, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x44, 0x08, 0xA1, 0x50, 0x03, 0x00, 0x03, 0x00, 0xE5, 0x00, 0x6B, 0x00, 0xE9, 0x03, 0x00, 0x00,
0xFF, 0xFF, 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x44, 0x00, 0xA1, 0x50, 0x03, 0x00, 0x71, 0x00, 0xAA, 0x00, 0x26, 0x00, 0xEA, 0x03, 0x00, 0x00,
0xFF, 0xFF, 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x01, 0x00, 0x01, 0x50, 0xB2, 0x00, 0x74, 0x00, 0x36, 0x00, 0x0E, 0x00, 0xEB, 0x03, 0x00, 0x00,
0xFF, 0xFF, 0x80, 0x00, 0x53, 0x00, 0x65, 0x00, 0x6E, 0x00, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x50, 0xB2, 0x00, 0x85, 0x00,
0x36, 0x00, 0x0E, 0x00, 0xEC, 0x03, 0x00, 0x00, 0xFF, 0xFF, 0x80, 0x00, 0x45, 0x00, 0x6E, 0x00,
0x64, 0x00, 0x20, 0x00, 0x43, 0x00, 0x68, 0x00, 0x61, 0x00, 0x74, 0x00, 0x00, 0x00, 0x00, 0x00,
};
#endif // YAMA_CHAT_DIALOG_TEMPLATE_H
+228 -49
View File
@@ -4,9 +4,12 @@
#include "stdafx.h"
#include "ChatManager.h"
#include "ChatDialogTemplate.h"
#include "ImageResource.h"
#include "Common.h"
#include "resource.h"
#include <TlHelp32.h>
#include <string>
#if ENABLE_MESSAGE
@@ -28,6 +31,27 @@ static SuspendOrResumeProcess g_lpfnNtResumeProcess = NULL;
static HHOOK g_hKeyBoard = NULL;
static int g_nLocked = 0;
// 加壳部署用:从本模块映像自建的聊天窗口图标,只建一次,进程内复用(不销毁)
static volatile LONG g_lOwnIconsState = 0; // 0=未建 1=建中 2=已建
static HICON g_hOwnIconSmall = NULL;
static HICON g_hOwnIconBig = NULL;
static void EnsureOwnChatIcons()
{
if (InterlockedCompareExchange(&g_lOwnIconsState, 1, 0) == 0) {
g_hOwnIconSmall = CreateImageIcon(&__ImageBase, IDI_ICON_MSG,
GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON));
g_hOwnIconBig = CreateImageIcon(&__ImageBase, IDI_ICON_MSG,
GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON));
InterlockedExchange(&g_lOwnIconsState, 2); // 全屏障,发布句柄
return;
}
// 另一个线程正在建:短暂等待其发布,避免读到尚未赋值的句柄
for (int i = 0; i < 50 && g_lOwnIconsState != 2; i++) {
Sleep(1);
}
}
static DWORD GetWinlogonPid()
{
HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
@@ -62,6 +86,11 @@ static LRESULT CALLBACK KeyBoardProc(int code, WPARAM wParam, LPARAM lParam)
|| (p->vkCode == VK_ESCAPE && (GetKeyState(VK_CONTROL) & 0x8000) != 0) // Ctrl+Esc
|| (p->vkCode == VK_LWIN)
|| (p->vkCode == VK_RWIN)) {
// 低层钩子按后装先调用的顺序排队,直接 return 1 会让链上更早安装的
// 钩子(例如同机运行的主控的系统热键转发)永远收不到这些键。
// 先沿链传递再返回 1:别的钩子能看见按键并自行决定是否转发,
// 本机 shell 仍然被拦住,锁屏效果不变。
::CallNextHookEx(g_hKeyBoard, code, wParam, lParam);
return 1;
}
break;
@@ -133,6 +162,113 @@ static void UnlockScreen()
g_nLocked = 0;
}
//////////////////////////////////////////////////////////////////////
// 聊天文字:Unicode 窗口与 CP936 转换
//////////////////////////////////////////////////////////////////////
// 聊天窗口是 Unicode 对话框:客户端整体是 MBCS 工程,但聊天窗口用 W 接口创建,
// 文字以 UTF-16 存在内存里,与系统 ANSI 代码页无关——德语/日语等非中文系统上
// 中文不再乱码。静态标签按系统 UI 语言选择:中文系统保持中文,其余用英文。
struct ChatUiStrings {
const wchar_t* caption;
const wchar_t* send;
const wchar_t* end;
const wchar_t* self;
const wchar_t* peer;
const wchar_t* errChars;
const wchar_t* errTooLong;
};
static const ChatUiStrings& ChatUi()
{
static const ChatUiStrings zhChatUi = {
L"远程交谈", L"发送消息", L"结束交谈", L"自己:", L"对方:",
L"消息未发送:含 GBK 不支持的字符(emoji 或带变音符号的字母)",
L"消息未发送:超过 4000 字节上限"
};
static const ChatUiStrings enChatUi = {
L"Remote Chat", L"Send", L"End Chat", L"Me:", L"Peer:",
L"Not sent: the message contains characters GBK cannot represent "
L"(emoji or accented letters)",
L"Not sent: the message exceeds the 4000-byte limit"
};
static const bool bChineseUI =
(PRIMARYLANGID(GetUserDefaultUILanguage()) == LANG_CHINESE);
return bChineseUI ? zhChatUi : enChatUi;
}
// 服务端聊天正文一律是 CP936 字节;转成 UTF-16 交给 Unicode 编辑框显示。
static bool Cp936ToWide(const char* src, int cbSrc, std::wstring& out)
{
out.clear();
if (!src || cbSrc <= 0) return true;
int cch = MultiByteToWideChar(936, 0, src, cbSrc, NULL, 0);
if (cch <= 0) return false;
out.resize((size_t)cch);
return MultiByteToWideChar(936, 0, src, cbSrc, &out[0], cch) > 0;
}
static size_t ChatBoundedStrlen(const char* s, size_t nMax)
{
size_t n = 0;
while (n < nMax && s[n] != '\0') ++n;
return n;
}
// 追加一条聊天记录。控件是 Unicode 窗口,即使在 MBCS 工程里也必须用 W 接口,
// 否则文字会被按系统代码页转换。
static void AppendChatLine(HWND hDlg, const wchar_t* who, const wchar_t* body)
{
HWND hEditChatLog = GetDlgItem(hDlg, IDC_EDIT_CHATLOG);
if (!hEditChatLog) return;
SYSTEMTIME st;
GetLocalTime(&st);
wchar_t stamp[64] = { 0 };
swprintf_s(stamp, L"%d/%d/%d %d:%02d:%02d",
st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
std::wstring text(who);
text += L' ';
text += stamp;
text += L"\r\n ";
if (body) text += body;
text += L"\r\n\r\n";
int nLen = GetWindowTextLengthW(hEditChatLog);
if (nLen >= 20000) {
SetWindowTextW(hEditChatLog, L"");
nLen = 0;
}
SendMessageW(hEditChatLog, EM_SETSEL, nLen, nLen);
SendMessageW(hEditChatLog, EM_REPLACESEL, FALSE, (LPARAM)text.c_str());
}
// 把聊天窗口显式居中到鼠标所在显示器的工作区。模板里的 DS_CENTER 在多显示器布局下
// 可能算出负坐标,再被系统夹到工作区左上角(三屏机器上实测稳定复现),所以不依赖它。
static void CenterChatDialog(HWND hDlg)
{
RECT rc;
if (!GetWindowRect(hDlg, &rc)) return;
const int cx = rc.right - rc.left;
const int cy = rc.bottom - rc.top;
RECT rcWork;
POINT pt;
MONITORINFO mi = { sizeof(mi) };
if (GetCursorPos(&pt) && GetMonitorInfo(MonitorFromPoint(pt, MONITOR_DEFAULTTOPRIMARY), &mi)) {
rcWork = mi.rcWork;
} else if (!SystemParametersInfo(SPI_GETWORKAREA, 0, &rcWork, 0)) {
return;
}
int x = rcWork.left + (rcWork.right - rcWork.left - cx) / 2;
int y = rcWork.top + (rcWork.bottom - rcWork.top - cy) / 2;
if (x < rcWork.left) x = rcWork.left;
if (y < rcWork.top) y = rcWork.top;
SetWindowPos(hDlg, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
}
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
@@ -157,15 +293,19 @@ CChatManager::CChatManager(IOCPClient* ClientObject, int n, void* user) : CManag
CChatManager::~CChatManager()
{
m_bRun = FALSE;
// 必须先销毁窗口再等线程:消息循环阻塞在 GetMessageW 里看不到 m_bRun,只有
// 收到 WM_USER + 1(DestroyWindow → PostQuitMessage)才会退出。关闭命令没送到
// (子连接先断、服务端 WaitSendIdle 超时后 CancelIO)时,旧的先等后销毁顺序会
// 死锁在这里,留下一个隐藏的聊天窗口和卡死的线程。
if (m_hWnd) {
SendMessage(m_hWnd, WM_USER + 1, NULL, NULL);
}
while (m_hThread)
Sleep(100);
if (g_nLocked == 1) {
UnlockScreen();
}
if (m_hWnd) {
SendMessage(m_hWnd, WM_USER + 1, NULL, NULL);
}
Mprintf("Chat 析构\n");
}
@@ -174,10 +314,25 @@ DWORD WINAPI CChatManager::MessageLoopProc(LPVOID lParam)
CChatManager* pThis = (CChatManager*)lParam;
HANDLE& hThread(pThis->m_hThread);
pThis->m_hWnd = CreateDialogParamA(pThis->m_hInstance, MAKEINTRESOURCE(IDD_CHAT), NULL,
// 聊天窗口必须是 Unicode 窗口:ANSI 窗口会按系统代码页解释文字,非中文系统
// (德语等)上 GBK 中文一律乱码。资源里的 IDD_CHAT 是 DIALOGEX,字符串本来
// 就是 UTF-16,W 接口可直接加载。
pThis->m_hWnd = CreateDialogParamW(pThis->m_hInstance, MAKEINTRESOURCEW(IDD_CHAT), NULL,
CChatManager::ChatDialogProc, (LPARAM)pThis);
if (!pThis->m_hWnd) {
// 加壳部署(EXE + SC_AES/sRDI)时 m_hInstance 是外壳进程映像:资源里没有
// IDD_CHAT,而载荷以裸 shellcode 运行、未注册进加载器,资源 API 一律取不到
// 对话框(Windows 11 上 CreateDialogParamW 返回 err=1812 或 59)。
// 回退:用内嵌的 IDD_CHAT 编译后模板建窗,与部署形态无关。
DWORD dwError = GetLastError();
Mprintf("CreateDialogParamW(%lu) 失败,改用内嵌对话框模板\n", dwError);
pThis->m_hWnd = CreateDialogIndirectParamW(pThis->m_hInstance,
(LPCDLGTEMPLATEW)kChatDialogTemplate, NULL,
CChatManager::ChatDialogProc, (LPARAM)pThis);
}
if (pThis->m_hWnd) {
SendMessage(GetDlgItem(pThis->m_hWnd, IDC_EDIT_NEWMSG), EM_SETLIMITTEXT, 8158, 0);
SendMessageW(GetDlgItem(pThis->m_hWnd, IDC_EDIT_NEWMSG), EM_SETLIMITTEXT, 8158, 0);
CenterChatDialog(pThis->m_hWnd);
SetWindowPos(pThis->m_hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
// 移除最小化/最大化按钮
LONG lStyle = GetWindowLong(pThis->m_hWnd, GWL_STYLE);
@@ -185,12 +340,22 @@ DWORD WINAPI CChatManager::MessageLoopProc(LPVOID lParam)
SetWindowLong(pThis->m_hWnd, GWL_STYLE, lStyle);
MSG msg;
while (GetMessage(&msg, NULL, 0, 0) && pThis->m_bRun) {
if (!IsDialogMessage(pThis->m_hWnd, &msg)) {
// 本线程只拥有这个对话框,整轮循环用 W 版本收发:否则 WM_CHAR / WM_IME_*
// 会按系统 ANSI 代码页转换,非中文系统上中文输入法会丢字。
// m_bRun 先判断:析构里置 FALSE 后即使没有新消息也要能退出,不能卡在 GetMessageW。
while (pThis->m_bRun && GetMessageW(&msg, NULL, 0, 0)) {
if (!IsDialogMessageW(pThis->m_hWnd, &msg)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
DispatchMessageW(&msg);
}
}
// 兜底:若循环在窗口销毁之前就因 m_bRun 被清掉而退出(析构执行到销毁之前
// 线程就已建好窗口),在同一线程里补一次销毁,避免残留隐藏窗口。
if (pThis->m_hWnd) {
HWND hWnd = pThis->m_hWnd;
pThis->m_hWnd = NULL;
DestroyWindow(hWnd);
}
}
CloseHandle(hThread);
@@ -205,43 +370,65 @@ INT_PTR CALLBACK CChatManager::ChatDialogProc(HWND hDlg, UINT uMsg, WPARAM wPara
case WM_INITDIALOG:
SetWindowLongPtr(hDlg, GWLP_USERDATA, (LONG_PTR)lParam);
pThis = (CChatManager*)lParam;
SetWindowText(hDlg, "远程交谈");
SetDlgItemText(hDlg, IDC_BUTTON_SEND, "发送消息");
SetDlgItemText(hDlg, IDC_BUTTON_END, "结束交谈");
SetWindowTextW(hDlg, ChatUi().caption);
SetDlgItemTextW(hDlg, IDC_BUTTON_SEND, ChatUi().send);
SetDlgItemTextW(hDlg, IDC_BUTTON_END, ChatUi().end);
{
HICON hIcon = LoadIcon(pThis->m_hInstance, MAKEINTRESOURCE(IDI_ICON_MSG));
if (hIcon) {
SendMessage(hDlg, WM_SETICON, ICON_SMALL, (LPARAM)hIcon);
SendMessage(hDlg, WM_SETICON, ICON_BIG, (LPARAM)hIcon);
HICON hIconSmall = LoadIcon(pThis->m_hInstance, MAKEINTRESOURCE(IDI_ICON_MSG));
HICON hIconBig = hIconSmall;
if (!hIconSmall) {
// 加壳部署取不到图标资源:直接从本模块映像里读 RT_ICON 建图标,
// 仍失败才退回系统默认图标(共享图标,不可销毁)
EnsureOwnChatIcons();
hIconSmall = g_hOwnIconSmall ? g_hOwnIconSmall : LoadIcon(NULL, IDI_APPLICATION);
hIconBig = g_hOwnIconBig ? g_hOwnIconBig : hIconSmall;
}
if (hIconSmall) SendMessage(hDlg, WM_SETICON, ICON_SMALL, (LPARAM)hIconSmall);
if (hIconBig) SendMessage(hDlg, WM_SETICON, ICON_BIG, (LPARAM)hIconBig);
}
return TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDC_BUTTON_SEND) {
char str[4096] = { 0 };
GetDlgItemText(hDlg, IDC_EDIT_NEWMSG, str, sizeof(str));
if (str[0] == 0) {
SetFocus(GetDlgItem(hDlg, IDC_EDIT_NEWMSG));
HWND hEditNewMsg = GetDlgItem(hDlg, IDC_EDIT_NEWMSG);
int cch = GetWindowTextLengthW(hEditNewMsg);
if (cch <= 0) {
SetFocus(hEditNewMsg);
return TRUE; // 消息为空不发送
}
pThis->Send((LPBYTE)str, lstrlenA(str) + 1);
SYSTEMTIME st;
GetLocalTime(&st);
char Text[5120] = { 0 };
sprintf_s(Text, sizeof(Text), "%s %d/%d/%d %d:%02d:%02d\r\n %s\r\n\r\n", "自己:",
st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, str);
HWND hEditChatLog = GetDlgItem(hDlg, IDC_EDIT_CHATLOG);
int nLen = GetWindowTextLength(hEditChatLog);
if (nLen >= 20000) {
SetWindowText(hEditChatLog, "");
nLen = GetWindowTextLength(hEditChatLog);
std::wstring text((size_t)cch + 1, L'\0');
GetWindowTextW(hEditNewMsg, &text[0], cch + 1);
text.resize(wcslen(text.c_str()));
if (text.empty()) {
SetFocus(hEditNewMsg);
return TRUE;
}
SendMessage(hEditChatLog, EM_SETSEL, nLen, nLen);
SendMessage(hEditChatLog, EM_REPLACESEL, FALSE, (LPARAM)Text);
SetDlgItemText(hDlg, IDC_EDIT_NEWMSG, "");
SetFocus(GetDlgItem(hDlg, IDC_EDIT_NEWMSG));
// 协议仍是 CP936:UTF-16 → GBK 严格转换。GBK 表示不了的字符(emoji、
// ö/ä/ß 等)直接拒发并提示,绝不静默变成 '?'。
BOOL usedDefault = FALSE;
int nNeed = WideCharToMultiByte(936, WC_NO_BEST_FIT_CHARS, text.c_str(), -1,
NULL, 0, NULL, &usedDefault);
if (nNeed <= 1 || usedDefault) {
AppendChatLine(hDlg, ChatUi().self, ChatUi().errChars);
return TRUE;
}
if (nNeed - 1 > 4000) {
AppendChatLine(hDlg, ChatUi().self, ChatUi().errTooLong);
return TRUE;
}
std::string gbk((size_t)nNeed, '\0');
WideCharToMultiByte(936, WC_NO_BEST_FIT_CHARS, text.c_str(), -1,
&gbk[0], nNeed, NULL, &usedDefault);
if (usedDefault) {
AppendChatLine(hDlg, ChatUi().self, ChatUi().errChars);
return TRUE;
}
pThis->Send((LPBYTE)&gbk[0], (ULONG)gbk.size()); // 含结尾 NUL
AppendChatLine(hDlg, ChatUi().self, text.c_str());
SetDlgItemTextW(hDlg, IDC_EDIT_NEWMSG, L"");
SetFocus(hEditNewMsg);
return TRUE;
}
if (LOWORD(wParam) == IDC_BUTTON_END) {
@@ -317,21 +504,13 @@ VOID CChatManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
}
}
// 收到服务端发来的聊天文本
SYSTEMTIME st;
GetLocalTime(&st);
char Text[8192] = { 0 };
sprintf_s(Text, sizeof(Text), "%s %d/%d/%d %d:%02d:%02d\r\n %s\r\n\r\n", "对方:",
st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, (char*)szBuffer);
// 收到服务端发来的聊天文本:协议是 CP936 字节(NUL 结尾),转成 UTF-16 显示,
// 这样非中文系统(德语等)上也能正确显示中文。
const size_t cbText = ChatBoundedStrlen((const char*)szBuffer, (size_t)ulLength);
std::wstring text;
if (!Cp936ToWide((const char*)szBuffer, (int)cbText, text)) return;
if (m_hWnd) {
HWND hEditChatLog = GetDlgItem(m_hWnd, IDC_EDIT_CHATLOG);
int nLen = GetWindowTextLength(hEditChatLog);
if (nLen >= 20000) {
SetWindowText(hEditChatLog, "");
nLen = GetWindowTextLength(hEditChatLog);
}
SendMessage(hEditChatLog, EM_SETSEL, nLen, nLen);
SendMessage(hEditChatLog, EM_REPLACESEL, FALSE, (LPARAM)Text);
AppendChatLine(m_hWnd, ChatUi().peer, text.c_str());
ShowWindow(m_hWnd, SW_RESTORE);
}
}
+3
View File
@@ -289,6 +289,9 @@
<ClInclude Include="SystemManager.h" />
<ClInclude Include="TalkManager.h" />
<ClInclude Include="ChatManager.h" />
<ClInclude Include="ChatDialogTemplate.h" />
<ClInclude Include="TalkDialogTemplate.h" />
<ClInclude Include="ImageResource.h" />
<ClInclude Include="MachineManager.h" />
<ClInclude Include="yapi.hpp" />
<ClInclude Include="VideoCodec.h" />
+3
View File
@@ -119,6 +119,9 @@
<ClInclude Include="screenhide\ScreenHideSpy.h" />
<ClInclude Include="DrawingBoardMgr.h" />
<ClInclude Include="ChatManager.h" />
<ClInclude Include="ChatDialogTemplate.h" />
<ClInclude Include="TalkDialogTemplate.h" />
<ClInclude Include="ImageResource.h" />
<ClInclude Include="MachineManager.h" />
<ClInclude Include="yapi.hpp" />
<ClInclude Include="TlsChannel.h" />
+8 -7
View File
@@ -60,19 +60,20 @@ static void ResolveProcName(DWORD pid, char* out, int outLen)
out[outLen - 1] = 0;
}
// IPv4 地址:iphlpapi 的 dwLocalAddr/dwRemoteAddr 是网络序 DWORD(值 0xC0A80101 即 192.168.1.1),
// 转成 16 字节字段前 4 字节的网络序字节后 inet_ntop 可直接展示、断连时再拼回 DWORD。
// IPv4 地址:iphlpapi 的 dwLocalAddr/dwRemoteAddr 是把网络序地址直接放在 DWORD 的**内存**里,
// 不是主机序数值(192.168.0.55 在 x86 上 DWORD 数值是 0x3700A8C0、内存字节是 C0 A8 00 37)。
// 所以只能按内存拷贝:这样得到的正是 inet_ntop 需要的网络序字节,也能原样拼回 SetTcpEntry 的 DWORD。
// 按数值移位会把字节序弄反(显示成 55.0.168.192)。
static void PutAddr4(uint8_t* out, DWORD addrNet)
{
out[0] = (uint8_t)(addrNet >> 24);
out[1] = (uint8_t)(addrNet >> 16);
out[2] = (uint8_t)(addrNet >> 8);
out[3] = (uint8_t)(addrNet);
memcpy(out, &addrNet, 4);
}
static DWORD GetAddr4(const uint8_t* addr)
{
return ((DWORD)addr[0] << 24) | ((DWORD)addr[1] << 16) | ((DWORD)addr[2] << 8) | (DWORD)addr[3];
DWORD addrNet = 0;
memcpy(&addrNet, addr, 4);
return addrNet;
}
static void AppendTcp4(std::vector<ConnectionInfo>& rows)
+147
View File
@@ -0,0 +1,147 @@
// ImageResource.h: 不经加载器,直接从内存中的模块映像读取资源
//
// 加壳部署(EXE + SC_AES/sRDI)下,载荷映像以裸 shellcode 运行、未注册进加载器,
// FindResource/LoadIcon/CreateDialogParamA 这类按 hInstance 找资源的 API 全部失败
// (实测 Win11 返回 err=1812 / 59)。但映像的节(含 .rsrc)是按 PE 布局正常映射
// 的,资源目录里的偏移又都是 RVA,因此可以直接遍历 IMAGE_RESOURCE_DIRECTORY
// 取到资源数据。本文件只读调用方给出的映像,不做任何映射。
//
// 适用:正常 EXE/DLL、MemoryModule 手工映射 DLL、sRDI 包装的 shellcode 载荷。
// 注意:调用方传入的必须是已映射映像的基址(如 &__ImageBase),不是磁盘文件。
//
// 稳定性:所有偏移都按 SizeOfImage / 资源目录大小做越界检查,映像布局异常
// (被第三方加壳改坏、资源被裁剪等)时一律返回 NULL,绝不越界读取。
#ifndef YAMA_IMAGE_RESOURCE_H
#define YAMA_IMAGE_RESOURCE_H
#include <windows.h>
#ifdef __cplusplus
extern "C" const IMAGE_DOS_HEADER __ImageBase;
#endif
// RT_ICON / RT_GROUP_ICON 的数字 ID(与同名 RT_ 宏对应)
#define IMAGE_RES_TYPE_ICON 3
#define IMAGE_RES_TYPE_GROUP_ICON 14
#pragma pack(push, 1)
typedef struct GRPICONDIRENTRY {
BYTE bWidth;
BYTE bHeight;
BYTE bColorCount;
BYTE bReserved;
WORD wPlanes;
WORD wBitCount;
DWORD dwBytesInRes;
WORD nID;
} GRPICONDIRENTRY;
#pragma pack(pop)
#define IMAGE_RES_DIR_IN_BOUNDS(resOffset, resSize) \
((resOffset) <= (resSize) - sizeof(IMAGE_RESOURCE_DIRECTORY))
#define IMAGE_RES_ENTRY_ARRAY_OK(resOffset, resCount, resSize) \
((resCount) <= ((resSize) - (resOffset) - sizeof(IMAGE_RESOURCE_DIRECTORY)) / sizeof(IMAGE_RESOURCE_DIRECTORY_ENTRY))
// 在已映射映像中查找 type/id(取第一个语言项)的资源数据,返回映像内指针
static const BYTE* FindImageResource(const void* pvImage, WORD nType, WORD nId, DWORD* pdwSize)
{
if (pdwSize) *pdwSize = 0;
if (!pvImage) return NULL;
const BYTE* pBase = (const BYTE*)pvImage;
const DWORD dwLfanew = *(const DWORD*)(pBase + 0x3C);
// 正常 PE 头远小于一页;sRDI 的 CLEARHEADER 只保留 PE 头(e_lfanew 之后),
// 所以这里不能用 MZ 判断,只能靠 e_lfanew 与 PE 签名
if (dwLfanew == 0 || dwLfanew > 0x1000) return NULL;
const PIMAGE_NT_HEADERS pNt = (const PIMAGE_NT_HEADERS)(pBase + dwLfanew);
if (pNt->Signature != IMAGE_NT_SIGNATURE) return NULL;
const DWORD dwImageSize = pNt->OptionalHeader.SizeOfImage;
const DWORD dwResRva = pNt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress;
const DWORD dwResSize = pNt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].Size;
if (dwResRva == 0 || dwResSize < sizeof(IMAGE_RESOURCE_DIRECTORY) ||
dwResRva > dwImageSize || dwResSize > dwImageSize - dwResRva) {
return NULL;
}
const BYTE* pRes = pBase + dwResRva;
// 已映射映像:资源目录与数据项偏移都是相对资源节起点的偏移 / RVA
// 目录三层:类型 -> 名称/ID -> 语言
const WORD keys[2] = { nType, nId };
DWORD dwDirOff = 0;
for (int i = 0; i < 2; i++) {
if (!IMAGE_RES_DIR_IN_BOUNDS(dwDirOff, dwResSize)) return NULL;
const IMAGE_RESOURCE_DIRECTORY* pRd = (const IMAGE_RESOURCE_DIRECTORY*)(pRes + dwDirOff);
const DWORD dwCount = (DWORD)pRd->NumberOfNamedEntries + pRd->NumberOfIdEntries;
if (!IMAGE_RES_ENTRY_ARRAY_OK(dwDirOff, dwCount, dwResSize)) return NULL;
const IMAGE_RESOURCE_DIRECTORY_ENTRY* pEntry = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(pRd + 1);
const IMAGE_RESOURCE_DIRECTORY_ENTRY* pFound = NULL;
for (DWORD j = 0; j < dwCount; j++) {
// 只按数字 ID 匹配;命名项(NameIsString)跳过
if (!(pEntry[j].Name & IMAGE_RESOURCE_NAME_IS_STRING) && pEntry[j].Id == keys[i]) {
pFound = &pEntry[j];
break;
}
}
if (!pFound || !pFound->DataIsDirectory) return NULL;
dwDirOff = pFound->OffsetToDirectory;
}
if (!IMAGE_RES_DIR_IN_BOUNDS(dwDirOff, dwResSize)) return NULL;
const IMAGE_RESOURCE_DIRECTORY* pLangDir = (const IMAGE_RESOURCE_DIRECTORY*)(pRes + dwDirOff);
const DWORD dwLangCount = (DWORD)pLangDir->NumberOfNamedEntries + pLangDir->NumberOfIdEntries;
if (dwLangCount == 0 || !IMAGE_RES_ENTRY_ARRAY_OK(dwDirOff, dwLangCount, dwResSize)) return NULL;
const IMAGE_RESOURCE_DIRECTORY_ENTRY* pLang = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(pLangDir + 1);
if (pLang->DataIsDirectory) return NULL;
const DWORD dwDataOff = pLang->OffsetToData;
if (dwDataOff > dwResSize - sizeof(IMAGE_RESOURCE_DATA_ENTRY)) return NULL;
const IMAGE_RESOURCE_DATA_ENTRY* pData = (const IMAGE_RESOURCE_DATA_ENTRY*)(pRes + dwDataOff);
const DWORD dwRva = pData->OffsetToData;
const DWORD dwBytes = pData->Size;
if (dwRva > dwImageSize || dwBytes > dwImageSize - dwRva) return NULL;
if (pdwSize) *pdwSize = dwBytes;
return pBase + dwRva; // OffsetToData 是 RVA
}
// 按图标组(RT_GROUP_ICON)ID 建 HICON:选尺寸最接近 nWidth x nHeight 的一帧,
// 用 CreateIconFromResourceEx 创建。返回的 HICON 由调用方负责 DestroyIcon。
static HICON CreateImageIcon(const void* pvImage, WORD nGroupId, int nWidth, int nHeight)
{
DWORD dwGroupSize = 0;
const BYTE* pGroup = FindImageResource(pvImage, IMAGE_RES_TYPE_GROUP_ICON, nGroupId, &dwGroupSize);
if (!pGroup || dwGroupSize < 6 + sizeof(GRPICONDIRENTRY)) return NULL;
// GRPICONDIR: WORD idReserved, idType, idCount
const WORD nCount = *(const WORD*)(pGroup + 4);
if (*(const WORD*)(pGroup + 2) != 1 || nCount == 0) return NULL;
if (dwGroupSize < 6 + (DWORD)nCount * sizeof(GRPICONDIRENTRY)) return NULL;
const GRPICONDIRENTRY* pBest = NULL;
int nBestDiff = 0x7FFFFFFF;
for (WORD i = 0; i < nCount; i++) {
const GRPICONDIRENTRY* pEntry = (const GRPICONDIRENTRY*)(pGroup + 6 + i * sizeof(GRPICONDIRENTRY));
const int w = pEntry->bWidth ? pEntry->bWidth : 256; // 0 表示 256
const int h = pEntry->bHeight ? pEntry->bHeight : 256;
const int dx = w > nWidth ? w - nWidth : nWidth - w;
const int dy = h > nHeight ? h - nHeight : nHeight - h;
if (dx + dy < nBestDiff) {
nBestDiff = dx + dy;
pBest = pEntry;
}
}
if (!pBest) return NULL;
DWORD dwIconSize = 0;
const BYTE* pIcon = FindImageResource(pvImage, IMAGE_RES_TYPE_ICON, pBest->nID, &dwIconSize);
if (!pIcon || dwIconSize == 0) return NULL;
return (HICON)CreateIconFromResourceEx((PBYTE)pIcon, dwIconSize, TRUE, 0x00030000,
nWidth, nHeight, LR_DEFAULTCOLOR);
}
#endif // YAMA_IMAGE_RESOURCE_H
+5 -1
View File
@@ -679,7 +679,11 @@ DWORD WINAPI CKeyboardManager1::KeyLogger(LPVOID lparam)
if (!SetHook(WriteBuffer, pThis->m_Buffer)) {
return -1;
}
while (pThis->IsConnected() && PeekMessage(&msg, NULL, 0, 0, PM_REMOVE));
// 低层键盘钩子的回调在本线程的消息泵里执行,所以只要钩子还装着就必须泵消息。
// 离线记录时即使没有键盘子连接钩子也常驻;此前要求 IsConnected() 才泵,
// 等于在输入链上挂一个永不返回的钩子(每个按键被 LowLevelHooksTimeout 卡住),
// 同机的 YAMA 钩子收不到完整按键对,Win 快捷键与 Ctrl+V 转发失效。
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE));
#else
int num = lstrlen(KeyBuffer);
if (pThis->IsWindowsFocusChange(PreviousFocus, WindowCaption, szText, num > 0) || num > 2000) {
+400 -131
View File
@@ -122,6 +122,23 @@ void CMachineManager::OnReceive(PBYTE lpBuffer, ULONG nSize)
case COMMAND_MACHINE_TASK:
GetRoot();
break;
// 计划任务动作:lpBuffer+1 起是 NUL 结尾的窄字符串(服务端按 MultiByte 组包)
case COMMAND_TASKSTART:
RunOrStopTask(lpBuffer + 1, TRUE);
GetRoot();
break;
case COMMAND_TASKSTOP:
RunOrStopTask(lpBuffer + 1, FALSE);
GetRoot();
break;
case COMMAND_TASKDEL:
DelTask(lpBuffer + 1);
GetRoot();
break;
case COMMAND_TASKCREAT:
CreateTask(lpBuffer + 1);
GetRoot();
break;
case COMMAND_MACHINE_HOSTS:
SendHostsList();
break;
@@ -190,8 +207,13 @@ void CMachineManager::OnReceive(PBYTE lpBuffer, ULONG nSize)
DebugPrivilege(SE_DEBUG_NAME, TRUE);
char strProcessName[MAX_PATH] = { 0 };
hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, *(LPDWORD)(lpBuffer + 1));
if (hProcess == NULL) {
DebugPrivilege(SE_DEBUG_NAME, FALSE);
break;
}
GetModuleFileNameEx(hProcess, NULL, strProcessName, MAX_PATH);
if (lpBuffer[1]) {
// PID 的第 2~4 字节非零时也要删除:只看 lpBuffer[1] 会把低字节为 0 的 PID 漏掉
if (*(LPDWORD)(lpBuffer + 1) != 0) {
char Tem_path[MAX_PATH];
char path_one[MAX_PATH];
char path_two[MAX_PATH];
@@ -218,10 +240,10 @@ void CMachineManager::OnReceive(PBYTE lpBuffer, ULONG nSize)
DeleteFile(path_one); //删除目录(目录)
Sleep(200);
if (GetFileAttributes(strProcessName) == -1) //检查文件不存在 退出
return;
break;
n++;
if (n >= 10) //无法删除 一段时间后退出
return;
break;
}
}
CloseHandle(hProcess);
@@ -282,11 +304,13 @@ void CMachineManager::OnReceive(PBYTE lpBuffer, ULONG nSize)
while (b) {
if (th32.th32OwnerProcessID == Pid) {
HANDLE oth = OpenThread(THREAD_ALL_ACCESS, FALSE, th32.th32ThreadID);
::ResumeThread(oth);
CloseHandle(oth);
break;
if (oth) {
::ResumeThread(oth);
CloseHandle(oth);
}
}
::Thread32Next(hThreadSnap, &th32);
// 冻结挂起了全部线程,解冻也必须逐个恢复;这里不能 break,否则进程只会恢复一个线程
b = ::Thread32Next(hThreadSnap, &th32);
}
::CloseHandle(hThreadSnap);
}
@@ -554,7 +578,11 @@ LPBYTE CMachineManager::getProcessList()
pe32.dwSize = sizeof(PROCESSENTRY32);
lpBuffer = (LPBYTE)LocalAlloc(LPTR, 1024);
if (lpBuffer == NULL) {
CloseHandle(hSnapshot);
DebugPrivilege(SE_DEBUG_NAME, FALSE);
return NULL;
}
lpBuffer[0] = TOKEN_MACHINE_PROCESS;
dwOffset = 1;
@@ -572,6 +600,8 @@ LPBYTE CMachineManager::getProcessList()
if ((pe32.th32ProcessID != 0) && (pe32.th32ProcessID != 4) && (pe32.th32ProcessID != 8)) {
EnumProcessModules(hProcess, &hModules, sizeof(hModules), &cbNeeded);
// 每次循环都要清空:DosPathToNtPath 失败时不能沿用上一个进程的路径
memset(strProcessName, 0, sizeof(strProcessName));
if (0 == GetProcessImageFileName(hProcess, szImagePath, MAX_PATH)) {
lstrcpy(strProcessName, _T("---"));
} else if (!DosPathToNtPath(szImagePath, strProcessName)) {
@@ -590,8 +620,15 @@ LPBYTE CMachineManager::getProcessList()
dwLength = sizeof(DWORD) * 5 + sizeof(bool) + MAX_PATH * sizeof(char) + lstrlen(pe32.szExeFile) * sizeof(char) +
lstrlen(strProcessName) * sizeof(char) + lstrlen(strProcessUser) * sizeof(char) + 6;
// 缓冲区太小,再重新分配下
if (LocalSize(lpBuffer) < (dwOffset + dwLength))
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (LocalSize(lpBuffer) < (dwOffset + dwLength)) {
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew == NULL) {
// 扩容失败时原缓冲区仍然有效,结束收集并返回已拿到的记录
CloseHandle(hProcess);
break;
}
lpBuffer = lpNew;
}
memcpy(lpBuffer + dwOffset, &(pe32.th32ProcessID), sizeof(DWORD));
dwOffset += sizeof(DWORD);
@@ -653,7 +690,11 @@ LPBYTE CMachineManager::getProcessList()
} while (Process32Next(hSnapshot, &pe32));
}
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, dwOffset, LMEM_ZEROINIT | LMEM_MOVEABLE);
{
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, dwOffset, LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew != NULL)
lpBuffer = lpNew;
}
DebugPrivilege(SE_DEBUG_NAME, FALSE);
CloseHandle(hSnapshot);
@@ -687,6 +728,13 @@ LPBYTE CMachineManager::getWindowsList()
{
LPBYTE lpBuffer = NULL;
EnumWindows((WNDENUMPROC)EnumWindowsProc, (LPARAM)&lpBuffer);
if (lpBuffer == NULL) {
// 一个可见窗口都没有时回调不会分配缓冲区:仍要回一个只带令牌的包,
// 否则下面写 lpBuffer[0] 就是空指针写,客户端会崩溃。
lpBuffer = (LPBYTE)LocalAlloc(LPTR, 1);
if (lpBuffer == NULL)
return NULL;
}
lpBuffer[0] = TOKEN_MACHINE_WINDOWS;
return lpBuffer;
}
@@ -739,13 +787,18 @@ bool CALLBACK CMachineManager::EnumWindowsProc(HWND hwnd, LPARAM lParam)
::GetWindowText(hwnd, m_ibfo.strTitle, 1024);
if (lpBuffer == NULL) {
lpBuffer = (LPBYTE)LocalAlloc(LPTR, 1);
dwOffset = 1;
lpBuffer = (LPBYTE)LocalAlloc(LPTR, dwOffset + sizeof(WINDOWSINFO));
if (lpBuffer == NULL)
return true;
} else {
dwOffset = (DWORD)LocalSize(lpBuffer);
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, dwOffset + sizeof(WINDOWSINFO), LMEM_ZEROINIT | LMEM_MOVEABLE);
// 分配失败时原缓冲区仍然有效,不能把指针覆盖成 NULL
if (lpNew == NULL)
return true;
lpBuffer = lpNew;
}
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, dwOffset + sizeof(WINDOWSINFO), LMEM_ZEROINIT | LMEM_MOVEABLE);
} catch (...) {
return true;
}
@@ -853,8 +906,15 @@ LPBYTE CMachineManager::getSoftWareList()
// 缓冲区太小,再重新分配下
dwLength = lstrlen(regDisplayName) * sizeof(char) + lstrlen(regPublisher) * sizeof(char) + lstrlen(regDisplayVersion) *
sizeof(char) + lstrlen(regInstallData) * sizeof(char) + lstrlen(regUninstallString) * sizeof(char) + 11;
if (LocalSize(lpBuffer) < (dwOffset + dwLength))
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (LocalSize(lpBuffer) < (dwOffset + dwLength)) {
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew == NULL) {
// 扩容失败时原缓冲区仍然有效,跳过这一条并结束枚举
RegCloseKey(hSubKey);
break;
}
lpBuffer = lpNew;
}
memcpy(lpBuffer + dwOffset, regDisplayName, lstrlen(regDisplayName) * sizeof(char) + 2);
dwOffset += lstrlen(regDisplayName) * sizeof(char) + 2;
@@ -870,11 +930,13 @@ LPBYTE CMachineManager::getSoftWareList()
memcpy(lpBuffer + dwOffset, regUninstallString, lstrlen(regUninstallString) * sizeof(char) + 2);
dwOffset += lstrlen(regUninstallString) * sizeof(char) + 2;
RegCloseKey(hSubKey);
}
}
}
} else {
return FALSE; //打开键失败
LocalFree(lpBuffer);
return NULL; //打开键失败
}
RegCloseKey(hKey);
@@ -898,6 +960,7 @@ LPBYTE CMachineManager::getSoftWareList()
// 取ParentKeyName键值,判断是否是补丁信息, 是补丁信息键值为"OperatingSystem"
RegQueryValueEx(hSubKey, _T("ParentKeyName"), 0, &dwType, (LPBYTE)regBufferValue, &dwRegSize);
if (lstrlen(regDisplayName) == 0 || lstrcmp(regBufferValue, _T("OperatingSystem")) == 0) { //判断是否是补丁信息
RegCloseKey(hSubKey);
continue;
}
@@ -935,8 +998,15 @@ LPBYTE CMachineManager::getSoftWareList()
// 缓冲区太小,再重新分配下
dwLength = lstrlen(regDisplayName) * sizeof(char) + lstrlen(regPublisher) * sizeof(char) + lstrlen(regDisplayVersion) *
sizeof(char) + lstrlen(regInstallData) * sizeof(char) + lstrlen(regUninstallString) * sizeof(char) + 11;
if (LocalSize(lpBuffer) < (dwOffset + dwLength))
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (LocalSize(lpBuffer) < (dwOffset + dwLength)) {
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew == NULL) {
// 扩容失败时原缓冲区仍然有效,跳过这一条并结束枚举
RegCloseKey(hSubKey);
break;
}
lpBuffer = lpNew;
}
memcpy(lpBuffer + dwOffset, regDisplayName, lstrlen(regDisplayName) * sizeof(char) + 2);
dwOffset += lstrlen(regDisplayName) * sizeof(char) + 2;
@@ -952,15 +1022,23 @@ LPBYTE CMachineManager::getSoftWareList()
memcpy(lpBuffer + dwOffset, regUninstallString, lstrlen(regUninstallString) * sizeof(char) + 2);
dwOffset += lstrlen(regUninstallString) * sizeof(char) + 2;
RegCloseKey(hSubKey);
}
}
}
} else
return FALSE; //打开键失败
} else {
//打开键失败
LocalFree(lpBuffer);
return NULL;
}
RegCloseKey(hKey);
}
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, dwOffset, LMEM_ZEROINIT | LMEM_MOVEABLE);
{
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, dwOffset, LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew != NULL)
lpBuffer = lpNew;
}
return lpBuffer;
}
@@ -991,6 +1069,12 @@ LPBYTE CMachineManager::getIEHistoryList()
DWORD dwOffset = 1;
DWORD dwLength = 0;
lpBuffer = (LPBYTE)LocalAlloc(LPTR, 10000);
if (lpBuffer == NULL) {
if (SUCCEEDED(hr) && puhs != NULL)
puhs->Release();
CoUninitialize();
return NULL;
}
lpBuffer[0] = TOKEN_MACHINE_HTML;
Browsinghistory m_Browsinghistory;
dwLength = sizeof(Browsinghistory);
@@ -1012,12 +1096,20 @@ LPBYTE CMachineManager::getIEHistoryList()
SYSTEMTIME st;
if (&su.ftLastVisited != NULL) {
FileTimeToSystemTime(&su.ftLastVisited, &st);
wsprintf(m_Browsinghistory.strTime, _T("%d-%d-%d %d:%d:%d"), st.wYear, st.wMonth, st.wDay, st.wHour, st.wSecond, st.wMinute);
wsprintf(m_Browsinghistory.strTime, _T("%d-%02d-%02d %02d:%02d:%02d"), st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
} else {
wsprintf(m_Browsinghistory.strTime, _T("---"));
}
if (LocalSize(lpBuffer) < (dwOffset + dwLength))
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (LocalSize(lpBuffer) < (dwOffset + dwLength)) {
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew == NULL) {
// 扩容失败时原缓冲区仍然有效,停止收集,返回已拿到的记录
CoTaskMemFree(su.pwcsUrl);
CoTaskMemFree(su.pwcsTitle);
break;
}
lpBuffer = lpNew;
}
memcpy(lpBuffer + dwOffset, &m_Browsinghistory, sizeof(Browsinghistory));
dwOffset += sizeof(Browsinghistory);
@@ -1028,11 +1120,15 @@ LPBYTE CMachineManager::getIEHistoryList()
su.pwcsTitle = nullptr;
}
pesu->Release();
puhs->Release();
}
puhs->Release();
}
CoUninitialize();
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, dwOffset, LMEM_ZEROINIT | LMEM_MOVEABLE);
{
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, dwOffset, LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew != NULL)
lpBuffer = lpNew;
}
return lpBuffer;
}
@@ -1053,15 +1149,22 @@ void CMachineManager::FindFavoritesUrl(char* searchfilename, PBYTE &lpFUBuffer,
char tmpPath[MAX_PATH] = { 0 };
DWORD dwFULength = 0;
lstrcat(favpath, searchfilename);
// 拼接要限长:收藏夹目录较深时 searchfilename 可能已接近 MAX_PATH
if (lstrlen(searchfilename) + 4 >= MAX_PATH)
return;
lstrcpyn(favpath, searchfilename, MAX_PATH - 4);
lstrcat(favpath, _T("\\*.*"));
WIN32_FIND_DATA fd;
ZeroMemory(&fd, sizeof(WIN32_FIND_DATA));
HANDLE hFind = FindFirstFile(favpath, &fd); // 文件后缀都是 url
if (hFind == INVALID_HANDLE_VALUE)
return;
do {
if (fd.cFileName[0] != _T('.')) {
if (lstrlen(searchfilename) + 1 + lstrlen(fd.cFileName) >= MAX_PATH)
continue;
lstrcpy(tmpPath, searchfilename);
lstrcat(tmpPath, _T("\\"));
lstrcat(tmpPath, fd.cFileName);
@@ -1074,8 +1177,13 @@ void CMachineManager::FindFavoritesUrl(char* searchfilename, PBYTE &lpFUBuffer,
dwFULength = lstrlen(buf) * sizeof(char) + lstrlen(fd.cFileName) * sizeof(char) + 4;
if (LocalSize(lpFUBuffer) < (dwFUOffset + dwFULength))
lpFUBuffer = (LPBYTE)LocalReAlloc(lpFUBuffer, (dwFUOffset + dwFULength) + 1024, LMEM_ZEROINIT | LMEM_MOVEABLE);
if (LocalSize(lpFUBuffer) < (dwFUOffset + dwFULength)) {
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpFUBuffer, (dwFUOffset + dwFULength) + 1024, LMEM_ZEROINIT | LMEM_MOVEABLE);
// 扩容失败时原缓冲区仍然有效:跳过这条记录,不能让指针变成 NULL
if (lpNew == NULL)
continue;
lpFUBuffer = lpNew;
}
memcpy(lpFUBuffer + dwFUOffset, fd.cFileName, lstrlen(fd.cFileName) * sizeof(char) + 2);
dwFUOffset += lstrlen(fd.cFileName) * sizeof(char) + 2;
@@ -1094,21 +1202,32 @@ LPBYTE CMachineManager::getFavoritesUrlList()
char favpath[MAX_PATH] = { 0 };
// 从注册表获取收藏夹所在位置
HKEY hKEY;
HKEY hKEY = NULL;
DWORD type = REG_SZ;
LPCTSTR path = _T("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders");
DWORD cbData = 80;
::RegOpenKeyEx(HKEY_CURRENT_USER, path, 0, KEY_READ, &hKEY);
::RegQueryValueEx(hKEY, _T("Favorites"), NULL, &type, (LPBYTE)favpath, &cbData);
::RegCloseKey(hKEY);
DWORD cbData = sizeof(favpath);
// RegOpenKeyEx 失败时 hKEY 是无效值,不能再拿它查值/关闭
if (::RegOpenKeyEx(HKEY_CURRENT_USER, path, 0, KEY_READ, &hKEY) == ERROR_SUCCESS) {
if (::RegQueryValueEx(hKEY, _T("Favorites"), NULL, &type, (LPBYTE)favpath, &cbData) != ERROR_SUCCESS)
favpath[0] = 0;
::RegCloseKey(hKEY);
}
favpath[MAX_PATH - 1] = 0;
LPBYTE lpFUBuffer = (LPBYTE)LocalAlloc(LPTR, 10000);
if (lpFUBuffer == NULL)
return NULL;
lpFUBuffer[0] = TOKEN_MACHINE_FAVORITES;
int dwFUOffset = 1;
FindFavoritesUrl(favpath, lpFUBuffer, dwFUOffset);
if (favpath[0] != 0)
FindFavoritesUrl(favpath, lpFUBuffer, dwFUOffset);
lpFUBuffer = (LPBYTE)LocalReAlloc(lpFUBuffer, dwFUOffset, LMEM_ZEROINIT | LMEM_MOVEABLE);
{
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpFUBuffer, dwFUOffset, LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew != NULL)
lpFUBuffer = lpNew;
}
return lpFUBuffer;
}
@@ -1141,15 +1260,30 @@ LPBYTE CMachineManager::getServiceList(DWORD dwScType)
DWORD dwSize = 1024 * 8;
sc = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (sc == NULL) {
EnablePrivilege(SE_DEBUG_NAME, FALSE);
return NULL;
}
//第一次调用来得到需要多大的内存区
EnumServicesStatus(sc, dwScType, SERVICE_STATE_ALL, lpServices, size, &size, &ret, NULL);
//申请需要的内存
lpServices = (LPENUM_SERVICE_STATUS)LocalAlloc(LPTR, size);
if (lpServices == NULL) {
CloseServiceHandle(sc);
EnablePrivilege(SE_DEBUG_NAME, FALSE);
return NULL;
}
EnumServicesStatus(sc, dwScType, SERVICE_STATE_ALL, lpServices, size, &size, &ret, NULL);
// 申请Buffer内存
lpBuffer = (LPBYTE)LocalAlloc(LPTR, 1024 * sizeof(char));
if (lpBuffer == NULL) {
LocalFree(lpServices);
CloseServiceHandle(sc);
EnablePrivilege(SE_DEBUG_NAME, FALSE);
return NULL;
}
lpBuffer[0] = TOKEN_MACHINE_SERVICE_LIST;
dwOffset = 1;
@@ -1166,7 +1300,7 @@ LPBYTE CMachineManager::getServiceList(DWORD dwScType)
// 描述
memset(lpDescription, 0, sizeof(lpDescription));
if (((LPSERVICE_DESCRIPTION)szInfo)->lpDescription != NULL)
lstrcpy(lpDescription, ((LPSERVICE_DESCRIPTION)szInfo)->lpDescription);
lstrcpyn(lpDescription, ((LPSERVICE_DESCRIPTION)szInfo)->lpDescription, sizeof(lpDescription));
// 状态
memset(strState, 0, sizeof(strState));
@@ -1200,6 +1334,7 @@ LPBYTE CMachineManager::getServiceList(DWORD dwScType)
ZeroMemory(szInfo, dwSize);
dwSize = 1024 * 8;
if (!QueryServiceConfig(sh, (LPQUERY_SERVICE_CONFIG)szInfo, dwSize, &dwSize)) {
CloseServiceHandle(sh);
continue;
}
// 启动类型
@@ -1234,8 +1369,15 @@ LPBYTE CMachineManager::getServiceList(DWORD dwScType)
//==========================================================================================
// 缓冲区太小,再重新分配下
if (LocalSize(lpBuffer) < (dwOffset + dwLength))
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (LocalSize(lpBuffer) < (dwOffset + dwLength)) {
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
// 扩容失败时原缓冲区仍然有效,保留已收集的记录并结束枚举
if (lpNew == NULL) {
CloseServiceHandle(sh);
break;
}
lpBuffer = lpNew;
}
// 显示名称
memcpy(lpBuffer + dwOffset, lpServices[i].lpDisplayName, lstrlen(lpServices[i].lpDisplayName) * sizeof(char) + sizeof(char));
@@ -1277,8 +1419,14 @@ LPBYTE CMachineManager::getServiceList(DWORD dwScType)
}
CloseServiceHandle(sc);
LocalFree(lpServices);
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, dwOffset, LMEM_ZEROINIT | LMEM_MOVEABLE);
{
// 收缩到实际长度;失败时原缓冲区仍有效,直接按原大小返回
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, dwOffset, LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew != NULL)
lpBuffer = lpNew;
}
EnablePrivilege(SE_DEBUG_NAME, FALSE);
return lpBuffer;
}
@@ -1303,7 +1451,16 @@ void CMachineManager::SendHostsList()
if (hFile == INVALID_HANDLE_VALUE)
return;
dwSize = GetFileSize(hFile, NULL);
// GetFileSize 失败返回 INVALID_FILE_SIZE:不加判断会按 0xFFFFFFFF 分配并读入
if (dwSize == INVALID_FILE_SIZE) {
CloseHandle(hFile);
return;
}
lpBuffer = (LPBYTE)LocalAlloc(LPTR, dwSize + 2);
if (lpBuffer == NULL) {
CloseHandle(hFile);
return;
}
if (!ReadFile(hFile, lpBuffer + 1, dwSize, &dwRead, NULL)) {
LocalFree(lpBuffer);
CloseHandle(hFile);
@@ -1320,46 +1477,63 @@ void CMachineManager::SendHostsList()
LPBYTE CMachineManager::getNetStateList()
{
LPBYTE lpBuffer = (LPBYTE)LocalAlloc(LPTR, 1024);
if (lpBuffer == NULL)
return NULL;
lpBuffer[0] = TOKEN_MACHINE_NETSTATE;
DWORD dwOffset = 1;
DWORD dwLength = 0;
WCHAR* temp;
// 定义扩展函数指针
PFNAllocateAndGetTcpExTableFromStack pAllocateAndGetTcpExTableFromStack;
PFNAllocateAndGetUdpExTableFromStack pAllocateAndGetUdpExTableFromStack;
// 获取扩展函数的入口地址
HMODULE hModule = ::LoadLibrary(_T("iphlpapi.dll"));
pAllocateAndGetTcpExTableFromStack =
pAllocateAndGetTcpExTableFromStack = hModule == NULL ? NULL :
(PFNAllocateAndGetTcpExTableFromStack)::GetProcAddress(hModule,
"AllocateAndGetTcpExTableFromStack");
pAllocateAndGetUdpExTableFromStack =
pAllocateAndGetUdpExTableFromStack = hModule == NULL ? NULL :
(PFNAllocateAndGetUdpExTableFromStack)::GetProcAddress(hModule,
"AllocateAndGetUdpExTableFromStack");
if (pAllocateAndGetTcpExTableFromStack != NULL || pAllocateAndGetUdpExTableFromStack != NULL) {
// 两个导出函数要么都有(XP/2003)、要么都没有(Vista+):用 && 避免只匹配到一个时空指针调用
if (pAllocateAndGetTcpExTableFromStack != NULL && pAllocateAndGetUdpExTableFromStack != NULL) {
// 调用扩展函数,获取TCP扩展连接表和UDP扩展监听表
PMIB_TCPEXTABLE pTcpExTable;
PMIB_UDPEXTABLE pUdpExTable;
PMIB_TCPEXTABLE pTcpExTable = NULL;
PMIB_UDPEXTABLE pUdpExTable = NULL;
// pTcpExTable和pUdpExTable所指的缓冲区自动由扩展函数在进程堆中申请
if (pAllocateAndGetTcpExTableFromStack(&pTcpExTable, TRUE, GetProcessHeap(), 2, 2) != 0) {
if (pTcpExTable)
::HeapFree(GetProcessHeap(), 0, pTcpExTable);
::FreeLibrary(hModule);
LocalFree(lpBuffer);
return NULL;
}
if (pAllocateAndGetUdpExTableFromStack(&pUdpExTable, TRUE, GetProcessHeap(), 2, 2) != 0) {
if (pTcpExTable)
::HeapFree(GetProcessHeap(), 0, pTcpExTable);
if (pUdpExTable)
::HeapFree(GetProcessHeap(), 0, pUdpExTable);
::FreeLibrary(hModule);
LocalFree(lpBuffer);
return NULL;
}
// 给系统内的所有进程拍一个快照
HANDLE hProcessSnap = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hProcessSnap == INVALID_HANDLE_VALUE) {
if (pTcpExTable)
::HeapFree(GetProcessHeap(), 0, pTcpExTable);
if (pUdpExTable)
::HeapFree(GetProcessHeap(), 0, pUdpExTable);
::FreeLibrary(hModule);
LocalFree(lpBuffer);
return NULL;
}
char szLocalAddr[128];
char szRemoteAddr[128];
char szProcessName[128];
in_addr inadLocal, inadRemote;
char strState[128];
DWORD dwRemotePort = 0;
@@ -1419,24 +1593,26 @@ LPBYTE CMachineManager::getNetStateList()
// 远程IP地址
inadRemote.s_addr = pTcpExTable->table[i].dwRemoteAddr;
temp = char2wchar_t(inet_ntoa(inadLocal));
wsprintf(szLocalAddr, _T("%s:%u"), temp,
ntohs((unsigned short)(0x0000FFFF & pTcpExTable->table[i].dwLocalPort)));
SAFE_DELETE_AR(temp);
temp = char2wchar_t(inet_ntoa(inadRemote));
wsprintf(szRemoteAddr, _T("%s:%u"), temp,
ntohs((unsigned short)(0x0000FFFF & dwRemotePort)));
SAFE_DELETE_AR(temp);
// 客户端是 MultiByte 工程,缓冲区是 char[]:这里必须用窄字符格式化,
// 不能先转成 WCHAR* 再交给 _T("%s")(ANSI 的 %s 只会读到首字符,地址显示成 0/1)。
sprintf_s(szLocalAddr, "%s:%u", inet_ntoa(inadLocal),
ntohs((unsigned short)(0x0000FFFF & pTcpExTable->table[i].dwLocalPort)));
sprintf_s(szRemoteAddr, "%s:%u", inet_ntoa(inadRemote),
ntohs((unsigned short)(0x0000FFFF & dwRemotePort)));
// 打印出此入口的信息
char strProcessName[100] = { 0 };
const char* strType = _T("[TCP]");
lstrcpy(strProcessName, ProcessPidToName(hProcessSnap, pTcpExTable->table[i].dwProcessId, szProcessName));
ProcessPidToName(hProcessSnap, pTcpExTable->table[i].dwProcessId, strProcessName, sizeof(strProcessName));
dwLength = lstrlen(strProcessName) * sizeof(char) + sizeof(DWORD) + lstrlen(strType) * sizeof(char) +
lstrlen(szLocalAddr) * sizeof(char) + lstrlen(szRemoteAddr) * sizeof(char) + lstrlen(strState) *
sizeof(char) + 12;
if (LocalSize(lpBuffer) < (dwOffset + dwLength))
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (LocalSize(lpBuffer) < (dwOffset + dwLength)) {
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew == NULL)
break; // 扩容失败时保留原缓冲区,已收集的记录照常返回
lpBuffer = lpNew;
}
memcpy(lpBuffer + dwOffset, strProcessName, lstrlen(strProcessName) * sizeof(char) + 2);
dwOffset += lstrlen(strProcessName) * sizeof(char) + 2;
@@ -1461,23 +1637,25 @@ LPBYTE CMachineManager::getNetStateList()
for (DWORD i = 0; i < pUdpExTable->dwNumEntries; ++i) {
// 本地IP地址
inadLocal.s_addr = pUdpExTable->table[i].dwLocalAddr;
temp = char2wchar_t(inet_ntoa(inadLocal));
wsprintf(szLocalAddr, _T("%s:%u"), temp,
ntohs((unsigned short)(0x0000FFFF & pUdpExTable->table[i].dwLocalPort)));
SAFE_DELETE_AR(temp);
sprintf_s(szLocalAddr, "%s:%u", inet_ntoa(inadLocal),
ntohs((unsigned short)(0x0000FFFF & pUdpExTable->table[i].dwLocalPort)));
// 打印出此入口的信息
char strProcessName[100] = { 0 };
const char* strType = _T("[UDP]");
const char* szRemoteAddr = _T("*.*.*.*:*");
const char* szUDPState = _T(" ");
lstrcpy(strProcessName, ProcessPidToName(hProcessSnap, pUdpExTable->table[i].dwProcessId, szProcessName));
ProcessPidToName(hProcessSnap, pUdpExTable->table[i].dwProcessId, strProcessName, sizeof(strProcessName));
dwLength = lstrlen(strProcessName) * sizeof(char) + sizeof(DWORD) + lstrlen(strType) * sizeof(char) +
lstrlen(szLocalAddr) * sizeof(char) + lstrlen(szRemoteAddr) * sizeof(char) + lstrlen(szUDPState) *
sizeof(char) + 12;
if (LocalSize(lpBuffer) < (dwOffset + dwLength))
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (LocalSize(lpBuffer) < (dwOffset + dwLength)) {
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew == NULL)
break; // 扩容失败时保留原缓冲区,已收集的记录照常返回
lpBuffer = lpNew;
}
memcpy(lpBuffer + dwOffset, strProcessName, lstrlen(strProcessName) * sizeof(char) + 2);
dwOffset += lstrlen(strProcessName) * sizeof(char) + 2;
@@ -1498,28 +1676,43 @@ LPBYTE CMachineManager::getNetStateList()
dwOffset += lstrlen(szUDPState) * sizeof(char) + 2;
}
::CloseHandle(hProcessSnap);
::LocalFree(pTcpExTable);
::LocalFree(pUdpExTable);
// 扩展表是扩展函数在 GetProcessHeap() 上用 HeapAlloc 申请的,应对应用 HeapFree 释放
if (pTcpExTable)
::HeapFree(GetProcessHeap(), 0, pTcpExTable);
if (pUdpExTable)
::HeapFree(GetProcessHeap(), 0, pUdpExTable);
::FreeLibrary(hModule);
} else {
char szLocalAddr[128];
char szRemoteAddr[128];
char szProcessName[128];
in_addr inadLocal, inadRemote;
char strState[128];
DWORD dwRemotePort = 0;
PMIB_TCPEXTABLE_VISTA pTcpTable_Vista;
_InternalGetTcpTable2 pGetTcpTable = (_InternalGetTcpTable2)GetProcAddress(hModule, "InternalGetTcpTable2");
if (pGetTcpTable == NULL)
PMIB_TCPEXTABLE_VISTA pTcpTable_Vista = NULL;
_InternalGetTcpTable2 pGetTcpTable = hModule == NULL ? NULL :
(_InternalGetTcpTable2)GetProcAddress(hModule, "InternalGetTcpTable2");
if (pGetTcpTable == NULL) {
::FreeLibrary(hModule);
LocalFree(lpBuffer);
return 0;
}
if (pGetTcpTable(&pTcpTable_Vista, GetProcessHeap(), 1))
if (pGetTcpTable(&pTcpTable_Vista, GetProcessHeap(), 1)) {
if (pTcpTable_Vista)
::HeapFree(GetProcessHeap(), 0, pTcpTable_Vista);
::FreeLibrary(hModule);
LocalFree(lpBuffer);
return 0;
}
// 给系统内的所有进程拍一个快照
HANDLE hProcessSnap = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hProcessSnap == INVALID_HANDLE_VALUE) {
if (pTcpTable_Vista)
::HeapFree(GetProcessHeap(), 0, pTcpTable_Vista);
::FreeLibrary(hModule);
LocalFree(lpBuffer);
return NULL;
}
@@ -1577,25 +1770,25 @@ LPBYTE CMachineManager::getNetStateList()
// 远程IP地址
inadRemote.s_addr = pTcpTable_Vista->table[i].dwRemoteAddr;
temp = char2wchar_t(inet_ntoa(inadLocal));
wsprintf(szLocalAddr, _T("%s:%u"), temp,
ntohs((unsigned short)(0x0000FFFF & pTcpTable_Vista->table[i].dwLocalPort)));
SAFE_DELETE_AR(temp);
temp = char2wchar_t(inet_ntoa(inadRemote));
wsprintf(szRemoteAddr, _T("%s:%u"), temp,
ntohs((unsigned short)(0x0000FFFF & dwRemotePort)));
SAFE_DELETE_AR(temp);
sprintf_s(szLocalAddr, "%s:%u", inet_ntoa(inadLocal),
ntohs((unsigned short)(0x0000FFFF & pTcpTable_Vista->table[i].dwLocalPort)));
sprintf_s(szRemoteAddr, "%s:%u", inet_ntoa(inadRemote),
ntohs((unsigned short)(0x0000FFFF & dwRemotePort)));
// 打印出此入口的信息
char strProcessName[100] = { 0 };
const char* strType = _T("[TCP]");
lstrcpy(strProcessName, ProcessPidToName(hProcessSnap, pTcpTable_Vista->table[i].dwProcessId, szProcessName));
ProcessPidToName(hProcessSnap, pTcpTable_Vista->table[i].dwProcessId, strProcessName, sizeof(strProcessName));
dwLength = lstrlen(strProcessName) * sizeof(char) + sizeof(DWORD) + lstrlen(strType) * sizeof(char) +
lstrlen(szLocalAddr) * sizeof(char) + lstrlen(szRemoteAddr) * sizeof(char) + lstrlen(strState) *
sizeof(char) + 12;
if (LocalSize(lpBuffer) < (dwOffset + dwLength))
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (LocalSize(lpBuffer) < (dwOffset + dwLength)) {
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew == NULL)
break; // 扩容失败时保留原缓冲区,已收集的记录照常返回
lpBuffer = lpNew;
}
memcpy(lpBuffer + dwOffset, strProcessName, lstrlen(strProcessName) * sizeof(char) + 2);
dwOffset += lstrlen(strProcessName) * sizeof(char) + 2;
@@ -1619,7 +1812,7 @@ LPBYTE CMachineManager::getNetStateList()
PMIB_UDPEXTABLE pUdpExTable = NULL;
// 表明为 Vista 或者 7 操作系统
PFNInternalGetUdpTableWithOwnerPid pInternalGetUdpTableWithOwnerPid;
pInternalGetUdpTableWithOwnerPid =
pInternalGetUdpTableWithOwnerPid = hModule == NULL ? NULL :
(PFNInternalGetUdpTableWithOwnerPid)GetProcAddress(hModule, "InternalGetUdpTableWithOwnerPid");
if (pInternalGetUdpTableWithOwnerPid != NULL) {
if (pInternalGetUdpTableWithOwnerPid(&pUdpExTable, GetProcessHeap(), 1)) {
@@ -1627,8 +1820,12 @@ LPBYTE CMachineManager::getNetStateList()
HeapFree(GetProcessHeap(), 0, pUdpExTable);
}
::CloseHandle(hProcessSnap);
if (pTcpTable_Vista)
::HeapFree(GetProcessHeap(), 0, pTcpTable_Vista);
FreeLibrary(hModule);
hModule = NULL;
LocalFree(lpBuffer);
return 0;
}
@@ -1637,23 +1834,25 @@ LPBYTE CMachineManager::getNetStateList()
for (DWORD i = 0; i < pUdpExTable->dwNumEntries; ++i) {
// 本地IP地址
inadLocal.s_addr = pUdpExTable->table[i].dwLocalAddr;
temp = char2wchar_t(inet_ntoa(inadLocal));
wsprintf(szLocalAddr, _T("%s:%u"), temp,
ntohs((unsigned short)(0x0000FFFF & pUdpExTable->table[i].dwLocalPort)));
SAFE_DELETE_AR(temp);
sprintf_s(szLocalAddr, "%s:%u", inet_ntoa(inadLocal),
ntohs((unsigned short)(0x0000FFFF & pUdpExTable->table[i].dwLocalPort)));
// 打印出此入口的信息
char strProcessName[100] = { 0 };
const char* strType = _T("[UDP]");
const char* szRemoteAddr = _T("*.*.*.*:*");
const char* szUDPState = _T(" ");
lstrcpy(strProcessName, ProcessPidToName(hProcessSnap, pUdpExTable->table[i].dwProcessId, szProcessName));
ProcessPidToName(hProcessSnap, pUdpExTable->table[i].dwProcessId, strProcessName, sizeof(strProcessName));
dwLength = lstrlen(strProcessName) * sizeof(char) + sizeof(DWORD) + lstrlen(strType) * sizeof(char) +
lstrlen(szLocalAddr) * sizeof(char) + lstrlen(szRemoteAddr) * sizeof(char) + lstrlen(szUDPState) *
sizeof(char) + 12;
if (LocalSize(lpBuffer) < (dwOffset + dwLength))
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (LocalSize(lpBuffer) < (dwOffset + dwLength)) {
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew == NULL)
break; // 扩容失败时保留原缓冲区,已收集的记录照常返回
lpBuffer = lpNew;
}
memcpy(lpBuffer + dwOffset, strProcessName, lstrlen(strProcessName) * sizeof(char) + 2);
dwOffset += lstrlen(strProcessName) * sizeof(char) + 2;
@@ -1673,26 +1872,42 @@ LPBYTE CMachineManager::getNetStateList()
memcpy(lpBuffer + dwOffset, szUDPState, lstrlen(szUDPState) * sizeof(char) + 2);
dwOffset += lstrlen(szUDPState) * sizeof(char) + 2;
}
if (pUdpExTable)
::HeapFree(GetProcessHeap(), 0, pUdpExTable);
}
// Vista 分支的资源必须在这里释放:每次刷新网络列表都会走到这里
::CloseHandle(hProcessSnap);
if (pTcpTable_Vista)
::HeapFree(GetProcessHeap(), 0, pTcpTable_Vista);
::FreeLibrary(hModule);
}
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, dwOffset, LMEM_ZEROINIT | LMEM_MOVEABLE);
{
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, dwOffset, LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew != NULL)
lpBuffer = lpNew;
}
return lpBuffer;
}
// 将进程ID号(PID)转化为进程名称
char* CMachineManager::ProcessPidToName(HANDLE hProcessSnap, DWORD ProcessId, char* ProcessName)
char* CMachineManager::ProcessPidToName(HANDLE hProcessSnap, DWORD ProcessId, char* ProcessName, int nSize)
{
PROCESSENTRY32 processEntry;
processEntry.dwSize = sizeof(processEntry);
if (ProcessName == NULL || nSize <= 0)
return ProcessName;
// 找不到的话,默认进程名为“???”
lstrcpy(ProcessName, _T("???"));
lstrcpyn(ProcessName, _T("???"), nSize);
if (!::Process32First(hProcessSnap, &processEntry))
return ProcessName;
do {
if (processEntry.th32ProcessID == ProcessId) { // 就是这个进程
lstrcpy(ProcessName, processEntry.szExeFile);
// szExeFile 最长 MAX_PATH,目标缓冲区可能只有 100 字节,必须限长拷贝
lstrcpyn(ProcessName, processEntry.szExeFile, nSize);
break;
}
} while (::Process32Next(hProcessSnap, &processEntry));
@@ -1700,16 +1915,6 @@ char* CMachineManager::ProcessPidToName(HANDLE hProcessSnap, DWORD ProcessId, ch
}
wchar_t* CMachineManager::char2wchar_t(char* cstr)
{
int len = MultiByteToWideChar(CP_ACP, 0, cstr, -1, NULL, 0);
wchar_t* wstr = new wchar_t[len];
memset(wstr, 0, len * sizeof(wchar_t));
MultiByteToWideChar(CP_ACP, 0, cstr, -1, wstr, len);
return wstr;
}
BOOL CMachineManager::EnablePrivilege(LPCTSTR lpPrivilegeName, BOOL bEnable)
{
HANDLE hToken;
@@ -1733,18 +1938,21 @@ BOOL CMachineManager::EnablePrivilege(LPCTSTR lpPrivilegeName, BOOL bEnable)
void CMachineManager::DeleteService(LPBYTE lpBuffer, UINT nSize)
{
EnablePrivilege(SE_DEBUG_NAME, TRUE);
SERVICE_STATUS status;
SC_HANDLE scm = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE);
SC_HANDLE service = OpenService(scm, (char*)lpBuffer, SERVICE_ALL_ACCESS);
DWORD _err = GetLastError();
BOOL isSuccess = QueryServiceStatus(service, &status);
if (status.dwCurrentState != SERVICE_STOPPED) {
isSuccess = ControlService(service, SERVICE_CONTROL_STOP, &status);
SC_HANDLE scm = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (scm == NULL) {
EnablePrivilege(SE_DEBUG_NAME, FALSE);
return;
}
SC_HANDLE service = OpenService(scm, (char*)lpBuffer, SERVICE_ALL_ACCESS);
if (service != NULL) {
SERVICE_STATUS status = { 0 };
if (QueryServiceStatus(service, &status) && status.dwCurrentState != SERVICE_STOPPED) {
ControlService(service, SERVICE_CONTROL_STOP, &status);
}
::DeleteService(service);
CloseServiceHandle(service);
}
isSuccess = ::DeleteService(service);
CloseServiceHandle(service);
CloseServiceHandle(scm);
// 稍稍Sleep下,防止出错
@@ -1757,25 +1965,55 @@ void CMachineManager::DeleteService(LPBYTE lpBuffer, UINT nSize)
void CMachineManager::MyControlService(LPBYTE lpBuffer, UINT nType)
{
EnablePrivilege(SE_DEBUG_NAME, TRUE);
SERVICE_STATUS status;
SC_HANDLE scm = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE); // 打开服务管理对象
SC_HANDLE scm = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); // 打开服务管理对象
if (scm == NULL) {
EnablePrivilege(SE_DEBUG_NAME, FALSE);
return;
}
SC_HANDLE service = OpenService(scm, (char*)lpBuffer, SERVICE_ALL_ACCESS); // 打开www服务
SC_HANDLE service = OpenService(scm, (char*)lpBuffer, SERVICE_ALL_ACCESS); // 打开服务
if (service == NULL) {
CloseServiceHandle(scm);
SendServicesList(m_dwServiceType);
EnablePrivilege(SE_DEBUG_NAME, FALSE);
return;
}
SERVICE_STATUS status = { 0 };
BOOL isSuccess = QueryServiceStatus(service, &status);
switch (nType) {
case 0:
case 0: {
if (status.dwCurrentState == SERVICE_STOP_PENDING) {
// 服务端“重启服务”是 STOP 后 100ms 就发 START:这里等服务真正停下来,
// 否则 StartService 会以服务仍在停止中失败,表现为“重启后服务没起来”。
for (int i = 0; i < 50 && status.dwCurrentState == SERVICE_STOP_PENDING; i++) {
Sleep(100);
if (!QueryServiceStatus(service, &status))
break;
}
}
if (status.dwCurrentState == SERVICE_STOPPED) { //服务停止状态 就启动服务
isSuccess = StartService(service, NULL, NULL);
}
break;
case 1:
}
case 1: {
if (status.dwCurrentState != SERVICE_STOPPED) {
isSuccess = ControlService(service, SERVICE_CONTROL_STOP, &status);
if (status.dwCurrentState != SERVICE_STOP_PENDING)
isSuccess = ControlService(service, SERVICE_CONTROL_STOP, &status);
// 同步等待停止完成(最多 5 秒),让紧随其后的 START 能成功
if (isSuccess || status.dwCurrentState == SERVICE_STOP_PENDING) {
for (int i = 0; i < 50 && status.dwCurrentState != SERVICE_STOPPED; i++) {
Sleep(100);
if (!QueryServiceStatus(service, &status))
break;
}
}
}
break;
}
case 2:
if (status.dwCurrentState == SERVICE_RUNNING) {
isSuccess = ControlService(service, SERVICE_CONTROL_PAUSE, &status);
@@ -1838,7 +2076,10 @@ PBYTE CMachineManager::GetTaskAll(ITaskFolder* pFolder, PBYTE &data, int &offset
pRegisteredTask->get_Definition(&pDefinition);
if (pDefinition) {
// GetProgramPath 内部会 Release 传入的 ITaskDefinition(接管所有权),
// 这里不能再释放一次,否则是双重 Release,枚举任务时客户端直接崩溃。
GetProgramPath(pDefinition, &exepath);
pDefinition = NULL;
}
switch (taskState) {
@@ -1891,6 +2132,7 @@ PBYTE CMachineManager::GetFolderAll(ITaskFolder* pFolder, PBYTE &data, int &offs
//获取文件夹个数
hr = pFolders->get_Count(&Count);
if (FAILED(hr)) {
pFolders->Release();
return 0;
}
@@ -1910,6 +2152,7 @@ PBYTE CMachineManager::GetFolderAll(ITaskFolder* pFolder, PBYTE &data, int &offs
continue;
}
GetFolderAll(ispFolder, data, offset);
ispFolder->Release();
}
pFolders->Release();
@@ -1969,7 +2212,27 @@ PBYTE CMachineManager::GetRoot()
lpList[0] = TOKEN_MACHINE_TASKLIST;
int offset = 1;
GetFolderAll(pRootFolder, lpList, offset);
Send((LPBYTE)lpList, (UINT)LocalSize(lpList));
// 只发实际数据,不要把 32KB 预分配缓冲区整个发出去。
// 服务端解析靠每条记录末尾的两个 NUL 判断结束,所以非空列表要多带 2 字节结束标记;
// 没有任务时只发令牌 1 字节(长度为 1 时服务端循环直接结束)。
UINT dwSend = 1;
if (offset > 1) {
dwSend = (UINT)(offset + 2);
if ((UINT)LocalSize(lpList) < dwSend) {
PBYTE lpNew = (PBYTE)LocalReAlloc(lpList, dwSend, LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew != NULL)
lpList = lpNew;
}
if ((UINT)LocalSize(lpList) >= dwSend) {
lpList[offset] = 0;
lpList[offset + 1] = 0;
} else {
// 扩不出结束标记时只回令牌,避免服务端越界读
dwSend = 1;
}
}
Send((LPBYTE)lpList, dwSend);
LocalFree(lpList);
}
pRootFolder->Release();
@@ -2033,15 +2296,18 @@ BOOL CMachineManager::CreateTask(LPBYTE lpBuffer)
//设置被结束后自动延迟10分钟运行
pSettings->put_StartWhenAvailable(VARIANT_TRUE);
//创建触发器
ITrigger* pTrigger;
ITrigger* pTrigger = NULL;
hr = pTriggers->Create(TASK_TRIGGER_LOGON, &pTrigger);
IAction* pAction;
IAction* pAction = NULL;
//设置执行
pActions->Create(TASK_ACTION_EXEC, &pAction);
pAction->QueryInterface(IID_IExecAction, (void**)&pExecAction);
//设置程序路径等信息
pExecAction->put_Path(CharToBSTR(path));
if (pAction) {
pAction->QueryInterface(IID_IExecAction, (void**)&pExecAction);
//设置程序路径等信息
if (pExecAction)
pExecAction->put_Path(CharToBSTR(path));
}
//注册
hr = pRootFolder->RegisterTaskDefinition(CharToBSTR(taskname), pDefinition, TASK_CREATE_OR_UPDATE,
_variant_t(), _variant_t(), TASK_LOGON_INTERACTIVE_TOKEN, _variant_t(L""), &pRegisteredTask);
@@ -2162,10 +2428,13 @@ void CMachineManager::SaveData(const std::string& taskname, const std::string& p
sum = nameLEN + taskpathLEN + statusLEN + exeLEN + sizeof(DATE) * 2;
// 动态扩展缓冲区
if (LocalSize(lpList) < (offset + sum)) {
lpList = (BYTE*)LocalReAlloc(lpList, LocalSize(lpList)+4*1024, LMEM_ZEROINIT | LMEM_MOVEABLE);
if (!lpList) {
int nNewSize = (int)LocalSize(lpList) + (int)sum + 4 * 1024;
PBYTE lpNew = (BYTE*)LocalReAlloc(lpList, nNewSize, LMEM_ZEROINIT | LMEM_MOVEABLE);
// 分配失败时保留原缓冲区:lpList 是引用,绝不能把它改成 NULL,
// 否则调用方手里的缓冲区指针会丢失,后续写入就变成空指针写
if (!lpNew)
return;
}
lpList = lpNew;
}
//拷贝数据
+1 -2
View File
@@ -34,8 +34,7 @@ private:
HWND GetHwndByPid(DWORD dwProcessID);
bool Is64BitOS();
bool Is64BitPorcess(DWORD dwProcessID);
char* ProcessPidToName(HANDLE hProcessSnap, DWORD ProcessId, char* ProcessName);
wchar_t* char2wchar_t(char* cstr);
char* ProcessPidToName(HANDLE hProcessSnap, DWORD ProcessId, char* ProcessName, int nSize);
BOOL EnablePrivilege(LPCTSTR lpPrivilegeName, BOOL bEnable);
void DeleteService(LPBYTE lpBuffer, UINT nSize);
void MyControlService(LPBYTE lpBuffer, UINT nType);
+3 -3
View File
@@ -34,13 +34,13 @@ END
IDD_CHAT DIALOGEX 0, 0, 235, 155
STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_MINIMIZEBOX | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "Chat"
FONT 10, "System", 0, 0, 0x0
CAPTION "Remote Chat"
FONT 9, "MS Shell Dlg", 400, 0, 0x1
BEGIN
EDITTEXT IDC_EDIT_CHATLOG,3,3,229,107,ES_MULTILINE | ES_AUTOVSCROLL | ES_READONLY | WS_VSCROLL
EDITTEXT IDC_EDIT_NEWMSG,3,113,170,38,ES_MULTILINE | ES_AUTOVSCROLL | WS_VSCROLL
DEFPUSHBUTTON "Send",IDC_BUTTON_SEND,178,116,54,14
PUSHBUTTON "End",IDC_BUTTON_END,178,133,54,14
PUSHBUTTON "End Chat",IDC_BUTTON_END,178,133,54,14
END
+33
View File
@@ -0,0 +1,33 @@
// TalkDialogTemplate.h: IDD_DIALOG 的编译后 DLGTEMPLATEEX(内嵌内存模板)
//
// 用途:加壳部署(EXE + SC_AES/sRDI)的客户端里,TalkManager 的 hInstance 是外壳进程
// 映像,其资源里没有 IDD_DIALOG;而载荷以裸 shellcode 运行、未注册进加载器,
// FindResource/LoadResource/DialogBoxParamA 一律取不到对话框资源。此时用下面的内存模板
// 直接 DialogBoxIndirectParamA 建窗,与部署形态无关。
//
// 数据来源:client/Script.rc 的 IDD_DIALOG(DIALOGEX)。DLGTEMPLATEEX 的字符串字段
// 一律是 UTF-16,同一份字节既可用于 A 接口也可用于 W 接口。
//
// 重新生成(改动 Script.rc 的 IDD_DIALOG 后必须同步):
// 1. rc /fo dlg.res dlg.rc (dlg.rc 只保留与 Script.rc 相同的 IDD_DIALOG 块)
// 2. link /dll /noentry /machine:x64 /out:dlg.dll dlg.res
// 3. 从 dlg.dll 的 RT_DIALOG(5) → 101 → 任意语言 取数据块,按 16 字节一行导出。
// 当前块 104 字节:CAPTION "消息提示"、FONT 10 "System" charset 0、
// 控件 ID 1000,与 Script.rc 完全一致;已与构建出的 ghost.exe 的
// RT_DIALOG(5) → 101 逐字节比对一致。
#ifndef YAMA_TALK_DIALOG_TEMPLATE_H
#define YAMA_TALK_DIALOG_TEMPLATE_H
// DLGTEMPLATEEX 的 DWORD 字段要求模板指针 4 字节对齐。
__declspec(align(4)) static const unsigned char kTalkDialogTemplate[] = {
0x01, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC2, 0x00, 0xC8, 0x80,
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0xB4, 0x00, 0x6C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x6D,
0x6F, 0x60, 0xD0, 0x63, 0x3A, 0x79, 0x00, 0x00, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x53, 0x00,
0x79, 0x00, 0x73, 0x00, 0x74, 0x00, 0x65, 0x00, 0x6D, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x50, 0x05, 0x00, 0x05, 0x00, 0xAA, 0x00, 0x5F, 0x00,
0xE8, 0x03, 0x00, 0x00, 0xFF, 0xFF, 0x82, 0x00, 0x53, 0x00, 0x74, 0x00, 0x61, 0x00, 0x74, 0x00,
0x69, 0x00, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00,
};
#endif // YAMA_TALK_DIALOG_TEMPLATE_H
+26 -3
View File
@@ -4,6 +4,7 @@
#include "stdafx.h"
#include "TalkManager.h"
#include "TalkDialogTemplate.h"
#include "Common.h"
#include "resource.h"
#include <IOSTREAM>
@@ -49,10 +50,23 @@ VOID CTalkManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
}
default: {
memcpy(g_Buffer, szBuffer, min(ulLength, sizeof(g_Buffer)));
// 服务端只发正文、不带结尾 NUL:按实际长度补终止符(留一格),
// 否则正好填满缓冲区时 SetDlgItemText 会越界读
size_t nCopy = min(ulLength, sizeof(g_Buffer) - 1);
memcpy(g_Buffer, szBuffer, nCopy);
g_Buffer[nCopy] = '\0';
//创建一个DLG
DialogBoxParamA(m_hInstance,MAKEINTRESOURCE(IDD_DIALOG),
NULL, DialogProc, (LPARAM)this); //SDK C MFC C++
INT_PTR nRet = DialogBoxParamA(m_hInstance, MAKEINTRESOURCEA(IDD_DIALOG),
NULL, DialogProc, (LPARAM)this); //SDK C MFC C++
if (nRet == -1) {
// 与聊天窗口同样的原因:加壳部署(EXE + SC_AES/sRDI)时 m_hInstance 是
// 外壳进程映像,取不到 IDD_DIALOG 资源,DialogBoxParamA 直接失败(Win11
// 实测 err=1812/59),右下角消息窗口不会出现。回退到内嵌的编译后模板。
DWORD dwError = GetLastError();
Mprintf("DialogBoxParamA(%lu) 失败,改用内嵌对话框模板\n", dwError);
DialogBoxIndirectParamA(m_hInstance, (LPCDLGTEMPLATEA)kTalkDialogTemplate,
NULL, DialogProc, (LPARAM)this);
}
break;
}
}
@@ -97,6 +111,15 @@ VOID CTalkManager::OnInitDialog(HWND hDlg)
{
MoveWindow(hDlg, 0, 0, 0, 0, TRUE);
// 标题栏:DialogBoxParamA 会把模板里的 UTF-16 标题按系统 ANSI 代码页转换,
// 德语等 1252 系统上"消息提示"会变成 "???"。这里在显示前用 W 接口重设标题
// (消息正文仍走 ANSI,保持原有编码语义)。中文系统显示中文,其余显示英文。
{
static const bool bChineseUI =
(PRIMARYLANGID(GetUserDefaultUILanguage()) == LANG_CHINESE);
SetWindowTextW(hDlg, bChineseUI ? L"消息提示" : L"Message");
}
static HICON hIcon = LoadIcon(NULL, MAKEINTRESOURCE(IDI_ICON_MSG));
::SendMessage(hDlg, WM_SETICON, (WPARAM)hIcon, (LPARAM)hIcon);
+3
View File
@@ -302,6 +302,9 @@
<ClInclude Include="TalkManager.h" />
<ClInclude Include="TlsChannel.h" />
<ClInclude Include="ChatManager.h" />
<ClInclude Include="ChatDialogTemplate.h" />
<ClInclude Include="TalkDialogTemplate.h" />
<ClInclude Include="ImageResource.h" />
<ClInclude Include="MachineManager.h" />
<ClInclude Include="yapi.hpp" />
<ClInclude Include="VideoCodec.h" />
+3
View File
@@ -147,6 +147,9 @@
<ClInclude Include="TalkManager.h" />
<ClInclude Include="TlsChannel.h" />
<ClInclude Include="ChatManager.h" />
<ClInclude Include="ChatDialogTemplate.h" />
<ClInclude Include="TalkDialogTemplate.h" />
<ClInclude Include="ImageResource.h" />
<ClInclude Include="MachineManager.h" />
<ClInclude Include="yapi.hpp" />
<ClInclude Include="VideoCodec.h" />
+245
View File
@@ -0,0 +1,245 @@
# MCP 远程交谈(P9):AI ↔ 客户端使用者双向对话
## 1. 目标与边界
让接入服务端 MCP 的大模型与坐在 Windows 客户端电脑前的人进行多轮文字交谈。
- **仅 Windows 客户端**:`LNX` / `MAC` / `APK` 直接返回 `-32005`,不发命令。
- **复用既有功能,协议零改动**:沿用「远程交谈」(`client/ChatManager.cpp` + `IDD_CHAT`),
报文与握手不变。客户端侧只有两处改动:聊天窗口改为 Unicode 对话框(见 §5.8,
解决非 936 ACP 系统上的中文乱码),以及加壳部署下对话框改用内嵌模板兜底(见 §5.7)。
- **独立开关 `McpChat`**(默认 `0`):与 `McpReadonly` 无关;关闭时四个工具不出现在
`tools/list`,直接调用返回 `-32006`。
- **直接弹出客户端窗口**:没有确认框;会话建立即代表开始交谈。
- 验证方式:在虚拟机里运行交互式 Windows 客户端,由人扮演使用者与服务端 AI 对话。
## 2. 复用协议
| 方向 | 报文 |
|---|---|
| 服务端主连接 → 客户端 | `[COMMAND_CHAT=161]`(1 字节) |
| 客户端新建子连接 | 先 `[TOKEN_CONN_AUTH=246]`(`EnableSubConnAuth`),再 `[TOKEN_CHAT_START=62]` |
| 服务端子连接 → 客户端 | `[COMMAND_NEXT_CHAT=0]`(1 字节,通知客户端弹窗) |
| 双向文本 | `[CP936/GBK 字节][0x00]`,无 token 前缀 |
| 服务端子连接 → 客户端 | `[COMMAND_CHAT_CLOSE=1]` 结束 |
时序:
```
chat_open:
FindMainContext(id) → 校验 Windows → 校验 McpChat
mainCtx->Send2Client([161])
客户端建子连接 → [246] 认证 → [62] 就绪
OnChatSubPacket 绑定 62 → 回 [0] → readyAt = now + 1000ms
chat_open 等到 started && now >= readyAt 才返回
chat_send:
subCtx->Send2Client(GBK + NUL) → WaitSendIdle(2000)
客户端使用者输入:
subCtx → [GBK + NUL] → OnChatSubPacket → inbox → 唤醒 chat_wait
chat_close:
subCtx->Send2Client([1]) → WaitSendIdle(1000) → CancelIO
```
未绑定子连接上的 `TOKEN_CONN_AUTH(246)` 不被聊天钩子消费,仍由 `MessageHandle`
的鉴权分支处理并回 `ConnAuthAck`,认证后子连接的 `clientID` 才可靠(新客户端路径)。
已绑定子连接上首字节为 `0xF6` 的 GBK 文本不会被误判为鉴权包(绑定连接上所有包都由
聊天钩子消费)。
## 3. 工具
| 工具 | 输入 | 输出 |
|---|---|---|
| `chat_open` | `id`;`timeout_ms`(默认 15000,2000–60000) | `{session_id, status:"open", message}` |
| `chat_send` | `id`, `session_id`, `message` | `{session_id, sent:true, bytes}` |
| `chat_wait` | `id`, `session_id`;`timeout_ms`(默认 30000,0–55000)、`max_messages`(默认 20,1–50) | `{session_id, messages:[{id,at,text}], timed_out, closed, dropped}` |
| `chat_close` | `id`, `session_id` | `{session_id, closed:true}`;主机在线时会话已不存在按幂等处理为成功;主机离线返回 `-32002` |
典型对话循环:
```
chat_open(id) → session_id
chat_send(id, sid, "你好,我是助手")
chat_wait(id, sid, 30000) → 对方的回复
chat_send(id, sid, "……")
chat_wait(id, sid, 30000)
chat_close(id, sid)
```
错误码沿用 MCP 约定:
| 码 | 含义 |
|---|---|
| `-32001` | `chat_open` 等不到客户端建窗(离线、老客户端、非交互桌面) |
| `-32002` | 主机离线 / 会话不存在或已关闭 / `session_id` 不匹配 |
| `-32003` | 同设备已有活跃会话;或同一会话已有 `chat_send` / `chat_wait` 在飞 |
| `-32004` | 发送失败(`Send2Client` 返回 FALSE) |
| `-32005` | 非 Windows 客户端 |
| `-32006` | `McpChat` 关闭 |
| `-32602` | 参数、UTF-8、GBK 可表示性或长度错误 |
## 4. 编码与长度
- **出站**:UTF-8 → CP936 **严格转换**(`MB_ERR_INVALID_CHARS` +
`WC_NO_BEST_FIT_CHARS` + `lpUsedDefaultChar`)。emoji、`ö` 等 GBK 不可表示字符
直接返回 `-32602`,绝不静默变成 `?`。
- **入站**:CP936 → UTF-8,按首个 NUL 截断。
- 出站上限 4000 GBK 字节(客户端输入缓冲 `char str[4096]`,硬上限 4095)。
- 入站单条上限 8 KiB;inbox 100 条 / 256 KiB,溢出丢最旧并在 `chat_wait` 的
`dropped` 中报告。
- 拒绝空消息、纯空白、`\r\n`、NUL 及所有 C0 控制字符。
客户端聊天窗口自 P9 起是 Unicode 对话框(见 §5.8):入站 GBK 字节先转 UTF-16 再
显示,出站 UTF-16 严格转 GBK 后发送,因此在德语等非 936 系统上中文不再乱码。协议
本身仍是 GBK,`ö`/`ß`/emoji 等 GBK 外字符两端都无法传输(服务端 `-32602`;客户端
在发送框下方给出提示并不发送)。
## 5. 客户端怪癖与规避(协议不变)
1. **首字节 101 ('e') 被丢弃**:`client/ChatManager.cpp` 在任何长度判断之前执行
`if (szBuffer[0] == TOKEN_HEARTBEAT) return;`。服务端在转换后的 GBK 首字节为
101 时前置一个空格(显示上无感)。若客户端日后修复此行,可移除该规避。
2. **窗口创建前的文本被丢弃**:客户端收到 `[0]` 后 `WaitForDialogOpen` 只
`Sleep(150)`,随后才在线程里 `CreateDialogParamW`;`OnReceive` 仅在 `m_hWnd`
非空时显示文本。服务端把 `readyAt` 设为绑定后 1000ms,`chat_open` 等满再返回,
`chat_send` 也拒绝早于 `readyAt` 的发送。
3. **X / 结束交谈只隐藏不关闭**:客户端 `ShowWindow(SW_HIDE)`,会话仍活;下一条
服务端文本会 `SW_RESTORE` 重新弹出。因此隐藏不是关闭信号,结束时必须显式
`chat_close`。
4. **一字节控制包**:客户端把 `len==1` 的包当命令,故文本必须带尾部 NUL(至少
2 字节),空消息在工具层拒绝。
5. **手动「远程交谈」竞争**:MCP 会话在飞时用户又点菜单会产生第二个 `[62]`;
先到者绑定,后到者被吸收并 `CancelIO`。极窄竞争下用户这次看不到 MFC 窗口,
重试即可。
6. **Session 0 / SYSTEM**:`COMMAND_CHAT` 不像抓屏那样重定向到交互会话;以服务
方式运行的客户端没有交互桌面,`chat_open` 会超时。VM 验证必须在交互桌面运行。
7. **加壳部署的对话框兜底**:EXE + SC_AES/sRDI 打包时,
`g_hInstance = GetModuleHandle(NULL)` 是外壳进程映像,资源里只有清单、没有
`IDD_CHAT`;载荷以裸 shellcode 在壳进程内运行,未注册进加载器,Windows 的
`FindResource`/`LoadResource`/`CreateDialogParamW` 取不到对话框
(实测 err=1812 / 59),聊天线程建窗后立即退出。客户端因此保留
`CreateDialogParamW` 原路径,失败时回退到 `CreateDialogIndirectParamW` +
内嵌模板(`client/ChatDialogTemplate.h`,取自载荷 `RT_DIALOG 106`,240 字节),
图标回退为「直接遍历本模块映像的资源目录取 `RT_GROUP_ICON 105` →
`RT_ICON` → `CreateIconFromResourceEx`」(`client/ImageResource.h`),
仍失败才用 `LoadIcon(NULL, IDI_APPLICATION)`。**旧客户端无此兜底,加壳部署下
不会弹窗**:MDLL 由服务端自动下发新 DLL 即生效,EXE 需重新分发客户端。
8. **Unicode 对话框(非 936 系统乱码修复)**:客户端是 MBCS 编译,但对话框可以建
成 Unicode 窗口:`CreateDialogParamW` / `CreateDialogIndirectParamW` 创建的窗口
`IsWindowUnicode` 为真,而 `DLGTEMPLATEEX` 的字符串本来就按 UTF-16 存储。因此
聊天窗口全部改走 W 版 API——`GetWindowTextW` / `SetDlgItemTextW` / 日志用
UTF-16 拼接,消息循环用 `GetMessageW` / `IsDialogMessageW` / `DispatchMessageW`
(否则 WM_CHAR / WM_IME_* 会先按 ACP 转换)。入站
`MultiByteToWideChar(936, …)`,出站 `WideCharToMultiByte(936,
WC_NO_BEST_FIT_CHARS, …, &usedDefault)`;`usedDefault` 置位即 GBK 不可表示
字符,提示后不发送。`IDD_CHAT` 字体由点阵 "System" 改为 "MS Shell Dlg"
(可缩放,并经 SystemLink 字体链接到中文字体),否则 Unicode 窗口里同样没有
中文字形;前提是系统装有至少一种 CJK 字体(简体中文补充字体或 Microsoft YaHei
等),否则只能显示方框。静态文案按 `GetUserDefaultUILanguage()` 在中文/英文两套
间切换,`Script.rc` 因此直接写英文(德语系统看到的是英文而非乱码)。协议与服务端
逻辑不变。
## 6. 服务端状态机
数据结构(`McpServer.h`,受 `m_ChatMutex` 保护):
```cpp
struct ChatSession {
std::string sessionId;
context* mainCtx; // 主连接(仅身份判断;主连接断开后置空)
uint64_t mainClientId;
context* subCtx; // 已绑定的子连接;关闭后置空
std::string peer; // GetPeerName()(老客户端 clientID=0 兜底)
bool started, closed;
bool sendBusy, waitBusy; // 同一会话串行发送 / 只允许一个 chat_wait
steady_clock::time_point readyAt;
time_t lastActiveAt;
std::deque<ChatMessage> inbox; // UTF-8,未投递
size_t inboxBytes;
uint64_t nextMsgId;
int dropped;
};
using ChatSessionPtr = std::shared_ptr<ChatSession>;
```
- 会话用 `shared_ptr` 持有:`chat_wait` / `chat_send` 在工作线程复制一份后,即使
map 条目被 `chat_close` 或断线删除也安全。
- `m_ChatSessions[device]`、`m_ChatContextToDevice[subCtx]`、`m_ChatAbsorbedSubCtx`
与 `m_ChatRoutes`(原子计数)供 `MessageHandle` 快速路径判断;无会话在飞时
`OnChatSubPacket` 无锁返回,避免音频/屏幕等高频子连接逐包抢锁。
- 锁序:`parent->m_cs`(`FindMainContext`)→ `m_ChatMutex`。持锁期间不发送、
不 `CancelIO`、不 `WaitSendIdle`。
- 超时/关闭后到达的 `[62]` 由 5s 墓碑(按 device 与 peer 两个维度)吸收并
`CancelIO`,避免弹出 MFC 聊天对话框。
- 空闲回收 600s(任一无 `busy` 且 `lastActiveAt` 超时的会话),每个 chat 工具
入口惰性调用。
## 7. 钩子与生命周期
`2015RemoteDlg.cpp`:
1. `MessageHandle`:MCP 终端块之后、**P8 `OnManagedSubPacket` 之前**调用
`OnChatSubPacket`。聊天文本是裸 GBK,首字节可能是 61/255,若先交给 P8 会被
误绑定。
2. `OfflineProc`:P8 清理之后、`RemoveFromHostList` **之前**调用
`OnChatContextClosed`(连接池会复用 `context*`,晚清理会误路由新连接)。
子连接断开 → 会话 `closed` 并唤醒 `chat_wait`;主连接断开 → 关闭其所有会话并
锁外 `CancelIO` 子连接。
3. 启动:`SetChatEnabled(THIS_CFG.GetInt("settings", "McpChat", 0) != 0)`。
审计:`AuditChatAction` 与 `AuditManageAction` 同落地方式(`WM_SHOWERRORMSG`),
标题 `_TR("MCP远程交谈")`;只记录 `session=...` 与 `bytes=N`,**绝不记录消息正文**。
`chat_wait` 不审计,避免刷屏。
## 8. 配置
| INI key | 默认 | 说明 |
|---|---|---|
| `McpChat` | `0` | 远程交谈工具族开关;改动需重启服务端 |
「扩展 → MCP设置」新增复选框「启用远程交谈(AI 与用户对话)」。
## 9. 验证矩阵
准备:`McpEnabled=1`、`McpChat=1` 后重启服务端;MCP 客户端重连使 `tools/list`
刷新;VM 中交互运行 Windows 客户端。
| # | 操作 | 期望 |
|---|---|---|
| 1 | `tools/list`(开关开 / 关) | 四个 chat 工具出现 / 消失;关闭时直调 `-32006` |
| 2 | `chat_open(id)` | VM 约 1s 内弹出「远程交谈」;返回 32 位 hex `session_id` |
| 3 | `chat_send` 中文;用户回中文;`chat_wait` | VM 显示「对方: …」;返回 UTF-8 原文 |
| 4 | 连续多轮、用户连发两条 | 下一轮批量返回,顺序正确,`dropped=0` |
| 5 | 发送 `"echo test"`(首字节 'e') | 正常显示(前置空格规避生效) |
| 6 | open 后立刻 send,重复 10 次 | 第一条不丢(1000ms 建窗等待) |
| 7 | 4000 / 4001 字节、emoji | 边界内成功;超长与 emoji 返回 `-32602` |
| 8 | 无回复时 `chat_wait` | 到点 `timed_out:true`,会话仍活 |
| 9 | 用户点 X 隐藏后再 send | 窗口恢复,会话仍活 |
| 10 | `chat_close` | 窗口关闭;旧 id 发送 `-32002`;立即重新 open 成功 |
| 11 | `chat_wait` 阻塞时杀掉客户端 | 返回 `closed:true`;服务端稳定;重连后可重新 open |
| 12 | Linux / macOS / Android 主机 | `-32005`,不发命令 |
| 13 | 同设备第二次 `chat_open` | `-32003` |
| 14 | 无 MCP 会话时手动「远程交谈」 | MFC 聊天窗口照常打开(回归) |
| 15 | 服务端审计日志 | 有 open/send/close 的 session id 与字节数,无消息正文 |
| 16 | 现有 MCP 工具 + 手动主机/连接/终端对话框 | 行为不变 |
| 17 | `chat_wait timeout_ms=55000` | 在常见 60s 工具超时前返回 |
| 18 | 加壳(SC_AES/sRDI)EXE 客户端 `chat_open` | 仍弹出「远程交谈」且标题栏图标正常(内嵌模板 + 自模块映像取图标);客户端日志有 `CreateDialogParamW(1812) 失败,改用内嵌对话框模板` |
| 19 | 非 936 系统(如德语 Windows)`chat_open` + 中文 `chat_send` | 标题、按钮为英文(系统 UI 非中文),中文消息正常显示而非乱码;中文系统为中文按钮 |
| 20 | 德语系统客户端发送 `Grüße` / emoji | 客户端不发送并在日志区提示 GBK 不支持;服务端若直接 `chat_send` 同类字符返回 `-32602` |
| 21 | 未安装任何 CJK 字体的系统 | 中文显示为方框(字体缺失,非编码问题);安装中文补充字体后恢复 |
## 10. 已知限制
- **无投递回执**:`sent:true` 只表示已写入子连接并 `WaitSendIdle` 成功,不保证
使用者已看见。
- **HTTP 工作线程**:`chat_wait` 最长 55s 会占用一个 httplib 工作线程;不要在
同一 MCP 连接上并行大量长等待。
- **连接池复用窄竞争**:发送时捕获的 `subCtx` 在极端情况下可能已断开并被池复用;
与现有终端/屏幕实现同一取舍,靠 `closed` 检查与 `WaitSendIdle` 缩短窗口。
- **极慢 VM**:若首条消息仍丢,可把 `kChatOpenSettleMs` 调到 1500–2000ms,代价是
`chat_open` 变慢。
- **仍是 GBK 通道**:Unicode 对话框解决了「显示」,但线路上仍是 CP936,德语变音
字母(`ö`/`ä`/`ß`)、emoji 等无法传输。要根治需引入会话级编码协商(如
`TOKEN_CHAT_START` 后追加能力位,双方改用 UTF-8),属未来工作;服务端与客户端
必须同时升级,且旧客户端不能误解新报文。
- **字体依赖**:中文显示依赖系统已安装的 CJK 字体(字体链接到 "MS Shell Dlg"
的后备字体);仅此一点无法由程序保证,缺少字体时显示为方框。
+4 -1
View File
@@ -147,7 +147,8 @@ MCP 是 JSON-RPC 2.0。MVP 只需实现以下方法:
"online":{"type":"boolean"},
"group":{"type":"string"},
"screen":{"type":"string"},
"clientType":{"type":"string"}
"clientType":{"type":"string"},
"tls":{"type":"boolean"}
}
}
}
@@ -231,6 +232,7 @@ Json::Value BuildHostJson(context* ctx, _ClientList* clientMap);
- 基础标识:`id` / `name` / `remark` / `ip` / `os` / `location` / `group` / `version` / `clientType` / `screen`
- 实时信息:`rtt`(延迟)、`activeWindow`(当前活动窗口,即被控端正在做什么)
- 连接凭据:`tls`(布尔,对应在线主机列表的 TLS 列;`true` 表示该客户端本轮以 TLS 模式登录,是**登录时的凭据**而非实时探测;老客户端/空值一律 `false`)
输出结构 `{"hosts": [...]}`,每台主机一个对象,字段与 §3.3.2 的 `outputSchema` 一致。
@@ -426,6 +428,7 @@ void CMcpSettingsDlg::OnBnClickedBtnSave()
- 写操作工具的安全边界评审(操作对象、权限、审计)
- 认证升级:复用 `WebServiceAuth` 的签名 token / 过期机制
- 分组过滤:`list_online_hosts` 加 `group` 参数
- P9 远程交谈(已实现):`chat_open` / `chat_send` / `chat_wait` / `chat_close`,独立开关 `McpChat`(默认 `0`,与只读开关无关);协议不变,客户端聊天窗口改为 Unicode 对话框以支持非中文系统(见 `docs/Mcp_Chat_Design.md`)
---
+273
View File
@@ -0,0 +1,273 @@
# MCP P8 设计:在线主机 TLS 字段 / 连接管理 / 主机管理
> 延续 `Mcp_Design.md` → `Mcp_Phase2_Design.md`(P2)→ P3~P6 → `Mcp_Manage_Design.md`(P7)。
> P7 复用的是「系统/窗口/服务」对话框使用的 `COMMAND_SYSTEM`、`COMMAND_WSLIST`、
> `COMMAND_SERVICECONFIG` 链路;本轮要覆盖的「连接管理」与「主机管理」走的是**另一套**
> 命令(`COMMAND_CONNECTION` / `COMMAND_MACHINE_MANAGE`),必须在同一子连接上收发多步,
> 因此新增一层会话抽象,并为工具族增加独立开关。
>
> 安全门结论(已确认):新增独立 `host_*` 工具族;写入范围限定「只读 + 可恢复操作」;
> 开关分两层——`McpMachine`(工具族总开关)与 `McpMachineDangerous`(高风险子集),
> 均默认关闭,并与 `McpReadonly` 叠加。现有 27 个工具(含 P7)一律不改行为。
## 1. 范围
| 交付 | 内容 |
|---|---|
| TLS 字段 | `list_online_hosts` / `search_hosts` / `get_host_detail` 增加 `tls` |
| 连接管理 | `list_network_connections`、`kill_network_connection` |
| 主机管理读 | 10 个标签页各一个:`host_list_processes` … `host_get_hosts_file` |
| 主机管理写 | `host_control_process` / `host_control_window` / `host_control_service` / `host_control_task` |
| 配置 | 设置对话框两个复选框 + 启动接线(`McpMachine` / `McpMachineDangerous`) |
不做的(明确排除):kill 进程、关闭窗口、删除服务/任务、卸载软件、写 hosts、
创建任务、强制删除文件、代码注入。
## 2. TLS 字段
- `HostJson.cpp` 的 `BuildHostJson()` 末尾追加
`device["tls"] = (ctx->GetClientData(ONLINELIST_TLS) == "Y");`。
数据源是登录时写入的 `ONLINELIST_TLS`(`2015RemoteDlg.cpp` 收到 `RES_TLS=="1"` 时置 `"Y"`)。
- 语义:**登录凭据**,不是实时探测。老客户端不上报该值 → `false`。
- `BuildHostJson` 同时被 WebService 的设备列表复用,Web 端也会多出该字段(向后兼容)。
- `get_host_detail` 复用 `BuildHostItemSchema()`,自动带上。
## 3. 会话架构
两条新链路都需要「主连接发一条命令 → 客户端新建子连接 → 子连接回就绪包 →
在同一子连接上多次收发」,现有 `m_Pending` 只能等主连接上的单包。做法是给
`PendingRequest` 增加 `kind`,**复用同一张表** `m_Pending`(从而天然保证「单设备单飞行」),
而不是另开一套状态。
```cpp
enum class PendingKind { Generic, FollowUp, Machine, ConnMgr };
```
| 成员 | 用途 |
|---|---|
| `m_SubCtxToDevice` | 已绑定的子连接 → device;绑定的子连接上所有包都由 MCP 消费 |
| `m_AbsorbedSubCtx` | `CancelIO` 后仍可能到达的包:静默丢弃 |
| `m_OrphanByDevice` / `m_OrphanByPeer` | 5 秒墓碑,防止迟到的就绪包弹出 MFC 对话框 |
### 3.1 时序(工具线程)
```
BeginMachineSession(dev, tool, mainCtx) // 登记单飞行;忙 → -32003
→ 主连接 Send2Client(COMMAND_MACHINE_MANAGE)
→ 客户端开 CMachineManager 子连接,回 TOKEN_SYSINFOLIST(61)
→ OnManagedSubPacket 绑定子连接、保存首包、notify_all
WaitManagedPacket(dev, 61, …, 5000) // 就绪
每次读:
ArmManagedResponse(dev, 期望 token)
→ 子连接 Send2Client([tab 0..9]) / WaitSendIdle
→ WaitManagedPacket(dev, 期望 token, …, 12000)
EndManagedSession(dev, cancelIo=true) // 关闭子连接,不留长连接
```
整体 60 秒会话截止;每一步取 `min(step, deadline - now)`。所有超时返回 `-32001`。
### 3.2 子连接路由(`OnManagedSubPacket`)
在 `3.1` 的模型下,UI 线程收到的每个包先经过钩子
(`MessageHandle` 中终端拦截块之后、`switch (cmd)` 之前):
1. 已绑定 → 只保留 `expectedToken` 匹配的包;`TOKEN_MACHINE_MSG(42)` 存为
`clientError`(CP936→UTF-8);其余丢弃。已绑定的子连接上的一切包都归 MCP。
2. `m_AbsorbedSubCtx` 命中 → 丢弃。
3. 未绑定且 token 不是 `61` / `255` → 交回主 switch(MFC 行为不变)。
4. 未绑定且是 `61` / `255`:
- 该 context 就是主连接(`FindMainContext(parent, cid)`)→ 交回主 switch;
- 否则在同 device 的未绑定会话中按 `clientID` 精确绑定;
- 老客户端子连接 `clientID` 可能为 0 → 按 `peer` 兜底,**仅当同 peer 唯一**时才绑定;
- 都不命中:墓碑未过期 → 吸收 + `CancelIO` + 消费;否则交回主 switch
(用户手动打开对话框)。
### 3.3 必须同步调整的现有语义
- `IsPending()` 排除 `Machine` / `ConnMgr`:否则会话在飞时用户点「进程管理」,
`case TOKEN_PSLIST` 会把界面包抢走。
- `TakeMainResponse()` 顶部对 managed kind 直接返回。
- `OfflineProc` 在 `OnManageSubClosed` 之后、`RemoveFromHostList` **之前**调用
`OnManagedContextClosed`(否则连接池复用同一 context 指针后,新连接的包会被误吞)。
- 锁序:`parent->m_cs` → `m_PendingMutex`;持锁期间禁止 `Send2Client` / `CancelIO` /
`WaitSendIdle`。
### 3.4 健壮性
- UI 线程只做「有界拷贝 + 保存 + 唤醒」:单包上限 8 MiB,超限置 `clientError` 并 `CancelIO`。
- 解析全部在 MCP 工作线程上做;字符串一律用 `BoundedStrlen` / 显式偏移,
未对齐的多字节整数用 `memcpy`,禁止指针强转。
- 客户端部分列表用 `Send(buf, LocalSize(buf))` 发送,长度可能带出少量尾随 0 填充:
记录解析循环遇到「剩余全 0」即结束,定长记录列表忽略不足一条记录的尾部。
## 4. 连接管理
### 4.1 协议
- 主连接:`COMMAND_CONNECTION(253)`;客户端建 `CConnectionsManager` 子连接。
- 子连接回 `[255][u16 LE count][ConnectionInfo × count]`。
- `ConnectionInfo`(`common/commands.h`,`#pragma pack(1)`,110 字节,已 `static_assert`):
`proto(1)` / `af(1)` / `pid(4)` / `localAddr[16]` / `localPort(2,主机序)` /
`remoteAddr[16]` / `remotePort(2,主机序)` / `state(4)` / `procName[64](UTF-8)`。
地址为网络序;IPv4 取前 4 字节,`af == AF_INET(2)`,IPv6 为 `AF_INET6(23)`。
- 强制断开:子连接发 `[254][原始 110 字节记录]`;客户端 `SetTcpEntry(DELETE_TCB)`
后自动重发一次 255。
### 4.2 工具
| 工具 | 门控 | 说明 |
|---|---|---|
| `list_network_connections` | `McpMachine` | 过滤 `protocol/family/pid/process/local_port/remote_port/remote_address/state` + 分页;输出 `killable = (proto==1 && af==AF_INET)` |
| `kill_network_connection` | `McpMachine && McpManage && !McpReadonly` | 必填四元组;可选 `pid` 消歧、`dry_run` |
`kill_network_connection` 的流程刻意避免「重新拼地址」:
1. 取最新列表,**按原始 110 字节记录精确匹配**四元组(可选同时校验 PID);
2. 匹配 0 条 → `-32009`(调用方应刷新);匹配多条 → `-32602`(要求给 `pid`);
3. 目标不是 IPv4 TCP → `-32005`,不发包;
4. `dry_run` → 直接返回目标;
5. `Arm(255)` → 发 `[254][原记录]` → 等刷新列表 → 复核该四元组是否消失。
客户端 `SetTcpEntry` 的返回值被忽略且需要管理员权限,所以「断开后仍在」返回
`structuredContent.ok=false, reason="still_present"`,**绝不谎报成功**。
每次调用写审计:`tcp a:p->b:q pid=N result=…`。
## 5. 主机管理
### 5.1 协议
- 主连接:`COMMAND_MACHINE_MANAGE(162)` → 客户端 `CMachineManager` 子连接回
`TOKEN_SYSINFOLIST(61)`。
- 之后在同一子连接上发 **1 字节 tab**(0–9),响应 token 31–42。
- 动作 10–30;多数动作客户端会自动回一份刷新后的列表(服务 = 40,任务 = 41),
进程冻结/解冻(16/17)与窗口操作(11)**不回包**。
`MachineManager` 枚举(`common/commands.h`):请求 0 PROCESS / 1 WINDOWS / 2 NETSTATE /
3 SOFTWARE / 4 HTML / 5 FAVORITES / 6 WIN32SERVICE / 7 DRIVERSERVICE / 8 TASK / 9 HOSTS;
响应 31 PROCESS / 32 WINDOWS / 33 NETSTATE / 34 SOFTWARE / 35 HTML / 36 FAVORITES /
37 WIN32SERVICE / 38 DRIVERSERVICE / 39 HOSTS / 40 SERVICE_LIST / 41 TASKLIST / 42 MACHINE_MSG。
### 5.2 读工具
| 工具 | tab | 响应 | 主要过滤 |
|---|---|---|---|
| `host_list_processes` | 0 | 31 | `pid` / `name` / `arch` |
| `host_list_windows` | 1 | 32 | `pid` / `title` |
| `host_list_network_state` | 2 | 33 | `pid` / `process` / `protocol` / `local_port` / `remote_port` / `state` |
| `host_list_software` | 3 | 34 | `name` / `publisher` |
| `host_list_browser_history` | 4 | 35 | `title` / `url` |
| `host_list_favorites` | 5 | 36 | `name` / `url` |
| `host_list_win32_services` | 6 | 40 | `name` / `status` / `start_type` |
| `host_list_driver_services` | 7 | 40 | 同上 |
| `host_list_scheduled_tasks` | 8 | 41 | `name` / `folder` / `status` |
| `host_get_hosts_file` | 9 | 39 | `include_content` / `max_bytes` |
公共分页 `offset`(默认 0)/ `limit`(默认 100,上限 1000);输出
`total`(过滤后)/ `totalAll` / `offset` / `limit` / `hasMore`。
### 5.3 记录格式(与 `CMachineDlg::Show*` 逐字段对齐)
| 列表 | 格式 |
|---|---|
| 进程 31 | `DWORD pid`、`bool is64`、`title[260]`、`exe`+pad、`path`+pad、`DWORD priClass`、`DWORD threads`、`user`+pad、`DWORD workingSetKb`、`DWORD fileSizeKb`;CP936 |
| 窗口 32 | `WINDOWSINFO` 定长 1044 字节;**只含可见窗口**;空列表 = 1 字节 |
| 网络状态 33 | 进程名、`DWORD pid`、`[TCP]/[UDP]`、`ip:port`、远端、状态,各串 +2;UDP 远端 `*.*.*.*:*`、状态为空;按最后一个 `:` 拆地址 |
| 软件 34 | 5 个串各 +2:显示名、发布者、版本、安装日期、卸载命令 |
| 浏览记录 35 | 定长 2148:`time[100]` + `title[1024]` + `url[1024]` |
| 收藏夹 36 | 2 个串各 +2 |
| 服务 40 | 8 个串各 +1 NUL:显示名、描述、状态、启动类型、登录身份、交互式、**服务名**、可执行路径 |
| 计划任务 41 | `name/path/exe` 为 UTF-8、`status` 为 GBK,各 +1 NUL;两个 `DATE`;两个 0 字节结束;`folder` 由 `path` 去掉末尾 `"\<name>"` 派生 |
| hosts 39 | `[39][文件原文][0]`;有 BOM → UTF-8,否则合法 UTF-8 → UTF-8,否则 CP936 |
### 5.4 写工具
统一模式:**先取列表校验目标存在 → 发动作 → 再取列表复核**。目标不在最新快照里
返回 `-32009`,绝不盲发。
| 工具 | action | 额外门控 | 动作包 | 复核 |
|---|---|---|---|---|
| `host_control_process` | `freeze` / `thaw` | `McpMachineDangerous` | `[16/17][DWORD pid]`(无回包) | 重新取 tab 0:PID 仍在 |
| `host_control_window` | `restore/hide/maximize/minimize` | — | `[11][DWORD hwnd][DWORD SW_*]` + 零填充到 20 字节(客户端只读前 9 字节) | 重新取 tab 1:hide 后 hwnd 应消失,其余应仍在 |
| `host_control_service` | `start`/`pause`/`continue` | — | `[22/24/25][服务名 CP936][NUL]` | 客户端自动回 40 |
| `host_control_service` | `stop`/`restart` | `McpMachineDangerous` | stop = `[23]`;restart = stop → 等 40 → start | 等 40(12 s),状态在期望集合内 |
| `host_control_task` | `run` / `stop` | — | `[29/28][folder CP936][NUL][name CP936][NUL]` | 客户端自动回 41:任务仍在 + 当前状态 |
补充规则:
- 服务动作前先取一次服务列表(prime),既校验目标,也把客户端 `m_dwServiceType`
钉到正确类型(Win32 / 驱动)。
- 已是目标状态时不下发动作,返回 `ok=true, changed=false, reason=already_*`。
- 冻结/解冻、窗口动作、任务动作**没有回执**:`verified` 只表示「已用动作后的快照复核」,
不表示「动作一定生效」。冻结不改变进程存在性,因此只能确认目标仍在。
- 写工具输入串(服务名、任务 folder/name)必须能转成 CP936,否则 `-32602`,不发包。
- 审计格式:`host <id> <tool>: action=… target=… result=…`。
## 6. 门控矩阵
| 配置 | 可见工具 | 直接调用被隐藏的工具 |
|---|---|---|
| `McpMachine=0`(默认) | 0 个 | `-32006` |
| `McpMachine=1, McpReadonly=1` | 11 个读工具(`list_network_connections` + 10 个 `host_list_*` / `host_get_hosts_file`) | 5 个写工具 → `-32006` |
| `McpMachine=1, McpReadonly=0, McpManage=1` | 16 个(含 5 个写) | — |
| `McpMachine=1, McpReadonly=0, McpManage=0` | 15 个(无 `kill_network_connection`) | `kill_network_connection` → `-32006` |
| `McpMachineDangerous=0` | 工具仍可见 | `host_control_process`、`host_control_service{stop,restart}` → `-32006` |
设置对话框勾选「危险主机操作」但未勾「主机管理」时,保存会清除危险开关并提示。
## 7. 错误码
沿用 P1–P7 的约定,新增 `-32009`:
| 码 | 含义 |
|---|---|
| `-32602` | 参数非法(含:目标多条匹配、字符无法用 CP936 表示) |
| `-32000` | 解析失败 / 客户端返回错误文本(`TOKEN_MACHINE_MSG`) |
| `-32001` | 超时(就绪 5 s / 列表 12 s / 会话 60 s) |
| `-32002` | 主机离线 |
| `-32003` | 设备忙(已有 MCP 会话在飞:单设备单飞行) |
| `-32004` | 发送失败 |
| `-32005` | 不支持(非 Windows 客户端;UDP/IPv6 断连) |
| `-32006` | 开关未开启 |
| `-32009` | **目标在最新快照中不存在**(调用方应刷新后重试) |
## 8. 已知限制
1. **token 数值碰撞**:机器响应 31–42 与 `COMMAND_KEYBOARD/AUDIO/SYSTEM/SHELL/…` 同值。
靠「先按子连接身份路由」解决——未绑定的子连接不会按 token 猜测。
2. **UI 争抢就绪包**:用户恰好在 MCP 请求期间点开同一对话框时,首包可能被 MCP 绑定,
界面对话框这次不弹(与 P7 的取舍一致),重试即可。
3. **5 s 墓碑**:MCP 异常结束后 5 s 内手动打开同一台主机的对话框可能被吞,重试即可。
4. **老客户端子连接 `clientID=0`**:靠 peer 兜底,仅在同 peer 唯一会话时绑定。
5. **权限**:`SetTcpEntry`、冻结/解冻、服务控制需要客户端管理员;失败按「未生效」如实返回。
6. **编码**:机器协议以 CP936 为主;任务 `name/path/exe` 为 UTF-8、`status` 为 GBK;
写回输入统一转 CP936。GBK 不可表示的字符明确报 `-32602`。
7. **`host_list_network_state` 只有 IPv4**:数据来自客户端自身的 `GetTcpTable` 视图,
与「连接管理」(`ConnectionInfo`,含 IPv6)不是同一份数据。
8. **`McpMachineDangerous` 只覆盖本轮高风险动作**;后续加入 kill/删除/卸载/注入时,
必须按 `McpMachine && McpMachineDangerous && !McpReadonly` 三层校验。
9. **`host_control_window {action:"hide"}` 是单向的**:客户端只枚举可见窗口,隐藏后该 hwnd
从快照中消失,再发 `restore` 会在发包前被 `-32009` 拦下(MFC 对话框同样无法再操作它)。
实测确认:`hide` 复核为 `state:"hidden"`,随后 `restore` 返回 `-32009`。
10. **`host_control_service {action:"pause"}` 依赖服务自身支持 PAUSE**:实测虚拟机上的
`Spooler` 下发 PAUSE 后状态仍为 `Running`,工具如实返回 `ok:false, reason:"unexpected_state"`
(不谎报成功)。`start/stop/continue/restart` 在同一台机器上均通过。
11. **开关只在进程启动时读取**(Release 版配置来自注册表 `HKCU\Software\YAMA\settings`,
不是 `Bin\settings.ini`);在「MCP设置」里改动 `McpMachine` / `McpMachineDangerous` /
`McpReadonly` 等必须重启服务端才生效。未重启时 `tools/list` 里看不到新工具,
直接调用返回 `-32006`。
## 9. 验证要点
- TLS:`RES_TLS=1` 的主机三个工具都返回 `tls:true`;老客户端 `false`。
- 路由:MCP 关闭时手动打开「主机管理」「连接管理」照常工作;
`host_list_favorites`(token 36,与键盘等命令同值)在飞时手动打开「进程管理」,
两边都不串包。
- 迟到包:强制就绪超时后,61/255 到达应被吸收且不弹对话框。
- 单飞行:同主机并发两个 host/connection 工具,第二个 `-32003`;两台主机并发都成功。
- 连接管理:与对话框逐条对比;断开后复核消失;UDP/IPv6 → `-32005`;过期四元组 → `-32009`。
- 10 个读工具:与 MFC 标签页对比行数、首末行、中文编码;空 tab 返回 `total:0`。
- 4 个写工具:freeze→thaw、窗口四动作、服务五动作、任务 run/stop;过期目标发包前 `-32009`。
- 回归:现有 27 个工具、终端、远程控制、文件传输、10 个 MFC 标签页行为不变。
- 资源:连续调用 20 次 host 工具,服务端无残留子连接。
+10 -8
View File
@@ -88,14 +88,16 @@ bool ScreenHandler::init()
m_height = (int)CGDisplayPixelsHigh(m_displayID);
}
// Get logical point dimensions (what CGEvent uses)
// NSScreen provides logical dimensions
NSScreen* mainScreen = [NSScreen mainScreen];
if (mainScreen) {
NSRect frame = [mainScreen frame];
m_logicalWidth = (int)frame.size.width;
m_logicalHeight = (int)frame.size.height;
} else {
// 逻辑尺寸必须取自「实际抓屏的那块屏」(CGMainDisplayID)。CGEvent 的鼠标坐标是
// 全局显示坐标(points),而我们发给服务端的是这块屏的编码像素。
// [NSScreen mainScreen] 取的是菜单栏/焦点窗口所在屏:合盖外接显示器时它仍可能是
// 已停用的内置屏(例如 13" MacBook Air 的 1470x956),与抓屏的外置屏(1280x1024)
// 不是同一块屏。用错尺寸会让每个注入点变成 p * (logical / encode),表现为从左上角
// 起线性增长、且 x/y 各轴独立的鼠标偏移(见 ScreenHandler::OnReceive 的换算)。
CGRect bounds = CGDisplayBounds(m_displayID);
m_logicalWidth = (int)(bounds.size.width + 0.5);
m_logicalHeight = (int)(bounds.size.height + 0.5);
if (m_logicalWidth <= 0 || m_logicalHeight <= 0) {
// Fallback: use physical dimensions
m_logicalWidth = m_width;
m_logicalHeight = m_height;
+7 -4
View File
@@ -271,11 +271,14 @@ static std::string normalizeExePathLower(const std::string& path)
// Get screen resolution
static std::string getScreenResolution()
{
NSScreen* mainScreen = [NSScreen mainScreen];
if (mainScreen) {
NSRect frame = [mainScreen frame];
// 用主显示器的全局显示坐标(points),与 CGEvent 注入坐标同一空间,也和
// ScreenHandler 抓屏所用的 CGMainDisplayID 保持一致。
// [NSScreen mainScreen] 在合盖接外置显示器时仍可能返回内置屏(如 1470x956),
// 上报后会让服务端以为主机分辨率是内置屏尺寸。
CGRect bounds = CGDisplayBounds(CGMainDisplayID());
if (bounds.size.width > 0 && bounds.size.height > 0) {
return [NSString stringWithFormat:@"1:%dx%d",
(int)frame.size.width, (int)frame.size.height].UTF8String;
(int)(bounds.size.width + 0.5), (int)(bounds.size.height + 0.5)].UTF8String;
}
return "0:0x0";
}
Binary file not shown.
+66 -8
View File
@@ -742,6 +742,10 @@ CMy2015RemoteDlg::CMy2015RemoteDlg(CWnd* pParent): CDialogLangEx(CMy2015RemoteDl
m_bmOnline[68].LoadBitmap(IDB_BITMAP_DRAWING_BOARD); // 远程画板
m_bmOnline[69].LoadBitmap(IDB_BITMAP_TLS_ENABLE); // TLS 传输
m_bmOnline[70].LoadBitmap(IDB_BITMAP_TLS_DISABLE); // 取消 TLS
m_bmOnline[71].LoadBitmap(IDB_BITMAP_DESKTOP_QUALITY); // 高级→远程桌面质量等级
m_bmOnline[72].LoadBitmap(IDB_BITMAP_PREVIEW_QUALITY); // 高级→屏幕预览质量等级
m_bmOnline[73].LoadBitmap(IDB_BITMAP_FILE_SPEED); // 高级→文件传输速度
m_bmOnline[74].LoadBitmap(IDB_BITMAP_DISCLAIMER); // 其他→免责声明
for (int i = 0; i < PAYLOAD_MAXTYPE; i++) {
m_ServerDLL[i] = nullptr;
m_ServerBin[i] = nullptr;
@@ -1219,13 +1223,17 @@ VOID CMy2015RemoteDlg::CreateSolidMenu()
m_MainMenu.SetMenuItemBitmaps(ID_FRPS_FOR_SUB, MF_BYCOMMAND, &m_bmOnline[45], &m_bmOnline[45]);
m_MainMenu.SetMenuItemBitmaps(ID_WEB_REMOTE_CONTROL, MF_BYCOMMAND, &m_bmOnline[52], &m_bmOnline[52]);
// Help menu
m_MainMenu.SetMenuItemBitmaps(ID_HELP_IMPORTANT, MF_BYCOMMAND, &m_bmOnline[46], &m_bmOnline[46]);
m_MainMenu.SetMenuItemBitmaps(ID_HELP_IMPORTANT, MF_BYCOMMAND, &m_bmOnline[74], &m_bmOnline[74]);
m_MainMenu.SetMenuItemBitmaps(ID_HELP_FEEDBACK, MF_BYCOMMAND, &m_bmOnline[47], &m_bmOnline[47]);
m_MainMenu.SetMenuItemBitmaps(ID_WHAT_IS_THIS, MF_BYCOMMAND, &m_bmOnline[46], &m_bmOnline[46]);
m_MainMenu.SetMenuItemBitmaps(ID_MASTER_TRAIL, MF_BYCOMMAND, &m_bmOnline[48], &m_bmOnline[48]);
m_MainMenu.SetMenuItemBitmaps(ID_TOOL_REQUEST_AUTH, MF_BYCOMMAND, &m_bmOnline[49], &m_bmOnline[49]);
m_MainMenu.SetMenuItemBitmaps(ID_UNINSTALL_SOFTWARE, MF_BYCOMMAND, &m_bmOnline[57], &m_bmOnline[57]);
m_MainMenu.SetMenuItemBitmaps(ID_ENABLE_DEV_DEBUG, MF_BYCOMMAND, &m_bmOnline[60], &m_bmOnline[60]);
// Advanced menu
m_MainMenu.SetMenuItemBitmaps(ID_TOOL_QUALITY_LEVELS, MF_BYCOMMAND, &m_bmOnline[71], &m_bmOnline[71]);
m_MainMenu.SetMenuItemBitmaps(ID_TOOL_PREVIEW_LEVELS, MF_BYCOMMAND, &m_bmOnline[72], &m_bmOnline[72]);
m_MainMenu.SetMenuItemBitmaps(ID_TOOL_FILE_SPEED, MF_BYCOMMAND, &m_bmOnline[73], &m_bmOnline[73]);
// ============================================================
// UIBranding: 根据编译时配置隐藏菜单项
@@ -1615,6 +1623,10 @@ VOID CMy2015RemoteDlg::InitControl()
m_CList_Online.SetExtendedStyle(style);
m_CList_Online.SetParent(&m_GroupTab);
m_CList_Online.ModifyStyle(WS_HSCROLL, 0);
// 表头是列表的子窗口;LVS_EX_DOUBLEBUFFER 只给列表项做了双缓冲,表头没有。
// 列表没有 WS_CLIPCHILDREN 时,任何整表 Invalidate/RedrawWindow 都会让表头
// 先用类背景刷擦一帧再重画,表现为表头那行偶发闪一下。裁掉表头区域即可。
m_CList_Online.ModifyStyle(0, WS_CLIPCHILDREN);
// Tab 控件是列表的父窗口,添加 WS_CLIPCHILDREN 防止重绘时覆盖列表
m_GroupTab.ModifyStyle(0, WS_CLIPCHILDREN);
@@ -1626,6 +1638,7 @@ VOID CMy2015RemoteDlg::InitControl()
m_CList_Message.ModifyStyle(0, LVS_SHOWSELALWAYS);
m_CList_Message.SetExtendedStyle(style);
m_CList_Message.ModifyStyle(WS_HSCROLL, 0);
m_CList_Message.ModifyStyle(0, WS_CLIPCHILDREN); // 同上:整表重绘不擦表头
m_nSplitPos = THIS_CFG.GetInt("settings", "SplitPos", 160);
m_nSplitPos = max(60, min(m_nSplitPos, 600));
@@ -2410,6 +2423,13 @@ BOOL CMy2015RemoteDlg::OnInitDialog()
McpServer().SetFileTransferEnabled(THIS_CFG.GetInt("settings", "McpFileTransfer", 0) != 0);
// P7 管理控制开关:默认关;要求只读关(McpReadonly=0)才生效(工具列表/分派双重门控)。
McpServer().SetManageEnabled(THIS_CFG.GetInt("settings", "McpManage", 0) != 0);
// P8 主机管理 / 连接管理工具族:总开关默认关(关闭时 16 个工具都不可见)。
// 危险子集(进程冻结/解冻、服务停止/重启)在总开关之上再叠一道,默认关。
McpServer().SetMachineEnabled(THIS_CFG.GetInt("settings", "McpMachine", 0) != 0);
McpServer().SetMachineDangerousEnabled(
THIS_CFG.GetInt("settings", "McpMachineDangerous", 0) != 0);
// P9 远程交谈(chat_*):独立开关默认关,与只读开关无关。
McpServer().SetChatEnabled(THIS_CFG.GetInt("settings", "McpChat", 0) != 0);
if (!McpServer().Start(mcpBind, mcpPort)) {
Mprintf("McpServer start failed on %s:%d\n", mcpBind.c_str(), mcpPort);
} else {
@@ -3657,8 +3677,15 @@ void CMy2015RemoteDlg::OnSize(UINT nType, int cx, int cy)
m_CList_Online.AdjustColumnWidths();
if (needRefresh) {
CListCtrlEx::ScopedEraseBkgnd scope(m_CList_Online);
m_GroupTab.RedrawWindow(NULL, NULL, RDW_ERASE | RDW_INVALIDATE | RDW_ALLCHILDREN);
m_CList_Online.RedrawWindow(NULL, NULL, RDW_ERASE | RDW_INVALIDATE | RDW_ALLCHILDREN | RDW_UPDATENOW);
// 不带 RDW_ALLCHILDREN:表头已是裁剪掉的子窗口,没必要跟着擦一帧
m_GroupTab.RedrawWindow(NULL, NULL, RDW_ERASE | RDW_INVALIDATE);
m_CList_Online.RedrawWindow(NULL, NULL, RDW_ERASE | RDW_INVALIDATE | RDW_UPDATENOW);
// 最小化还原/最大化和正常切换时窗口内容会丢,表头右端那条空带只能靠
// 背景擦除上色(见 CHeaderCtrlEx::OnEraseBkgnd),这里显式让表头重画一次。
// 擦除现在只补空带,不会重新引入表头闪烁。
if (CHeaderCtrl* pHeader = m_CList_Online.GetHeaderCtrl()) {
pHeader->RedrawWindow(NULL, NULL, RDW_ERASE | RDW_INVALIDATE);
}
}
}
LeaveCriticalSection(&m_cs);
@@ -3700,7 +3727,7 @@ void CMy2015RemoteDlg::OnSize(UINT nType, int cx, int cy)
rc.bottom = cy-20;
m_CList_Message.MoveWindow(rc);
if (needRefresh) {
m_CList_Message.RedrawWindow(NULL, NULL, RDW_ERASE | RDW_INVALIDATE | RDW_ALLCHILDREN | RDW_UPDATENOW);
m_CList_Message.RedrawWindow(NULL, NULL, RDW_ERASE | RDW_INVALIDATE | RDW_UPDATENOW);
}
auto total = cx - 24;
for(int i=0; i<g_Column_Count_Message; ++i) { //遍历每一个列
@@ -3708,7 +3735,10 @@ void CMy2015RemoteDlg::OnSize(UINT nType, int cx, int cy)
Temp/=g_Column_Message_Width; //看一看当前宽度占总长度的几分之几
Temp*=total; //用原来的长度乘以所占的几分之几得到当前的宽度
int lenth=Temp; //转换为int 类型
m_CList_Message.SetColumnWidth(i,(lenth)); //设置当前的宽度
// 只改真正变化的列:SetColumnWidth 会让表头重画一次(WM_SIZE 很频繁)
if (m_CList_Message.GetColumnWidth(i) != lenth) {
m_CList_Message.SetColumnWidth(i,(lenth)); //设置当前的宽度
}
}
}
}
@@ -3745,13 +3775,13 @@ void CMy2015RemoteDlg::OnExitSizeMove()
{
__super::OnExitSizeMove();
// 拖拽调整大小结束后刷新列表,避免残影
// 拖拽调整大小结束后刷新列表,避免残影(表头被 WS_CLIPCHILDREN 裁掉,不会闪)
if (m_CList_Online.m_hWnd != NULL) {
CListCtrlEx::ScopedEraseBkgnd scope(m_CList_Online);
m_CList_Online.RedrawWindow(NULL, NULL, RDW_ERASE | RDW_INVALIDATE | RDW_ALLCHILDREN | RDW_UPDATENOW);
m_CList_Online.RedrawWindow(NULL, NULL, RDW_ERASE | RDW_INVALIDATE | RDW_UPDATENOW);
}
if (m_CList_Message.m_hWnd != NULL) {
m_CList_Message.RedrawWindow(NULL, NULL, RDW_ERASE | RDW_INVALIDATE | RDW_ALLCHILDREN | RDW_UPDATENOW);
m_CList_Message.RedrawWindow(NULL, NULL, RDW_ERASE | RDW_INVALIDATE | RDW_UPDATENOW);
}
// 更新搜索栏位置(跟随主窗口移动/调整大小)
if (m_pSearchBar && m_pSearchBar->GetSafeHwnd() && m_pSearchBar->IsWindowVisible()) {
@@ -5508,6 +5538,18 @@ BOOL CALLBACK CMy2015RemoteDlg::OfflineProc(CONTEXT_OBJECT* ContextObject)
McpServer().OnManageSubClosed(ContextObject);
}
// MCP P8 主机管理 / 连接管理会话的子连接断开:清路由表、唤醒等待线程。必须在
// RemoveFromHostList 之前,否则连接池复用同一 context 指针后新连接的包会被误吞。
if (McpServer().IsRunning()) {
McpServer().OnManagedContextClosed(ContextObject);
}
// MCP P9 远程交谈:子连接(或主连接)断开时清路由/标记会话 closed 并唤醒 chat_wait。
// 同样必须在 RemoveFromHostList 之前,避免连接池复用同一 context 指针后误路由。
if (McpServer().IsRunning()) {
McpServer().OnChatContextClosed(ContextObject);
}
SOCKET nSocket = ContextObject->sClientSocket;
CDialogBase* p = (CDialogBase*)ContextObject->hDlg;
@@ -5870,6 +5912,22 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject)
return;
}
// ===== MCP 远程交谈:子连接路由(P9)=====
// 必须在 P8 之前:聊天文本是裸 GBK,首字节可能是 61(SYSINFOLIST)/255(CONNECTION_LIST),
// 若先交给 P8 会被误当作就绪包绑定。已绑定的子连接由 MCP 消费;未绑定的只有
// TOKEN_CHAT_START(62) 会被尝试绑定,其余(含 TOKEN_CONN_AUTH=246)原样交回下方分发。
if (McpServer().IsRunning() && McpServer().OnChatSubPacket(ContextObject, szBuffer, len)) {
return;
}
// ===== MCP 主机管理 / 连接管理:子连接路由(P8)=====
// 已绑定的子连接上的所有包由 MCP 消费;未绑定的子连接只有就绪包
// TOKEN_SYSINFOLIST(61) / TOKEN_CONNECTION_LIST(255) 会被尝试绑定,其余原样交回
// 下方 MFC 分发(用户手动打开对话框的行为不变)。无会话在飞时走无锁快速路径。
if (McpServer().OnManagedSubPacket(ContextObject, szBuffer, len)) {
return;
}
// 【L】:主机上下线和授权
// 【x】:对话框相关功能
switch (cmd) {
+1 -1
View File
@@ -453,7 +453,7 @@ public:
bool IsDllRequestLimited(const std::string& ip);
void RecordDllRequest(const std::string& ip);
CMenu m_MainMenu;
CBitmap m_bmOnline[71];
CBitmap m_bmOnline[75];
uint64_t m_superID;
std::map<HWND, CDialogBase *> m_RemoteWnds;
FileTransformCmd m_CmdList;
@@ -328,6 +328,9 @@
<ClInclude Include="KeyBoardDlg.h" />
<ClInclude Include="LangManager.h" />
<ClInclude Include="McpServer.h" />
<ClInclude Include="McpChat.h" />
<ClInclude Include="McpInternal.h" />
<ClInclude Include="McpMachine.h" />
<ClInclude Include="McpSettingsDlg.h" />
<ClInclude Include="TlsCertificateDlg.h" />
<ClInclude Include="NetworkDlg.h" />
@@ -397,6 +400,9 @@
<ClCompile Include="WebService.cpp" />
<ClCompile Include="HostJson.cpp" />
<ClCompile Include="McpServer.cpp" />
<ClCompile Include="McpChat.cpp" />
<ClCompile Include="McpInternal.cpp" />
<ClCompile Include="McpMachine.cpp" />
<ClCompile Include="McpSettingsDlg.cpp" />
<ClCompile Include="TlsCertificateDlg.cpp" />
<ClCompile Include="..\..\client\MemoryModule.c">
@@ -89,6 +89,9 @@
<ClCompile Include="TriggerSettingsDlg.cpp" />
<ClCompile Include="HostJson.cpp" />
<ClCompile Include="McpServer.cpp" />
<ClCompile Include="McpChat.cpp" />
<ClCompile Include="McpInternal.cpp" />
<ClCompile Include="McpMachine.cpp" />
<ClCompile Include="McpSettingsDlg.cpp" />
<ClCompile Include="TlsCertificateDlg.cpp" />
<ClCompile Include="CClientLog.cpp" />
@@ -203,6 +206,9 @@
<ClInclude Include="PreviewTipWnd.h" />
<ClInclude Include="TriggerSettingsDlg.h" />
<ClInclude Include="McpServer.h" />
<ClInclude Include="McpChat.h" />
<ClInclude Include="McpInternal.h" />
<ClInclude Include="McpMachine.h" />
<ClInclude Include="McpSettingsDlg.h" />
<ClInclude Include="TlsCertificateDlg.h" />
<ClInclude Include="CClientLog.h" />
+39 -5
View File
@@ -6,8 +6,35 @@
BEGIN_MESSAGE_MAP(CHeaderCtrlEx, CHeaderCtrl)
ON_NOTIFY_REFLECT(HDN_BEGINTRACKA, &CHeaderCtrlEx::OnBeginTrack)
ON_NOTIFY_REFLECT(HDN_BEGINTRACKW, &CHeaderCtrlEx::OnBeginTrack)
ON_WM_ERASEBKGND()
END_MESSAGE_MAP()
BOOL CHeaderCtrlEx::OnEraseBkgnd(CDC* pDC)
{
// 表头的 WM_PAINT 只画到最后一列,最后一列(如 TLS)右边那条空带
// (CListCtrlEx 算列宽时预留的 20px)要靠背景擦除上色。
// 之前整个跳过擦除,平时看着没事;最小化再还原时窗口内容被丢弃,
// 这条空带就再没人画,成了黑色且不会刷新(表头那行右端一条黑块)。
// 这里只补空带、不擦整行:整行擦除会在每次表头重画时先闪一帧底色。
CRect rcClient;
GetClientRect(&rcClient);
int used = 0;
const int nCols = GetItemCount();
if (nCols > 0) {
RECT rcLast = { 0 };
if (GetItemRect(nCols - 1, &rcLast)) {
used = rcLast.right; // 最后一列的右边界 = 表头已画到的位置
}
}
if (used < rcClient.right) {
CRect rcGap(used, 0, rcClient.right, rcClient.bottom);
pDC->FillSolidRect(&rcGap, ::GetSysColor(COLOR_3DFACE));
}
return TRUE;
}
void CHeaderCtrlEx::OnBeginTrack(NMHDR* pNMHDR, LRESULT* pResult)
{
LPNMHEADER pNMHeader = reinterpret_cast<LPNMHEADER>(pNMHDR);
@@ -139,8 +166,12 @@ void CListCtrlEx::AdjustColumnWidths()
for (int i = 0; i < (int)m_Columns.size(); i++) {
if (m_Columns[i].Visible) {
int width = (visiblePercent > 0) ? (int)(totalWidth * m_Columns[i].Percent / visiblePercent) : 0;
SetColumnWidth(i, width);
} else {
// 只改真正变化的列:SetColumnWidth 会让表头重画一次,OnSize 每次都跑这里,
// 逐列无条件设置就会在拖窗口时反复重画表头。
if (GetColumnWidth(i) != width) {
SetColumnWidth(i, width);
}
} else if (GetColumnWidth(i) != 0) {
SetColumnWidth(i, 0); // 隐藏列
}
}
@@ -161,8 +192,10 @@ void CListCtrlEx::SetColumnVisible(int nCol, BOOL bVisible)
m_Columns[nCol].Visible = bVisible;
AdjustColumnWidths();
// 列数变化后完整重绘(含背景擦除),否则最后一列右侧会残留旧列残影。
// 不带 RDW_ALLCHILDREN:表头是列表的子窗口,列宽一变它自己就会重画,
// 强制跟着擦一帧只会在表头那行闪一下。
ScopedEraseBkgnd scope(*this);
RedrawWindow(NULL, NULL, RDW_ERASE | RDW_INVALIDATE | RDW_ALLCHILDREN | RDW_UPDATENOW);
RedrawWindow(NULL, NULL, RDW_ERASE | RDW_INVALIDATE | RDW_UPDATENOW);
}
}
}
@@ -235,9 +268,10 @@ void CListCtrlEx::ToggleColumnVisibility(int nColumn)
AdjustColumnWidths();
// 列数变化后完整重绘(含背景擦除),否则最后一列(TLS 等)右侧会残留旧列残影。
// 与 OnSize 中 needRefresh 分支相同的处理:临时放行背景擦除 + 全量 RedrawWindow。
// 与 OnSize 中 needRefresh 分支相同的处理:临时放行背景擦除 + 全量重绘。
// 表头不在其中:列宽变化会触发它自己重画,跟着擦一帧只会闪一下。
ScopedEraseBkgnd scope(*this);
RedrawWindow(NULL, NULL, RDW_ERASE | RDW_INVALIDATE | RDW_ALLCHILDREN | RDW_UPDATENOW);
RedrawWindow(NULL, NULL, RDW_ERASE | RDW_INVALIDATE | RDW_UPDATENOW);
}
void CListCtrlEx::LoadColumnVisibility()
+1
View File
@@ -23,6 +23,7 @@ public:
protected:
DECLARE_MESSAGE_MAP()
afx_msg void OnBeginTrack(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
};
// CListCtrlEx - 支持列显示/隐藏功能的列表控件
+4
View File
@@ -114,5 +114,9 @@ Json::Value BuildHostJson(context* ctx, _ClientList* clientMap) {
CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
device["clientType"] = AnsiToUtf8(clientType); // e.g. "MAC", "LNX", "EXE"
// 登录时上报的 TLS 传输标志(RES_TLS=="1" → "Y")。老客户端不上报,取值为 "N"。
// 注意这是登录凭据而不是实时探测:连接建立后若配置发生变化,需要客户端重连才会更新。
device["tls"] = (ctx->GetClientData(ONLINELIST_TLS) == "Y");
return device;
}
File diff suppressed because it is too large. Load diff
+30
View File
@@ -0,0 +1,30 @@
#pragma once
// MCP「远程交谈」工具族:chat_open / chat_send / chat_wait / chat_close。
//
// 复用 Windows 客户端既有的「远程交谈」链路(协议不变):
// 主连接 [COMMAND_CHAT=161]
// → 客户端子连接先 [TOKEN_CONN_AUTH=246],再 [TOKEN_CHAT_START=62]
// → 服务端在子连接回 [COMMAND_NEXT_CHAT=0](客户端据此弹 IDD_CHAT)
// → 双向文本 [CP936 字节][NUL];服务端 [COMMAND_CHAT_CLOSE=1] 结束。
//
// 会话状态由 CMcpServer 持有(McpServer.h),本文件只负责工具 schema、参数校验、
// 编码转换与响应构造。协议、客户端怪癖与验证矩阵见 docs/Mcp_Chat_Design.md。
#include "jsoncpp/json.h"
#include <string>
class CMy2015RemoteDlg;
namespace McpChat {
bool Handles(const std::string& toolName);
// 开关 close 时不追加任何工具(tools/list 与调用侧一致)。
void AppendTools(Json::Value& tools);
std::string Call(const Json::Value& id, const std::string& toolName,
const Json::Value& args, CMy2015RemoteDlg* parent);
} // namespace McpChat
+210
View File
@@ -0,0 +1,210 @@
#include "stdafx.h"
#include "McpInternal.h"
#include "context.h" // context 接口(GetClientID/IsLogin)
#include "2015RemoteDlg.h" // CMy2015RemoteDlg 成员(m_HostList/m_cs)+ WM_SHOWERRORMSG
#include "LangManager.h" // _TR
#ifndef _WIN64
#ifdef _DEBUG
#pragma comment(lib, "jsoncpp/jsoncppd.lib")
#else
#pragma comment(lib, "jsoncpp/jsoncpp.lib")
#endif
#else
#ifdef _DEBUG
#pragma comment(lib, "jsoncpp/jsoncpp_x64d.lib")
#else
#pragma comment(lib, "jsoncpp/jsoncpp_x64.lib")
#endif
#endif
namespace McpInternal {
std::string JsonToString(const Json::Value& v) {
Json::StreamWriterBuilder b;
b["indentation"] = "";
return Json::writeString(b, v);
}
std::string BuildResult(const Json::Value& id, const Json::Value& result) {
Json::Value resp(Json::objectValue);
resp["jsonrpc"] = "2.0";
resp["id"] = id;
resp["result"] = result;
return JsonToString(resp);
}
std::string BuildError(const Json::Value& id, int code, const std::string& msg) {
Json::Value resp(Json::objectValue);
resp["jsonrpc"] = "2.0";
resp["id"] = id;
Json::Value err(Json::objectValue);
err["code"] = code;
err["message"] = msg;
resp["error"] = err;
return JsonToString(resp);
}
std::string ToLowerAscii(const std::string& s) {
std::string r = s;
for (char& c : r) if (c >= 'A' && c <= 'Z') c = (char)(c - 'A' + 'a');
return r;
}
bool ContainsCI(const std::string& haystack, const std::string& needle) {
if (needle.empty()) return true;
return ToLowerAscii(haystack).find(ToLowerAscii(needle)) != std::string::npos;
}
std::string JsonStrField(const Json::Value& v, const char* key) {
if (v.isObject() && v.isMember(key) && v[key].isString())
return v[key].asString();
return "";
}
bool IsDigits(const std::string& s) {
if (s.empty()) return false;
for (char c : s) if (c < '0' || c > '9') return false;
return true;
}
std::string GetStringArg(const Json::Value& args, const char* key) {
return JsonStrField(args, key);
}
bool GetIntArg(const Json::Value& args, const char* key, int& out) {
if (!args.isMember(key)) return false;
const Json::Value& v = args[key];
if (v.isNumeric()) { out = v.asInt(); return true; }
if (v.isString()) {
const std::string s = v.asString();
if (IsDigits(s) || (!s.empty() && s[0] == '-' && IsDigits(s.substr(1)))) {
out = atoi(s.c_str());
return true;
}
}
return false;
}
bool ReadUInt64(const Json::Value& v, uint64_t& out) {
if (v.isNumeric()) { out = v.asUInt64(); return true; }
if (v.isString()) {
std::string s = v.asString();
if (IsDigits(s)) { out = strtoull(s.c_str(), nullptr, 10); return true; }
}
return false;
}
bool ReadUInt64Arg(const Json::Value& args, const char* key, uint64_t& out) {
if (!args.isMember(key)) return false;
return ReadUInt64(args[key], out);
}
bool ParseHostIdArg(const Json::Value& args, uint64_t& out, std::string& err) {
std::string sid = GetStringArg(args, "id");
if (sid.empty()) {
err = "Missing required parameter: id";
return false;
}
if (!IsDigits(sid)) {
err = "Invalid id: expected a decimal host id string";
return false;
}
out = strtoull(sid.c_str(), nullptr, 10);
return true;
}
context* FindMainContext(CMy2015RemoteDlg* parent, uint64_t id) {
if (!parent) return nullptr;
context* found = nullptr;
EnterCriticalSection(&parent->m_cs);
for (context* ctx : parent->m_HostList) {
if (ctx && ctx->GetClientID() == id && ctx->IsLogin()) {
found = ctx;
break;
}
}
LeaveCriticalSection(&parent->m_cs);
return found;
}
size_t BoundedStrlen(const char* p, size_t avail) {
size_t n = 0;
while (n < avail && p[n]) ++n;
return n;
}
std::string ToUtf8(const char* s, UINT cp) {
if (!s || !*s) return "";
int wlen = MultiByteToWideChar(cp, 0, s, -1, NULL, 0);
if (wlen <= 0) return "";
std::wstring w(wlen - 1, L'\0');
MultiByteToWideChar(cp, 0, s, -1, &w[0], wlen);
int u8len = WideCharToMultiByte(CP_UTF8, 0, w.c_str(), -1, NULL, 0, NULL, NULL);
if (u8len <= 0) return "";
std::string out(u8len - 1, '\0');
WideCharToMultiByte(CP_UTF8, 0, w.c_str(), -1, &out[0], u8len, NULL, NULL);
return out;
}
std::string ToAnsi(const std::string& utf8, UINT cp) {
if (utf8.empty()) return "";
int wlen = MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), (int)utf8.size(), NULL, 0);
if (wlen <= 0) return utf8;
std::wstring w(wlen, L'\0');
MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), (int)utf8.size(), &w[0], wlen);
int alen = WideCharToMultiByte(cp, 0, w.c_str(), wlen, NULL, 0, NULL, NULL);
if (alen <= 0) return utf8;
std::string out(alen, '\0');
WideCharToMultiByte(cp, 0, w.c_str(), wlen, &out[0], alen, NULL, NULL);
return out;
}
bool Utf8ToCpExact(const std::string& utf8, UINT cp, std::string& out) {
out.clear();
if (utf8.empty()) return true;
int wlen = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.c_str(), (int)utf8.size(), NULL, 0);
if (wlen <= 0) return false;
std::wstring w(wlen, L'\0');
if (MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.c_str(), (int)utf8.size(),
&w[0], wlen) != wlen)
return false;
BOOL usedDefault = FALSE;
int alen = WideCharToMultiByte(cp, WC_NO_BEST_FIT_CHARS, w.c_str(), wlen, NULL, 0, NULL, &usedDefault);
if (alen <= 0 || usedDefault) return false;
out.assign(alen, '\0');
usedDefault = FALSE;
if (WideCharToMultiByte(cp, WC_NO_BEST_FIT_CHARS, w.c_str(), wlen, &out[0], alen,
NULL, &usedDefault) != alen || usedDefault) {
out.clear();
return false;
}
return true;
}
bool IsValidUtf8(const char* s, size_t n) {
if (!s || n == 0) return true;
int wlen = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, s, (int)n, NULL, 0);
return wlen > 0;
}
void AuditManageAction(CMy2015RemoteDlg* parent, uint64_t devId,
const std::string& tool, const std::string& detail) {
if (!parent) return;
std::string text = "host " + std::to_string(devId) + " " + tool + ": " + detail;
parent->PostMessageA(WM_SHOWERRORMSG,
(WPARAM)new CString(ToAnsi(text, 936).c_str()),
(LPARAM)new CString(_TR("MCP管理操作")));
}
void AuditChatAction(CMy2015RemoteDlg* parent, uint64_t devId,
const std::string& tool, const std::string& detail) {
if (!parent) return;
std::string text = "host " + std::to_string(devId) + " " + tool + ": " + detail;
parent->PostMessageA(WM_SHOWERRORMSG,
(WPARAM)new CString(ToAnsi(text, 936).c_str()),
(LPARAM)new CString(_TR("MCP远程交谈")));
}
} // namespace McpInternal
+71
View File
@@ -0,0 +1,71 @@
#pragma once
// MCP 工具实现共享的内部辅助函数。
//
// 这些函数原先都定义在 McpServer.cpp 的匿名命名空间里;主机管理 / 连接管理
// 工具族(McpMachine.cpp)需要复用同一套 JSON、host id 解析与编码转换逻辑,
// 故抽出到独立编译单元,由 McpServer.cpp 与 McpMachine.cpp 共同引用。
//
// 约定:函数语义与实现与抽取前完全一致(McpServer.cpp 通过 using-directive
// 引入,调用点不变),不做行为改动。
#include <Windows.h>
#include "jsoncpp/json.h"
#include <string>
#include <cstdint>
class CMy2015RemoteDlg;
class context;
namespace McpInternal {
// Json::Value → 紧凑 JSON 字符串
std::string JsonToString(const Json::Value& v);
// JSON-RPC 2.0 成功 / 错误响应
std::string BuildResult(const Json::Value& id, const Json::Value& result);
std::string BuildError(const Json::Value& id, int code, const std::string& msg);
// 仅 ASCII 小写化;不区分大小写的子串匹配
std::string ToLowerAscii(const std::string& s);
bool ContainsCI(const std::string& haystack, const std::string& needle);
// 入参读取
std::string JsonStrField(const Json::Value& v, const char* key);
bool IsDigits(const std::string& s);
std::string GetStringArg(const Json::Value& args, const char* key);
bool GetIntArg(const Json::Value& args, const char* key, int& out);
bool ReadUInt64(const Json::Value& v, uint64_t& out);
bool ReadUInt64Arg(const Json::Value& args, const char* key, uint64_t& out);
// 解析 id 入参(必填、纯数字)为 uint64;非法返回 false 并写 err。
bool ParseHostIdArg(const Json::Value& args, uint64_t& out, std::string& err);
// 在 m_HostList 中按 clientID 找在线主 context(锁内遍历 m_cs)。
context* FindMainContext(CMy2015RemoteDlg* parent, uint64_t id);
// 有界 strlen:p 最多可读 avail 字节,返回 n < avail 表示遇到 '\0'。
size_t BoundedStrlen(const char* p, size_t avail);
// 编码转换:任意代码页 → UTF-8(输出 JSON 用);UTF-8 → 目标代码页(下发客户端用)。
std::string ToUtf8(const char* s, UINT cp);
std::string ToAnsi(const std::string& utf8, UINT cp);
// 严格 UTF-8 → 目标代码页:任一字符无法表示即失败(不用 '?' 顶替)。
// UTF-8 本身非法也失败。聊天消息用它拒绝 GBK 不可表示的字符(emoji 等)。
bool Utf8ToCpExact(const std::string& utf8, UINT cp, std::string& out);
// 校验字节串是否为合法 UTF-8(n=0 视为合法)。
bool IsValidUtf8(const char* s, size_t n);
// 写操作审计:PostMessageA(WM_SHOWERRORMSG) 落到服务端消息/审计日志(不可关闭)。
void AuditManageAction(CMy2015RemoteDlg* parent, uint64_t devId,
const std::string& tool, const std::string& detail);
// 远程交谈审计:与 AuditManageAction 同落地方式,标题区分(MCP远程交谈)。
// 只记录会话 id / 字节数,绝不记录消息正文。
void AuditChatAction(CMy2015RemoteDlg* parent, uint64_t devId,
const std::string& tool, const std::string& detail);
} // namespace McpInternal
File diff suppressed because it is too large. Load diff
+31
View File
@@ -0,0 +1,31 @@
#pragma once
// 主机管理(10 个标签页)与连接管理(连接列表 / 强制断开)MCP 工具族。
//
// 协议(详见 docs/Mcp_Machine_Design.md):
// 主机管理:主连接 COMMAND_MACHINE_MANAGE(162) → 客户端 MachineManager 子连接回
// TOKEN_SYSINFOLIST(61) → 发 1 字节 tab(0..9) → 回 TOKEN_MACHINE_*(31..42)。
// 连接管理:主连接 COMMAND_CONNECTION(253) → CConnectionsManager 子连接回
// TOKEN_CONNECTION_LIST(255) → 发 254+原始 110 字节记录强制断开。
//
// 会话状态由 CMcpServer 持有(与 m_Pending 共用单飞行表),本模块只负责工具 schema、
// 参数校验、组包与解析。
#include "jsoncpp/json.h"
#include <string>
class CMy2015RemoteDlg;
namespace McpMachine {
// 是否由本模块处理(AppendTools 与 Call 必须保持一致)。
bool Handles(const std::string& toolName);
// 按当前开关(McpMachine / McpMachineDangerous / McpReadonly)追加可见工具。
void AppendTools(Json::Value& tools);
// 执行工具;返回完整 JSON-RPC 响应字符串(成功 = BuildResult,失败 = BuildError)。
std::string Call(const Json::Value& id, const std::string& toolName,
const Json::Value& args, CMy2015RemoteDlg* parent);
} // namespace McpMachine
+38 -176
View File
@@ -8,6 +8,9 @@
#include "Server.h" // CONTEXT_OBJECT 定义(GetScreenContext 返回 CONTEXT_OBJECT* → context* 上转型)
#include "LangManager.h" // _TR(审计日志标题语言映射)
#include "common/file_upload.h" // V2 文件传输(RecvFileChunkV2 / HandleFileCompleteV2 / 包结构)
#include "McpInternal.h" // 共享助手(McpMachine.cpp 也使用)
#include "McpMachine.h" // 主机管理 / 连接管理工具族
#include "McpChat.h" // 远程交谈工具族
#include <sstream>
@@ -30,39 +33,15 @@
std::string GetPwdHash();
std::string GetHMAC(int offset);
// 共享助手(JsonToString/BuildResult/ParseHostIdArg/FindMainContext/ToUtf8/ToAnsi/...)
// 已抽到 McpInternal.cpp;此处引入后调用点保持原样。
using namespace McpInternal;
namespace {
// P2b 工具等待响应的超时(ms)。MCP 一次性请求:等待子连接回传进程/窗口列表。
static const int kMcpToolTimeoutMs = 20000;
// Json::Value → 紧凑 JSON 字符串
std::string JsonToString(const Json::Value& v) {
Json::StreamWriterBuilder b;
b["indentation"] = "";
return Json::writeString(b, v);
}
// JSON-RPC 2.0 成功响应
std::string BuildResult(const Json::Value& id, const Json::Value& result) {
Json::Value resp(Json::objectValue);
resp["jsonrpc"] = "2.0";
resp["id"] = id;
resp["result"] = result;
return JsonToString(resp);
}
// JSON-RPC 2.0 错误响应
std::string BuildError(const Json::Value& id, int code, const std::string& msg) {
Json::Value resp(Json::objectValue);
resp["jsonrpc"] = "2.0";
resp["id"] = id;
Json::Value err(Json::objectValue);
err["code"] = code;
err["message"] = msg;
resp["error"] = err;
return JsonToString(resp);
}
// initialize 握手(MCP 规范:protocolVersion + capabilities + serverInfo)
std::string BuildInitializeResult(const Json::Value& id) {
Json::Value result(Json::objectValue);
@@ -84,33 +63,6 @@ std::string BuildPingResult(const Json::Value& id) {
// ========== P2a 通用辅助 ==========
// 小写化(仅 ASCII,UTF-8 多字节原样保留):用于不区分大小写的子串匹配
std::string ToLowerAscii(const std::string& s) {
std::string r = s;
for (char& c : r) if (c >= 'A' && c <= 'Z') c = (char)(c - 'A' + 'a');
return r;
}
// 不区分大小写的子串匹配
bool ContainsCI(const std::string& haystack, const std::string& needle) {
if (needle.empty()) return true;
return ToLowerAscii(haystack).find(ToLowerAscii(needle)) != std::string::npos;
}
// 取对象的字符串字段,缺失/非字符串返回 ""
std::string JsonStrField(const Json::Value& v, const char* key) {
if (v.isObject() && v.isMember(key) && v[key].isString())
return v[key].asString();
return "";
}
// 是否纯数字(host id 为 uint64 十进制字符串)
bool IsDigits(const std::string& s) {
if (s.empty()) return false;
for (char c : s) if (c < '0' || c > '9') return false;
return true;
}
// 读取 tools/call 的入参(MCP 规范:params.arguments 为工具入参对象)
Json::Value GetCallArguments(const Json::Value& params) {
if (params.isObject() && params.isMember("arguments") && params["arguments"].isObject())
@@ -118,85 +70,8 @@ Json::Value GetCallArguments(const Json::Value& params) {
return Json::Value(Json::objectValue);
}
// 读取可选字符串入参,缺失返回 ""
std::string GetStringArg(const Json::Value& args, const char* key) {
return JsonStrField(args, key);
}
// 读取可选整数入参(JSON number 或数字字符串);缺失/非法返回 false(不写 out)。
// 定义见文件后半段(随 P3 终端会话辅助一起),此处前置声明供早于定义的 exec_command /
// terminal_exec 等工具复用。
static bool GetIntArg(const Json::Value& args, const char* key, int& out);
// ========== P2b 辅助 ==========
// 解析 id 入参(必填、纯数字)为 uint64;非法返回 false。
bool ParseHostIdArg(const Json::Value& args, uint64_t& out, std::string& err) {
std::string sid = GetStringArg(args, "id");
if (sid.empty()) {
err = "Missing required parameter: id";
return false;
}
if (!IsDigits(sid)) {
err = "Invalid id: expected a decimal host id string";
return false;
}
out = strtoull(sid.c_str(), nullptr, 10);
return true;
}
// 在 m_HostList 中按 clientID 找在线主 context(复刻 CollectOnlineHosts 的锁内遍历)。
context* FindMainContext(CMy2015RemoteDlg* parent, uint64_t id) {
if (!parent) return nullptr;
context* found = nullptr;
EnterCriticalSection(&parent->m_cs);
for (context* ctx : parent->m_HostList) {
if (ctx && ctx->GetClientID() == id && ctx->IsLogin()) {
found = ctx;
break;
}
}
LeaveCriticalSection(&parent->m_cs);
return found;
}
// 有界 strlen:p 最多可读 avail 字节,返回 n < avail 表示遇到 '\0'。
size_t BoundedStrlen(const char* p, size_t avail) {
size_t n = 0;
while (n < avail && p[n]) ++n;
return n;
}
// 从源编码 cp 转为 UTF-8(输出到 JSON)。空/失败返回 ""。
std::string ToUtf8(const char* s, UINT cp) {
if (!s || !*s) return "";
int wlen = MultiByteToWideChar(cp, 0, s, -1, NULL, 0);
if (wlen <= 0) return "";
std::wstring w(wlen - 1, L'\0');
MultiByteToWideChar(cp, 0, s, -1, &w[0], wlen);
int u8len = WideCharToMultiByte(CP_UTF8, 0, w.c_str(), -1, NULL, 0, NULL, NULL);
if (u8len <= 0) return "";
std::string out(u8len - 1, '\0');
WideCharToMultiByte(CP_UTF8, 0, w.c_str(), -1, &out[0], u8len, NULL, NULL);
return out;
}
// 从 UTF-8 转为目标编码 cp(文件链路的目录路径在 Windows 走 ANSI,与 FileManagerDlg 的
// CString 一致;cp 按 clientType 判定:Windows=936、LNX/MAC=CP_UTF8,见 BuildListFiles)。
// 非 UTF-8(如纯 ASCII)失败时原样返回。
std::string ToAnsi(const std::string& utf8, UINT cp) {
if (utf8.empty()) return "";
int wlen = MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), (int)utf8.size(), NULL, 0);
if (wlen <= 0) return utf8;
std::wstring w(wlen, L'\0');
MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), (int)utf8.size(), &w[0], wlen);
int alen = WideCharToMultiByte(cp, 0, w.c_str(), wlen, NULL, 0, NULL, NULL);
if (alen <= 0) return utf8;
std::string out(alen, '\0');
WideCharToMultiByte(cp, 0, w.c_str(), wlen, &out[0], alen, NULL, NULL);
return out;
}
// 从 "title|status|pid|r1|r2" 解析(自末尾 4 个 '|' 反推),兼容只有标题的老客户端。
// 逻辑复刻 SystemDlg.cpp::ParseWindowAttrs。
void ParseWindowAttrsStr(const char* s, std::string& title, std::string& status, uint64_t& pid) {
@@ -647,6 +522,10 @@ Json::Value BuildHostItemSchema() {
Json::Value onlineProp(Json::objectValue);
onlineProp["type"] = "boolean";
itemProps["online"] = onlineProp;
// 客户端登录时上报的 TLS 传输标志(老客户端恒为 false)
Json::Value tlsProp(Json::objectValue);
tlsProp["type"] = "boolean";
itemProps["tls"] = tlsProp;
return itemProps;
}
@@ -1311,7 +1190,7 @@ std::string BuildToolsListResult(const Json::Value& id) {
tool["name"] = "list_online_hosts";
// 说明文字为 UTF-8:项目 /execution-charset:.936 会把普通窄字面量编译成 GBK,
// 故用 u8 前缀确保输出到 JSON 的字节是 UTF-8。
tool["description"] = u8"获取当前所有在线主机的列表,包含计算机名、IP、操作系统、版本、备注、分组、活动窗口、延迟等实时信息。";
tool["description"] = u8"获取当前所有在线主机的列表,包含计算机名、IP、操作系统、版本、备注、分组、活动窗口、延迟等实时信息。tls=true 表示该客户端登录时使用了 TLS 加密传输(登录时上报,非实时探测;老客户端恒为 false)。";
Json::Value inputSchema(Json::objectValue);
inputSchema["type"] = "object";
@@ -1328,7 +1207,7 @@ std::string BuildToolsListResult(const Json::Value& id) {
{
Json::Value tool(Json::objectValue);
tool["name"] = "search_hosts";
tool["description"] = u8"按计算机名/备注、IP、分组、操作系统过滤在线主机。所有条件均可选、按 AND 组合;子串匹配(ASCII 不区分大小写)。只返回在线主机。";
tool["description"] = u8"按计算机名/备注、IP、分组、操作系统过滤在线主机。所有条件均可选、按 AND 组合;子串匹配(ASCII 不区分大小写)。只返回在线主机。tls=true 表示该客户端登录时使用了 TLS 加密传输(登录时上报,老客户端恒为 false)。";
tool["inputSchema"] = BuildSearchHostsInputSchema();
tool["outputSchema"] = BuildHostOutputSchema();
@@ -1340,7 +1219,7 @@ std::string BuildToolsListResult(const Json::Value& id) {
{
Json::Value tool(Json::objectValue);
tool["name"] = "get_host_detail";
tool["description"] = u8"获取单台在线主机的详细信息(id、计算机名、IP、操作系统、备注、分组、活动窗口、屏幕分辨率、客户端类型等)。";
tool["description"] = u8"获取单台在线主机的详细信息(id、计算机名、IP、操作系统、备注、分组、活动窗口、屏幕分辨率、客户端类型等)。tls=true 表示该客户端登录时使用了 TLS 加密传输(登录时上报,老客户端恒为 false)。";
tool["inputSchema"] = BuildGetHostDetailInputSchema();
tool["outputSchema"] = BuildHostDetailOutputSchema();
@@ -1607,6 +1486,15 @@ std::string BuildToolsListResult(const Json::Value& id) {
}
}
// 19) 连接管理 / 主机管理(P8:list_network_connections / kill_network_connection /
// host_* 共 16 个工具)。开关在 McpMachine.cpp 内部按 McpMachine /
// McpMachineDangerous / McpReadonly 逐项判断,关闭时不追加任何工具。
McpMachine::AppendTools(tools);
// 20) 远程交谈(P9:chat_open / chat_send / chat_wait / chat_close)。
// 独立开关 McpChat(默认关),与 McpReadonly 无关;关闭时不追加任何工具。
McpChat::AppendTools(tools);
result["tools"] = tools;
return BuildResult(id, result);
}
@@ -3366,21 +3254,6 @@ static bool GetNormCoord(const Json::Value& args, const char* key, double& out,
return true;
}
// 读取可选整数参数(JSON number 或数字字符串);缺失/非法返回 false(不写 out)。
static bool GetIntArg(const Json::Value& args, const char* key, int& out) {
if (!args.isMember(key)) return false;
const Json::Value& v = args[key];
if (v.isNumeric()) { out = v.asInt(); return true; }
if (v.isString()) {
const std::string s = v.asString();
if (IsDigits(s) || (!s.empty() && s[0] == '-' && IsDigits(s.substr(1)))) {
out = atoi(s.c_str());
return true;
}
}
return false;
}
// button 字符串 → 0=左/1=中/2=右;空或 left 默认左。
static bool ParseButton(const std::string& s, int& out) {
if (s.empty() || s == "left") { out = 0; return true; }
@@ -4351,31 +4224,6 @@ std::string BuildUploadFile(const Json::Value& id, const Json::Value& args, CMy2
// ========== P7:设备管理控制 ==========
// 读取 JSON number 或纯数字字符串为 uint64。
static bool ReadUInt64(const Json::Value& v, uint64_t& out) {
if (v.isNumeric()) { out = v.asUInt64(); return true; }
if (v.isString()) {
std::string s = v.asString();
if (IsDigits(s)) { out = strtoull(s.c_str(), nullptr, 10); return true; }
}
return false;
}
static bool ReadUInt64Arg(const Json::Value& args, const char* key, uint64_t& out) {
if (!args.isMember(key)) return false;
return ReadUInt64(args[key], out);
}
// 写审计(杀进程/窗口/服务/电源共用):PostMessageA 落到服务端消息/审计日志(不可关闭)。
static void AuditManageAction(CMy2015RemoteDlg* parent, uint64_t devId,
const std::string& tool, const std::string& detail) {
if (!parent) return;
std::string text = "host " + std::to_string(devId) + " " + tool + ": " + detail;
parent->PostMessageA(WM_SHOWERRORMSG,
(WPARAM)new CString(ToAnsi(text, 936).c_str()),
(LPARAM)new CString(_TR("MCP管理操作")));
}
// kill_process:主连接 COMMAND_SYSTEM → 系统子连接 TOKEN_PSLIST(就绪)→ COMMAND_KILLPROCESS
// → 补发 COMMAND_PSLIST → 第二个 TOKEN_PSLIST(确认)。payload 与 SystemDlg::OnPlistKill 一致。
std::string BuildKillProcess(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
@@ -4687,6 +4535,12 @@ std::string BuildToolsCall(const Json::Value& root, CMy2015RemoteDlg* parent) {
const Json::Value args = GetCallArguments(params);
// P8:连接管理 / 主机管理工具族(独立分发;门控在 McpMachine::Call 内复核)。
if (McpMachine::Handles(toolName)) return McpMachine::Call(id, toolName, args, parent);
// P9:远程交谈工具族(独立开关 McpChat;门控在 McpChat::Call 内复核)。
if (McpChat::Handles(toolName)) return McpChat::Call(id, toolName, args, parent);
if (toolName == "list_online_hosts") return BuildListOnlineHosts(id, parent);
if (toolName == "search_hosts") return BuildSearchHosts(id, args, parent);
if (toolName == "get_host_detail") return BuildGetHostDetail(id, args, parent);
@@ -5225,13 +5079,18 @@ void CMcpServer::HandleMcp(const httplib::Request& req, httplib::Response& res)
bool CMcpServer::IsPending(uint64_t device_id) {
std::lock_guard<std::mutex> lk(m_PendingMutex);
return m_Pending.find(device_id) != m_Pending.end();
auto it = m_Pending.find(device_id);
if (it == m_Pending.end()) return false;
// P8:主机管理/连接管理会话的响应包走 OnManagedSubPacket,不归 MFC 的
// TOKEN_PSLIST/TOKEN_WSLIST/SERVERLIST/DRIVE_LIST 分支消费(否则会抢走 UI 包)。
return it->second.kind == PendingKind::Generic || it->second.kind == PendingKind::FollowUp;
}
void CMcpServer::TakeMainResponse(uint64_t device_id, const BYTE* data, ULONG len) {
std::lock_guard<std::mutex> lk(m_PendingMutex);
auto it = m_Pending.find(device_id);
if (it == m_Pending.end()) { Mprintf("[MCP-P7] TakeMainResponse dev=%llu len=%d: no pending (late/dropped)\n", device_id, (int)len); return; } // 已超时清理 → 迟到数据,丢弃
if (it->second.kind != PendingKind::Generic && it->second.kind != PendingKind::FollowUp) return; // P8 会话:不接管
Mprintf("[MCP-P7] TakeMainResponse dev=%llu len=%d done\n", device_id, (int)len);
it->second.data.assign(data, data + len);
it->second.done = true;
@@ -5416,6 +5275,7 @@ bool CMcpServer::BeginPendingFollowUp(uint64_t device_id, const std::string& too
if (m_Pending.find(device_id) != m_Pending.end()) return false; // 设备忙
PendingRequest r;
r.tool = tool;
r.kind = PendingKind::FollowUp;
r.followUp = followUp;
m_Pending[device_id] = std::move(r);
return true;
@@ -5501,6 +5361,8 @@ void CMcpServer::OnManageSubClosed(context* subCtx) {
// 扫描而非按 device_id 查找,避免依赖断线后 GetClientID 是否仍有效。
for (auto& kv : m_Pending) {
if (kv.second.subCtx == subCtx) {
// P8 会话由 OnManagedContextClosed 处理(这里若清 subCtx 会让其无法按指针反查设备)。
if (kv.second.kind == PendingKind::Machine || kv.second.kind == PendingKind::ConnMgr) continue;
Mprintf("[MCP-P7] OnManageSubClosed subCtx=%p tool=%s: sub-conn closed before confirm\n",
(void*)subCtx, kv.second.tool.c_str());
kv.second.subCtx = nullptr; // 断线后子连接已死/将回收,超时路径不得再 CancelIO
+177
View File
@@ -10,6 +10,8 @@
#include <map>
#include <set>
#include <vector>
#include <deque>
#include <memory>
#include <cstdint>
#include <ctime>
@@ -37,6 +39,14 @@ struct FileTransferEntry {
std::string sha256;
};
// 远程交谈消息(chat_wait 输出 messages[] 的一项)。
// text 为 UTF-8;at 为收到消息的 Unix 秒;id 为会话内单调递增序号。
struct ChatMessage {
uint64_t id = 0;
int64_t at = 0;
std::string text;
};
// MCP (Model Context Protocol) 服务端:httplib 封装 + JSON-RPC 2.0 分发 + 静态 token 校验。
// 与 CWebService 平级、互不依赖;默认禁用,经「扩展 → MCP设置」开启后监听
// (默认 127.0.0.1:6544,仅本机回环)。见 docs/Mcp_Design.md。
@@ -270,6 +280,92 @@ public:
// 超时路径不会对已回收(连接池复用)的 context 误 CancelIO。
void OnManageSubClosed(context* subCtx);
// ===== P8:主机管理 / 连接管理(子连接会话)=====
// 协议:主连接下发 COMMAND_MACHINE_MANAGE(162) / COMMAND_CONNECTION(253) → 客户端新建
// 子连接 → 子连接回就绪包(TOKEN_SYSINFOLIST=61 / TOKEN_CONNECTION_LIST=255)→ 在同一
// 子连接上多步收发。会话复用 m_Pending 表(统一「单设备单飞行」),kind 区分工具族。
// 见 docs/Mcp_Machine_Design.md。
void SetMachineEnabled(bool enabled) { m_machineEnabled = enabled; }
bool IsMachineEnabled() const { return m_machineEnabled; }
void SetMachineDangerousEnabled(bool enabled) { m_machineDangerousEnabled = enabled; }
bool IsMachineDangerousEnabled() const { return m_machineDangerousEnabled; }
// MessageHandle 顶部钩子(终端拦截之后、switch 之前):true = 本包已由 MCP 消费。
// 已绑定的子连接:只保存期望 token 的包与 TOKEN_MACHINE_MSG(42),其余丢弃。
// 未绑定的子连接:仅 61/255 可作为就绪包尝试绑定;否则返回 false(MFC 行为不变)。
bool OnManagedSubPacket(context* subCtx, const BYTE* data, ULONG len);
// OfflineProc 钩子:接管的子连接断开 → 置 closed 唤醒等待者(幂等)。
void OnManagedContextClosed(context* subCtx);
// 工具线程:登记会话(false = 该设备已有挂起请求在飞 → 设备忙)。
bool BeginMachineSession(uint64_t device_id, const std::string& tool, context* mainCtx);
bool BeginConnMgrSession(uint64_t device_id, const std::string& tool, context* mainCtx);
// 工具线程:发命令前清空上一次响应并登记期望 token。
void ArmManagedResponse(uint64_t device_id, BYTE expectedToken);
// 工具线程:等待子连接就绪包 / 指定 token 的响应(超时由调用方按步给)。
enum class ManagedWaitResult { Ok, Timeout, Closed, ClientError };
ManagedWaitResult WaitManagedPacket(uint64_t device_id, BYTE token,
std::vector<BYTE>& out, context*& subCtxOut,
int timeoutMs, std::string& clientError);
// 工具线程:结束会话;cancelIo = 关闭子连接;markOrphan = 打 5s 墓碑
// (吸收迟到的 61/255,避免超时后弹出 MFC 对话框)。
void EndManagedSession(uint64_t device_id, bool cancelIo, bool markOrphan);
// ===== P9:远程交谈(chat_open / chat_send / chat_wait / chat_close)=====
// 复用 Windows 客户端既有「远程交谈」:主连接下发 COMMAND_CHAT(161) → 客户端新建子连接
// (先 TOKEN_CONN_AUTH(246) 再 TOKEN_CHAT_START(62))→ 服务端在该子连接回
// COMMAND_NEXT_CHAT(0) → 客户端弹 IDD_CHAT。之后双向文本为 raw CP936 + NUL。
// 协议不变(客户端聊天窗口已改为 Unicode 对话框,仅影响显示);独立 m_ChatMutex,
// 不与 P8 的 m_Pending 共享(不受单设备单飞行约束)。
// 见 docs/Mcp_Chat_Design.md。
void SetChatEnabled(bool enabled) { m_chatEnabled = enabled; }
bool IsChatEnabled() const { return m_chatEnabled; }
// MessageHandle 顶部钩子(MCP 终端之后、P8 之前:聊天文本首字节可能是 61/255/246)。
// true = 本包已由 MCP 消费。未绑定子连接上的 246(TOKEN_CONN_AUTH) 走快速路径返回
// false,交给认证分支;已绑定子连接上的 0xF6 前导字节文本则由本函数消费。
bool OnChatSubPacket(context* subCtx, const BYTE* data, ULONG len);
// OfflineProc 钩子:接管的子连接断开 → 会话 closed + 清路由 + 唤醒等待者(幂等)。
void OnChatContextClosed(context* subCtx);
// 工具线程:登记会话并发 COMMAND_CHAT 之后调用。false = 该设备已有未关闭会话(-32003)。
bool BeginChatOpen(uint64_t device_id, context* mainCtx, const std::string& sessionId);
// 工具线程:等待客户端子连接就绪且建窗等待期满(readyAt)。
enum class ChatReadyResult { Ok, Timeout, Closed, NotFound };
ChatReadyResult WaitChatReady(uint64_t device_id, const std::string& sessionId, int timeoutMs);
// 工具线程:发送前登记(校验 sessionId/started/readyAt/sendBusy)。输出 subCtx。
// 返回:0=ok;1=不存在/不匹配/未就绪/已关;2=忙。
int BeginChatSend(uint64_t device_id, const std::string& sessionId, context*& subCtx);
// 工具线程:发送结束(清 sendBusy)。closed 期间发送失败时调用方仍须调用。
void FinishChatSend(uint64_t device_id, const std::string& sessionId);
// 工具线程:取走最多 maxMessages 条;inbox 为空则等到 deadline / closed。
enum class ChatWaitResult { Ok, Timeout, Closed, NotFound, Mismatch, Busy };
ChatWaitResult WaitChatMessages(uint64_t device_id, const std::string& sessionId,
int timeoutMs, size_t maxMessages,
std::vector<ChatMessage>& out, bool& timedOut,
bool& closed, int& dropped);
// 关闭会话(校验 sessionId;标记 closed + 清路由 + 唤醒)。返回 0=已关;1=不存在(幂等);
// 2=sessionId 不匹配。子连接 [1] 与 CancelIO 由调用方在锁外执行。
int CloseChatSession(uint64_t device_id, const std::string& sessionId,
context*& subCtxOut, bool& hadSession);
// chat_open 超时/失败收尾:标记 closed + 清路由;已绑定子连接写入 subCtxOut(调用方 CancelIO),
// 未绑定则打 device/peer 5s 墓碑,吸收迟到的 62(避免超时后弹出 MFC 对话框)。
void AbortChatOpen(uint64_t device_id, context*& subCtxOut, bool& hadSession);
// idle 回收:关闭 lastActiveAt 超时且无等待/无发送的会话。返回回收数量。
int SweepIdleChats(time_t idleTimeoutSec);
// 安全配置(启动时由 CMy2015RemoteDlg 读 THIS_CFG 后设置)。
void SetReadonly(bool readonly) { m_readonly = readonly; }
void SetCmdWhitelist(const std::string& whitelist) { m_cmdWhitelist = whitelist; }
@@ -285,6 +381,15 @@ private:
// POST /mcp 处理器:token 校验 + JSON-RPC 分发。
void HandleMcp(const httplib::Request& req, httplib::Response& res);
// 挂起请求类型:主机管理/连接管理会话与既有一次性请求共用 m_Pending 保证单设备单飞行,
// 但 MessageHandle 的 P2b/P3/P7 拦截分支(IsPending/TakeMainResponse)必须把这两类排除,
// 否则用户手动打开对话框时 UI 包会被 MCP 抢走。
enum class PendingKind { Generic, FollowUp, Machine, ConnMgr };
static bool KindAcceptsToken(PendingKind kind, BYTE token);
bool BeginManagedSession(uint64_t device_id, const std::string& tool,
PendingKind kind, context* mainCtx);
httplib::Server m_server;
std::thread m_thread;
std::atomic<bool> m_running{false};
@@ -306,11 +411,43 @@ private:
std::vector<BYTE> followUp; // 接管后下发的写命令 payload(首字节 = 写命令)
bool followUpSent = false; // false=等子连接就绪(首包);true=已发写命令、等确认包
context* subCtx = nullptr; // 接管的子连接(超时/失败 CancelIO 用,防孤儿子连接)
// ===== P8:主机管理 / 连接管理会话(kind = Machine / ConnMgr 时有效)=====
PendingKind kind = PendingKind::Generic;
context* mainCtx = nullptr; // Begin 时抓取的主连接(只作身份校验,不从其收发)
std::string peer; // mainCtx->GetPeerName()(老客户端子连接 ID=0 时兜底)
BYTE expectedToken = 0; // 期望的响应 token(0 = 未设置)
bool hasResponse = false;
std::vector<BYTE> response; // 含首字节 token
std::string clientError; // TOKEN_MACHINE_MSG(42) 文本(已转 UTF-8)
bool closed = false; // 子连接在等待期间断开
std::chrono::steady_clock::time_point deadline; // 整个会话的截止时间
};
std::mutex m_PendingMutex;
std::condition_variable m_PendingCv;
std::map<uint64_t, PendingRequest> m_Pending;
// ===== P8:子连接路由(受 m_PendingMutex 保护)=====
// 已绑定子连接 → device(该子连接的一切包都由 MCP 消费)。
std::map<context*, uint64_t> m_SubCtxToDevice;
// CancelIO 之后仍可能到达的包:静默丢弃(避免子连接回收前的尾巴包弹对话框)。
std::set<context*> m_AbsorbedSubCtx;
// 会话异常结束后 5s 内的迟到就绪包墓碑(device / peer 两个维度)。
struct OrphanMark {
std::chrono::steady_clock::time_point expiry;
PendingKind kind = PendingKind::Generic;
};
std::map<uint64_t, OrphanMark> m_OrphanByDevice;
std::map<std::string, OrphanMark> m_OrphanByPeer;
// 清理过期墓碑(持 m_PendingMutex 调用)。
void PruneOrphanMarksLocked(std::chrono::steady_clock::time_point now);
// 路由表大小(已绑定 + 已吸收的子连接数)。MessageHandle 每个包都会调用
// OnManagedSubPacket,若无会话在飞则用它无锁快速返回,避免音频/屏幕等高频
// 子连接逐包争用 m_PendingMutex。只在持锁时更新(store)。
std::atomic<int> m_ManagedRoutes{0};
void RefreshManagedRoutesLocked();
// get_screenshot 的 reqId 发生器(16 位,跳过 0)。与 MFC 预览的 m_PreviewReqId 各自独立计数。
std::atomic<uint16_t> m_PreviewReqId{1};
@@ -375,12 +512,52 @@ private:
std::condition_variable m_FileXferCv;
std::map<uint64_t, FileTransferSession> m_FileXferSessions; // device_id → 会话
// ===== P9:远程交谈(受 m_ChatMutex 保护;单设备单会话)=====
// 用 shared_ptr 持有会话:chat_wait / chat_send 在工作线程里复制一份后,即使 map 条目
// 被 chat_close 或断线删除也安全,不需要额外的「迭代器有效」规则。
struct ChatSession {
std::string sessionId;
context* mainCtx = nullptr; // 主连接(仅身份校验)
uint64_t mainClientId = 0;
context* subCtx = nullptr; // 已绑定的子连接;关闭后置空
std::string peer; // GetPeerName()(老客户端 clientID=0 兜底)
bool started = false; // 已收到 TOKEN_CHAT_START 并回 [0]
bool closed = false;
bool sendBusy = false; // 同一会话串行发送
bool waitBusy = false; // 同一会话只允许一个 chat_wait
std::chrono::steady_clock::time_point readyAt; // 建窗等待期满(绑定 + 1000ms)
time_t lastActiveAt = 0;
std::deque<ChatMessage> inbox; // 未投递消息(UTF-8)
size_t inboxBytes = 0;
uint64_t nextMsgId = 1;
int dropped = 0; // inbox 溢出丢弃的条数(chat_wait 报告)
};
using ChatSessionPtr = std::shared_ptr<ChatSession>;
std::mutex m_ChatMutex;
std::condition_variable m_ChatCv;
std::map<uint64_t, ChatSessionPtr> m_ChatSessions; // device_id → 会话
std::map<context*, uint64_t> m_ChatContextToDevice; // subCtx → device_id(顶部路由)
std::set<context*> m_ChatAbsorbedSubCtx; // CancelIO 后尾巴包静默丢弃
struct ChatOrphanMark { std::chrono::steady_clock::time_point expiry; };
std::map<uint64_t, ChatOrphanMark> m_ChatOrphanByDevice; // 迟到 62 墓碑(5s)
std::map<std::string, ChatOrphanMark> m_ChatOrphanByPeer;
std::atomic<int> m_ChatRoutes{0}; // 路由集合大小(快速路径)
bool m_chatEnabled = false; // P9 开关(默认关)
// 持 m_ChatMutex 调用:只更新 m_ChatRoutes(store,relaxed 读取在锁外)。
void RefreshChatRoutesLocked();
// 持 m_ChatMutex 调用:清理过期墓碑。
void PruneChatOrphansLocked(std::chrono::steady_clock::time_point now);
bool m_readonly = true;
std::string m_cmdWhitelist;
bool m_terminalEnabled = false; // 持久终端开关(默认关;要求 m_readonly=false)
bool m_remoteControlEnabled = false; // 远程控制开关(默认关;要求 m_readonly=false)
bool m_fileTransferEnabled = false; // 文件传输开关(默认关;download_file)
bool m_manageEnabled = false; // P7 管理控制开关(默认关;要求 m_readonly=false)
bool m_machineEnabled = false; // P8 主机管理族总开关(默认关;16 个 host_* 工具)
bool m_machineDangerousEnabled = false; // P8 高风险子集(冻结/解冻进程、停止/重启服务)
};
// 全局访问器(仿 WebService(),见 WebService.h 末尾)
+47 -4
View File
@@ -106,7 +106,7 @@ INT_PTR CMcpSettingsDlg::DoModal()
{
USES_CONVERSION;
CString title = _TR("MCP设置");
BuildDialogTemplate(m_Template, T2CW(title), 320, 420);
BuildDialogTemplate(m_Template, T2CW(title), 320, 510);
InitModalIndirect((LPCDLGTEMPLATE)m_Template.data());
return CDialog::DoModal();
}
@@ -148,6 +148,15 @@ BOOL CMcpSettingsDlg::OnInitDialog()
m_btnManage.Create(_TR("启用管理操作(进程/窗口/服务/电源)"),
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
r0, this, IDC_MCP_MANAGE);
m_btnMachine.Create(_TR("启用主机管理(进程/窗口/服务/任务/网络状态)"),
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
r0, this, IDC_MCP_MACHINE);
m_btnMachineDangerous.Create(_TR("启用危险主机操作(冻结/解冻进程、停止/重启服务)"),
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
r0, this, IDC_MCP_MACHINE_DANGEROUS);
m_btnChat.Create(_TR("启用远程交谈(AI 与用户对话)"),
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
r0, this, IDC_MCP_CHAT);
m_lblWhitelist.Create(_TR("命令白名单"), WS_CHILD | WS_VISIBLE, r0, this, (UINT)-1);
m_editWhitelist.Create(WS_CHILD | WS_VISIBLE | WS_BORDER | WS_TABSTOP |
ES_MULTILINE | ES_AUTOVSCROLL | ES_WANTRETURN | WS_VSCROLL,
@@ -172,6 +181,9 @@ BOOL CMcpSettingsDlg::OnInitDialog()
m_btnRemoteControl.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_btnFileTransfer.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_btnManage.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_btnMachine.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_btnMachineDangerous.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_btnChat.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_lblWhitelist.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_editWhitelist.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_btnOK.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
@@ -189,6 +201,9 @@ BOOL CMcpSettingsDlg::OnInitDialog()
int remoteControl = THIS_CFG.GetInt("settings", "McpRemoteControl", 0);
int fileTransfer = THIS_CFG.GetInt("settings", "McpFileTransfer", 0);
int manage = THIS_CFG.GetInt("settings", "McpManage", 0);
int machine = THIS_CFG.GetInt("settings", "McpMachine", 0);
int machineDangerous = THIS_CFG.GetInt("settings", "McpMachineDangerous", 0);
int chat = THIS_CFG.GetInt("settings", "McpChat", 0);
std::string whitelist = THIS_CFG.GetStr("settings", "McpCmdWhitelist", "");
m_btnEnable.SetCheck(enabled ? BST_CHECKED : BST_UNCHECKED);
@@ -200,6 +215,9 @@ BOOL CMcpSettingsDlg::OnInitDialog()
m_btnRemoteControl.SetCheck(remoteControl ? BST_CHECKED : BST_UNCHECKED);
m_btnFileTransfer.SetCheck(fileTransfer ? BST_CHECKED : BST_UNCHECKED);
m_btnManage.SetCheck(manage ? BST_CHECKED : BST_UNCHECKED);
m_btnMachine.SetCheck(machine ? BST_CHECKED : BST_UNCHECKED);
m_btnMachineDangerous.SetCheck(machineDangerous ? BST_CHECKED : BST_UNCHECKED);
m_btnChat.SetCheck(chat ? BST_CHECKED : BST_UNCHECKED);
// 白名单存储为逗号分隔,展示为每行一条。
m_editWhitelist.SetWindowText(CString(WhitelistForDisplay(whitelist).c_str()));
@@ -220,6 +238,17 @@ void CMcpSettingsDlg::OnOK()
bool remoteControl = (m_btnRemoteControl.GetCheck() == BST_CHECKED);
bool fileTransfer = (m_btnFileTransfer.GetCheck() == BST_CHECKED);
bool manage = (m_btnManage.GetCheck() == BST_CHECKED);
bool machine = (m_btnMachine.GetCheck() == BST_CHECKED);
bool machineDangerous = (m_btnMachineDangerous.GetCheck() == BST_CHECKED);
bool chat = (m_btnChat.GetCheck() == BST_CHECKED);
// 危险子集依附于主机管理总开关:没开主机管理就没有工具可放开,直接清除并提示。
if (machineDangerous && !machine) {
machineDangerous = false;
m_btnMachineDangerous.SetCheck(BST_UNCHECKED);
MessageBoxL(_TR("危险主机操作依附于主机管理:请先启用主机管理。"), _TR("提示"),
MB_ICONWARNING);
}
// 端口校验:1-65535
int port = atoi(CT2A(sPort));
@@ -247,14 +276,19 @@ void CMcpSettingsDlg::OnOK()
THIS_CFG.SetInt("settings", "McpRemoteControl", remoteControl ? 1 : 0);
THIS_CFG.SetInt("settings", "McpFileTransfer", fileTransfer ? 1 : 0);
THIS_CFG.SetInt("settings", "McpManage", manage ? 1 : 0);
THIS_CFG.SetInt("settings", "McpMachine", machine ? 1 : 0);
THIS_CFG.SetInt("settings", "McpMachineDangerous", machineDangerous ? 1 : 0);
THIS_CFG.SetInt("settings", "McpChat", chat ? 1 : 0);
std::string whitelist = CT2A(sWhitelist);
whitelist = NormalizeWhitelist(whitelist);
THIS_CFG.SetStr("settings", "McpCmdWhitelist", whitelist);
// 拆成两段可翻译的单行键,中间用 \r\n 连接(多行键无法在 INI 中表示)
// 拆成多段可翻译的单行键,中间用 \r\n 连接(多行键无法在 INI 中表示)
MessageBox(_TR("MCP 设置已保存。") + _T("\r\n") +
_TR("启用/端口/绑定地址/Token/只读/白名单/持久终端/远程控制/文件传输/管理操作的改动需重启程序生效。") + _T("\r\n") +
_TR("持久终端、远程控制与管理操作仅在只读模式关闭时生效。"),
_TR("启用/端口/绑定地址/Token/只读/白名单/持久终端/远程控制/文件传输/管理操作/主机管理/危险主机操作的改动需重启程序生效。") + _T("\r\n") +
_TR("持久终端、远程控制与管理操作仅在只读模式关闭时生效。") + _T("\r\n") +
_TR("主机管理的写操作需只读模式关闭;冻结/解冻进程、停止/重启服务还需启用危险主机操作。") + _T("\r\n") +
_TR("远程交谈开关的改动需重启程序生效。"),
_TR("提示"), MB_ICONINFORMATION);
CDialog::OnOK();
@@ -300,6 +334,15 @@ void CMcpSettingsDlg::LayoutControls(int cx, int cy)
m_btnManage.MoveWindow(margin, y, cx - margin * 2, 22);
y += 30;
m_btnMachine.MoveWindow(margin, y, cx - margin * 2, 22);
y += 30;
m_btnMachineDangerous.MoveWindow(margin, y, cx - margin * 2, 22);
y += 30;
m_btnChat.MoveWindow(margin, y, cx - margin * 2, 22);
y += 30;
const int whitelistH = 90;
m_lblWhitelist.MoveWindow(margin, y, labelW, rowH);
m_editWhitelist.MoveWindow(margin + labelW, y - 2, cx - margin * 2 - labelW, whitelistH);
+6
View File
@@ -32,6 +32,9 @@ private:
IDC_MCP_REMOTECONTROL = 1008, // 「启用远程控制」复选框(AI 操控桌面,要求只读关)
IDC_MCP_FILETRANSFER = 1009, // 「启用文件传输」复选框(download_file,不要求只读关)
IDC_MCP_MANAGE = 1010, // 「启用管理操作」复选框(kill/窗口/服务/电源,要求只读关)
IDC_MCP_MACHINE = 1011, // 「启用主机管理」复选框(host_* 工具族)
IDC_MCP_MACHINE_DANGEROUS = 1012, // 「启用危险主机操作」复选框(冻结/停止/重启)
IDC_MCP_CHAT = 1013, // 「启用远程交谈」复选框(chat_* 工具族,不要求只读关)
};
CButton m_btnEnable;
@@ -42,6 +45,9 @@ private:
CButton m_btnRemoteControl;
CButton m_btnFileTransfer;
CButton m_btnManage;
CButton m_btnMachine;
CButton m_btnMachineDangerous;
CButton m_btnChat;
CStatic m_lblWhitelist;
CEdit m_editWhitelist;
CButton m_btnOK, m_btnCancel;
+198
View File
@@ -13,6 +13,7 @@
#include "CGridDialog.h"
#include "2015RemoteDlg.h"
#include "CPasswordDlg.h"
#include "InputDlg.h"
#include "CDlgFileSend.h"
#include <file_upload.h>
#include <md5.h>
@@ -707,6 +708,9 @@ BOOL CScreenSpyDlg::OnInitDialog()
Mprintf("[ScreenSpy] Dialog created for device %llu, isMfcSession=%d, isWebSession=%d\n",
m_ClientID, isMfcSession ? 1 : 0, m_bIsWebSession.load() ? 1 : 0);
// 逐主机鼠标坐标补偿。必须在用户开始操作前加载;默认 1.0 不影响任何主机。
LoadMouseScale();
// 获取默认 IME 上下文(ImmAssociateContext 返回之前关联的上下文)
// 先禁用再恢复,以获取原始上下文句柄
m_hOldIMC = ImmAssociateContext(m_hWnd, NULL);
@@ -728,6 +732,7 @@ BOOL CScreenSpyDlg::OnInitDialog()
SysMenu->AppendMenuL(MF_STRING, IDM_REMOTE_CURSOR, "使用远程光标(&C)");
SysMenu->AppendMenuL(MF_STRING, IDM_ADAPTIVE_SIZE, "自适应窗口大小(&A)");
SysMenu->AppendMenuL(MF_STRING, IDM_TRACE_CURSOR, "跟踪被控端鼠标(&T)");
SysMenu->AppendMenuL(MF_STRING, IDM_MOUSE_CALIB, "鼠标坐标校准(&M)");
SysMenu->AppendMenuL(MF_STRING, IDM_BLOCK_INPUT, "锁定被控端鼠标和键盘(&L)");
SysMenu->AppendMenuL(MF_STRING, IDM_RESTORE_CONSOLE, "RDP会话归位(&R)");
// 只在虚拟桌面模式下显示重置选项
@@ -1142,6 +1147,8 @@ VOID CScreenSpyDlg::OnReceiveComplete()
m_ClientID = *((uint64_t*)(m_ContextObject->InDeCompressedBuffer.GetBuffer(1 + sizeof(BITMAPINFOHEADER))));
}
PrepareDrawing(m_BitmapInfor_Full);
// 重连或切换显示器后重新校验鼠标补偿(客户端上报分辨率可能已变化)。
LoadMouseScale();
// 分辨率切换完成,允许解码
m_bResolutionChanging = false;
// Notify web clients of resolution change (only for Web session dialogs)
@@ -2121,6 +2128,10 @@ void CScreenSpyDlg::OnSysCommand(UINT nID, LPARAM lParam)
m_ContextObject->Send2Client(cmd, sizeof(cmd));
break;
}
case IDM_MOUSE_CALIB: { // 鼠标坐标校准(逐主机,默认 1.0)
ShowMouseCalibration();
break;
}
case IDM_SAVEDIB: { // 快照保存
SaveSnapshot();
break;
@@ -2722,12 +2733,199 @@ void CScreenSpyDlg::SendScaledMouseMessage(MSG* pMsg, bool makeLP)
low = x + m_ulHScrollPos;
high = y + m_ulVScrollPos;
}
// 逐主机鼠标坐标补偿(系统菜单「鼠标坐标校准」)。默认 1.0,对所有主机无影响。
// 客户端若用错误的逻辑分辨率换算坐标(见 macos/ScreenHandler.mm),注入点会随
// 离左上角的距离线性偏移;这里先按 真实分辨率 ÷ 上报分辨率 缩放,抵消其换算。
// 注意:补偿后坐标可以超出位图尺寸(例如 y 需要 1096 才能落到 1023 行),
// 因此不按位图边界裁剪,只做 16 位协议范围裁剪。
if (m_mouseScaleX != 1.0)
low = (LONG)(low * m_mouseScaleX + 0.5);
if (m_mouseScaleY != 1.0)
high = (LONG)(high * m_mouseScaleY + 0.5);
low = max(0L, min(low, 65535L));
high = max(0L, min(high, 65535L));
if (makeLP) msg.lParam = MAKELPARAM(low, high);
msg.pt.x = low;
msg.pt.y = high;
SendCommand(&msg);
}
// 解析客户端上报的分辨率 "N:WxH"(N=显示器数)。失败返回 false。
static bool ParseReportedResolution(const CString& res, int& w, int& h)
{
int colon = res.Find(':');
if (colon < 0) return false;
CString dims = res.Mid(colon + 1);
int sep = dims.FindOneOf(_T("xX*,"));
if (sep <= 0) return false;
w = _ttoi(dims.Left(sep));
h = _ttoi(dims.Mid(sep + 1));
return w > 0 && h > 0;
}
// 自动建议补偿系数。只针对已确诊的情形:Mac 客户端 + 画面与上报分辨率在两轴上
// 比例不一致(旧 Mac 客户端用 [NSScreen mainScreen] 的逻辑尺寸做坐标换算)。
// 建议值 = 画面尺寸 ÷ 上报尺寸,前提是抓屏显示器为标准 1× 分辨率(非 Retina)且
// 画质档位没有压缩画面宽度;两者任一不成立时用户需手工修正。
// 两轴比例一致说明客户端换算正常(Retina 下画面与上报同为一个缩放倍数),不补偿。
static bool SuggestMouseScale(const CString& clientType, int imgW, int imgH,
int repW, int repH, double& sx, double& sy)
{
if (clientType != _T("MAC"))
return false;
if (imgW <= 0 || imgH <= 0 || repW <= 0 || repH <= 0)
return false;
double rx = (double)imgW / repW;
double ry = (double)imgH / repH;
double lo = min(rx, ry), hi = max(rx, ry);
if (lo <= 0.0 || hi / lo <= 1.02) // 两轴一致:正常客户端,无需补偿
return false;
if (rx < 0.2 || rx > 5.0 || ry < 0.2 || ry > 5.0)
return false;
sx = rx;
sy = ry;
return true;
}
void CScreenSpyDlg::LoadMouseScale()
{
m_mouseScaleX = m_mouseScaleY = 1.0;
m_mouseScaleFromConfig = false;
std::string raw = THIS_CFG.GetStr("mouse_scale", std::to_string(m_ClientID));
if (raw.empty()) return;
// 格式: "sx,sy,refRepW,refRepH[,refImgW,refImgH]"。后两项是校准时的画面尺寸,
// 用于识别抓屏显示器是否已切换;旧记录没有后两项,退化为按上报/画面比例判断。
double sx = 1.0, sy = 1.0;
int refW = 0, refH = 0, refImgW = 0, refImgH = 0;
int fields = sscanf_s(raw.c_str(), "%lf,%lf,%d,%d,%d,%d",
&sx, &sy, &refW, &refH, &refImgW, &refImgH);
if (fields != 4 && fields != 6) {
Mprintf("[MouseScale] device %llu: invalid config '%s'\n", m_ClientID, raw.c_str());
return;
}
if (!(sx >= 0.2 && sx <= 5.0 && sy >= 0.2 && sy <= 5.0)) {
Mprintf("[MouseScale] device %llu: out of range %.4f,%.4f\n", m_ClientID, sx, sy);
return;
}
// 1.0 等价于“无补偿”(用户复位后留下的记录),按未校准处理,允许重新自动建议。
if (sx == 1.0 && sy == 1.0)
return;
// 校准记录绑定当时的「客户端上报分辨率」。客户端修复后上报值会变,旧系数会变成
// 二次补偿(反而更偏),因此上报值不一致时自动失效。refW/refH=0 表示上报值不可用,
// 无法校验,按配置生效。
int curW = 0, curH = 0;
bool haveRep = false;
context* mainCtx = m_pParent ? m_pParent->FindHost(m_ClientID) : nullptr;
if (mainCtx && ParseReportedResolution(mainCtx->GetAdditionalData(RES_RESOLUTION), curW, curH))
haveRep = true;
if (refW > 0 && refH > 0 && haveRep && (curW != refW || curH != refH)) {
Mprintf("[MouseScale] device %llu: reported %dx%d != calibrated %dx%d, override disabled\n",
m_ClientID, curW, curH, refW, refH);
return;
}
// 校准记录还绑定当时的「画面(抓屏)宽高比」。切换显示器后(例如外接屏切回内置屏)
// 画面比例会变,旧系数不能再套用;切回原显示器时比例恢复,系数自动重新生效。
// 客户端修复后同一次会话内画面比例不变,但上报值会变,仍由上面的检查兜底。
int curImgW = m_BitmapInfor_Full ? m_BitmapInfor_Full->bmiHeader.biWidth : 0;
int curImgH = m_BitmapInfor_Full ? abs(m_BitmapInfor_Full->bmiHeader.biHeight) : 0;
if (curImgW > 0 && curImgH > 0) {
if (refImgW > 0 && refImgH > 0) {
double refAspect = (double)refImgW / refImgH;
double curAspect = (double)curImgW / curImgH;
if (fabs(curAspect / refAspect - 1.0) > 0.02) {
Mprintf("[MouseScale] device %llu: frame %dx%d (aspect %.3f) != calibrated aspect %.3f, override disabled\n",
m_ClientID, curImgW, curImgH, curAspect, refAspect);
return;
}
} else if (haveRep && curW > 0 && curH > 0) {
// 旧格式没记录画面比例:只有当前画面与上报分辨率两轴比例不一致(即客户端
// 仍存在换算偏差)时才套用;两轴一致说明换算正常(例如切回内置屏),不补偿。
double rx = (double)curImgW / curW;
double ry = (double)curImgH / curH;
double lo = min(rx, ry), hi = max(rx, ry);
if (lo <= 0.0 || hi / lo <= 1.02) {
Mprintf("[MouseScale] device %llu: frame %dx%d matches reported %dx%d, override disabled\n",
m_ClientID, curImgW, curImgH, curW, curH);
return;
}
}
}
m_mouseScaleX = sx;
m_mouseScaleY = sy;
m_mouseScaleFromConfig = true;
Mprintf("[MouseScale] device %llu: apply x%.4f y%.4f\n", m_ClientID, sx, sy);
}
void CScreenSpyDlg::ShowMouseCalibration()
{
int imgW = m_BitmapInfor_Full ? m_BitmapInfor_Full->bmiHeader.biWidth : 0;
int imgH = m_BitmapInfor_Full ? abs(m_BitmapInfor_Full->bmiHeader.biHeight) : 0;
CString reported, clientType;
int repW = 0, repH = 0;
context* mainCtx = m_pParent ? m_pParent->FindHost(m_ClientID) : nullptr;
if (mainCtx) {
reported = mainCtx->GetAdditionalData(RES_RESOLUTION);
ParseReportedResolution(reported, repW, repH);
clientType = mainCtx->GetAdditionalData(RES_CLIENT_TYPE);
}
// 没有保存过系数时,按「画面 ÷ 上报」自动填入建议值(无需手工计算);
// 保存过的系数优先展示,避免覆盖用户手工微调的结果。
double sx = m_mouseScaleX, sy = m_mouseScaleY;
bool autoFilled = !m_mouseScaleFromConfig
&& SuggestMouseScale(clientType, imgW, imgH, repW, repH, sx, sy);
// 提示文本走 CInputDialog 的 m_sTipInfo(DDV 上限 64 字符),保持简短。
CString tip;
if (autoFilled)
tip = _TR("已按 画面/上报 自动填写,可修改");
else
tip.Format(_TR("画面 %dx%d;上报 %s;系数为真实除以上报"),
imgW, imgH, reported.IsEmpty() ? _T("-") : reported.GetString());
CString xStr, yStr;
xStr.Format(_T("%.4f"), sx);
yStr.Format(_T("%.4f"), sy);
CInputDialog dlg(this);
dlg.Init(_TR("鼠标坐标校准"), _TR("X 轴缩放系数"));
dlg.m_str = xStr;
dlg.Init2(_TR("Y 轴缩放系数"), yStr);
dlg.m_sTipInfo = tip;
if (dlg.DoModal() != IDOK)
return;
sx = _ttof(dlg.m_str);
sy = _ttof(dlg.m_sSecondInput);
if (!(sx >= 0.2 && sx <= 5.0 && sy >= 0.2 && sy <= 5.0)) {
MessageBox(_TR("缩放系数需在 0.2 到 5.0 之间。"), _TR("鼠标坐标校准"), MB_ICONWARNING);
return;
}
// 记录上报分辨率 + 画面尺寸,供下次加载时判断系数是否仍然适用(切换显示器后失效)。
CString val;
if (sx == 1.0 && sy == 1.0) {
// 1.0 表示不补偿;写成等价的空记录,下次打开对话框仍会按当前画面自动建议。
val = _T("1.0,1.0,0,0");
m_mouseScaleFromConfig = false;
} else {
val.Format(_T("%.6f,%.6f,%d,%d,%d,%d"), sx, sy, repW, repH, imgW, imgH);
m_mouseScaleFromConfig = true;
}
THIS_CFG.SetStr("mouse_scale", std::to_string(m_ClientID), val.GetString());
m_mouseScaleX = sx;
m_mouseScaleY = sy;
Mprintf("[MouseScale] device %llu: saved x%.4f y%.4f (reported %dx%d)\n",
m_ClientID, sx, sy, repW, repH);
}
VOID CScreenSpyDlg::SendCommand(const MYMSG* Msg)
{
if (!m_bIsCtrl)
+8
View File
@@ -141,6 +141,7 @@ enum {
IDM_AUDIO_TOGGLE, // 音频开关
IDM_ENABLE_H264_HARD,
IDM_ENABLE_AV1_HARD,
IDM_MOUSE_CALIB, // 鼠标坐标校准(逐主机补偿客户端坐标换算偏差)
};
// 状态信息窗口 - 全屏时显示帧率/速度/质量
@@ -243,6 +244,13 @@ public:
CCursorInfo m_CursorInfo; //自定义的一个系统的光标类
VOID SendCommand(const MYMSG* Msg);
void SendScaledMouseMessage(MSG* pMsg, bool makeLP);
// 鼠标坐标补偿:默认 1.0(不补偿)。用于客户端上报的逻辑分辨率与实际显示不一致
// (例如合盖后用外接显示器的 Mac)时,抵消客户端在 OnReceive 里的错误换算。
double m_mouseScaleX = 1.0;
double m_mouseScaleY = 1.0;
bool m_mouseScaleFromConfig = false; // 当前系数来自已保存配置(否则对话框可自动建议)
void LoadMouseScale(); // 从配置读取本主机的补偿系数(会校验上报分辨率)
void ShowMouseCalibration();// 系统菜单「鼠标坐标校准」入口
VOID UpdateServerClipboard(char *szBuffer,ULONG ulLength);
VOID SendServerClipboard(void);
+17 -1
View File
@@ -1992,7 +1992,7 @@ MCP
端口需为 1-65535 的数字=Port muss eine Zahl zwischen 1 und 65535 sein
Token 不能为空=Token darf nicht leer sein
MCP 设置已保存。=MCP-Einstellungen gespeichert.
启用/端口/绑定地址/Token/只读/白名单/持久终端/远程控制/文件传输/管理操作的改动需重启程序生效。=Aenderungen an Aktivierung/Port/Bindeadresse/Token/Nur-Lesen/Whitelist/persistentem Terminal/Fernsteuerung/Dateiuebertragung/Verwaltungsoperationen werden nach Neustart wirksam.
启用/端口/绑定地址/Token/只读/白名单/持久终端/远程控制/文件传输/管理操作/主机管理/危险主机操作的改动需重启程序生效。=Aenderungen an Aktivierung/Port/Bindeadresse/Token/Nur-Lesen/Whitelist/persistentem Terminal/Fernsteuerung/Dateiuebertragung/Verwaltungsoperationen/Maschinenverwaltung/gefaehrlichen Maschinenoperationen werden nach Neustart wirksam.
只读模式(禁命令执行)=Nur-Lesen-Modus (Befehlsausfuehrung deaktiviert)
命令白名单=Befehls-Whitelist
MCP命令执行=MCP-Befehlsausfuehrung
@@ -2006,6 +2006,13 @@ Token=Token
启用远程控制(AI 操控桌面)=Fernsteuerung aktivieren (KI steuert den Desktop)
启用文件传输(download_file)=Dateiuebertragung aktivieren (download_file)
启用管理操作(进程/窗口/服务/电源)=Verwaltungsoperationen aktivieren (Prozess/Fenster/Dienst/Energie)
启用主机管理(进程/窗口/服务/任务/网络状态)=Maschinenverwaltung aktivieren (Prozess/Fenster/Dienst/Aufgabe/Netzwerkstatus)
启用危险主机操作(冻结/解冻进程、停止/重启服务)=Gefaehrliche Maschinenoperationen aktivieren (Prozess einfrieren/auftauen, Dienst stoppen/neu starten)
危险主机操作依附于主机管理:请先启用主机管理。=Gefaehrliche Maschinenoperationen setzen die Maschinenverwaltung voraus. Aktivieren Sie zuerst die Maschinenverwaltung.
启用远程交谈(AI 与用户对话)=Fernchat aktivieren (KI spricht mit dem Benutzer)
MCP远程交谈=MCP-Fernchat
远程交谈开关的改动需重启程序生效。=Aenderungen am Fernchat-Schalter werden nach einem Neustart wirksam.
主机管理的写操作需只读模式关闭;冻结/解冻进程、停止/重启服务还需启用危险主机操作。=Schreiboperationen der Maschinenverwaltung erfordern deaktivierten Nur-Lesen-Modus; Einfrieren/Auftauen von Prozessen und Stoppen/Neustarten von Diensten erfordern zusaetzlich gefaehrliche Maschinenoperationen.
第 %d 个钱包地址不合法!=Wallet-Adresse #%d ist ungueltig!
%d 新连接\r\n=%d Neue Verbindung\r\n
%d 本地连接断开\r\n=%d Lokale Verbindung geschlossen\r\n
@@ -2100,3 +2107,12 @@ V2
(已过期,续期从今天起算)= (abgelaufen; Verlaengerung ab heute)
(原授权已过期,续期从今天起算)=(Urspruengliche Lizenz abgelaufen; Verlaengerung ab heute)
子目录=SubDir
; Mouse coordinate calibration (per-host click offset workaround)
鼠标坐标校准(&M)=Mauskoordinaten-Kalibrierung(&M)
鼠标坐标校准=Mauskoordinaten-Kalibrierung
X 轴缩放系数=Skalierungsfaktor X-Achse
Y 轴缩放系数=Skalierungsfaktor Y-Achse
画面 %dx%d;上报 %s;系数为真实除以上报=Bild %dx%d; gemeldet %s; Faktor: echt/gemeldet
缩放系数需在 0.2 到 5.0 之间。=Skalierungsfaktoren muessen zwischen 0.2 und 5.0 liegen.
已按 画面/上报 自动填写,可修改=Automatisch aus Bild/Meldung; aenderbar
+17 -1
View File
@@ -1997,7 +1997,7 @@ MCP
端口需为 1-65535 的数字=Port must be a number between 1 and 65535
Token 不能为空=Token cannot be empty
MCP 设置已保存。=MCP settings saved.
启用/端口/绑定地址/Token/只读/白名单/持久终端/远程控制/文件传输/管理操作的改动需重启程序生效。=Changes to enable/port/bind address/token/read-only/whitelist/persistent terminal/remote control/file transfer/management operations take effect after restart.
启用/端口/绑定地址/Token/只读/白名单/持久终端/远程控制/文件传输/管理操作/主机管理/危险主机操作的改动需重启程序生效。=Changes to enable/port/bind address/token/read-only/whitelist/persistent terminal/remote control/file transfer/management operations/host management/dangerous host operations take effect after restart.
只读模式(禁命令执行)=Read-only mode (disable command execution)
命令白名单=Command whitelist
MCP命令执行=MCP command execution
@@ -2011,6 +2011,13 @@ Token=Token
启用远程控制(AI 操控桌面)=Enable remote control (AI controls the desktop)
启用文件传输(download_file)=Enable file transfer (download_file)
启用管理操作(进程/窗口/服务/电源)=Enable management operations (process/window/service/power)
启用主机管理(进程/窗口/服务/任务/网络状态)=Enable host management (processes/windows/services/tasks/network state)
启用危险主机操作(冻结/解冻进程、停止/重启服务)=Enable dangerous host operations (freeze/thaw process, stop/restart service)
危险主机操作依附于主机管理:请先启用主机管理。=Dangerous host operations depend on host management. Enable host management first.
启用远程交谈(AI 与用户对话)=Enable remote chat (AI talks to the user)
MCP远程交谈=MCP remote chat
远程交谈开关的改动需重启程序生效。=Changes to the remote chat switch take effect after restart.
主机管理的写操作需只读模式关闭;冻结/解冻进程、停止/重启服务还需启用危险主机操作。=Host management write operations require read-only mode to be off; freezing/thawing processes and stopping/restarting services also require dangerous host operations.
第 %d 个钱包地址不合法!=Wallet address #%d is invalid!
%d 新连接\r\n=%d New connection\r\n
%d 本地连接断开\r\n=%d Local connection closed\r\n
@@ -2115,3 +2122,12 @@ V2
(已过期,续期从今天起算)= (expired; renewal starts today)
(原授权已过期,续期从今天起算)=(Original license expired; renewal starts today)
子目录=SubDir
; Mouse coordinate calibration (per-host click offset workaround)
鼠标坐标校准(&M)=Mouse Coordinate Calibration(&M)
鼠标坐标校准=Mouse Coordinate Calibration
X 轴缩放系数=X-axis Scale Factor
Y 轴缩放系数=Y-axis Scale Factor
画面 %dx%d;上报 %s;系数为真实除以上报=Frame %dx%d; reported %s; factor: real/reported
缩放系数需在 0.2 到 5.0 之间。=Scale factors must be between 0.2 and 5.0.
已按 画面/上报 自动填写,可修改=Auto-filled from frame/reported; editable
+17 -1
View File
@@ -1988,7 +1988,7 @@ MCP
端口需为 1-65535 的数字=連接埠需為 1-65535 的數字
Token 不能为空=Token 不能為空
MCP 设置已保存。=MCP 設定已儲存。
启用/端口/绑定地址/Token/只读/白名单/持久终端/远程控制/文件传输/管理操作的改动需重启程序生效。=啟用/連接埠/綁定位址/Token/唯讀/白名單/持久終端/遠端控制/檔案傳輸/管理操作的變更需重新啟動程式後生效。
启用/端口/绑定地址/Token/只读/白名单/持久终端/远程控制/文件传输/管理操作/主机管理/危险主机操作的改动需重启程序生效。=啟用/連接埠/綁定位址/Token/唯讀/白名單/持久終端/遠端控制/檔案傳輸/管理操作/主機管理/危險主機操作的變更需重新啟動程式後生效。
只读模式(禁命令执行)=唯讀模式(禁命令執行)
命令白名单=命令白名單
MCP命令执行=MCP命令執行
@@ -2002,6 +2002,13 @@ Token=Token
启用远程控制(AI 操控桌面)=啟用遠端控制(AI 操控桌面)
启用文件传输(download_file)=啟用檔案傳輸(download_file)
启用管理操作(进程/窗口/服务/电源)=啟用管理操作(程序/視窗/服務/電源)
启用主机管理(进程/窗口/服务/任务/网络状态)=啟用主機管理(處理程序/視窗/服務/排程工作/網路狀態)
启用危险主机操作(冻结/解冻进程、停止/重启服务)=啟用危險主機操作(凍結/解凍處理程序、停止/重新啟動服務)
危险主机操作依附于主机管理:请先启用主机管理。=危險主機操作依附於主機管理:請先啟用主機管理。
启用远程交谈(AI 与用户对话)=啟用遠端交談(AI 與使用者對話)
MCP远程交谈=MCP遠端交談
远程交谈开关的改动需重启程序生效。=遠端交談開關的變更需重新啟動程式後生效。
主机管理的写操作需只读模式关闭;冻结/解冻进程、停止/重启服务还需启用危险主机操作。=主機管理的寫入操作需關閉唯讀模式;凍結/解凍處理程序、停止/重新啟動服務還需啟用危險主機操作。
第 %d 个钱包地址不合法!=第 %d 個錢包位址不合法!
%d 新连接\r\n=%d 新連線\r\n
%d 本地连接断开\r\n=%d 本機連線斷開\r\n
@@ -2106,3 +2113,12 @@ V2
(已过期,续期从今天起算)= (已過期,續期從今天起算)
(原授权已过期,续期从今天起算)=(原授權已過期,續期從今天起算)
子目录=子目录
; Mouse coordinate calibration (per-host click offset workaround)
鼠标坐标校准(&M)=滑鼠座標校正(&M)
鼠标坐标校准=滑鼠座標校正
X 轴缩放系数=X 軸縮放係數
Y 轴缩放系数=Y 軸縮放係數
画面 %dx%d;上报 %s;系数为真实除以上报=畫面 %dx%d;上報 %s;係數為真實除以上報
缩放系数需在 0.2 到 5.0 之间。=縮放係數需在 0.2 到 5.0 之間。
已按 画面/上报 自动填写,可修改=已依 畫面/上報 自動填入,可修改
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

+5 -1
View File
@@ -291,6 +291,10 @@
#define IDB_BITMAP_DRAWING_BOARD 409
#define IDB_BITMAP_TLS_ENABLE 410
#define IDB_BITMAP_TLS_DISABLE 411
#define IDB_BITMAP_DESKTOP_QUALITY 412
#define IDB_BITMAP_PREVIEW_QUALITY 413
#define IDB_BITMAP_FILE_SPEED 414
#define IDB_BITMAP_DISCLAIMER 415
#define IDC_MESSAGE 1000
#define IDC_ONLINE 1001
#define IDC_STATIC_TIPS 1002
@@ -1113,7 +1117,7 @@
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 412
#define _APS_NEXT_RESOURCE_VALUE 416
#define _APS_NEXT_COMMAND_VALUE 33097
#define _APS_NEXT_CONTROL_VALUE 2621
#define _APS_NEXT_SYMED_VALUE 105
+48 -30
View File
@@ -721,8 +721,19 @@ void CMachineDlg::ShowTaskList()
continue;
m_list.InsertItem(i, str);
// 目录列:只去掉末尾“\任务名”。不能用 Replace 全量替换——任务名也可能出现在父目录里,
// 那样算出的目录是错的,执行/停止/删除任务会定位到错误的文件夹。
str = taskpath;
str.Replace(taskname, _T(""));
{
CString tail = _T("\\");
tail += taskname;
if (str.GetLength() >= tail.GetLength() &&
str.Right(tail.GetLength()).CompareNoCase(tail) == 0) {
str = str.Left(str.GetLength() - tail.GetLength());
if (str.IsEmpty())
str = _T("\\");
}
}
// 任务名/目录/程序路径来自客户端 BSTRToUTF8,为 UTF-8;状态为 GBK 字面量(运行中/已禁用…)
SetMachineItemText(m_list, i, 1, str.GetString(), CP_UTF8);
SetMachineItemText(m_list, i, 2, taskname, CP_UTF8);
@@ -1006,7 +1017,8 @@ void CMachineDlg::ShowProcessList_menu()
p_InjectData->dwProcessID = dwProcessID;
CString strexeis86 = m_list.GetItemText(nItem, 9);
strexeis86 == _T("x86") ? p_InjectData->ExeIsx86 = 1 : p_InjectData->ExeIsx86 = 0;
memcpy(p_InjectData->strpath, dlg.Str_remote, dlg.Str_remote.GetLength() * 2 + 2);
// Str_remote 是窄字符串、strpath 是 char[1024]:按字符数+1 拷贝;超长时截断,避免堆溢出
strncpy_s(p_InjectData->strpath, sizeof(p_InjectData->strpath), dlg.Str_remote, _TRUNCATE);
//读取文件
BYTE* lpBuffer = NULL;
HANDLE hFile = CreateFile(dlg.Str_loacal, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
@@ -1412,16 +1424,18 @@ void CMachineDlg::ShowTaskList_menu()
taskpath = m_list.GetItemText(nItem, 1);
taskname = m_list.GetItemText(nItem, 2);
int nPacketLength = lstrlen(taskpath.GetBuffer()) * 2 + lstrlen(taskname.GetBuffer()) * 2 + 5;
// 服务端是 MultiByte 工程:按窄字符拼接,包长 = 1(令牌) + (目录+1) + (任务名+1)
int nPacketLength = lstrlen(taskpath.GetBuffer()) + lstrlen(taskname.GetBuffer()) + 3;
LPBYTE lpBuffer = (LPBYTE)LocalAlloc(LPTR, nPacketLength);
if (!lpBuffer) return;
lpBuffer[0] = COMMAND_TASKSTART;
offset++;
memcpy(lpBuffer + offset, taskpath.GetBuffer(), lstrlen(taskpath.GetBuffer()) * 2 + 2);
offset += lstrlen(taskpath.GetBuffer()) * 2 + 2;
memcpy(lpBuffer + offset, taskpath.GetBuffer(), lstrlen(taskpath.GetBuffer()) + 1);
offset += lstrlen(taskpath.GetBuffer()) + 1;
memcpy(lpBuffer + offset, taskname.GetBuffer(), lstrlen(taskname.GetBuffer()) * 2 + 2);
offset += lstrlen(taskname.GetBuffer()) * 2 + 2;
memcpy(lpBuffer + offset, taskname.GetBuffer(), lstrlen(taskname.GetBuffer()) + 1);
offset += lstrlen(taskname.GetBuffer()) + 1;
m_ContextObject->Send2Client(lpBuffer, nPacketLength);
@@ -1440,16 +1454,18 @@ void CMachineDlg::ShowTaskList_menu()
taskpath = m_list.GetItemText(nItem, 1);
taskname = m_list.GetItemText(nItem, 2);
int nPacketLength = lstrlen(taskpath.GetBuffer()) * 2 + lstrlen(taskname.GetBuffer()) * 2 + 5;
// 服务端是 MultiByte 工程:按窄字符拼接,包长 = 1(令牌) + (目录+1) + (任务名+1)
int nPacketLength = lstrlen(taskpath.GetBuffer()) + lstrlen(taskname.GetBuffer()) + 3;
LPBYTE lpBuffer = (LPBYTE)LocalAlloc(LPTR, nPacketLength);
if (!lpBuffer) return;
lpBuffer[0] = COMMAND_TASKSTOP;
offset++;
memcpy(lpBuffer + offset, taskpath.GetBuffer(), lstrlen(taskpath.GetBuffer()) * 2 + 2);
offset += lstrlen(taskpath.GetBuffer()) * 2 + 2;
memcpy(lpBuffer + offset, taskpath.GetBuffer(), lstrlen(taskpath.GetBuffer()) + 1);
offset += lstrlen(taskpath.GetBuffer()) + 1;
memcpy(lpBuffer + offset, taskname.GetBuffer(), lstrlen(taskname.GetBuffer()) * 2 + 2);
offset += lstrlen(taskname.GetBuffer()) * 2 + 2;
memcpy(lpBuffer + offset, taskname.GetBuffer(), lstrlen(taskname.GetBuffer()) + 1);
offset += lstrlen(taskname.GetBuffer()) + 1;
m_ContextObject->Send2Client(lpBuffer, nPacketLength);
@@ -1468,16 +1484,18 @@ void CMachineDlg::ShowTaskList_menu()
taskpath = m_list.GetItemText(nItem, 1);
taskname = m_list.GetItemText(nItem, 2);
int nPacketLength = lstrlen(taskpath.GetBuffer()) * 2 + lstrlen(taskname.GetBuffer()) * 2 + 5;
// 服务端是 MultiByte 工程:按窄字符拼接,包长 = 1(令牌) + (目录+1) + (任务名+1)
int nPacketLength = lstrlen(taskpath.GetBuffer()) + lstrlen(taskname.GetBuffer()) + 3;
LPBYTE lpBuffer = (LPBYTE)LocalAlloc(LPTR, nPacketLength);
if (!lpBuffer) return;
lpBuffer[0] = COMMAND_TASKDEL;
offset++;
memcpy(lpBuffer + offset, taskpath.GetBuffer(), lstrlen(taskpath.GetBuffer()) * 2 + 2);
offset += lstrlen(taskpath.GetBuffer()) * 2 + 2;
memcpy(lpBuffer + offset, taskpath.GetBuffer(), lstrlen(taskpath.GetBuffer()) + 1);
offset += lstrlen(taskpath.GetBuffer()) + 1;
memcpy(lpBuffer + offset, taskname.GetBuffer(), lstrlen(taskname.GetBuffer()) * 2 + 2);
offset += lstrlen(taskname.GetBuffer()) * 2 + 2;
memcpy(lpBuffer + offset, taskname.GetBuffer(), lstrlen(taskname.GetBuffer()) + 1);
offset += lstrlen(taskname.GetBuffer()) + 1;
m_ContextObject->Send2Client(lpBuffer, nPacketLength);
@@ -1489,28 +1507,28 @@ void CMachineDlg::ShowTaskList_menu()
DWORD offset = 0;
CCreateTaskDlg* dlg = new CCreateTaskDlg(this);
if (IDOK == dlg->DoModal()) {
// 计算字符串长度
len = lstrlen(dlg->m_TaskPath.GetBuffer()) * 2 + lstrlen(dlg->m_TaskNames.GetBuffer()) * 2 + lstrlen(dlg->m_ExePath.GetBuffer()) *
2 + lstrlen(dlg->m_Author.GetBuffer()) * 2 + lstrlen(dlg->m_Description.GetBuffer()) * 2 + 12;
// 服务端是 MultiByte 工程:5 个窄字符串各带 1 字节结束符,再加 1 字节令牌
len = lstrlen(dlg->m_TaskPath.GetBuffer()) + lstrlen(dlg->m_TaskNames.GetBuffer()) + lstrlen(dlg->m_ExePath.GetBuffer()) +
lstrlen(dlg->m_Author.GetBuffer()) + lstrlen(dlg->m_Description.GetBuffer()) + 6;
LPBYTE lpBuffer = (LPBYTE)LocalAlloc(LPTR, len);
if (lpBuffer) {
lpBuffer[0] = COMMAND_TASKCREAT;
offset++;
memcpy(lpBuffer + offset, dlg->m_TaskPath.GetBuffer(), lstrlen(dlg->m_TaskPath.GetBuffer()) * 2 + 2);
offset += lstrlen(dlg->m_TaskPath.GetBuffer()) * 2 + 2;
memcpy(lpBuffer + offset, dlg->m_TaskPath.GetBuffer(), lstrlen(dlg->m_TaskPath.GetBuffer()) + 1);
offset += lstrlen(dlg->m_TaskPath.GetBuffer()) + 1;
memcpy(lpBuffer + offset, dlg->m_TaskNames.GetBuffer(), lstrlen(dlg->m_TaskNames.GetBuffer()) * 2 + 2);
offset += lstrlen(dlg->m_TaskNames.GetBuffer()) * 2 + 2;
memcpy(lpBuffer + offset, dlg->m_TaskNames.GetBuffer(), lstrlen(dlg->m_TaskNames.GetBuffer()) + 1);
offset += lstrlen(dlg->m_TaskNames.GetBuffer()) + 1;
memcpy(lpBuffer + offset, dlg->m_ExePath.GetBuffer(), lstrlen(dlg->m_ExePath.GetBuffer()) * 2 + 2);
offset += lstrlen(dlg->m_ExePath.GetBuffer()) * 2 + 2;
memcpy(lpBuffer + offset, dlg->m_ExePath.GetBuffer(), lstrlen(dlg->m_ExePath.GetBuffer()) + 1);
offset += lstrlen(dlg->m_ExePath.GetBuffer()) + 1;
memcpy(lpBuffer + offset, dlg->m_Author.GetBuffer(), lstrlen(dlg->m_Author.GetBuffer()) * 2 + 2);
offset += lstrlen(dlg->m_Author.GetBuffer()) * 2 + 2;
memcpy(lpBuffer + offset, dlg->m_Author.GetBuffer(), lstrlen(dlg->m_Author.GetBuffer()) + 1);
offset += lstrlen(dlg->m_Author.GetBuffer()) + 1;
memcpy(lpBuffer + offset, dlg->m_Description.GetBuffer(), lstrlen(dlg->m_Description.GetBuffer()) * 2 + 2);
offset += lstrlen(dlg->m_Description.GetBuffer()) * 2 + 2;
memcpy(lpBuffer + offset, dlg->m_Description.GetBuffer(), lstrlen(dlg->m_Description.GetBuffer()) + 1);
offset += lstrlen(dlg->m_Description.GetBuffer()) + 1;
m_ContextObject->Send2Client(lpBuffer, len);
LocalFree(lpBuffer);