42 Commits
Author SHA1 Message Date
yuanyuanxianganddeepseek-flash 106ac2ff0f Fix: Resolve the Desktop, Downloads and home shortcuts on Unix clients
The file manager's remote shortcut buttons send "%USERPROFILE%\Desktop\" and
friends, which the Windows client expands with ExpandEnvironmentStringsA. Unix
clients had no such expansion, so the literal %USERPROFILE% was taken as a
directory name: opendir() failed and the Desktop, Downloads and home buttons
listed nothing at all.

Add common/UnixPath.h, which expands the variables the server can send
(%USERPROFILE%, %HOME%, %HOMEDRIVE%%HOMEPATH%, %USERNAME%) and maps
$HOME/Desktop to the localized folder named in ~/.config/user-dirs.dirs (for
example ~/桌面), falling back to the plain $HOME/<Name> path when that folder
does not exist. Unknown %VAR% tokens are left untouched, so paths that really
contain a percent sign behave as before.

FileManager and the two Windows-to-Unix converters in FileTransferV2 now share
that one conversion. Besides the listing itself, this fixes downloads into a
shortcut directory, which used to be created under a literal %USERPROFILE%
tree instead of the user's real desktop.

Co-Authored-By: deepseek-flash
2026-10-28 14:44:54 +01:00
6bfa4294cc Feature: Switch a Linux client's transport TLS at runtime
The server's TLS menu already wrote the trust anchor into the Windows
client's registry and expected a restart. The Linux client grew the same
command handling (166/167) but, like Windows, only read the anchor once at
startup, so enabling or disabling TLS still meant restarting it. Both
handlers now take effect immediately.

TlsChannelLinux.cpp no longer initialises through std::call_once. The
process-level state (context, enabled, load error) lives behind a mutex and
TlsReload() rebuilds it from whatever anchor file is on disk, so
TlsEnabled() reflects the new transport as soon as the anchor is written or
removed. In-flight sessions survive the swap because SSL_new increments the
SSL_CTX reference count; the unit test pins that down by keeping an
established TLS connection open across a reload that frees the old context.
A reload that hits a bad anchor keeps the previous state and only logs: one
bad push should not brick a working client, and the next start is still
fail-closed. The pushed PEM is parsed before it is written for the same
reason -- a corrupt anchor on disk would lock the client out of the server
with no way to correct it remotely.

Only a real transport flip (plaintext <-> TLS) asks for a reconnect. An
anchor swap alone, as in a certificate rotation, leaves the current session
alone and applies to the next connection. The receive thread never closes
the socket itself; it sets g_needReconnect and the main heartbeat loop
disconnects so the outer reconnect loop can re-handshake, matching how the
heartbeat timeout path already works.

IOCPClient now latches the transport per connection (m_useTls) at handshake
time instead of consulting TlsEnabled() on every send and receive. Without
the latch, the second or so between the reload and the reconnect would push
plaintext into an established TLS session, or the reverse, producing
protocol errors for no reason.

RES_TLS (szReserved[19]) is refreshed right before each login, including
the resend after a group change, so the TLS column on the server flips with
the transport instead of showing the value from process start.

The confirmation dialogs now say what each platform does, with translations
in en_US, zh_TW and de_DE; the keys carry the literal \n escape the INI
parser understands.

Ending a sub-connection is not an error. OpenSSL 3 classifies a peer that
closes without close_notify as an unexpected-EOF protocol error, so every
terminal or file transfer session logged an SSL_read failure on the real
servers even though Recv promises 0 for a plain close and neither side sends
close_notify. SSL_OP_IGNORE_UNEXPECTED_EOF restores the intended semantics.

Verified with the reload unit test (RELOAD-OK, covering the in-flight
connection across a context swap, garbage payload rejection and a broken
anchor keeping TLS alive), an abrupt-close test (recv now returns 0 instead
of SOCKET_ERROR) and end to end against a protocol-faithful fake server that
signs MasterSettings with libsign: plaintext login, 166, TLS reconnect with
RES_TLS=1, 167, plaintext reconnect with RES_TLS=0. The Linux client, the
Debug Windows client and the Debug MFC server all build.

The cost is inherent to taking effect immediately: a remote session in
progress is dropped when the transport changes, and the MFC server briefly
shows the client as a duplicate login until the old connection is reaped
and the standby entry is promoted.

Co-Authored-By: deepseek-flash
Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-10-28 14:15:40 +01:00
yuanyuanxianganddeepseek-flash c11df75225 Fix: Report the real runtime instead of a timezone skew in host info
The host info popup showed a constant "7h" runtime for every Linux host.
szStartTime carries no timezone marker and the two sides disagree: the
Windows client sends its own wall clock (client/LoginServer.cpp
getProcessTime), while the Linux and Android clients send Beijing time
unconditionally (linux/main.cpp and common/commands.h ToPekingTimeAsString
hardcode UTC+8). GetElapsedTime then built the base time with CTime as
local time and subtracted it from the local clock, so on any server that
is not at UTC+8 the start time landed in the future; the absolute value
turned that skew into a plausible-looking duration (UTC+1 gives exactly
7h).

GetElapsedTime now picks the reference "now" by client type: LNX and APK
are compared against the current Beijing time, everything else keeps
using the local clock. A start time in the future now clamps to 0 instead
of being mirrored, so a clock disagreement shows as unknown rather than
as a fake runtime.

The Linux client also reported the wrong thing entirely: it sent the
current time at login, not the process start time, so the value was
always about zero whenever the timezones happened to agree. It now
records its own wall clock once at load and reports Beijing time built
from it, matching the semantics of the Windows client. An upgrade forks
a new process, so the counter restarts after an upgrade as expected.

The first implementation read /proc/self/stat starttime plus /proc/stat
btime, which looked like the exact equivalent of the Windows call, but
btime is computed from the wall clock at boot and never corrected when
NTP later steps the clock, so on WSL2 it drifted by 1.8h. Recording the
value in the process itself has no such failure mode.

Verified against a Debug server with a WSL Ubuntu 24.04 client and a
Windows client: the popup now reports "2.3m" for a Linux process started
2.3 minutes earlier (previously 7h), the startup timestamp is the process
load time in Beijing time, and the Windows host still reports 14s right
after it connects.

Co-Authored-By: deepseek-flash
2026-10-27 21:39:31 +01:00
yuanyuanxianganddeepseek-flash 4d2abf34d0 Feature: Support the Tier 1 MCP tools on Linux clients
All of these tools already had a working wire protocol on the Linux
client (SystemManager.h, common/PTYHandler.h, ScreenHandler.h); only the
server-side client-type gates rejected LNX hosts. kill_process,
exec_command, terminal_open/exec/close and remote_open/close/mouse/
keyboard/clipboard now accept LNX and reject only MAC (plus APK where it
applied). No client change, no capability bit.

exec_command and terminal_exec needed platform-aware plumbing because a
POSIX shell understands none of the Windows constructs: the sentinel is
now "PS1=" / the command / "echo __MCP_DONE_<nonce>__$?" over the Linux
PTY, with output decoded as UTF-8. The PS1= line exists because
interactive bash prints its prompt after every line it reads, which
otherwise leaks into stdout; its echo sits ahead of the command echo and
is removed together with it. The Windows ConPTY and legacy non-PTY forms
are unchanged.

The default command whitelist is now platform-specific: identically named
POSIX commands can write files or change system state (find -exec,
sort -o, hostname), so kDefaultCmdWhitelistPosix only lists commands that
stay read-only even with arguments. env is deliberately excluded, since
"env <program>" runs arbitrary programs and would defeat the whitelist
entirely. An explicit McpCmdWhitelist still overrides both platforms. The
forbidden metacharacter set is split the same way: on Linux it covers
& | < > ; backtick and $( / ${ / !, where ! triggers history expansion in
interactive bash. ^ is not a POSIX metacharacter, so read-only commands
like "grep -v ^# /etc/hosts" are accepted on Linux while Windows keeps
rejecting them.

Input injection had to be sent one MSG64 per COMMAND_SCREEN_CONTROL
packet. The protocol allows batching and the Windows client handles it,
but linux/ScreenHandler.h only processes the first message of a packet,
so a batch left key_press stuck down (X11 autorepeat), click
half-pressed and type emitting only its first character. Splitting the
packets is equivalent for Windows, which processes one message at a time
anyway, and keeps already-deployed Linux clients working without an
upgrade.

Verified on a Debug server against a WSL Ubuntu 24.04 client and a
Windows client: exec_command returned real exit codes (0/1/2) with clean
output, -32007/-32008 negatives, and the POSIX-only ^ allowance;
persistent terminals kept cwd and environment, returned 1 for false and
the last exit code for ";" chains, and closed idempotently; kill_process
killed a test process, returned an empty remaining list and skipped
pid 1; remote_open reported 3840x1140, remote_mouse mapped (0.5,0.5) to
(1920,570), xev showed balanced press/release pairs for keys and buttons,
and a Chinese clipboard round-trip came back as UTF-8. The Windows
regression of the same tools was unchanged, including the multi-monitor
gate on remote_open.

Co-Authored-By: deepseek-flash
2026-10-27 21:15:44 +01:00
yuanyuanxianganddeepseek-flash 3a158a241c Feature: Support upload_file and download_file on Linux and macOS hosts
Both tools used to reject LNX/MAC targets outright. The server now gates
on the target client type instead: a POSIX target must pass an absolute
POSIX remote path without a backslash or a ".." segment (-32602
otherwise), while Windows targets keep their exact previous behaviour.

upload_file needed no new client command; the POSIX receiver already
handles COMMAND_SEND_FILE_V2 and derives the destination from the packet
name. It now also reports a real receiver_ack: the upload session
records dstClientID/transferID, and OnC2CRecvResult matches the 176
acknowledgement from Linux targets, so a destination write failure
becomes -32011 and a missing ack (with bytes in flight) becomes -32001.

download_file needed two pieces on the POSIX side, both shared by Linux
and macOS through common/FileTransferV2.h: a FileCompletePacketV2 per
file with a streaming SHA-256 (new self-contained common/sha256_posix.h,
since BCrypt is Windows-only) so the server can count completed files
and verify digests, and a TOKEN_DOWNLOAD_ERROR reply when the requested
paths do not exist or are denied, which the server maps to
-32009/-32010 within milliseconds instead of waiting for the stall
watchdog.

Zero-byte files were lost when uploading to POSIX targets because the
worker sends no data chunk for them and the complete packet carries no
path, so the receiver had nothing to create. The server now injects a
zero-length final chunk for each empty file, only for POSIX targets;
Windows targets keep their existing behaviour.

Also fixes a download completion edge case found while testing: the
client decides entry order, so a directory may arrive after all files
(an empty subdirectory, for example), and the directory branch only
completed when the directory count alone covered totalFiles. The check
is now filesDone + directoryCount >= totalFiles.

Verified end to end against a WSL Linux client and a Windows client:
upload and download of a tree with a 3 MB binary, a Chinese filename, an
empty file and an empty subdirectory all round-trip with matching
SHA-256; the documented error paths (-32602, -32009, -32011, -32001) and
the Windows upload/download/C2C regressions were exercised as well.

Co-Authored-By: deepseek-flash
2026-10-27 20:39:22 +01:00
yuanyuanxianganddeepseek-flash 4146c73657 Feature: Make Linux a copy_files_c2c destination
The C2C file transfer tool required both ends to be Windows clients. A Linux
client can already land the files: the Windows source worker builds every
entry name by plain string concatenation of dst_dir and the relative path, so
a POSIX dst_dir such as /tmp/recv arrives as "/tmp/recv\sub\file", which the
POSIX receiver normalizes to "/" and writes below an absolute path. What was
missing was the server gate and any way to tell whether the writes succeeded.

The server now accepts LNX/MAC destinations instead of rejecting them, and
validates dst_dir by destination type: an absolute Windows path for Windows
targets, an absolute POSIX path without backslashes for POSIX targets. The
paths and dst_dir arguments also reject embedded NULs, and a POSIX dst_dir is
converted to CP936 exactly so unencodable characters fail loudly instead of
silently becoming '?'.

To make receiver_ack meaningful, a Linux client that receives a C2C transfer
now reports what it wrote. It tracks the outcome per transferID, counting a
directory entry, the last chunk of a file and the completion packet of an
empty file as the three ways an item is settled, with done sets so that
source retries and the trailing completion packet never double count. When
every item is settled it sends one C2CSendResultPacket back on its main
connection under the new TOKEN_C2C_RECV_RESULT (176), with the first errno in
the win32err field and the mapped FEV2_* status. A dedicated token is used
instead of reusing 175 because a host can be the destination of one transfer
while being the source of another, and a destination result must never latch
the source side's done flag.

The server waits up to five seconds for that acknowledgement after the source
reports success, and only for destinations advertising the new
CLIENT_CAP_C2C_RECV_ACK capability bit (Linux only, macOS reports nothing).
A failed acknowledgement becomes -32011 with the status, errno and received
file count; a missing acknowledgement stays an error only for transfers that
actually moved bytes, since a transfer of empty files alone gives the
receiver nothing to learn totalFiles from. Windows destinations are unchanged
and skip the wait entirely.

Verified on the debug instance: Windows to Linux (WSL Ubuntu 24.04) with
subdirectories, an empty directory, a Chinese file name and a 3 MB binary
lands with matching SHA-256 and receiver_ack true; a Windows-style dst_dir
returns -32602; an unwritable POSIX destination returns -32011; the existing
Windows to Windows cases still pass with receiver_ack false and the same
latency.

Co-Authored-By: deepseek-flash
2026-10-27 19:22:12 +01:00
yuanyuanxianganddeepseek-flash 4c0e86dcc5 Feature: Upgrade a Linux client from the server
The Linux client is a standalone ELF with no in-memory loader and no
COMMAND_UPDATE handler, so the server's upgrade menu silently did nothing
for an LNX host. It can now push a new binary and have the client replace
and restart itself.

The server grows an LNX branch next to EXE/DLL/SC. It takes the ELF from an
explicit settings.ini LinuxClientPath, then ghost_linux_amd64 in the
program directory, then res\ghost_linux, then IDR_LINUX_GHOST, the copy
the server has always embedded for the client-build dialog, so a server
with nothing on disk can still upgrade; a configured path that cannot be
read is an error rather than a silent fallback. Only x86_64 ELF64 is
accepted. The payload adds a 32-byte MD5 trailer to the existing
[cmd][size:8][payload] layout, which the Windows branches keep unchanged.

linux/ghost in the tree is still the build from before this change and is
not updated here. It has to be refreshed before release: the embedded
default is copied from it at build time, and a stale copy would install a
client with no COMMAND_UPDATE handler, which can never be upgraded
remotely again.

The client verifies the declared size, elf magic, e_machine against its own
ELF header and the MD5 before touching anything, so a miscopied or corrupted
file never lands on disk. It then writes a same-directory temp file with
fsync and 0755 (a running executable cannot be truncated in place), renames
it over its own path atomically, keeps the replaced inode as .old, removes
the PID file, forks a detached child that waits for the old process to exit
and execs the new binary with the original argv, and finally exits with
S_CLIENT_UPDATE. Doing the rename and the exec in that order avoids ETXTBSY,
double connections under one client id, and a new instance that
isAlreadyRunning() would refuse to start.

Any failure (unwritable install directory, bad payload, fork) leaves the
client running on the old version; the reason goes to the client log and to
the server's message log through TOKEN_CLIENT_MSG, which required moving
that struct out of the Windows-only block in common/commands.h.

The shared client source had also stopped compiling off Windows: the
unknown-header diagnostic in IOCPClient::OnServerReceiving printed
TlsEnabled() and m_tls.IsReady() unconditionally, but TlsChannel and m_tls
only exist on Windows. That diagnostic now keeps the TLS details where the
channel exists and prints just the buffer dump everywhere else.

Verified end to end in WSL against the Debug server, foreground and -d
daemon: the PID changes, the installed file matches the pushed MD5, the host
reconnects, and ghost.old holds the previous binary. A read-only install
directory reports "cannot create ...: Permission denied" in the server log
with the client still online. With an invalid file at ghost_linux_amd64 the
server refuses it and names that path, which shows the disk source wins;
with nothing on disk the update goes through from the embedded ELF.

Co-Authored-By: deepseek-flash
2026-10-27 18:25:34 +01:00
yuanyuanxianganddeepseek-flash bfb17d0d25 Feature: Draw the remote cursor in the web desktop out of control mode
Screen frames are captured without the pointer composed in (GDI SRCCOPY,
DXGI), so browsers only ever knew the cursor's shape index and could show a
cursor just in control mode, where the local pointer stands in for the remote
one. Both servers now relay the cursor position that every per-frame header
already carries: shape changes go out immediately, position changes at most
every 50 ms, and an unchanged cursor is re-sent once a second so a viewer that
joins while the pointer is idle still learns where it is.

The page hides the local pointer and draws the remote cursor at its true
position while out of control mode; entering control mode restores exactly the
old behaviour (remote-shaped CSS cursor on desktop, touchpad pointer on touch).
A server that never sends x/y leaves the page on its previous fallback.

The C++ server broadcasts from the per-frame path, so header-only frames keep a
static desktop's cursor fresh; the Go hub dedups and throttles before fanning
out. Tests cover the throttle/refresh rules and the relayed payload.

Co-Authored-By: deepseek-flash
2026-10-26 17:44:13 +01:00
yuanyuanxianganddeepseek-flash 6236ed1eb4 Fix: Make the Go web console wheel scroll correctly
The Go web server's mouse handler read deltaY as an int, so json.Unmarshal
rejected the entire mouse message whenever the browser reported a
fractional delta (Chrome's smooth scrolling splits one 100px notch into
33.33 + 33.33 + 33.34), and the wheel was dead while clicks and moves
kept working. Treating every event as one notch was wrong the other way:
it scrolled three to four times too far, and sub-pixel deltas from a
touchpad truncated to zero.

The server now accumulates the delta in notch units per client and
injects WM_MOUSEWHEEL only once a whole notch is reached. The remainder
is rounded, not truncated, so a float sum of 99.99px still lands on
exactly one notch and the first notch fires halfway through a physical
one, like native scrolling. The page forwards e.deltaMode so line and
page based deltas convert correctly, and touchpad flings are capped at
20 notches per event.

Verified against a live Go server with a connected client: 100px sends
one packet, three 33.33px events send one, 53.33px sends one, sub-pixel
events accumulate to none, and the wParam is -120 down / +120 up with
SendToScreen returning no error. The MFC web console is untouched.

Co-Authored-By: deepseek-flash
2026-10-26 17:10:09 +01:00
yuanyuanxianganddeepseek-flash c271911fcb Feature: Add copy_files_c2c to transfer files between clients directly
Adds the 54th MCP tool, copy_files_c2c, which asks the source client to
push a set of files straight to another online client. Previously the only
way to move files between two clients was to download them to the server
machine and upload them again, so the data crossed the wire twice and
needed free disk on the server. With C2C the server only relays packets
and never parses or stores the payload.

Protocol. Two new ids in common/commands.h: COMMAND_C2C_SEND_FILES (174),
carrying the destination directory followed by a NUL-separated path list,
and TOKEN_C2C_SEND_RESULT (175), a fixed 45-byte result packet sent back
over the same sub-connection the transfer used. Clients advertise support
with the LOGIN_INFOR capability bit CLIENT_CAP_C2C_PATHS (0x0008), exposed
server side as Context::SupportsC2CPaths(). File transfer V2 already knew
how to push to dstClientID, so the destination side needed no change at
all; existing V2 receive paths keep working, and older clients simply do
not advertise the bit and are rejected with a clear error instead of
hanging.

Client. OnC2CSendFiles expands environment variables, collects directories
recursively, opens its own sub-connection (with sub-connection auth), and
runs FileBatchTransferWorkerV2 in a detached thread, then reports the
result on that same connection. Every early exit now reports a structured
failure rather than staying silent. The worker needs the process-level
InitFileUpload call that the receive path performs lazily, and a source
client may never have opened a file manager or received an upload, so the
initialization is factored into EnsureV2TransferInited() and called from
both paths.

Server. copy_files_c2c mirrors the existing upload tool: gates, id parsing,
capability checks, path validation, then a session keyed on the source host
that WaitC2CDone polls until the result packet arrives. The C2C relay
branch used to attach a CDlgFileSend progress dialog to the source's
sub-connection; NotifyProc then routed every later packet on that
connection to the dialog, which parsed the result packet as a V1 file
chunk and dropped it, so the tool always timed out even though the files
had arrived. IsC2CTransferPending() now suppresses dialog creation for
MCP-driven transfers only, leaving manual Ctrl+V transfers untouched.
Errors map to -32001 for a source-side transfer failure, -32010 for access
denied, -32009 for a missing path and -32002 for an offline destination.
Both hosts must be Windows: the destination is restricted too, because the
source embeds dst_dir in each V2 chunk name as an absolute Windows path and
only the Windows receiver applies it literally. A Linux or macOS receiver
never gets a target directory here (the clipboard flow sets one with
COMMAND_C2C_PREPARE, which this path does not send), so it would strip the
drive letter and write under / instead. Supporting that needs a prepare
packet carrying an explicit path plus an upgrade of those clients, so for
now the tool rejects them with -32005 rather than writing somewhere wrong.

Verified end to end on the Debug build: three files including a non-ASCII
name, an empty directory and a 3 MB binary arrived with matching SHA-256
in 3.2 s, a non-existent destination directory was created, and the
negative cases returned the documented codes. mcp_smoke.ps1 passes 41/41
with two new assertions and 27/27 in -SkipHost mode. Design notes, error
table and limitations are in docs/Mcp_FileTransfer_Design.md section 14
and docs/Mcp_Design.md section 15.

Co-Authored-By: deepseek-flash
2026-10-26 15:38:07 +01:00
yuanyuanxianganddeepseek-flash 27d40f5678 Fix: Expose tool payloads in the content text block
List and query tools put only a human summary in content and kept the real
payload in structuredContent. Clients that hand just content to the model
(WorkBuddy does) therefore never saw a host id: search_hosts answered "1 host
matched" and every follow-up tool was out of reach, and guessed ids 1-3100
could never work because host ids are 64-bit snowflake values.

BuildResult now appends the serialized structuredContent as a second text
block, as the MCP spec recommends for tools with structured output. The append
sits in the single result choke point, so every tool in McpServer, McpMachine
and McpChat gains it, including future ones; empty action results such as
remote_mouse keep their bare "ok".

Tools whose text already carries the payload expose only the difference:
exec_command and terminal_exec add exit_code, get_keylog adds counters,
get_activity_history exposes records without the duplicated raw dump, and the
hosts file reader drops its copy of the content. The override rides in a $
key that BuildResult consumes and removes, so responses change only by the
extra block.

Verified on a Debug instance: list_all_hosts, search_hosts, get_server_status
and list_registry return parseable JSON in content[1] with ids intact, and
tools/mcp_smoke.ps1 -SkipHost passes 27/27 with four new assertions.

Co-Authored-By: deepseek-flash
2026-10-26 14:12:50 +01:00
yuanyuanxianganddeepseek-flash a7dd86ff0f Feature: Terminate TLS for the MCP endpoint inside YAMA
MCP was served by a plain httplib::Server, so remote clients could only use
cleartext HTTP. YAMA now terminates TLS itself: a small front-end owns the
MCP port, sniffs the first byte and either runs a Schannel handshake and
forwards the decrypted bytes or passes plaintext through, with httplib
moving to a loopback-only internal port. No OpenSSL, no frp change, existing
local HTTP clients keep working, and an unusable certificate fails closed
instead of falling back to cleartext.

The identity loader grew the two things a public certificate needs. ECDSA
(P-256/P-384/P-521) keys are persisted by importing PKCS#8 with an
NCRYPTBUFFER_PKCS_KEY_NAME parameter, the only route MS Software KSP
supports for Schannel; RSA keeps its old export-and-repersist path.
Fullchains are accepted, and the intermediates are added to the current
user's CA store so Schannel, which builds chains only from system stores,
actually sends them. The shared handshake also now buffers a full TLS
record before the first AcceptSecurityContext, which a partial ClientHello
would otherwise poison (SEC_E_UNKNOWN_CREDENTIALS).

Session resumption exposed a second trap: when a client resumes a session,
ChangeCipherSpec, Finished and the first application record arrive in one
segment and AcceptSecurityContext leaves the application record pending in
the session. Nothing drained it, because both callers only decrypt when new
ciphertext arrives, so the request waited until the peer gave up (the MCP
front-end saw no request at all and the client reported "fetch failed
(other side closed)"; the device port had the same hole behind its
occasional login timeouts). Decrypt now drains pending data on len == 0, and
both the front-end and the device port's handshake thread use it before
entering their receive loops.

Configuration is McpHttps, McpCertPath, McpKeyPath and McpInternalPort, the
first three editable in the MCP settings dialog (the certificate rows stay
greyed out until HTTPS is enabled and saving rejects missing files).

Verified with a real Let's Encrypt ECDSA fullchain (53 tools over TLS, 401
with no or bad token), a local three-level chain whose intermediate was
absent from the store, Node 24's fetch on a resumed session (initialize,
notifications/initialized and tools/list all complete), and the device
port's RSA handshake as a regression check. Details in docs/Mcp_Design.md
section 13.

Co-Authored-By: deepseek-flash
2026-10-26 13:56:41 +01:00
yuanyuanxianganddeepseek-flash b4cb34fea9 Fix: Stop MCP tool timeouts from popping MFC dialogs
A sub-connection's first packet doubles as the readiness packet: the file,
service, registry, process, log and terminal tools all get answered that way.
Once a tool has given up (timeout or failure) its pending entry is gone, so if
the client only gets around to sending that first packet afterwards,
MessageHandle cannot tell it apart from a human click and opens the matching
modeless dialog - a File Manager window appeared while timeouts were being
exercised on this machine.

The wait paths now record, per device, which first-packet token the abandoned
tool would have sent (MarkLateFirstPacketForTool from WaitPending,
WaitPendingRegistry, WaitPendingWrite, WaitFileTransferDone and
WaitTerminalReady), and every dialog-opening case consumes that marker before
falling back to the MFC path. The marker is one-shot, expires after five
minutes and is never set on the success path, so normal use is unaffected; the
worst case is that a single manual open on a host that just had an MCP timeout
is swallowed.

ClientMsg packets are dropped with a log line while a tool is pending for that
host: new clients still send the legacy popup message alongside the structured
failure token, which would otherwise put a modal box on the server UI during an
MCP call.

Co-Authored-By: deepseek-flash
2026-10-25 18:12:56 +01:00
yuanyuanxianganddeepseek-flash 1456882f16 Docs: Record the structured failure protocol and -32010
Spell out the new token layout and who sends it, add -32010 to the error
table, and narrow -32008 to parameter validation now that capability
limits report -32005. Document McpToolTimeoutMs as an ini-only key and
correct the note about where the list_files 500-entry cap is applied.

Update the remote-control design and the test report so P2, P6 and P8
show as fixed with the measured evidence.

Co-Authored-By: deepseek-flash
2026-10-25 17:59:24 +01:00
yuanyuanxianganddeepseek-flash 3b1626f415 Feature: Turn client failure reports into branchable MCP errors
Wire the four new failure tokens into MessageHandle and translate them
in the tool builders, so the three previously silent failures now return
a code an agent can branch on: list_services on a non-elevated client is
-32010 in well under a second instead of a 20 s timeout, list_files and
list_registry distinguish a missing path or key (-32009) from an empty
one, and download_file no longer waits for the stall watchdog when the
remote path does not exist. Access denied gets its own code, -32010, and
the win32 code is kept in the message for every case.

TakeRegError fills both registry wait flags in one packet because a
failing client sends no subkey or value packet at all. OnDownloadError
sets the session error without cancelling the file-manager sub-connection,
which stays owned by ClearFileTransfer. ListRemoteTopLevelNames treats
"not found" as "directory not created yet" so uploading into a fresh
directory keeps working now that the client reports it.

Also converge the error codes that were overloaded: a multi-monitor host
is a capability limit, not a parameter mistake, so remote_open reports
-32005 instead of -32008. The tool wait timeout moves from a compile-time
constant to McpToolTimeoutMs in settings.ini (default 20000, clamped to
1-600 s), which makes it possible to tune without a rebuild.

The smoke test gains the three reproducible negatives.

Co-Authored-By: deepseek-flash
2026-10-25 17:59:21 +01:00
yuanyuanxianganddeepseek-flash 315a0855dc Feature: Let the client report structured failures for MCP tools
Four new client-to-server tokens carry a win32/LSTATUS code when a
command fails instead of returning empty data: TOKEN_SERVICE_ERROR
(170), TOKEN_FILE_LIST_ERROR (171), TOKEN_REG_ERROR (172) and
TOKEN_DOWNLOAD_ERROR (173). They sit on byte values that were unused,
so existing numbering is untouched.

The three data paths that used to collapse "failed" and "empty" into
the same packet now distinguish them: OpenSCManager failures, directory
enumeration failures and RegOpenKeyEx failures all report the code that
was actually returned, and UploadToRemoteV2 reports why it found no
file to transfer before the transfer sub-connection is ever created.

Every failure branch still sends the packet the old server expects
(TOKEN_FILE_LIST, the empty TOKEN_REG_PATH/KEY pair, the ClientMsg
popup), so a new client talking to an old server degrades to exactly
today's behaviour instead of timing out. Success paths are byte-for-
byte unchanged.

Co-Authored-By: deepseek-flash
2026-10-25 17:59:17 +01:00
yuanyuanxianganddeepseek-flash eaa10cc7d3 Fix: Make the MCP command sentinel robust and fail stalled downloads fast
Re-verified every finding of the 2026-10-25 MCP test report against the source and
then end-to-end on the Debug instance, and fixed the ones that live on the server.

P1/P3/P4 share one root cause: the sentinel was appended to the command line, so any
command that swallows the rest of its line (rem, cmd /c, if, for) swallowed the
sentinel too and the call always timed out. On ConPTY clients the command and the
sentinel are now sent as two lines, the sentinel prints %errorlevel% (whose echoed
text is a literal template, not digits) so folding echo can no longer be mistaken
for the sentinel, and FindSentinel returns the real exit code (9009, 1, 0, ...)
instead of 0/1. Old non-PTY clients keep the single-line form, since their echo
skipping depends on the write length.

ConPTY also returns a rendered screen stream rather than a byte stream, so stripped
VT sequences leave duplicate text behind; output cleaning now cuts through the
echoed command line, strips the echoed sentinel line and erases any leftover
sentinel text by its per-command nonce. StripAnsi no longer leaves the backslash of
an OSC terminated by ST.

A terminal session destroyed by a timeout used to report the same "not found" text
as a typo in the session id; a 600s tombstone now says what happened instead.
download_file gets a stall watchdog: no data for 60s fails with a clear message and
releases the host, where a missing remote path used to hold the whole host for the
full 600s default timeout.

Also corrects the get_activity_history annotation (it does reach the remote host),
completes the -32007/-32008/-32009 error table, documents the sentinel design in
Mcp_Design.md 12.1, and corrects the report's claim that the tools blocked during a
transfer are local DB reads -- they are remote machine-manager fetches, and purely
server-local tools are unaffected.

Co-Authored-By: deepseek-flash
2026-10-25 17:09:39 +01:00
yuanyuanxianganddeepseek-flash 1c5fab1645 Fix: Stop the client dropping chat messages that begin with e
CChatManager::OnReceive opened with the same heartbeat guard the other
managers use, `if (szBuffer[0] == TOKEN_HEARTBEAT) return;`, before it
looked at the length. TOKEN_HEARTBEAT is 101, which is also the letter e,
and this channel carries free text rather than command bytes, so every
message starting with e -- "echo", "error", anything -- was silently
discarded. The sender never learned: the server's chat dialog had already
written the text into its own log, so the two sides disagreed about what
was said.

The guard is dead code here. Heartbeats travel on the main connection
only, as a multi-byte [101][Heartbeat] packet consumed by the main
dispatcher; the server never sends one on a chat sub-connection. Delete
it and keep the length check that follows.

The server keeps prepending a space when the GBK payload starts with
101, because already-deployed clients still carry the guard and losing
the message outright is worse than an invisible leading space. Note the
same guard, harmless today, still sits in the machine, file, proxy and
screen-hide managers.

Verified with the Debug instance and a local Debug client: with the
server's space temporarily disabled, chat_send "echo test" and
"second line" both showed up verbatim in the client dialog (read back
with WM_GETTEXT); with the space restored the first arrives as
" echo test". Details in docs/Mcp_Chat_Design.md section 5.

Co-Authored-By: deepseek-flash
2026-10-25 14:57:47 +01:00
yuanyuanxianganddeepseek-flash cc3e11d30d Improve: Cover protocol and policy error codes in the MCP smoke test
The suite only exercised the happy paths, so a regression in the
negative paths -- unknown method, unknown tool, a missing required
argument, an oversized batch or a policy refusal -- would have gone
unnoticed. Add those checks alongside a section that reads the switches
from get_server_status, picks a feature that is actually turned off and
asserts its tool answers -32006; with every switch on it skips rather
than guessing, and with -AuditLog it also asserts the refusal shows up
as CALL_DENIED.

Document the full error-code table in section 12, including which codes
mean "retry with different arguments" and which mean "this is a policy
decision, retrying is pointless", and note that a batch call never
fails as a whole for per-host errors.

Verified against the Debug instance with McpKeylog temporarily set to
zero: get_keylog refused with -32006 and the audit log gained the
matching CALL_DENIED line, 34 checks passing; with the switch restored
32 pass, and 37 with a search path.

Co-Authored-By: deepseek-flash
2026-10-25 14:44:45 +01:00
yuanyuanxianganddeepseek-flash 7c5bf3e73d Feature: Filter search_file results by size, mtime and slim fields
Add four optional arguments to search_file that narrow the match list
after the client has returned it: min_size and max_size in bytes,
modified_after in either YYYY-MM-DD or YYYY-MM-DD HH:MM:SS form, and
name_only to keep just path and name per entry. The client still runs
the same name-matched recursive search, so these filters cut the
response size and the reasoning work on our side, not the scan time on
the host -- the summary sentence says so and totalAll keeps the
pre-filter count so a too-narrow condition is obvious. Invalid values
(negative sizes, an inverted range, a malformed timestamp) are rejected
with -32602 before any packet goes out.

The timestamp validator only accepted the ten-character form because
its shape loop never allowed the two colons, which rejected every
nineteen-character value; the loop now whitelists them.

Smoke tests cover the unchanged totalAll under a size filter, the slim
name_only payload and a rejected timestamp, for 33 checks when the
search path is supplied. Design notes are in section 11.4.

Co-Authored-By: deepseek-flash
2026-10-25 14:41:52 +01:00
yuanyuanxianganddeepseek-flash 929065e7be Feature: Filter the MCP host lists by group, OS and client type
list_online_hosts and list_all_hosts could only page, so finding "the
hosts in this group" or "the Linux ones" meant walking pages or falling
back to search_hosts, which has no client type filter and treats online
and offline hosts differently.

Both tools now accept group, os and client_type. They are substring
matches, combined with AND and case-insensitive over ASCII, matching the
semantics search_hosts already used, and the shared implementation keeps
the two tools from drifting apart. The filter runs before paging, so
total counts the matches and totalAll keeps the pre-filter size, and the
summary switches to the "matches" wording with a trailing line naming
the unfiltered size - a mistyped condition then shows up immediately
instead of silently returning nothing.

Offline hosts carry no clientType in their stored record, so a
client_type filter never matches them; the tool description says so and
points at os for that case.

Verified on the Debug instance: client_type=exe matches the single EXE
host while client_type=lnx matches nothing and still reports totalAll=1;
list_all_hosts with group=default matches all 3161 recorded hosts and
splits them into 1 online and 3160 offline, and os=zzz matches none. The
smoke test gains two checks and passes 28/28.

Co-Authored-By: deepseek-flash
2026-10-25 14:37:28 +01:00
yuanyuanxianganddeepseek-flash 5ce453797c Feature: Add a get_server_status tool to the MCP server
Answering "did my rebuild actually take effect" or "why was that tool
refused" used to mean reading list_online_hosts and get_audit_log and
inferring the rest. A single read-only call now returns the server's own
state: brand and version, the exe link time (taken from the file's last
write, which unlike __DATE__ reflects the whole build), how long the
process has been up, the address and port MCP is actually listening on,
every MCP switch, online and offline host counts, the number of sessions
in flight per family, and how many source IPs are currently blocked.

The bind and port are recorded by Start rather than re-read from the
configuration, so the tool reports what the listener really got. Session
counters take each subsystem's lock in turn and release it immediately,
so the numbers are an estimate of one moment, not a consistent snapshot.
Nothing sensitive is exposed: the token and the command whitelist never
appear, and the switches are reported as booleans only.

The tool is registered as read-only, non-destructive, idempotent and
server-local, which brings tools/list to 53 entries. The smoke test gains
three checks for it, including one that fails if a token-shaped field
ever appears in the output.

Verified on the Debug instance: the summary line reports version, uptime
and listener correctly, sessions.terminal goes 0 to 1 while a persistent
terminal is open and back to 0 after terminal_close, and the smoke test
passes 26/26.

Co-Authored-By: deepseek-flash
2026-10-25 14:35:19 +01:00
yuanyuanxianganddeepseek-flash ae37e812ee Feature: Page and filter the MCP audit log tool
get_audit_log used to hand back every entry in the main window's message
mirror on each call. The mirror is a 1000-entry ring buffer, so a busy
server returned a lot of text the caller never looked at, and there was
no way to ask for just the MCP entries or just the ones mentioning a
particular subject.

The tool now takes the same limit/offset pair as the other list tools
and two optional substring filters: type matches the type column and
keyword matches the message text, both case-insensitive. Filtering runs
before paging, so total counts the matches while totalAll keeps the size
of the whole mirror, and the summary line adds the pre-filter count when
a filter is in use so a typo is easy to spot. The GBK to UTF-8
conversion moved into the filter loop so the comparison happens between
strings in the same encoding, still under the dialog's critical section.

The output schema gains total/totalAll/offset/limit/hasMore, and the
smoke test now asserts the paging fields, the limit bound and an empty
result for a filter that cannot match, bringing it to 23 checks.

Verified on the Debug instance: limit=2 returns entries 1-2 then 3-4
with hasMore set, offset=999 reports the out-of-range text, type=mcp
matches the "MCP命令执行" entry, type=提示 matches both hint types and
keyword=监听 matches the listening-port line.

Co-Authored-By: deepseek-flash
2026-10-25 14:31:14 +01:00
yuanyuanxianganddeepseek-flash d9a1a9ebcb Fix: Record policy refusals in the MCP audit log
Every policy denial - read-only mode, one of the Mcp* switches turned
off, or a host that lacks the required capability - answers -32006. The
audit log only ever showed CALL_FAIL for those, which lumped them
together with parameter errors, offline hosts and timeouts, so after the
fact there was no way to tell "nobody called this" from "it was blocked
by policy".

The hooks all live in one place: the tools/call exit in the HTTP
handler now also reads error.code and error.message from the response it
already parses, and appends a CALL_DENIED event when the code is -32006.
The original CALL_FAIL line is still written, so its statistics keep
their old meaning, and the reason text is the fixed English sentence
each branch already returns - no tool arguments or user input reach the
log. Tool names taken from the request are flattened to a single line
first, both in the denied event and in the existing CALL_OK/CALL_FAIL
lines, so a crafted name cannot forge extra audit rows.

Also refresh the stale note in the design document that still called the
client search MAX_PATH overflow unfixed; the source was fixed in
8f718d9, but already-deployed clients still carry it, which is why the
smoke test keeps its search cases opt-in.

Verified on the Debug instance: with McpFileTransfer temporarily set to
0, download_file returns -32006 and the audit log gains the expected
CALL_DENIED line right after its CALL_FAIL; with the switch restored the
same call is CALL_OK again and no denied line appears. The read-only
smoke test passes 20/20.

Co-Authored-By: deepseek-flash
2026-10-25 14:28:16 +01:00
yuanyuanxianganddeepseek-flash 16f23e164c Fix: Clear the file transfer session when its sub-connection drops
A file transfer session holds raw pointers to its file-manager and
stream sub-connections, but nothing on the offline path looked at them.
OfflineProc cleans up terminal, remote-control and chat sessions and
skipped file transfers entirely, so a client that disconnected in the
middle of a transfer left the session pointing at a context that went
back to the connection pool. When the tool thread timed out it called
CancelIO on that stale pointer, which could cancel somebody else's
connection.

Add a context-to-device table next to the sessions, kept under the same
mutex and erased by ClearFileTransfer so a recycled pointer is never
mistaken for a live one. OfflineProc now calls
OnFileTransferContextClosed, which drops both pointers. A dropped
stream sub-connection means the transfer cannot complete, so it also
fails the session with error 1003 and wakes the waiting thread; the
file-manager sub-connection only issues the command and its loss is not
treated as a failure of the transfer itself.

Verified against the debug client: killing it 1.2 s into a 500 MB
download returns "Connection lost: the transfer sub-connection closed"
after about 1 s instead of waiting out timeout_ms, and the server stays
up. After the client restarts, two consecutive downloads and one upload
still work.

Co-Authored-By: deepseek-flash
2026-10-25 14:20:13 +01:00
yuanyuanxianganddeepseek-flash 39f0928de7 Fix: Finish a directory-only download instead of waiting for the timeout
The completion check compared filesDone against totalFiles minus
directoryCount and only ran on COMMAND_FILE_COMPLETE_V2. The client
sends no COMPLETE for directory entries, so a download of an empty
directory, or of a tree that holds only subdirectories, had zero
expected files and could never satisfy the check. The call sat there
until timeout_ms expired (600 s by default) and then reported 1002.

Mark the session done as soon as the directory entries account for
every entry the client declared. Verified with the debug client: an
empty directory returns in 0.2 s with zero files, a tree of nested
subdirectories returns in 0.2 s with the directories created, and a
directory holding three files still downloads them with the same
sizes and hashes as before.

Co-Authored-By: deepseek-flash
2026-10-25 14:16:46 +01:00
yuanyuanxianganddeepseek-flash 8f718d9b39 Fix: Stop the client file search from overflowing its path buffers
SearchFilesRecursive built "%s\*.*" and "%s\%s" with wsprintf into
char[MAX_PATH] buffers and never checked the lengths. The recursion
allows 32 levels, so a search from a drive root accumulates paths well
past 260 characters and writes off the end of the stack frame. Debug
builds raise Run-Time Check Failure #2 and the dialog blocks the search
thread; release builds corrupt the stack silently.

Check the length before each build and skip the entry when the full
path does not fit, so neither the name nor the recursion below it is
recorded. The root directory is checked once at function entry, which
also stops an over-long root from being enumerated at all.

Apply the same guard to the directory listing paths in both file
managers, and bound the search pattern built from the incoming keyword.
Zero-initialize the buffers filled by ExpandEnvironmentStringsA so a
failed expansion is treated as an empty path instead of reading
uninitialized stack.

Verified against the debug client with a full C:\ scan (10,000 results,
finished, no dialog) and a repeated deep search afterwards.

Co-Authored-By: deepseek-flash
2026-10-25 14:05:25 +01:00
yuanyuanxianganddeepseek-flash abe7e99a77 Feature: Harden the MCP transport and add non-destructive host tools
Cap MCP request bodies at 2 MB, set a 15 s idle read timeout and a 60 s
write timeout, and give httplib an explicit 32-thread pool: long tools
such as chat_wait hold a worker for up to 55 s, and the default pool of
8 to 15 left other callers queued.

Every tool returned by tools/list now carries readOnlyHint,
destructiveHint, idempotentHint and openWorldHint. The table is
per-tool; anything not registered defaults to destructive so a new
write tool cannot silently look harmless. Read-only tools are forced
to destructiveHint=false.

get_host_detail appends the technical fields the host store already
holds (cpuCores, memoryGB, systemBits, programBits, user, isAdmin,
installTime, expiredDate, monitors, exeVersion, clientPath, pid,
publicIp). The JSON writer is pinned to 15 significant digits so
memoryGB renders as 27.8 instead of 27.800000000000001. list hosts
output is unchanged.

Add host_set_remark and host_set_watch_level. Both validate the host
against the store, are refused in readonly mode, repaint the affected
row, and are audited without recording the value written.

Add search_file, which drives the client file-manager search channel
and returns paged results. The root path is normalized before sending:
the client enumerates with wsprintf("%s\*.*"), so a trailing
backslash produced C:\*.* and FindFirstFile failed, returning zero
hits instantly. The client only searches recursively, so non-recursive
requests are filtered server-side by comparing the parent directory.
Collection stops at 5000 records or 4 MB and the client is told to
stop; on timeout the partial results are returned. Search result
packets are never closed early: the sub-connection stays open until
TOKEN_SEARCH_FILE_FINISH, because the client's search thread holds a
pointer into the file manager object.

Batch reads report a skipped counter and are bounded to 50 ids and a
50 s deadline.

Add tools/mcp_smoke.ps1, a read-only end-to-end smoke test that asserts
auth rejection, the payload limit, annotation coverage, paging fields
and the main read tools. It takes the token from the environment and
never prints it.

Document all of the above in docs/Mcp_Design.md section 10, including
the client-side MAX_PATH stack overflow that a deep search_file call
can trigger, together with the workaround of searching shallow
directories.

Co-Authored-By: deepseek-flash
2026-10-25 13:59:17 +01:00
yuanyuanxianganddeepseek-flash ac5b174b5f Feature: Add offline hosts, batch reads and MCP hardening
Expose hosts the server already knows about. list_all_hosts enumerates
both live contexts and the historical records in the client list, with
authStatus as a three-state string instead of a boolean. search_hosts
now honours online=false instead of returning an empty list, while the
default stays online-only so existing callers see the same results.
get_host_detail falls back to the last known record for an offline host
rather than failing with -32002.

Let read-only tools take an ids array of up to 50 hosts in one call.
The batch path reuses the single-host dispatcher and pages per host, so
behaviour cannot drift; write tools reject ids with -32602 so a mistake
cannot fan out across machines.

Add get_keylog behind its own McpKeylog switch. It drives the client's
existing keylogger sub-connection, accumulates the streamed text for a
bounded window and byte cap, then closes the sub-connection and returns
UTF-8 lines. The client pushes its buffered history first, so a result
contains both history and fresh keystrokes; the tool description says so.

Harden the endpoint. Failed bearer checks are counted per source IP and
ten failures within a minute block the IP for fifteen minutes. Auth
failures and tool calls append to logs\mcp_audit.log with metadata only:
no token, no arguments, no response bodies, and rotation at 5 MB. Loopback
sources are audited but never blocked, because the built-in frp tunnel
makes every remote request arrive from 127.0.0.1 and banning that address
would lock out legitimate clients along with the attacker.

Give list-style tools one pagination contract (limit/offset plus
total/totalAll/hasMore) and fix the generated schemas so id and ids are
genuine alternatives: the stale required:[id] left over from the
single-host schema would otherwise reject ids-only calls.

Co-Authored-By: deepseek-flash
2026-10-25 12:44:45 +01:00
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
97 changed files with 15474 additions and 1037 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
+233 -50
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) {
@@ -278,7 +465,11 @@ INT_PTR CALLBACK CChatManager::ChatDialogProc(HWND hDlg, UINT uMsg, WPARAM wPara
VOID CChatManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
{
if (szBuffer[0] == TOKEN_HEARTBEAT) return;
// 这里没有心跳包:心跳只走主连接([TOKEN_HEARTBEAT][Heartbeat],且由主连接分发消费),
// 服务端从不给交谈子连接发心跳。原先照搬其它 manager 的
// if (szBuffer[0] == TOKEN_HEARTBEAT) return;
// 会在任何长度判断之前丢掉首字节为 101('e') 的包——而本通道承载的是自由文本,
// 于是「echo」「error」这类以 e 开头的消息被静默吞掉。删掉即可,保留长度判断。
if (ulLength == 1) {
switch (szBuffer[0]) {
@@ -317,21 +508,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)
+61 -6
View File
@@ -433,9 +433,14 @@ UINT CFileManager::SendFilesList(LPCTSTR lpszDirectory)
m_nTransferMode = TRANSFER_MODE_NORMAL;
// 展开环境变量 (如 %USERPROFILE%, %DESKTOP% 等)
char szExpandedDir[MAX_PATH];
char szExpandedDir[MAX_PATH] = { 0 }; // 展开失败时保持空串,避免下面的长度判断读未初始化栈
ExpandEnvironmentStringsA(lpszDirectory, szExpandedDir, MAX_PATH);
// 展开失败 / 目录 + "\*.*" + NUL 装不下:按空目录回(放在分配缓冲之前,免得多一条泄漏路径)
if (szExpandedDir[0] == '\0' || lstrlenA(szExpandedDir) + 5 > MAX_PATH) {
return SendListError(ERROR_INVALID_NAME);
}
UINT nRet = 0;
char strPath[MAX_PATH];
char *pszFileName = NULL;
@@ -455,8 +460,8 @@ UINT CFileManager::SendFilesList(LPCTSTR lpszDirectory)
hFile = FindFirstFile(strPath, &FindFileData);
if (hFile == INVALID_HANDLE_VALUE) {
BYTE bToken = TOKEN_FILE_LIST;
return Send(&bToken, 1);
// 路径不存在/不可访问:回结构化失败(TOKEN_FILE_LIST_ERROR),不再和「空目录」混为一包。
return SendListError(GetLastError());
}
*lpList = TOKEN_FILE_LIST;
@@ -556,6 +561,10 @@ void CFileManager::SearchFilesRecursive(LPCTSTR lpszDirectory, LPCTSTR lpszPatte
return;
}
// wsprintf 不做边界检查,超长会写穿栈(Debug 版弹 Run-Time Check Failure #2,
// Release 版静默破坏栈)。递归最多 32 层,深度累加很容易超过 MAX_PATH,必须逐层预判。
if (lstrlenA(lpszDirectory) + 5 > MAX_PATH) return; // 目录 + "\*.*" + NUL
char strPath[MAX_PATH];
WIN32_FIND_DATA FindFileData;
@@ -572,6 +581,11 @@ void CFileManager::SearchFilesRecursive(LPCTSTR lpszDirectory, LPCTSTR lpszPatte
BOOL bIsDir = FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
// 单个条目也要预判:全路径装不下就跳过(既不记录也不递归进去),
// 否则下面的 wsprintf 会写穿 szFullPath。
if (lstrlenA(lpszDirectory) + 1 + lstrlenA(FindFileData.cFileName) + 1 > MAX_PATH)
continue;
char szFullPath[MAX_PATH];
wsprintf(szFullPath, "%s\\%s", lpszDirectory, FindFileData.cFileName);
@@ -646,11 +660,21 @@ DWORD WINAPI CFileManager::SearchThreadProc(LPVOID lpParam)
void CFileManager::SearchFiles(LPCTSTR lpszSearchPath, LPCTSTR lpszSearchName)
{
// 展开环境变量
char szExpandedPath[MAX_PATH];
char szExpandedPath[MAX_PATH] = { 0 }; // 展开失败时为空串,递归里直接返回
ExpandEnvironmentStringsA(lpszSearchPath, szExpandedPath, MAX_PATH);
if (szExpandedPath[0] == '\0') { // 展开失败:直接按「0 条结果」结束
SendToken(TOKEN_SEARCH_FILE_FINISH);
return;
}
// 构建搜索模式 (如 *.txt 或 *keyword*)
char szPattern[MAX_PATH];
// 关键字来自网络包,最多 MAX_PATH 字节,加通配符后可能超出 szPattern。
if (lstrlenA(lpszSearchName) + 3 > MAX_PATH) {
SendToken(TOKEN_SEARCH_FILE_FINISH);
return;
}
if (strchr(lpszSearchName, '*') == NULL && strchr(lpszSearchName, '?') == NULL) {
wsprintf(szPattern, "*%s*", lpszSearchName);
} else {
@@ -825,6 +849,32 @@ int CFileManager::SendToken(BYTE bToken)
return Send(&bToken, 1);
}
// 列目录失败的结构化回报:[TOKEN_FILE_LIST_ERROR:1][win32err:4 LE]。
// 服务端(MCP list_files)据此返回「路径不存在/权限不足」,而不是一个空列表。
// 随后再补一个老的 1 字节 TOKEN_FILE_LIST:老服务端不认识新 token,仍按「空目录」处理,
// 行为与改动前完全一致。
UINT CFileManager::SendListError(DWORD dwErr)
{
if (dwErr == 0) dwErr = ERROR_GEN_FAILURE;
BYTE pkt[1 + sizeof(DWORD)] = { 0 };
pkt[0] = TOKEN_FILE_LIST_ERROR;
memcpy(pkt + 1, &dwErr, sizeof(DWORD));
int n = Send(pkt, (UINT)sizeof(pkt));
SendToken(TOKEN_FILE_LIST);
return n > 0 ? (UINT)n : 0;
}
// 下载请求无可用文件的结构化回报:[TOKEN_DOWNLOAD_ERROR:1][win32err:4 LE]。
// 走文件管理器子连接(传输子连接此时尚未建立),服务端立即失败而不是等停滞看门狗。
void CFileManager::SendDownloadError(DWORD dwErr)
{
if (dwErr == 0) dwErr = ERROR_FILE_NOT_FOUND;
BYTE pkt[1 + sizeof(DWORD)] = { 0 };
pkt[0] = TOKEN_DOWNLOAD_ERROR;
memcpy(pkt + 1, &dwErr, sizeof(DWORD));
m_ClientObject->Send2Server((char*)pkt, (UINT)sizeof(pkt));
}
bool CFileManager::UploadToRemote(LPBYTE lpBuffer)
{
if (lpBuffer[lstrlen((char *)lpBuffer) - 1] == '\\') {
@@ -1119,19 +1169,23 @@ void CFileManager::UploadToRemoteV2(LPBYTE lpBuffer, UINT nSize)
if (remotePaths.empty()) {
Mprintf("[V2] 没有要传输的文件\n");
SendDownloadError(ERROR_INVALID_PARAMETER);
return;
}
// 收集所有文件(展开目录)
std::vector<std::string> allFiles;
std::vector<std::string> rootCandidates; // 用于计算公共根目录
DWORD dwFirstErr = 0; // 首个失败的 win32 码(全部不存在时回传)
for (const auto& remotePath : remotePaths) {
std::string localPath = ExpandPath(remotePath.c_str());
DWORD attrs = GetFileAttributesA(localPath.c_str());
if (attrs == INVALID_FILE_ATTRIBUTES)
if (attrs == INVALID_FILE_ATTRIBUTES) {
if (dwFirstErr == 0) dwFirstErr = GetLastError();
continue;
}
if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
// 目录:递归收集
@@ -1150,7 +1204,8 @@ void CFileManager::UploadToRemoteV2(LPBYTE lpBuffer, UINT nSize)
}
if (allFiles.empty()) {
Mprintf("[V2] 没有找到可传输的文件\n");
Mprintf("[V2] 没有找到可传输的文件 (win32=%lu)\n", dwFirstErr);
SendDownloadError(dwFirstErr);
return;
}
+2
View File
@@ -55,6 +55,8 @@ private:
void CreateFolder(LPBYTE lpBuffer);
void Rename(LPBYTE lpBuffer);
int SendToken(BYTE bToken);
UINT SendListError(DWORD dwErr); // 列目录失败的结构化回报(TOKEN_FILE_LIST_ERROR + win32 码)
void SendDownloadError(DWORD dwErr); // 下载无可用文件的结构化回报(TOKEN_DOWNLOAD_ERROR + win32 码)
void CreateLocalRecvFile(LPBYTE lpBuffer);
void SetTransferMode(LPBYTE lpBuffer);
+18 -5
View File
@@ -467,10 +467,13 @@ BOOL IOCPClient::ConnectServer(const char* szServerIP, unsigned short uPort)
SetKeepAliveOptions(m_sClientSocket);
#endif
}
#ifdef _WIN32
#ifdef YAMA_TLS_CHANNEL
// 单向 TLS:证书存在(TlsEnabled())时,在应用协议首包前完成握手;握手失败即断开,
// 不回退明文(fail-closed,防降级)。证书存在但加载失败(TlsLoadError())同样拒绝
// 连接。握手须在 m_bConnected 置位前,确保工作线程不会在握手尚未完成时就开始 recv。
// m_useTls 在这里一次性锁定:Linux 客户端可能在此后收到服务端下发并热切换传输方式,
// 那条连接已建立,本连接的 Send/Recv 必须继续按握手时的传输方式走。
m_useTls = false;
if (TlsLoadError()) {
Mprintf("[TLS] 证书加载失败,拒绝连接(fail-closed)\n");
closesocket(m_sClientSocket);
@@ -484,6 +487,7 @@ BOOL IOCPClient::ConnectServer(const char* szServerIP, unsigned short uPort)
m_sClientSocket = INVALID_SOCKET;
return FALSE;
}
m_useTls = true;
}
#endif
m_bConnected = TRUE;
@@ -549,9 +553,9 @@ DWORD WINAPI IOCPClient::WorkThreadProc(LPVOID lParam)
Sleep(50);
continue;
}
#ifdef _WIN32
#ifdef YAMA_TLS_CHANNEL
// TLS 会话里可能有已解密、尚未交付的明文(select 只看底层 socket,看不到
// Schannel 内部缓冲),优先消费,避免被 select 卡住。
// TLS 库内部缓冲),优先消费,避免被 select 卡住。
if (This->HasPendingData()) {
if (!This->ProcessRecvData(&m_CompressedBuffer, szBuffer, MAX_RECV_BUFFER - 1, 0)) {
break;
@@ -665,8 +669,14 @@ VOID IOCPClient::OnServerReceiving(CBuffer* m_CompressedBuffer, char* szBuffer,
for (int i = 0; i < 16 && i < (int)bufLen; ++i) {
char tmp[12]; sprintf(tmp, "%02X ", (unsigned char)src[i]); buf += tmp;
}
Mprintf("[ERROR] Unknown header! this=%p bufLen=%lu, first 16 bytes: %s (TlsEnabled=%d tlsReady=%d)\n",
this, bufLen, buf.c_str(), (int)TlsEnabled(), (int)m_tls.IsReady());
#ifdef YAMA_TLS_CHANNEL
Mprintf("[ERROR] Unknown header! this=%p bufLen=%lu, first 16 bytes: %s (useTls=%d tlsReady=%d)\n",
this, bufLen, buf.c_str(), (int)m_useTls, (int)m_tls.IsReady());
#else
// macOS/Android 没有 TlsChannel(TLS 只在这两个平台之外的客户端实现)
Mprintf("[ERROR] Unknown header! this=%p bufLen=%lu, first 16 bytes: %s\n",
this, bufLen, buf.c_str());
#endif
m_CompressedBuffer->ClearBuffer();
break;
}
@@ -895,6 +905,9 @@ VOID IOCPClient::Disconnect()
closesocket(m_sClientSocket);
m_sClientSocket = INVALID_SOCKET;
#ifdef YAMA_TLS_CHANNEL
m_useTls = false; // 连接已断,Send/Recv 回到明文路径(下次 ConnectServer 重新锁定)
#endif
m_bConnected = FALSE;
}
+17 -9
View File
@@ -8,10 +8,13 @@
#include "stdafx.h"
#include <WinSock2.h>
#include <MSTcpIP.h>
#include "TlsChannel.h"
#pragma comment(lib,"ws2_32.lib")
#endif
// TLS 通道:Windows 走 Schannel,Linux 走 OpenSSL;macOS/Android 下该头为空,
// 且不定义 YAMA_TLS_CHANNEL,下方代码自动退回明文。
#include "TlsChannel.h"
#include "Buffer.h"
#include "zstd/zstd.h"
#include "domain_pool.h"
@@ -290,8 +293,8 @@ public:
protected:
virtual int ReceiveData(char* buffer, int bufSize, int flags)
{
#ifdef _WIN32
if (TlsEnabled())
#ifdef YAMA_TLS_CHANNEL
if (m_useTls)
return m_tls.Recv(m_sClientSocket, buffer, bufSize - 1);
#endif
// TCP版本调用 recv
@@ -301,18 +304,18 @@ protected:
virtual bool ProcessRecvData(CBuffer* m_CompressedBuffer, char* szBuffer, int len, int flag);
virtual int SendTo(const char* buf, int len, int flags)
{
#ifdef _WIN32
if (TlsEnabled())
#ifdef YAMA_TLS_CHANNEL
if (m_useTls)
return m_tls.Send(m_sClientSocket, buf, len);
#endif
return ::send(m_sClientSocket, buf, len, flags);
}
// TLS 会话里可能有已解密但尚未交付的明文(select 只能看到底层 socket 可读性,
// 看不到 Schannel 内部缓冲),接收线程在 select 前须优先消费,避免其被卡住。
// 看不到 TLS 库内部缓冲),接收线程在 select 前须优先消费,避免其被卡住。
bool HasPendingData() const
{
#ifdef _WIN32
return m_tls.HasPending();
#ifdef YAMA_TLS_CHANNEL
return m_useTls && m_tls.HasPending();
#else
return false;
#endif
@@ -325,8 +328,13 @@ protected:
protected:
sockaddr_in m_ServerAddr;
SOCKET m_sClientSocket;
#ifdef _WIN32
#ifdef YAMA_TLS_CHANNEL
TlsChannel m_tls; // TLS 会话(证书存在时才启用,见 TlsChannel.h)
// 本连接是否走 TLS:在 ConnectServer 里握手成功时置位、Disconnect 时清除,Send/Recv
// 一律按这个快照走,不再每次现查 TlsEnabled()。Linux 客户端支持服务端下发后热切换
// 传输方式(TlsReload),若现查全局开关,切换后到重连完成之间的这一秒里会把明文塞进
// 已建立的 TLS 会话(或反过来),白白制造协议错误。
bool m_useTls = false;
#endif
BOOL m_bWorkThread;
HANDLE m_hWorkThread;
+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
+183 -8
View File
@@ -1512,14 +1512,7 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
case COMMAND_SEND_FILE_V2: {
// 主连接接收 V2 上传:确保文件传输模块已初始化(RecvFileChunkV2 依赖 g_status==1)。
// static 标志保证进程内只初始化一次,不随主连接重连反复 Init/Uninit。
static bool s_v2RecvInited = false;
if (!s_v2RecvInited) {
int chunkKb, durMs;
GetTransferSpeed(*m_cfg, chunkKb, durMs);
InitFileUpload({}, m_LoginMsg, m_LoginSignature, chunkKb, durMs, Logf);
s_v2RecvInited = true;
}
EnsureV2TransferInited();
// C2C/V2 文件接收(RecvFileChunkV2 内部会打印进度)
// 展开文件名中的环境变量(如 %USERPROFILE%),与 V1 的 COMMAND_FILE_SIZE 保持一致。
// 快捷图标定位远程目录时,主控端下发的 targetDir 仍含未展开的 %USERPROFILE%
@@ -1563,6 +1556,12 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
break;
}
case COMMAND_C2C_SEND_FILES: {
// C2C 按路径清单发送:服务端指定「源端路径 + 目标端目录」,见 OnC2CSendFiles。
OnC2CSendFiles(szBuffer, ulLength);
break;
}
case COMMAND_CLIPBOARD_V2: {
// C2C 剪贴板请求:被请求发送剪贴板文件到另一个客户端
ClipboardRequestV2* req = (ClipboardRequestV2*)szBuffer;
@@ -1838,6 +1837,182 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
}
}
// V2 文件传输模块是进程级的(InitFileUpload/UninitFileUpload 成对),发送与接收共用一次初始化:
// static 标志保证进程内只初始化一次,不随主连接重连反复 Init/Uninit,也不会被发送/接收两个
// 入口各自初始化一次(第二次 Init 会重置状态并泄漏前一次的上下文)。
void CKernelManager::EnsureV2TransferInited()
{
static bool s_v2Inited = false;
if (s_v2Inited) return;
int chunkKb, durMs;
GetTransferSpeed(*m_cfg, chunkKb, durMs);
int rc = InitFileUpload({}, m_LoginMsg, m_LoginSignature, chunkKb, durMs, Logf);
if (rc != 0) Mprintf("[V2] InitFileUpload 返回 %d,V2 文件传输可能不可用\n", rc);
s_v2Inited = true;
}
// 收集目录下的文件与子目录(语义同 CFileManager::CollectFilesRecursiveV2:
// 目录本身先作为一条 V2 目录项,随后是子项)。无成员依赖,主连接侧直接复用。
static void CollectFilesForC2C(const std::string& dirPath, std::vector<std::string>& files)
{
std::string dirEntry = dirPath;
while (!dirEntry.empty() && (dirEntry.back() == '\\' || dirEntry.back() == '/'))
dirEntry.pop_back();
if (!dirEntry.empty()) files.push_back(dirEntry);
WIN32_FIND_DATAA wfd;
HANDLE hFind = FindFirstFileA((dirPath + "*.*").c_str(), &wfd);
if (hFind == INVALID_HANDLE_VALUE) return;
do {
if (wfd.cFileName[0] == '.') continue;
std::string fullPath = dirPath + wfd.cFileName;
if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
CollectFilesForC2C(fullPath + "\\", files);
else
files.push_back(fullPath);
} while (FindNextFileA(hFind, &wfd));
FindClose(hFind);
}
// 展开 %VAR%(与 CFileManager 的静态 ExpandPath 同语义,展开失败返回原路径)
static std::string ExpandPathForC2C(const char* path)
{
char szExpanded[MAX_PATH * 2] = { 0 };
DWORD len = ExpandEnvironmentStringsA(path, szExpanded, (DWORD)sizeof(szExpanded));
if (len > 0 && len < (DWORD)sizeof(szExpanded)) return szExpanded;
return path;
}
// C2C 按路径清单发送(服务端 → 源客户端)。
// 包格式:[C2CSendFilesPacket][targetDir\0][path1\0]...[pathN\0][\0](ANSI/936)。
// 与 COMMAND_CLIPBOARD_V2 的差别只在文件来源:这里的路径由服务端指定,不取剪贴板/资源管理器选中项。
// 数据由本端新开子连接上行,服务端按包内 dstClientID 原样中继到目标客户端的主连接。
void CKernelManager::OnC2CSendFiles(PBYTE szBuffer, ULONG ulLength)
{
if (ulLength < sizeof(C2CSendFilesPacket)) return;
const C2CSendFilesPacket* req = (const C2CSendFilesPacket*)szBuffer;
const char* p = (const char*)szBuffer + sizeof(C2CSendFilesPacket);
const char* end = (const char*)szBuffer + ulLength;
std::string targetDir = (p < end) ? std::string(p) : std::string();
p += targetDir.size() + 1;
std::vector<std::string> paths;
while (p < end && *p != '\0') {
paths.push_back(p);
p += strlen(p) + 1;
}
// 收包缓冲在 OnReceive 返回后即失效:先把要用的字段拷出来,线程里只用副本。
const uint64_t transferID = req->transferID;
const uint64_t dstClientID = req->dstClientID;
std::string hash(req->hash, strnlen(req->hash, sizeof(req->hash)));
std::string hmac(req->hmac, strnlen(req->hmac, sizeof(req->hmac)));
// 结果包(服务端 TOKEN_C2C_SEND_RESULT → MCP 等待线程)。任何早退都要回一包,
// 否则服务端只能干等超时——这与 download_file 早期的「静默超时」是同一种毛病。
auto sendResult = [&](uint32_t status, uint32_t win32err, int32_t workerRc,
uint32_t fileCount, uint64_t totalBytes) {
C2CSendResultPacket res = {};
res.cmd = TOKEN_C2C_SEND_RESULT;
res.transferID = transferID;
res.dstClientID = dstClientID;
res.status = status;
res.win32err = win32err;
res.workerRc = workerRc;
res.fileCount = fileCount;
res.totalBytes = totalBytes;
m_ClientObject->Send2Server((char*)&res, sizeof(res));
};
// FileBatchTransferWorkerV2 依赖 g_status==1(InitFileUpload 已调用),否则直接返回 -1。
// 源端可能从未打开过文件管理器、也从未接收过上传,所以这里必须显式初始化。
EnsureV2TransferInited();
if (paths.empty() || targetDir.empty()) {
Mprintf("[C2C] 路径清单发送请求非法: transferID=%llu, paths=%zu, targetDir=%s\n",
transferID, paths.size(), targetDir.c_str());
sendResult(FEV2_FILE_NOT_FOUND, ERROR_INVALID_PARAMETER, 0, 0, 0);
return;
}
// 收集文件:展开环境变量、递归展开目录(目录项本身也发给目标端,用于建空目录)
std::vector<std::string> allFiles;
DWORD dwFirstErr = 0;
for (const std::string& raw : paths) {
std::string localPath = ExpandPathForC2C(raw.c_str());
DWORD attrs = GetFileAttributesA(localPath.c_str());
if (attrs == INVALID_FILE_ATTRIBUTES) {
if (dwFirstErr == 0) dwFirstErr = GetLastError();
Mprintf("[C2C] 源路径不可访问: %s (win32=%lu)\n", localPath.c_str(), dwFirstErr);
continue;
}
if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
std::string dirPath = localPath;
if (dirPath.back() != '\\') dirPath += '\\';
CollectFilesForC2C(dirPath, allFiles);
} else {
allFiles.push_back(localPath);
}
}
if (allFiles.empty()) {
sendResult(FEV2_FILE_NOT_FOUND,
dwFirstErr ? dwFirstErr : (DWORD)ERROR_FILE_NOT_FOUND, 0, 0, 0);
return;
}
// 统计(目录项不计入 fileCount/totalBytes)
uint32_t fileCount = 0;
uint64_t totalBytes = 0;
for (const std::string& f : allFiles) {
WIN32_FILE_ATTRIBUTE_DATA fad;
if (!GetFileAttributesExA(f.c_str(), GetFileExInfoStandard, &fad)) continue;
if (fad.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue;
fileCount++;
totalBytes += ((uint64_t)fad.nFileSizeHigh << 32) | fad.nFileSizeLow;
}
IOCPClient* pClient = new IOCPClient(g_bExit, true, MaskTypeNone, m_conn);
pClient->EnableSubConnAuth(); // V2 文件传输子连接:每次连上后自动发 TOKEN_CONN_AUTH 校验
if (!pClient->ConnectServer(m_ClientObject->ServerIP().c_str(), m_ClientObject->ServerPort())) {
delete pClient;
Mprintf("[C2C] 连接服务器失败\n");
sendResult(1001, 0, -1, 0, 0);
return;
}
TransferOptionsV2 opts;
opts.transferID = transferID;
opts.srcClientID = m_MyClientID;
opts.dstClientID = dstClientID;
opts.enableResume = false; // v1 不做断点续传:失败即整包重发(目标端状态按 transferID 索引)
std::thread([allFiles, targetDir, pClient, opts, hash, hmac,
transferID, dstClientID, fileCount, totalBytes]() {
int rc = FileBatchTransferWorkerV2(allFiles, targetDir, pClient,
[](void* user, FileChunkPacketV2* chunk, unsigned char* data, int size) -> bool {
IOCPClient* client = (IOCPClient*)user;
return client->Send2Server((char*)data, size) != FALSE;
},
nullptr, hash, hmac, opts);
C2CSendResultPacket res = {};
res.cmd = TOKEN_C2C_SEND_RESULT;
res.transferID = transferID;
res.dstClientID = dstClientID;
res.status = (rc == 0) ? (uint32_t)FEV2_OK : (uint32_t)1001;
res.win32err = 0;
res.workerRc = (int32_t)rc;
res.fileCount = fileCount;
res.totalBytes = totalBytes;
pClient->Send2Server((char*)&res, sizeof(res));
delete pClient;
Mprintf("[C2C] 路径清单发送结束: transferID=%llu, %u 个文件, rc=%d\n",
transferID, fileCount, rc);
}).detach();
}
void CKernelManager::OnHeatbeatResponse(PBYTE szBuffer, ULONG ulLength)
{
if (ulLength > 8) {
+5
View File
@@ -200,6 +200,11 @@ public:
std::string m_hash;
std::string m_hmac;
uint64_t m_MyClientID = 0;
// COMMAND_C2C_SEND_FILES:按服务端指定的路径清单把文件直接发给另一个客户端。
// 包格式 [C2CSendFilesPacket][targetDir\0][path1\0]...[pathN\0][\0],结果用 TOKEN_C2C_SEND_RESULT 回传。
void OnC2CSendFiles(PBYTE szBuffer, ULONG ulLength);
// 进程级 V2 文件传输模块初始化(幂等),发送与接收两条路径共用。
void EnsureV2TransferInited();
// 执行代码
std::map<std::string, std::vector<BYTE>> m_MemDLL;
void SetLoginMsg(const std::string& msg)
+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);
+16
View File
@@ -57,6 +57,22 @@ VOID CRegisterManager::Find(char bToken, char *szPath)
// 子键包(TOKEN_REG_PATH):无子键时也回传空包,保证服务端(含 MCP 无头查询)
// 能确定性收齐 PATH+KEY 两包,无需靠超时猜测是否有第二包。
char *szBuffer= Opt.FindPath();
// 键打不开(不存在 / 路径不存在 / 拒绝访问 …):回结构化错误包。此前这种情况与
// 「空键」同为 NULL,服务端只能回一个空列表,调用方无法区分。
LSTATUS st = Opt.GetLastOpenStatus();
if (st != ERROR_SUCCESS) {
BYTE pkt[1 + sizeof(LSTATUS)] = { 0 };
pkt[0] = TOKEN_REG_ERROR;
memcpy(pkt + 1, &st, sizeof(LSTATUS));
m_ClientObject->Send2Server((char*)pkt, sizeof(pkt));
// 老服务端不认识 TOKEN_REG_ERROR:补上原来的两个空包,仍按「空键」处理,行为不变。
char empty[1 + sizeof(REGMSG)] = { 0 };
empty[0] = TOKEN_REG_PATH;
m_ClientObject->Send2Server(empty, sizeof(empty));
empty[0] = TOKEN_REG_KEY;
m_ClientObject->Send2Server(empty, sizeof(empty));
return;
}
if(szBuffer!=NULL) {
m_ClientObject->Send2Server((char*)szBuffer, LocalSize(szBuffer));
//目录下的目录
+5 -2
View File
@@ -60,6 +60,7 @@ RegisterOperation::RegisterOperation(char bToken)
}
ZeroMemory(KeyPath,MAX_PATH);
m_lastOpenStatus = ERROR_SUCCESS;
}
RegisterOperation::~RegisterOperation()
@@ -73,7 +74,8 @@ char* RegisterOperation::FindPath()
char *szBuffer=NULL;
HKEY hKey; //注册表返回句柄
/*打开注册表 User kdjfjkf\kdjfkdjf\ */
if(RegOpenKeyEx(MKEY,KeyPath,0,KEY_READ,&hKey)==ERROR_SUCCESS) { //打开
m_lastOpenStatus = RegOpenKeyEx(MKEY,KeyPath,0,KEY_READ,&hKey);
if(m_lastOpenStatus==ERROR_SUCCESS) { //打开
DWORD dwIndex=0,NameCount,NameMaxLen;
DWORD KeySize,KeyCount,KeyMaxLen,MaxDataLen;
//这就是枚举了
@@ -127,7 +129,8 @@ char* RegisterOperation::FindKey()
char *szBuffer=NULL;
HKEY hKey; //注册表返回句柄
if(RegOpenKeyEx(MKEY,KeyPath,0,KEY_READ,&hKey)==ERROR_SUCCESS) { //打开
m_lastOpenStatus = RegOpenKeyEx(MKEY,KeyPath,0,KEY_READ,&hKey);
if(m_lastOpenStatus==ERROR_SUCCESS) { //打开
DWORD dwIndex=0,NameSize,NameCount,NameMaxLen,Type;
DWORD KeyCount,KeyMaxLen,DataSize,MaxDataLen;
//这就是枚举了
+5
View File
@@ -19,6 +19,11 @@ public:
char KeyPath[MAX_PATH];
void SetPath(char *szPath);
char* FindKey();
// 最近一次 RegOpenKeyEx 的状态:区分「键打不开」(不存在/拒绝访问)与「键为空」
// (后者返回 NULL 但状态是 ERROR_SUCCESS)。
LSTATUS GetLastOpenStatus() const { return m_lastOpenStatus; }
private:
LSTATUS m_lastOpenStatus;
};
#endif // !defined(AFX_REGISTEROPERATION_H__BB4F3ED1_FA98_4BA4_97D6_A78E683131CC__INCLUDED_)
+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
+17 -4
View File
@@ -24,11 +24,20 @@ CServicesManager::~CServicesManager()
VOID CServicesManager::SendServicesList()
{
LPBYTE szBuffer = GetServicesList();
DWORD dwErr = 0;
LPBYTE szBuffer = GetServicesList(&dwErr);
if (szBuffer == NULL) {
if (dwErr == 0) dwErr = ERROR_GEN_FAILURE;
Mprintf("Get service list failed[IP: %s][win32=%lu]\n", m_ClientObject->GetPublicIP().c_str(), dwErr);
// 结构化失败回报:MCP 端据此立即返回「权限不足/SCM 打不开」,不必等 20s 超时。
// 老服务端不认识 TOKEN_SERVICE_ERROR,走 default 分支丢弃,随后仍按原样收到 ClientMsg。
BYTE pkt[1 + sizeof(DWORD)] = { 0 };
pkt[0] = TOKEN_SERVICE_ERROR;
memcpy(pkt + 1, &dwErr, sizeof(DWORD));
m_ClientObject->Send2Server((char*)pkt, sizeof(pkt));
// 保留原有弹窗消息:老服务端与 MFC 服务管理器(新 token 由对话框忽略)行为不变。
char buf[128];
sprintf_s(buf, "Get service list failed[IP: %s]", m_ClientObject->GetPublicIP().c_str());
Mprintf("%s\n", buf);
ClientMsg msg("服务管理", buf);
m_ClientObject->Send2Server((char*)&msg, sizeof(msg));
return;
@@ -42,7 +51,7 @@ VOID CServicesManager::SendServicesList()
#define skCrypt(p) p
#endif
LPBYTE CServicesManager::GetServicesList()
LPBYTE CServicesManager::GetServicesList(DWORD* err)
{
LPENUM_SERVICE_STATUS ServicesStatus = NULL;
LPQUERY_SERVICE_CONFIG ServicesInfor = NULL;
@@ -52,12 +61,14 @@ LPBYTE CServicesManager::GetServicesList()
DWORD dwLength = 0;
DWORD dwOffset = 0;
if((m_hscManager=OpenSCManager(NULL,NULL,SC_MANAGER_ALL_ACCESS))==NULL) {
if (err) *err = GetLastError(); // 典型 5=拒绝访问(未提权)
return NULL;
}
ServicesStatus = (LPENUM_SERVICE_STATUS) LocalAlloc(LPTR,64*1024);
if (ServicesStatus==NULL) {
if (err) *err = ERROR_NOT_ENOUGH_MEMORY;
CloseServiceHandle(m_hscManager);
return NULL;
}
@@ -75,8 +86,10 @@ LPBYTE CServicesManager::GetServicesList()
&dwResumeHandle);
szBuffer = (LPBYTE)LocalAlloc(LPTR, MAX_PATH);
if (szBuffer == NULL)
if (szBuffer == NULL) {
if (err) *err = ERROR_NOT_ENOUGH_MEMORY;
return NULL;
}
szBuffer[0] = TOKEN_SERVERLIST;
dwOffset = 1;
for (unsigned long i = 0; i < dwServicesCount; ++i) { // Display The Services,显示所有的服务
+1 -1
View File
@@ -20,7 +20,7 @@ public:
CServicesManager(IOCPClient* ClientObject, int n, void* user = nullptr);
virtual ~CServicesManager();
VOID SendServicesList();
LPBYTE GetServicesList();
LPBYTE GetServicesList(DWORD* err = NULL);
VOID OnReceive(PBYTE szBuffer, ULONG ulLength);
void ServicesConfig(PBYTE szBuffer, ULONG ulLength);
SC_HANDLE m_hscManager;
+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);
+95 -15
View File
@@ -1,25 +1,29 @@
// TlsChannel.h — Windows 客户端单向 TLS(Schannel)会话封装
// TlsChannel.h — 客户端单向 TLS 会话封装(Windows: Schannel;Linux: OpenSSL)
//
// 用途:为 YAMA 客户端(被控端)提供「按需开启」的传输层加密。当信任锚证书存在时
// (注册表 Software\<exehash>\settings\tls_cert,或 yama-ca.pem 文件,见 TlsChannel.cpp
// 的 InitTls),所有出站 TCP 连接在应用协议首包前先完成 TLS 握手;握手失败一律断开
// 用途:为 YAMA 客户端(被控端)提供「按需开启」的传输层加密。当信任锚证书存在时,
// 所有出站 TCP 连接在应用协议首包前先完成 TLS 握手;握手失败一律断开
// (fail-closed,不回退明文)。
//
// 选型:Schannel(Windows 原生 SSPI),零第三方依赖;secur32.lib / crypt32.lib 为
// 系统库。单向 TLS:客户端只校验服务端证书链到固定的信任锚,不提供客户端证书,
// 客户端身份仍由隧道内登录(V1 PwdHmac / V2 ECDSA)承担。
// 选型:
// - Windows:Schannel(原生 SSPI),零第三方依赖;secur32.lib / crypt32.lib 为系统库。
// - Linux:OpenSSL(构建链已因 libsign 链接 libcrypto,另加 libssl 即可)。
// 两者都是单向 TLS:客户端只校验服务端证书链到固定的信任锚,不提供客户端证书,
// 客户端身份仍由隧道内登录(V1 PwdHmac / V2 ECDSA)承担;均不校主机名(客户端按 IP
// 连接),不做吊销检查——与 Windows 版既有语义保持一致。
//
// 线程模型:Handshake 在连接建立线程上、m_bConnected 置位前调用;Send/Recv 分别在
// 发送线程 / 接收线程上调用。上下文生命周期(Handshake/CloseHandles 释放 m_ctx)与
// Send/Recv 对 m_ctx 的使用(EncryptMessage/DecryptMessage)由 m_ctxMtx 互斥,避免
// 重连线程释放上下文时与使用线程产生 use-after-free。本对象作为 IOCPClient 的值成员
// 存在,析构时释放上下文。
// 发送线程 / 接收线程上调用。上下文生命周期(Handshake/CloseHandles 释放上下文)与
// Send/Recv 对上下文的使用由 m_ctxMtx 互斥,避免重连线程释放上下文时与使用线程产生
// use-after-free。本对象作为 IOCPClient 的值成员存在,析构时释放上下文。
//
// 注意:本文件仅在 _WIN32 下有效,非 Windows 构建(Linux/macOS/Android)不含任何内容,
// 客户端维持明文(TLS 接入按设计文档延后)。
// 平台范围:_WIN32 与 Linux(非 Android)有实现;macOS / Android 不含任何内容,客户端
// 维持明文(TLS 接入按设计文档延后)。两平台都通过 YAMA_TLS_CHANNEL 宏告知调用方
// 「本平台有 TLS 通道」。
#pragma once
#ifdef _WIN32
#if defined(_WIN32)
#define YAMA_TLS_CHANNEL 1
#include <WinSock2.h>
@@ -91,4 +95,80 @@ private:
std::vector<BYTE> m_pending; // 已解密、未交付给应用层的明文
};
#endif // _WIN32
#elif defined(__linux__) && !defined(__ANDROID__)
#define YAMA_TLS_CHANNEL 1
#include <string>
#include <mutex>
struct ssl_st; // OpenSSL 的 SSL 类型,避免头文件把 openssl/ssl.h 拖进所有翻译单元
// 进程级 TLS 开关:首次调用时加载信任锚文件,返回是否启用。线程安全、幂等。
// Linux 版是「可热切换」的:TlsReload() 之后本函数立刻反映新状态(不是 call_once)。
bool TlsEnabled();
// 信任锚已配置但加载失败(无法读取/格式错误/内容为空)时为 true:客户端必须拒绝连接
// (fail-closed),不得静默回退明文。线程安全、幂等。
bool TlsLoadError();
// 服务端下发信任锚(COMMAND_TLS_ENABLE):把 PEM 正文写入
// $XDG_CONFIG_HOME/ghost/yama-ca.pem(默认 ~/.config/ghost/yama-ca.pem,无 HOME 时退回
// 程序目录),原子替换、权限 0600。写入前先解析验证,不是合法证书就整包拒绝。
// 落盘后用 TlsReload() 立即生效(Windows 客户端仍要重启进程)。
bool TlsTrustAnchorSave(const std::string& pem, std::string& err);
// 服务端撤销信任锚(COMMAND_TLS_DISABLE):删除上述配置文件(含程序目录同名文件)。
// 返回是否删掉了至少一个文件;之后同样用 TlsReload() 立即生效。
bool TlsTrustAnchorRemove(std::string& err);
// 按当前信任锚文件重建 TLS 上下文并更新开关,让随后建立的新连接立刻走新传输方式
// (已建立的连接不受影响:SSL 对象自持 SSL_CTX 引用)。信任锚无效时不做任何改动、
// 返回 false 并给出原因——一次坏下发不该把正在工作的客户端打死(下次启动仍 fail-closed)。
// 线程安全:与 TlsEnabled/TlsLoadError/Handshake 互斥。
bool TlsReload(std::string& err);
class TlsChannel
{
public:
TlsChannel() {}
~TlsChannel() { CloseHandles(); }
// 持 SSL*,禁止拷贝/赋值(避免上下文被二次释放)。
TlsChannel(const TlsChannel&) = delete;
TlsChannel& operator=(const TlsChannel&) = delete;
// 在已连通的 socket 上完成 TLS 1.2 客户端握手并按信任锚校验服务端证书链。失败返回
// false,调用方必须关闭 socket(fail-closed)。可重复调用(重连时复用同一对象)。
bool Handshake(int sock);
// 解密读取:返回 >0 的明文字节数;0 表示对端正常关闭;SOCKET_ERROR(-1) 出错。
int Recv(int sock, char* buf, int len);
// 加密发送 len 字节:成功返回已完整发送的明文字节数(== len);失败返回已发送的
// 前缀字节数(>0)或 SOCKET_ERROR(一个字节都没发出去时)。
int Send(int sock, const char* buf, int len);
// 是否有待交付的数据(SSL 内部已缓冲)供接收线程在 select 前优先消费。OpenSSL 会在
// 一个 TLS 记录里装多条应用数据,一次 SSL_read 只交付一部分;剩余的留在 SSL 内部,
// select 看不到,必须用 SSL_has_pending() 才能避免被 2 秒超时卡住。
bool HasPending() const;
// 握手是否已完成(Send/Recv 可用)。诊断用:区分「本连接已走 TLS」与「裸连接」。
bool IsReady() const { return m_ready; }
private:
void CloseHandles();
ssl_st* m_ssl = nullptr;
int m_fd = -1;
bool m_ready = false; // 握手完成,Send/Recv 可用
// 保护上下文生命周期:重连线程的 Handshake/CloseHandles(释放 m_ssl)与工作线程的
// Recv(SSL_read)、发送线程的 Send(SSL_write)互斥。OpenSSL 的 SSL 对象不允许
// 并发使用,所以 Send/Recv 也持锁——与 Windows 版同样式。
// mutable 是因为 HasPending() 是 const 但需要持锁读 m_ssl。
mutable std::recursive_mutex m_ctxMtx;
};
#endif // _WIN32 / __linux__ && !__ANDROID__
+559
View File
@@ -0,0 +1,559 @@
// TlsChannelLinux.cpp — 见 TlsChannel.h 头注释。仅 Linux(非 Android)编译。
//
// 与 Windows 的 Schannel 实现语义对齐:
// - 单向 TLS 1.2(min=max=1.2,与 SP_PROT_TLS1_2_CLIENT 及两套服务端一致);
// - 信任锚严格钉扎:证书链只按信任锚文件里的证书校验,不含系统根库;
// - 不校主机名(客户端按 IP 连接,与 Windows 版一致)、不做吊销检查;
// - 信任锚「存在即已配置」:读取/解析失败一律 TlsLoadError()=true → 调用方拒绝连接。
//
// 与 Windows 实现的差异:OpenSSL 自己管理 TLS 记录缓冲,不需要 m_raw/m_pending;
// 一次性交付不出去的明文留在 SSL 内部,由 SSL_has_pending()/SSL_pending() 暴露给
// 接收线程在 select 前优先消费。
#if defined(__linux__) && !defined(__ANDROID__)
#include "TlsChannel.h"
#include "common/commands.h" // SOCKET_ERROR / closesocket 等 POSIX 兼容宏
#include "common/logger.h" // Mprintf
#include <openssl/err.h>
#include <openssl/pem.h>
#include <openssl/ssl.h>
#include <openssl/x509.h>
#include <openssl/x509_vfy.h>
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iterator>
#include <mutex>
#include <string>
#include <vector>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
namespace {
const char* const kAnchorName = "yama-ca.pem";
// 进程级 TLS 状态。与 Windows 版的 call_once 不同,这里可由 TlsReload() 热切换
// (服务端 COMMAND_TLS_ENABLE/DISABLE 落盘后立即重建),因此用互斥量而不是 once_flag。
std::mutex g_stateMtx; // 保护下面四项
bool g_inited = false; // 首次加载已完成(含 fail-closed 基态)
bool g_tlsEnabled = false; // TLS 会话可用:send/recv 走加密
bool g_tlsError = false; // 信任锚存在但加载失败:拒绝连接(fail-closed)
SSL_CTX* g_tlsCtx = nullptr; // 进程级上下文(线程安全,可被多条连接共享)
std::string g_anchorPath; // 仅用于日志
// 配置目录:与 LinuxConfig 相同规则($XDG_CONFIG_HOME/ghost 或 ~/.config/ghost)。
std::string ConfigDir()
{
const char* xdg = getenv("XDG_CONFIG_HOME");
if (xdg && xdg[0])
return std::string(xdg) + "/ghost";
const char* home = getenv("HOME");
if (!home || !home[0])
return std::string();
return std::string(home) + "/.config/ghost";
}
// 可执行文件所在目录(readlink /proc/self/exe,失败返回空)。
std::string ExeDir()
{
char buf[4096];
ssize_t n = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
if (n <= 0)
return std::string();
buf[n] = '\0';
char* slash = strrchr(buf, '/');
if (!slash)
return std::string();
*slash = '\0';
return std::string(buf);
}
// 信任锚候选路径(按优先级),只返回已经存在的那个:
// 1) $XDG_CONFIG_HOME/ghost/yama-ca.pem(默认 ~/.config/ghost/yama-ca.pem)
// 2) 可执行文件同目录 yama-ca.pem(兼容手工投递,与 Windows 的 exe 同名文件回退一致)
bool FindAnchorPath(std::string& out)
{
std::vector<std::string> cands;
std::string dir = ConfigDir();
if (!dir.empty())
cands.push_back(dir + "/" + kAnchorName);
std::string exed = ExeDir();
if (!exed.empty())
cands.push_back(exed + "/" + kAnchorName);
for (size_t i = 0; i < cands.size(); ++i) {
if (access(cands[i].c_str(), F_OK) == 0) {
out = cands[i];
return true;
}
}
return false;
}
// 递归 mkdir -p(已存在视为成功)。
bool MkdirP(const std::string& path, mode_t mode)
{
if (path.empty())
return false;
struct stat st;
if (stat(path.c_str(), &st) == 0)
return S_ISDIR(st.st_mode);
size_t slash = path.find_last_of('/');
if (slash != std::string::npos && slash > 0) {
if (!MkdirP(path.substr(0, slash), mode))
return false;
}
if (mkdir(path.c_str(), mode) != 0 && errno != EEXIST)
return false;
return true;
}
// 把 PEM(可含多张证书)或 DER 信任锚写入 store。返回加入的证书数。
int LoadAnchors(const std::string& data, X509_STORE* store)
{
int added = 0;
if (data.find("-----BEGIN") != std::string::npos) {
BIO* bio = BIO_new_mem_buf(data.data(), (int)data.size());
if (bio) {
for (;;) {
X509* cert = PEM_read_bio_X509(bio, NULL, NULL, NULL);
if (!cert)
break;
if (X509_STORE_add_cert(store, cert) == 1)
++added;
else
ERR_clear_error(); // 重复证书等:忽略该张,继续读后面的
X509_free(cert);
}
BIO_free(bio);
}
ERR_clear_error();
}
if (added == 0) {
// 退回 DER(单张)
const unsigned char* p = (const unsigned char*)data.data();
X509* cert = d2i_X509(NULL, &p, (long)data.size());
if (cert) {
if (X509_STORE_add_cert(store, cert) == 1)
++added;
else
ERR_clear_error();
X509_free(cert);
}
ERR_clear_error();
}
return added;
}
enum BuildResult
{
BUILD_PLAINTEXT, // 没有信任锚文件 → 明文模式
BUILD_READY, // *outCtx 为新建上下文,调用方接管所有权
BUILD_INVALID, // 文件存在但读不了/解析不出证书(err 说明原因)
};
// 按当前信任锚文件构建一份新的 TLS 上下文。不读写任何全局状态,便于「先构建、成功再替换」。
BuildResult BuildState(SSL_CTX** outCtx, std::string& anchorPath, std::string& err, int& certs)
{
*outCtx = nullptr;
certs = 0;
anchorPath.clear();
std::string path;
if (!FindAnchorPath(path)) {
// 无证书 → 明文(默认,与老客户端一致)
return BUILD_PLAINTEXT;
}
anchorPath = path;
// 证书已配置:管理员已「颁发」,必须走 TLS;读取/解析失败即拒绝连接(fail-closed),
// 不能静默回退明文。
std::ifstream f(path.c_str(), std::ios::binary);
if (!f) {
err = "cannot open " + path + ": " + strerror(errno);
return BUILD_INVALID;
}
std::string pem((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
SSL_CTX* ctx = SSL_CTX_new(TLS_client_method());
if (!ctx) {
err = "SSL_CTX_new failed";
return BUILD_INVALID;
}
// TLS 1.2 钉扎:与 Windows 客户端(SP_PROT_TLS1_2_CLIENT)及两套服务端(Schannel
// SP_PROT_TLS1_2_SERVER / Go MinVersion=TLS1.2)保持一致。
SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
SSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION);
// SSL_VERIFY_PEER + 自定义 store = 严格钉扎到信任锚(不含系统根库),链校验在握手内
// 完成,失败即握手失败。verify 回调传 NULL 使用默认行为(只验链,不校主机名)。
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
SSL_CTX_set_verify_depth(ctx, 8);
// 对端不打招呼就断开(不发 close_notify)在这里是常态:服务端关闭子连接时不发,
// 客户端自己也同样不发(见 CloseHandles 的说明)。OpenSSL 3.0 起这种 unexpected EOF
// 被归为 SSL_ERROR_SSL 协议错误,于是每结束一个终端/文件传输子连接都会记一条
// 「SSL_read failed」——线上日志看着像 TLS 坏了。打开这个选项让它按正常关闭处理
// (SSL_read 返回 0),与 Recv 的文档语义以及 Windows 版的行为一致。
#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
SSL_CTX_set_options(ctx, SSL_OP_IGNORE_UNEXPECTED_EOF);
#endif
X509_STORE* store = X509_STORE_new();
certs = store ? LoadAnchors(pem, store) : 0;
if (!store || certs <= 0) {
if (store)
X509_STORE_free(store);
SSL_CTX_free(ctx);
certs = 0;
err = "trust anchor " + path + " present but empty/invalid";
return BUILD_INVALID;
}
SSL_CTX_set_cert_store(ctx, store); // ctx 接管 store 所有权
*outCtx = ctx;
return BUILD_READY;
}
// 替换全局状态并释放旧上下文(调用方持 g_stateMtx)。SSL 对象在 SSL_new 时已递增
// SSL_CTX 的引用计数,所以已经建立的连接不会因为这里释放旧 ctx 而失效。
void InstallStateLocked(SSL_CTX* ctx, bool enabled, bool error, const std::string& anchor)
{
SSL_CTX* old = g_tlsCtx;
g_tlsCtx = ctx;
g_tlsEnabled = enabled;
g_tlsError = error;
g_anchorPath = anchor;
if (old)
SSL_CTX_free(old);
}
// 首次加载(调用方持锁):锚存在但无效时置 fail-closed。
void EnsureInitLocked()
{
if (g_inited)
return;
g_inited = true;
SSL_CTX* ctx = nullptr;
std::string anchor, err;
int certs = 0;
switch (BuildState(&ctx, anchor, err, certs)) {
case BUILD_PLAINTEXT:
InstallStateLocked(nullptr, false, false, anchor);
Mprintf("[TLS] disabled: no trust anchor configured, plaintext mode\n");
break;
case BUILD_READY:
InstallStateLocked(ctx, true, false, anchor);
Mprintf("[TLS] enabled: trust anchor loaded (%s, %d cert(s)), all connections use TLS\n",
anchor.c_str(), certs);
break;
case BUILD_INVALID:
InstallStateLocked(nullptr, false, true, anchor);
Mprintf("[TLS] FATAL: %s; refusing connections (fail-closed)\n", err.c_str());
break;
}
}
} // namespace
bool TlsEnabled()
{
std::lock_guard<std::mutex> lk(g_stateMtx);
EnsureInitLocked();
return g_tlsEnabled;
}
bool TlsLoadError()
{
std::lock_guard<std::mutex> lk(g_stateMtx);
EnsureInitLocked();
return g_tlsError;
}
bool TlsReload(std::string& err)
{
std::lock_guard<std::mutex> lk(g_stateMtx);
EnsureInitLocked(); // 未初始化就先按启动语义建立基态,保持 fail-closed 行为
SSL_CTX* ctx = nullptr;
std::string anchor;
int certs = 0;
BuildResult r = BuildState(&ctx, anchor, err, certs);
if (r == BUILD_INVALID) {
// 保留原状态:一次坏下发不该让正在工作的客户端失联(下次启动仍会 fail-closed)。
Mprintf("[TLS] reload FAILED: %s; keeping current transport (%s)\n",
err.c_str(), g_tlsEnabled ? "TLS" : "plaintext");
return false;
}
if (r == BUILD_PLAINTEXT) {
InstallStateLocked(nullptr, false, false, anchor);
Mprintf("[TLS] reloaded: no trust anchor, transport is now plaintext\n");
return true;
}
InstallStateLocked(ctx, true, false, anchor);
Mprintf("[TLS] reloaded: trust anchor %s (%d cert(s)), transport is now TLS\n",
anchor.c_str(), certs);
return true;
}
// ---- 信任锚下发 / 撤销(服务端 COMMAND_TLS_ENABLE / COMMAND_TLS_DISABLE)----
bool TlsTrustAnchorSave(const std::string& pem, std::string& err)
{
if (pem.empty()) {
err = "empty certificate payload";
return false;
}
// 先验证再落盘:文件一旦写进去,下次启动就会被无条件信任,坏锚等于把客户端锁死
// (fail-closed 连不上,也没法再从服务端改回来)。宁可拒绝一次下发。
{
X509_STORE* probe = X509_STORE_new();
int n = probe ? LoadAnchors(pem, probe) : 0;
if (probe)
X509_STORE_free(probe);
if (n <= 0) {
err = "payload is not a valid PEM/DER certificate";
return false;
}
}
std::string dir = ConfigDir();
if (dir.empty()) {
dir = ExeDir(); // 无 HOME 的极端环境:退回程序目录
if (dir.empty()) {
err = "cannot resolve config directory";
return false;
}
}
if (!MkdirP(dir, 0700)) {
err = "cannot create directory " + dir + ": " + strerror(errno);
return false;
}
std::string path = dir + "/" + kAnchorName;
std::string tmp = path + ".tmp";
int fd = open(tmp.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0600);
if (fd < 0) {
err = "cannot create " + tmp + ": " + strerror(errno);
return false;
}
size_t off = 0;
while (off < pem.size()) {
ssize_t w = write(fd, pem.data() + off, pem.size() - off);
if (w <= 0) {
if (w < 0 && errno == EINTR)
continue;
err = "cannot write " + tmp + ": " + strerror(errno);
close(fd);
unlink(tmp.c_str());
return false;
}
off += (size_t)w;
}
fsync(fd);
close(fd);
// 原子替换 + 收紧权限(目录可能已由 LinuxConfig 以 0755 创建)
if (rename(tmp.c_str(), path.c_str()) != 0) {
err = "cannot replace " + path + ": " + strerror(errno);
unlink(tmp.c_str());
return false;
}
chmod(path.c_str(), 0600);
Mprintf("[TLS] trust anchor saved to %s\n", path.c_str());
return true;
}
bool TlsTrustAnchorRemove(std::string& err)
{
std::vector<std::string> paths;
std::string dir = ConfigDir();
if (!dir.empty())
paths.push_back(dir + "/" + kAnchorName);
std::string exed = ExeDir();
if (!exed.empty())
paths.push_back(exed + "/" + kAnchorName);
bool removed = false;
for (size_t i = 0; i < paths.size(); ++i) {
if (unlink(paths[i].c_str()) == 0) {
removed = true;
Mprintf("[TLS] trust anchor removed: %s\n", paths[i].c_str());
} else if (errno != ENOENT) {
err = "cannot remove " + paths[i] + ": " + strerror(errno);
return false;
}
}
if (!removed) {
err = "no trust anchor configured";
return false;
}
return true;
}
// ---- TlsChannel ----
void TlsChannel::CloseHandles()
{
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
if (m_ssl) {
SSL_free(m_ssl); // 不发送 close_notify:与 Windows 的 DeleteSecurityContext 同语义
m_ssl = nullptr;
}
m_fd = -1;
m_ready = false;
}
bool TlsChannel::Handshake(int sock)
{
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
CloseHandles(); // 重连时清理上一次会话(recursive 锁,此处可重入)
// 在状态锁内取一份上下文:SSL_new 会递增 SSL_CTX 引用计数,此后即使 TlsReload()
// 把全局上下文换掉(旧 ctx 被 SSL_CTX_free),本次握手的 SSL 仍然安全。
SSL* ssl = nullptr;
{
std::lock_guard<std::mutex> lk(g_stateMtx);
EnsureInitLocked();
if (g_tlsCtx)
ssl = SSL_new(g_tlsCtx);
}
if (!ssl) {
Mprintf("[TLS] handshake called but no TLS context is available\n");
return false;
}
if (SSL_set_fd(ssl, sock) != 1) {
Mprintf("[TLS] SSL_set_fd failed\n");
SSL_free(ssl);
return false;
}
SSL_set_connect_state(ssl);
// 阻塞 socket:WANT_READ / WANT_WRITE 只在记录分片等极端情形出现,重试即可。
for (;;) {
ERR_clear_error();
int r = SSL_do_handshake(ssl);
if (r == 1)
break;
int e = SSL_get_error(ssl, r);
if (e == SSL_ERROR_WANT_READ || e == SSL_ERROR_WANT_WRITE)
continue;
if (e == SSL_ERROR_SSL) {
unsigned long err = ERR_peek_last_error();
char ebuf[256] = {0};
if (err)
ERR_error_string_n(err, ebuf, sizeof(ebuf));
Mprintf("[TLS] handshake failed: %s\n", ebuf[0] ? ebuf : "SSL error");
} else if (e == SSL_ERROR_SYSCALL) {
Mprintf("[TLS] handshake failed: syscall error (%s)\n", strerror(errno));
} else {
Mprintf("[TLS] handshake failed: SSL_get_error=%d (peer closed?)\n", e);
}
SSL_free(ssl);
return false;
}
// 单向 TLS:链必须钉扎到信任锚,且服务端确实出示了证书。默认 verify 只验链不校主机名,
// 与 Windows 版(CertGetCertificateChain 只验链)行为一致。
long vr = SSL_get_verify_result(ssl);
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
X509* peer = SSL_get1_peer_certificate(ssl);
#else
X509* peer = SSL_get_peer_certificate(ssl);
#endif
if (!peer || vr != X509_V_OK) {
Mprintf("[TLS] server certificate not trusted against trust anchor (%s)\n",
X509_verify_cert_error_string(vr));
if (peer)
X509_free(peer);
SSL_free(ssl);
return false;
}
X509_free(peer);
m_ssl = ssl;
m_fd = sock;
m_ready = true;
Mprintf("[TLS] handshake OK (%s, server cert trusted)\n", SSL_get_version(ssl));
return true;
}
int TlsChannel::Recv(int sock, char* out, int outLen)
{
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
if (!m_ready || outLen <= 0) {
Mprintf("[TLS] Recv called but m_ready=%d (outLen=%d), returning SOCKET_ERROR\n",
(int)m_ready, outLen);
return SOCKET_ERROR;
}
(void)sock; // SSL 已绑定 fd
for (;;) {
ERR_clear_error();
int n = SSL_read(m_ssl, out, outLen);
if (n > 0)
return n;
int e = SSL_get_error(m_ssl, n);
if (e == SSL_ERROR_WANT_READ || e == SSL_ERROR_WANT_WRITE)
continue;
if (e == SSL_ERROR_ZERO_RETURN)
return 0; // close_notify:对端正常关闭
if (e == SSL_ERROR_SYSCALL && ERR_peek_last_error() == 0)
return 0; // 对端未发 close_notify 就断开(unexpected EOF),按关闭处理
Mprintf("[TLS] SSL_read failed: SSL_get_error=%d (%s)\n", e, strerror(errno));
return SOCKET_ERROR;
}
}
int TlsChannel::Send(int sock, const char* data, int len)
{
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
if (!m_ready)
return SOCKET_ERROR;
if (len <= 0)
return 0;
(void)sock; // SSL 已绑定 fd
int total = 0;
while (total < len) {
ERR_clear_error();
int n = SSL_write(m_ssl, data + total, len - total);
if (n > 0) {
total += n;
continue;
}
int e = SSL_get_error(m_ssl, n);
if (e == SSL_ERROR_WANT_READ || e == SSL_ERROR_WANT_WRITE)
continue;
Mprintf("[TLS] SSL_write failed: SSL_get_error=%d (%s), sent=%d/%d\n",
e, strerror(errno), total, len);
return total > 0 ? total : SOCKET_ERROR;
}
return total;
}
bool TlsChannel::HasPending() const
{
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
if (!m_ready || !m_ssl)
return false;
// SSL_pending: 已解密未交付的明文;SSL_has_pending: 内部还缓冲着未处理的记录字节。
// 任一为真都说明 select 看不到但可以立刻读,必须优先消费。
return SSL_pending(m_ssl) > 0 || SSL_has_pending(m_ssl) == 1;
}
#endif // __linux__ && !__ANDROID__
+5
View File
@@ -573,6 +573,11 @@ UINT CFileManager::SendFilesList(TCHAR* lpszDirectory)
else
lpszSlash = _T("");
TCHAR str_last[] = { _T('%'),_T('s'),_T('%'),_T('s'),_T('*'),_T('.'),_T('*'),_T('\0') };
// wsprintf 不做边界检查:目录 + "\*.*" + NUL 装不下就按空目录回,别写穿 strPath。
if ((int)(_tcslen(lpszDirectory) + _tcslen(lpszSlash)) + 4 > MAX_PATH) {
BYTE bToken = TOKEN_FILE_LIST;
return Send(&bToken, 1);
}
wsprintf(strPath, str_last, lpszDirectory, lpszSlash);
hFile = FindFirstFile(strPath, &FindFileData);
+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" />
+4 -26
View File
@@ -36,6 +36,7 @@
// FileTransferV2 is in the same directory (common/)
#include "FileTransferV2.h"
#include "UnixPath.h"
// External declaration of clientID (defined in main.cpp/main.mm)
extern uint64_t g_myClientID;
@@ -186,34 +187,11 @@ private:
// /:\ -> /
// /: -> /
// C:\Users\file.txt -> /Users/file.txt
// %USERPROFILE%\Desktop\ -> /home/user/Desktop/ (or the XDG desktop folder)
static std::string winPathToLinux(const char* winPath)
{
if (!winPath || !*winPath) return "/";
std::string p(winPath);
// 1. Backslash -> forward slash
for (auto& c : p) {
if (c == '\\') c = '/';
}
// 2. Remove "X:/" or "X:" prefix (handles both /: and C: style)
if (p.size() >= 3 && p[1] == ':' && p[2] == '/') {
p = p.substr(3);
} else if (p.size() >= 2 && p[1] == ':') {
p = p.substr(2);
}
// 3. Ensure starts with /
if (p.empty() || p[0] != '/') {
p = "/" + p;
}
// 4. Merge consecutive slashes
std::string result;
result.reserve(p.size());
for (size_t i = 0; i < p.size(); i++) {
if (i > 0 && p[i] == '/' && p[i - 1] == '/')
continue;
result += p[i];
}
return result.empty() ? "/" : result;
// 展开 %USERPROFILE% 等变量并把路径风格转成 Unix(见 UnixPath.h)
return UnixPath::ToUnixPath(winPath ? winPath : "");
}
// ---- Linux path -> Windows path (for sending to server) ----
+222 -43
View File
@@ -18,6 +18,7 @@
#include "commands.h"
#include "file_upload.h"
#include "UnixPath.h"
#include "../client/IOCPClient.h"
#include <unistd.h>
#include <sys/stat.h>
@@ -25,9 +26,13 @@
#include <dirent.h>
#include <iconv.h>
#include <cstring>
#include <cctype>
#include <cerrno>
#include "sha256_posix.h"
#include <string>
#include <vector>
#include <map>
#include <set>
#include <mutex>
#include <fstream>
#include <thread>
@@ -164,11 +169,15 @@ public:
// 处理 V2 文件数据包
// 返回: 0=成功, >0=错误码
static int RecvFileChunkV2(const uint8_t* buf, size_t len, uint64_t myClientID)
// reply:主连接(Linux 传 g_pMainClient)。非空时,C2C 传输的最后一个条目处理完会回一包
// 落盘结果(TOKEN_C2C_SEND_RESULT),服务端据此把 receiver_ack 变成真实值;
// 传 nullptr(macOS 目前没有全局主连接)则保持旧行为,不发回执。
static int RecvFileChunkV2(const uint8_t* buf, size_t len, uint64_t myClientID,
IOCPClient* reply = nullptr)
{
// 检查是否是 FILE_COMPLETE_V2 包
if (len >= 1 && buf[0] == COMMAND_FILE_COMPLETE_V2) {
return HandleFileComplete(buf, len, myClientID);
return HandleFileComplete(buf, len, myClientID, reply);
}
if (len < sizeof(FileChunkPacketV2)) {
@@ -210,10 +219,10 @@ public:
for (char& c : relPath) {
if (c == '\\') c = '/';
}
// 移除盘符前缀 (如 C:/)
if (relPath.size() >= 3 && relPath[1] == ':' && relPath[2] == '/') {
// 移除盘符前缀 (如 C:/)——只认「字母 + 冒号」,否则 /:data 这类合法路径会被改写
if (relPath.size() >= 3 && isalpha((unsigned char)relPath[0]) && relPath[1] == ':' && relPath[2] == '/') {
relPath = relPath.substr(3);
} else if (relPath.size() >= 2 && relPath[1] == ':') {
} else if (relPath.size() >= 2 && isalpha((unsigned char)relPath[0]) && relPath[1] == ':') {
relPath = relPath.substr(2);
}
// 移除开头的 /
@@ -222,26 +231,24 @@ public:
}
savePath += relPath;
} else {
// 服务端传输:使用相对路径
// 将 Windows 路径转换为 Linux 路径
savePath = fileName;
for (char& c : savePath) {
if (c == '\\') c = '/';
}
// 移除盘符前缀 (如 C:/)
if (savePath.size() >= 3 && savePath[1] == ':' && savePath[2] == '/') {
savePath = savePath.substr(2);
}
// 确保以 / 开头
if (savePath.empty() || savePath[0] != '/') {
savePath = "/" + savePath;
}
// 服务端传输:用服务端下发的绝对路径。
// 快捷按钮(桌面/下载/用户主页)下发的目标目录是 %USERPROFILE%\...,
// 由 WinPathToLinux 展开(见 UnixPath.h),与 Windows 上
// ExpandEnvironmentStringsA 的效果一致。
savePath = WinPathToLinux(fileName);
}
// 目录处理
if (pkt->flags & FFV2_DIRECTORY) {
MakeDirs(savePath + "/dummy");
// MakeDirs 不回报 mkdir 的失败(它还要给服务端下载复用),这里单独确认一次:
// 目录没建成也要让回执带上 errno,否则会向服务端谎报成功。
struct stat st;
int mkErr = 0;
if (stat(savePath.c_str(), &st) != 0) mkErr = errno ? errno : EIO;
else if (!S_ISDIR(st.st_mode)) mkErr = EIO;
Mprintf("[V2 Recv] Created directory: %s\n", savePath.c_str());
FinishC2CItem(pkt, reply, myClientID, false, true, 0, mkErr);
return 0;
}
@@ -250,9 +257,11 @@ public:
// 获取或创建接收状态
uint64_t stateKey = pkt->transferID ^ ((uint64_t)pkt->fileIndex << 48);
RecvState* state = GetOrCreateState(stateKey, pkt, savePath);
int openErr = 0;
RecvState* state = GetOrCreateState(stateKey, pkt, savePath, &openErr);
if (!state) {
Mprintf("[V2 Recv] Failed to create state\n");
FinishC2CItem(pkt, reply, myClientID, true, IsFinalChunk(pkt), 0, openErr ? openErr : EIO);
return 5;
}
@@ -260,7 +269,9 @@ public:
const char* data = (const char*)buf + sizeof(FileChunkPacketV2) + pkt->nameLength;
if (lseek(state->fd, pkt->offset, SEEK_SET) == -1) {
Mprintf("[V2 Recv] lseek failed: errno=%d\n", errno);
int e = errno;
Mprintf("[V2 Recv] lseek failed: errno=%d\n", e);
FinishC2CItem(pkt, reply, myClientID, true, IsFinalChunk(pkt), 0, e);
return 6;
}
@@ -270,7 +281,9 @@ public:
ssize_t n = write(state->fd, data + written, toWrite - written);
if (n <= 0) {
if (errno == EINTR) continue;
Mprintf("[V2 Recv] write failed: errno=%d\n", errno);
int e = errno;
Mprintf("[V2 Recv] write failed: errno=%d\n", e);
FinishC2CItem(pkt, reply, myClientID, true, IsFinalChunk(pkt), 0, e);
return 7;
}
written += n;
@@ -292,6 +305,15 @@ public:
// 文件完成
if (isLast) {
// 落盘长度自检:写到一半失败过、或偏移被改写,都会在这里落成「长度不符」
struct stat st;
int szErr = 0;
if (fstat(state->fd, &st) != 0) szErr = errno ? errno : EIO;
else if ((uint64_t)st.st_size != pkt->fileSize) szErr = EIO;
// 记账 + 最后一个条目时回执(要在拿 s_statesMtx 之前做:里面会 Send2Server)
FinishC2CItem(pkt, reply, myClientID, true, true, pkt->fileSize, szErr);
close(state->fd);
state->fd = -1;
Mprintf("[V2 Recv] File complete: %s\n", savePath.c_str());
@@ -306,7 +328,8 @@ public:
}
// 处理文件完成校验包
static int HandleFileComplete(const uint8_t* buf, size_t len, uint64_t myClientID)
static int HandleFileComplete(const uint8_t* buf, size_t len, uint64_t myClientID,
IOCPClient* reply = nullptr)
{
if (len < sizeof(FileCompletePacketV2)) {
return 1;
@@ -322,6 +345,9 @@ public:
Mprintf("[V2] File complete verify: transferID=%llu, fileIndex=%u, size=%llu\n",
pkt->transferID, pkt->fileIndex, pkt->fileSize);
// 空文件不发任何数据块(worker 只发这个完成包),C2C 回执只能靠它把该条目算作已处理
NoteC2CComplete(pkt, reply, myClientID);
// TODO: 实现 SHA-256 校验
// 目前简单返回成功
return 0;
@@ -404,25 +430,37 @@ public:
closedir(d);
}
// Windows 路径转 Linux 路径
// Windows 路径转 Linux 路径。服务端对话框的快捷按钮(桌面/下载/用户主页)下发的是
// %USERPROFILE%\Desktop\ 这类 Windows 变量路径,必须先展开(见 UnixPath.h)。
static std::string WinPathToLinux(const std::string& winPath)
{
std::string p = winPath;
// 1. 反斜杠 -> 正斜杠
for (auto& c : p) {
if (c == '\\') c = '/';
return UnixPath::ToUnixPath(winPath);
}
// errno -> Win32 错误码:服务端 TOKEN_DOWNLOAD_ERROR 按 Win32 码分类
// (McpServer::OnDownloadError: 2/3 -> 路径不存在,5 -> 拒绝访问,其余 -> 一般失败)。
static uint32_t PosixErrnoToWin32(int e)
{
switch (e) {
case ENOENT: return 2; // ERROR_FILE_NOT_FOUND
case ENOTDIR: return 3; // ERROR_PATH_NOT_FOUND
case EACCES:
case EPERM: return 5; // ERROR_ACCESS_DENIED
default: return 2;
}
// 2. 移除 "X:/" 或 "X:" 前缀
if (p.size() >= 3 && p[1] == ':' && p[2] == '/') {
p = p.substr(3);
} else if (p.size() >= 2 && p[1] == ':') {
p = p.substr(2);
}
// 3. 确保以 / 开头
if (p.empty() || p[0] != '/') {
p = "/" + p;
}
return p;
}
// 下载请求无可用文件的结构化回报:[TOKEN_DOWNLOAD_ERROR:1][win32err:4 LE]。
// 走文件管理器子连接(服务端此时还在等第一批 chunk),让它立即失败而不是等停滞看门狗。
// 与 Windows 客户端 CFileManager::SendDownloadError 等价。
static void SendDownloadError(IOCPClient* client, uint32_t win32err)
{
if (client == nullptr) return;
if (win32err == 0) win32err = 2; // ERROR_FILE_NOT_FOUND
uint8_t pkt[1 + sizeof(uint32_t)] = { 0 };
pkt[0] = (uint8_t)TOKEN_DOWNLOAD_ERROR;
memcpy(pkt + 1, &win32err, sizeof(uint32_t));
client->Send2Server((char*)pkt, (ULONG)sizeof(pkt));
}
// 处理 CMD_DOWN_FILES_V2 请求 - 上传文件到服务端
@@ -448,19 +486,22 @@ public:
if (remotePaths.empty()) {
Mprintf("[V2 Send] No files to send\n");
SendDownloadError(client, 87); // ERROR_INVALID_PARAMETER(与 Windows 客户端一致)
return;
}
// 收集所有文件 (展开目录)
std::vector<std::string> allFiles;
std::vector<std::string> rootCandidates;
int firstErrno = 0; // 首个失败的 errno(全部不存在时回报给服务端)
for (const auto& remotePath : remotePaths) {
std::string localPath = WinPathToLinux(remotePath);
struct stat st;
if (stat(localPath.c_str(), &st) != 0) {
Mprintf("[V2 Send] File not found: %s\n", localPath.c_str());
if (firstErrno == 0) firstErrno = errno ? errno : ENOENT;
Mprintf("[V2 Send] File not found: %s (errno=%d)\n", localPath.c_str(), errno);
continue;
}
@@ -481,7 +522,8 @@ public:
}
if (allFiles.empty()) {
Mprintf("[V2 Send] No files found\n");
Mprintf("[V2 Send] No files found (errno=%d)\n", firstErrno);
SendDownloadError(client, PosixErrnoToWin32(firstErrno));
return;
}
@@ -596,6 +638,9 @@ public:
uint64_t offset = 0;
std::vector<uint8_t> buffer;
buffer.reserve(sizeof(FileChunkPacketV2) + targetNameGbk.length() + CHUNK_SIZE);
Sha256 hasher; // 流式 SHA-256:服务端落盘后会用它校验
bool truncated = false; // 读失败/文件变短 → 不发完成包,避免谎报校验通过
bool sendOk = true;
while (offset < fileSize || (offset == 0 && fileSize == 0)) {
size_t toRead = std::min(CHUNK_SIZE, (size_t)(fileSize - offset));
@@ -628,21 +673,26 @@ public:
ssize_t n = read(fd, dataPtr, toRead);
if (n < 0) {
Mprintf("[V2 Send] read failed: errno=%d\n", errno);
truncated = true;
break;
}
hasher.update(dataPtr, (size_t)n);
if ((size_t)n < toRead) {
// 文件读取不完整,调整包大小
// 文件读取不完整(传输中被截断):调整包大小后作为末块发出,
// 但不发完成包 —— 服务端按原 fileSize 收不全,必须让它失败而不是校验通过。
toRead = n;
pkt->dataLength = toRead;
buffer.resize(sizeof(FileChunkPacketV2) + targetNameGbk.length() + toRead);
isLast = true;
pkt->flags |= FFV2_LAST_CHUNK;
truncated = true;
}
}
// 发送
if (!client->Send2Server((char*)buffer.data(), (ULONG)buffer.size())) {
Mprintf("[V2 Send] Send failed\n");
sendOk = false;
break;
}
@@ -650,12 +700,31 @@ public:
// 空文件处理
if (fileSize == 0) break;
if (truncated) break; // 已按末块发出,不再续读
// 发送间隔 (避免发送过快)
usleep(10000); // 10ms
}
close(fd);
// 完成校验包:服务端凭它判定该文件结束并比对 SHA-256(目录项不发)。
// 与 Windows 客户端 FileBatchTransferWorkerV2 的发送点一致;没有它 MCP
// download_file 的会话永远等不到 filesDone 达标。
if (sendOk && !truncated) {
FileCompletePacketV2 cpkt;
memset(&cpkt, 0, sizeof(cpkt));
cpkt.cmd = COMMAND_FILE_COMPLETE_V2;
cpkt.transferID = transferID;
cpkt.srcClientID = myClientID;
cpkt.dstClientID = 0; // 目标是主控端
cpkt.fileIndex = fileIndex;
cpkt.fileSize = fileSize;
hasher.final(cpkt.sha256);
if (!client->Send2Server((char*)&cpkt, (ULONG)sizeof(cpkt))) {
Mprintf("[V2 Send] Send complete packet failed\n");
}
}
}
Mprintf("[V2 Send] Transfer complete: transferID=%llu\n", transferID);
@@ -663,7 +732,7 @@ public:
private:
static RecvState* GetOrCreateState(uint64_t key, const FileChunkPacketV2* pkt,
const std::string& savePath)
const std::string& savePath, int* openErrno = nullptr)
{
std::lock_guard<std::mutex> lock(s_statesMtx);
@@ -682,6 +751,7 @@ private:
// 打开文件
state->fd = open(savePath.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (state->fd < 0) {
if (openErrno) *openErrno = errno; // errno 会被下面的 Mprintf 冲掉,先存
Mprintf("[V2 Recv] open failed: %s, errno=%d\n", savePath.c_str(), errno);
return nullptr;
}
@@ -691,6 +761,111 @@ private:
return ptr;
}
// ===== C2C 接收回执 =====
// C2C 的目标端不再只是「收包落盘」:本次传输的每个条目都定案后回一包
// C2CSendResultPacket(TOKEN_C2C_RECV_RESULT,与源端的 175 分开,免得两种语义混在一个 token 里),
// 把「是否真的写进去了」告诉服务端。Windows 目标端没有这个能力,服务端对它们保持旧语义。
//
// 条目定案的三个来源(缺一不可):
// 1) 目录项:worker 发的 FFV2_DIRECTORY 包(不带 LAST_CHUNK);
// 2) 非空文件:最后一块写盘成功(再 fstat 核对长度);
// 3) 空文件:worker 不发任何数据块,只发 COMMAND_FILE_COMPLETE_V2。
// 源端的重发(最多 3 次)和「最后一块 + 完成包」都会重复命中同一 fileIndex,用 done 集合去重。
struct RecvProgress {
uint32_t totalFiles = 0; // 从任意数据块/目录包学到(完成包里没有这个字段)
std::set<uint32_t> doneFiles; // 已定案的文件 fileIndex
std::set<uint32_t> doneDirs; // 已定案的目录项 fileIndex
uint64_t bytes = 0; // 实收文件字节数
bool failed = false;
int firstErrno = 0;
};
static bool IsFinalChunk(const FileChunkPacketV2* pkt)
{
return (pkt->flags & FFV2_LAST_CHUNK) != 0;
}
static uint8_t MapErrnoToFileError(int e)
{
switch (e) {
case EACCES:
case EPERM:
case EROFS: return FEV2_ACCESS_DENIED;
case ENOENT:
case ENOTDIR: return FEV2_FILE_NOT_FOUND;
case ENOSPC: return FEV2_DISK_FULL;
default: return FEV2_WRITE_FAILED;
}
}
// 记录一个条目的处理结果;finalChunk 表示这一包关掉了该条目(文件的最后一块 / 目录项 / 完成包)。
// 所有条目都定案后就发回执。err != 0 表示这一条目失败(errno 原样带给服务端)。
static void FinishC2CItem(const FileChunkPacketV2* pkt, IOCPClient* reply, uint64_t myClientID,
bool isFile, bool finalChunk, uint64_t bytes, int err)
{
if (pkt->dstClientID == 0 || reply == nullptr) return; // 服务端上传/下载、或没有回执通道
C2CSendResultPacket res = {};
{
std::lock_guard<std::mutex> lk(s_recvProgressMtx);
// 传输中途断掉时条目会残留:攒多了整体清一次(残留的都是已废弃的 transferID)
if (s_recvProgress.size() > 32) s_recvProgress.clear();
RecvProgress& e = s_recvProgress[pkt->transferID];
if (pkt->totalFiles != 0) e.totalFiles = pkt->totalFiles; // 完成包里没有,沿用学到的值
if (err != 0) {
e.failed = true;
if (e.firstErrno == 0) e.firstErrno = err;
}
if (finalChunk) {
if (isFile) {
if (e.doneFiles.insert(pkt->fileIndex).second && err == 0) e.bytes += bytes;
} else {
e.doneDirs.insert(pkt->fileIndex);
}
}
const bool finished = e.totalFiles != 0
&& e.doneFiles.size() + e.doneDirs.size() >= e.totalFiles;
if (!finished) return;
res.cmd = (uint8_t)TOKEN_C2C_RECV_RESULT;
res.transferID = pkt->transferID;
res.dstClientID = myClientID; // 服务端按连接身份 + dstClientID 双重核对
res.status = e.failed ? (uint32_t)MapErrnoToFileError(e.firstErrno)
: (uint32_t)FEV2_OK;
res.win32err = (uint32_t)e.firstErrno; // 176 包里放的是 errno,不是 win32 码
res.workerRc = 0; // 恒 0:不是源端 worker 返回码
res.fileCount = (uint32_t)e.doneFiles.size();
res.totalBytes = e.bytes;
s_recvProgress.erase(pkt->transferID);
}
// 锁外发送:Send2Server 可能阻塞,不应占着进度表
if (reply->IsConnected() && reply->Send2Server((char*)&res, sizeof(res))) {
Mprintf("[V2 Recv] C2C ack: transferID=%llu, files=%u, bytes=%llu, status=%u, errno=%u\n",
(unsigned long long)res.transferID, res.fileCount,
(unsigned long long)res.totalBytes, res.status, res.win32err);
} else {
Mprintf("[V2 Recv] C2C ack send failed: transferID=%llu\n",
(unsigned long long)res.transferID);
}
}
// COMMAND_FILE_COMPLETE_V2:空文件的唯一「定案」来源(也用来给已定案的非空文件去重)
static void NoteC2CComplete(const FileCompletePacketV2* cp, IOCPClient* reply, uint64_t myClientID)
{
if (cp->dstClientID == 0 || reply == nullptr) return;
FileChunkPacketV2 probe = {};
probe.cmd = COMMAND_SEND_FILE_V2;
probe.transferID = cp->transferID;
probe.dstClientID = cp->dstClientID;
probe.fileIndex = cp->fileIndex;
probe.totalFiles = 0; // 完成包没有 totalFiles,沿用进度表里学到的
probe.fileSize = cp->fileSize;
FinishC2CItem(&probe, reply, myClientID, true, true, 0, 0); // 空文件 bytes=0
}
// 接收状态存储
static inline std::map<uint64_t, std::unique_ptr<RecvState>> s_states;
static inline std::mutex s_statesMtx;
@@ -698,4 +873,8 @@ private:
// C2C 目标目录存储
static inline std::map<uint64_t, std::string> s_targetDirs;
static inline std::mutex s_targetDirMtx;
// C2C 接收进度(按 transferID;定案发完回执即删)
static inline std::map<uint64_t, RecvProgress> s_recvProgress;
static inline std::mutex s_recvProgressMtx;
};
+214
View File
@@ -0,0 +1,214 @@
/**
* UnixPath.h - Windows-style path handling on Unix clients
*
* The Windows server sends paths in its own dialect: drive letters ("C:\", or
* "/:" for a Unix root), backslashes, and environment variables that the Windows
* client expands with ExpandEnvironmentStringsA. The remote shortcut buttons
* (server/2015Remote/FileManagerDlg.cpp: OnRemoteDesktop/OnRemoteDownloads/
* OnRemoteHome) are the visible case — they send "%USERPROFILE%\Desktop\" and
* friends, which a Unix client cannot open as-is.
*
* This header turns such paths into something the Unix clients can use:
* %USERPROFILE% / %HOME% / %HOMEDRIVE%%HOMEPATH% -> $HOME
* %USERNAME% / %USER% / %LOGNAME% -> login name
* $HOME/Desktop (etc.) -> the XDG folder when
* user-dirs.dirs maps it
* (e.g. ~/桌面)
* Unknown %VAR% tokens are left untouched, so paths that legitimately contain a
* percent sign keep working as before.
*
* PLATFORM SUPPORT: Linux, macOS. Windows resolves these natively and does not
* include this header.
*/
#pragma once
#include <unistd.h>
#include <pwd.h>
#include <sys/stat.h>
#include <cctype>
#include <cstdlib>
#include <fstream>
#include <map>
#include <string>
namespace UnixPath
{
// ---- Home directory of the account the client runs as ----
inline std::string HomeDir()
{
const char* home = getenv("HOME");
if (home && *home) return home;
struct passwd* pw = getpwuid(getuid());
if (pw && pw->pw_dir && *pw->pw_dir) return pw->pw_dir;
return "/";
}
inline std::string TrimTrailingSlashes(std::string path)
{
while (path.size() > 1 && path.back() == '/') path.pop_back();
return path;
}
// Read ~/.config/user-dirs.dirs into {"Desktop" -> "/home/user/桌面", ...}.
// The shortcuts use the English folder names, but on a localized desktop the
// real folders are translated and only user-dirs.dirs knows where they are.
// Entries pointing at a missing directory are dropped so the caller falls back
// to the plain "$HOME/<Name>" path.
inline std::map<std::string, std::string> LoadXdgUserDirs()
{
std::map<std::string, std::string> dirs;
std::string home = TrimTrailingSlashes(HomeDir());
const char* cfgHome = getenv("XDG_CONFIG_HOME");
std::string file = (cfgHome && *cfgHome) ? cfgHome : (home + "/.config");
file += "/user-dirs.dirs";
std::ifstream in(file.c_str());
std::string line;
while (std::getline(in, line)) {
size_t eq = line.find('=');
if (eq == std::string::npos || line.compare(0, 4, "XDG_") != 0)
continue;
std::string key = line.substr(4, eq - 4); // DESKTOP_DIR
if (key.size() <= 4 || key.compare(key.size() - 4, 4, "_DIR") != 0)
continue;
std::string value = line.substr(eq + 1);
if (value.size() >= 2 && value.front() == '"' && value.back() == '"')
value = value.substr(1, value.size() - 2);
// $HOME / ${HOME} are the only variables user-dirs.dirs may use
for (size_t pos; (pos = value.find("${HOME}")) != std::string::npos; )
value.replace(pos, 7, home);
for (size_t pos; (pos = value.find("$HOME")) != std::string::npos; )
value.replace(pos, 5, home);
// DESKTOP_DIR -> "Desktop"
std::string name = key.substr(0, key.size() - 4);
for (auto& c : name) c = (char)tolower((unsigned char)c);
if (!name.empty()) name[0] = (char)toupper((unsigned char)name[0]);
if (!value.empty() && access(value.c_str(), F_OK) == 0)
dirs[name] = TrimTrailingSlashes(value);
}
return dirs;
}
inline const std::map<std::string, std::string>& XdgUserDirs()
{
// C++11 guarantees a thread-safe one-time initialization of the local static
static const std::map<std::string, std::string> dirs = LoadXdgUserDirs();
return dirs;
}
// Rewrite $HOME/Desktop (etc.) to the localized folder user-dirs.dirs names.
// Expects a slash-separated absolute path.
inline std::string RemapXdgUserDir(const std::string& path)
{
std::string home = TrimTrailingSlashes(HomeDir());
if (path.compare(0, home.size(), home) != 0)
return path;
const std::map<std::string, std::string>& dirs = XdgUserDirs();
if (dirs.empty())
return path;
std::string base = (home == "/") ? "" : home;
for (const auto& kv : dirs) {
std::string prefix = base + "/" + kv.first;
if (path == prefix ||
(path.compare(0, prefix.size(), prefix) == 0 && path[prefix.size()] == '/'))
return kv.second + path.substr(prefix.size());
}
return path;
}
// Expand %USERPROFILE% style variables in a path the server sent.
inline std::string ExpandWindowsEnvVars(const std::string& in)
{
std::string out;
out.reserve(in.size());
for (size_t i = 0; i < in.size(); ) {
if (in[i] != '%') {
out += in[i++];
continue;
}
size_t end = in.find('%', i + 1);
if (end == std::string::npos) {
out.append(in, i, std::string::npos);
break;
}
// Windows variable names are case-insensitive
std::string name = in.substr(i + 1, end - i - 1);
for (auto& c : name) c = (char)toupper((unsigned char)c);
bool known = true;
std::string value;
if (name == "USERPROFILE" || name == "HOME" || name == "HOMEPATH") {
value = HomeDir();
} else if (name == "HOMEDRIVE") {
// "%HOMEDRIVE%%HOMEPATH%" has to come out as a single absolute home path
value = "";
} else if (name == "USERNAME" || name == "USER" || name == "LOGNAME") {
const char* user = getenv("USER");
if (!user || !*user) user = getenv("LOGNAME");
struct passwd* pw = getpwuid(getuid());
value = (user && *user) ? user : ((pw && pw->pw_name) ? pw->pw_name : "");
} else {
known = false;
}
if (known)
out += value;
else
out.append(in, i, end - i + 1);
i = end + 1;
}
return out;
}
// Convert a Windows-dialect path into one the Unix clients can open:
// %USERPROFILE%\Desktop\ -> /home/user/Desktop/ (or the XDG desktop folder)
// /:\home\user\file.txt -> /home/user/file.txt
// C:\Users\file.txt -> /Users/file.txt
// "" -> /
inline std::string ToUnixPath(const std::string& winPath)
{
if (winPath.empty()) return "/";
std::string p = ExpandWindowsEnvVars(winPath);
// 1. Backslash -> forward slash
for (auto& c : p) {
if (c == '\\') c = '/';
}
// 2. Remove "X:/" or "X:" prefix (handles both /: and C: style)
if (p.size() >= 3 && p[1] == ':' && p[2] == '/') {
p = p.substr(3);
} else if (p.size() >= 2 && p[1] == ':') {
p = p.substr(2);
}
// 3. Ensure starts with /
if (p.empty() || p[0] != '/') {
p = "/" + p;
}
// 4. Merge consecutive slashes
std::string result;
result.reserve(p.size());
for (size_t i = 0; i < p.size(); i++) {
if (i > 0 && p[i] == '/' && p[i - 1] == '/')
continue;
result += p[i];
}
if (result.empty()) return "/";
// 5. "$HOME/Desktop" -> localized folder (~/桌面 ...) when user-dirs.dirs says so
return RemapXdgUserDir(result);
}
} // namespace UnixPath
+25 -1
View File
@@ -136,6 +136,8 @@ inline int isValid_10s()
#define CLIENT_CAP_UTF8 0x0002 // 协议字符串字段统一使用 UTF-8 编码(活动窗口、窗口列表、键盘记录中的窗口标题等)
// 无此位 = 老客户端,按系统 ANSI(默认 CP936)解读
#define CLIENT_CAP_SCREEN_PREVIEW 0x0004 // 支持屏幕预览(双击在线主机时弹缩略图)
#define CLIENT_CAP_C2C_PATHS 0x0008 // 支持按路径清单向另一客户端发送文件(COMMAND_C2C_SEND_FILES,仅 Windows)
#define CLIENT_CAP_C2C_RECV_ACK 0x0010 // 作为 C2C 目标端时,落盘完成后回执(TOKEN_C2C_RECV_RESULT,目前仅 Linux)
#define TALK_DLG_MAXLEN 1024 // 最大输入字符长度
@@ -330,6 +332,20 @@ enum {
COMMAND_REGEN_CLIENT_ID = 168, // 服务端 → 客户端:撞 ID 的克隆机重生成 client_id(掺随机 UUID)后重连
COMMAND_SCREEN_KEYFRAME_REQ = 169, // 服务端 → 客户端:下一次屏幕编码强制输出 IDR(Web 屏幕墙恢复用)
// MCP 结构化失败回报(客户端 → 服务端,仅失败分支发送;成功路径报文不变)。
// 170-198 是当前未占用的字节值,显式赋值避免后续插入重编号。
TOKEN_SERVICE_ERROR = 170, // [token:1][win32err:4 LE] 服务枚举失败(典型:OpenSCManager 权限不足)
TOKEN_FILE_LIST_ERROR = 171, // [token:1][win32err:4 LE] 文件列表失败(典型:路径不存在/非法)
TOKEN_REG_ERROR = 172, // [token:1][lstatus:4 LE] 注册表打开失败(键不存在/拒绝访问)
TOKEN_DOWNLOAD_ERROR = 173, // [token:1][win32err:4 LE] 下载请求无可用文件(路径全部不存在)
// MCP C2C 文件传输(服务端 → 源客户端 → 目标客户端;数据由服务端原样中继)。
// COMMAND_C2C_SEND_FILES / TOKEN_C2C_SEND_RESULT 只有声明 CLIENT_CAP_C2C_PATHS 的新客户端认识;
// TOKEN_C2C_RECV_RESULT 由声明 CLIENT_CAP_C2C_RECV_ACK 的目标端回发,老服务端走 default 丢弃。
COMMAND_C2C_SEND_FILES = 174, // [C2CSendFilesPacket][targetDir\0][path1\0]...[\0]
TOKEN_C2C_SEND_RESULT = 175, // [C2CSendResultPacket] 源客户端回传的发送结果
TOKEN_C2C_RECV_RESULT = 176, // [C2CSendResultPacket] 目标客户端回传的落盘回执(win32err 放 errno)
TOKEN_DECRYPT = 199,
TOKEN_REGEDIT = 200, // 注册表
COMMAND_REG_FIND, // 注册表 管理标识
@@ -1097,6 +1113,11 @@ typedef struct LOGIN_INFOR {
unsigned int caps = CLIENT_CAP_V2 | CLIENT_CAP_UTF8;
#ifdef _WIN32
caps |= CLIENT_CAP_SCREEN_PREVIEW;
caps |= CLIENT_CAP_C2C_PATHS;
#elif defined(__linux__) && !defined(__ANDROID__)
// Linux 客户端作为 C2C 目标端时会回执落盘结果(common/FileTransferV2.h)。
// macOS 暂未接线(无全局主连接句柄),不声明——服务端就不会为它空等回执。
caps |= CLIENT_CAP_C2C_RECV_ACK;
#endif
sprintf_s(moduleVersion, "%s-%04X", DLL_VERSION, caps);
}
@@ -1682,6 +1703,10 @@ typedef struct CharMsg {
}
} CharMsg;
#endif
// 客户端 -> 服务端的老式提示框消息(TOKEN_CLIENT_MSG)。原来定义在 _WIN32 区内,
// Linux 客户端自升级失败回报也要用,故移到公共区(strcpy_s 在非 Windows 下已 alias)。
typedef struct ClientMsg {
unsigned char cmd;
char title[31];
@@ -1704,4 +1729,3 @@ typedef struct ClientMsg {
}
} ClientMsg;
#endif
+29
View File
@@ -99,6 +99,34 @@ struct C2CPrepareRespPacket {
// char path[pathLength]; // UTF-8 目标目录
}; // 19 bytes + path
// C2C 路径清单发送请求(服务端 → 源客户端):让源客户端把指定路径(文件或目录)直接发给另一个客户端。
// 与 COMMAND_CLIPBOARD_V2 的区别是「路径由服务端指定」,而不是取源端剪贴板/资源管理器选中项。
// 字符串一律用 ANSI(936),与 CMD_DOWN_FILES_V2 一致:客户端用 A 版 API 访问文件系统。
struct C2CSendFilesPacket {
uint8_t cmd; // COMMAND_C2C_SEND_FILES = 174
uint64_t transferID; // 传输ID(服务端生成,结果包原样带回)
uint64_t srcClientID; // 源客户端(收包方)
uint64_t dstClientID; // 目标客户端(收包方即发送方,数据包里带上它)
char hash[64]; // 认证哈希(与上一级主控一致,目标端按自己的 m_hash 解密)
char hmac[16]; // HMAC
uint8_t flags; // 保留(bit0 = 断点续传,v1 恒 0,不启用)
// char targetDir[...]; '\0'; // 目标端保存目录(绝对路径,不以 '\' 结尾也可)
// char path1[...]; '\0'; ...; // 源端绝对路径(文件或目录),列表以空串结束:额外一个 '\0'
}; // 106 bytes + 字符串
// C2C 结果包:源客户端 → 服务端(TOKEN_C2C_SEND_RESULT,发送结果)
// 或 目标客户端 → 服务端(TOKEN_C2C_RECV_RESULT,落盘回执;win32err 位置放 errno,workerRc 恒 0)
struct C2CSendResultPacket {
uint8_t cmd; // TOKEN_C2C_SEND_RESULT = 175 / TOKEN_C2C_RECV_RESULT = 176
uint64_t transferID; // 对应请求的 transferID
uint64_t dstClientID; // 目标客户端
uint32_t status; // 0=已全部发送;FEV2_* 失败码;1001=发送线程失败(见 workerRc)
uint32_t win32err; // status=FEV2_FILE_NOT_FOUND/ACCESS_DENIED 时的首个 win32 码
int32_t workerRc; // FileBatchTransferWorkerV2 返回值(0=成功)
uint32_t fileCount; // 实际发出的文件数(不含目录项)
uint64_t totalBytes; // 实际发出的(回执里是实际落盘的)文件字节数
}; // 41 bytes(#pragma pack(1))
// V2 文件完成校验包
struct FileCompletePacketV2 {
uint8_t cmd; // COMMAND_FILE_COMPLETE_V2 = 91
@@ -130,6 +158,7 @@ enum FileErrorV2 : uint8_t {
FEV2_TRANSFER_CANCEL = 6, // 传输被取消
FEV2_CHECKSUM_ERROR = 7, // 校验和错误(块级CRC)
FEV2_HASH_MISMATCH = 8, // 哈希不匹配(文件级SHA-256)
FEV2_WRITE_FAILED = 9, // 接收端写盘失败(POSIX 端 errno 无法归类时用它,明细在 win32err)
};
// V2 续传查询包(发送方在传输前发送)
+148
View File
@@ -0,0 +1,148 @@
/**
* sha256_posix.h - 最小实现 SHA-256(POSIX 侧)
*
* 为什么不用现成的:Windows 侧的 SHA-256 走 BCrypt(common/VerifyV2.h),
* Linux/macOS 没有 BCrypt,也没有 OpenSSL 依赖,而 V2 文件发送要向服务端
* 回报 FileCompletePacketV2.sha256,必须自己算。
*
* 只实现 FileTransferV2 需要的流式接口(update/final),不做别的事。
*/
#pragma once
#if defined(_WIN32) || defined(_WIN64)
#error "sha256_posix.h is POSIX-only; Windows uses BCrypt via VerifyV2.h."
#endif
#include <cstddef>
#include <cstdint>
#include <cstring>
class Sha256
{
public:
Sha256() { reset(); }
void reset()
{
static const uint32_t init[8] = {
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
};
memcpy(m_h, init, sizeof(m_h));
m_bufLen = 0;
m_totalLen = 0;
}
void update(const void* data, size_t len)
{
const uint8_t* p = (const uint8_t*)data;
m_totalLen += len;
if (m_bufLen > 0) {
size_t take = 64 - m_bufLen;
if (take > len) take = len;
memcpy(m_buf + m_bufLen, p, take);
m_bufLen += take;
p += take;
len -= take;
if (m_bufLen == 64) {
transform(m_buf);
m_bufLen = 0;
}
}
while (len >= 64) {
transform(p);
p += 64;
len -= 64;
}
if (len > 0) {
memcpy(m_buf, p, len);
m_bufLen = len;
}
}
// 输出 32 字节摘要;调用后对象可 reset() 复用(不自动 reset,避免隐式行为)
void final(uint8_t out[32])
{
uint64_t bitLen = m_totalLen * 8;
// 0x80 + 零填充 + 64 位长度,凑满整块
uint8_t pad[72];
memset(pad, 0, sizeof(pad));
pad[0] = 0x80;
size_t padLen = (m_bufLen < 56) ? (56 - m_bufLen) : (120 - m_bufLen);
update(pad, padLen);
uint8_t lenBytes[8];
for (int i = 0; i < 8; ++i) {
lenBytes[i] = (uint8_t)(bitLen >> (56 - 8 * i));
}
update(lenBytes, sizeof(lenBytes));
for (int i = 0; i < 8; ++i) {
out[4 * i] = (uint8_t)(m_h[i] >> 24);
out[4 * i + 1] = (uint8_t)(m_h[i] >> 16);
out[4 * i + 2] = (uint8_t)(m_h[i] >> 8);
out[4 * i + 3] = (uint8_t)(m_h[i]);
}
}
static void hash(const void* data, size_t len, uint8_t out[32])
{
Sha256 s;
s.update(data, len);
s.final(out);
}
private:
static uint32_t rotr(uint32_t x, int n) { return (x >> n) | (x << (32 - n)); }
void transform(const uint8_t block[64])
{
static const uint32_t K[64] = {
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
};
uint32_t w[64];
for (int i = 0; i < 16; ++i) {
w[i] = ((uint32_t)block[4 * i] << 24) | ((uint32_t)block[4 * i + 1] << 16) |
((uint32_t)block[4 * i + 2] << 8) | (uint32_t)block[4 * i + 3];
}
for (int i = 16; i < 64; ++i) {
uint32_t s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >> 3);
uint32_t s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >> 10);
w[i] = w[i - 16] + s0 + w[i - 7] + s1;
}
uint32_t a = m_h[0], b = m_h[1], c = m_h[2], d = m_h[3];
uint32_t e = m_h[4], f = m_h[5], g = m_h[6], h = m_h[7];
for (int i = 0; i < 64; ++i) {
uint32_t S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
uint32_t ch = (e & f) ^ (~e & g);
uint32_t t1 = h + S1 + ch + K[i] + w[i];
uint32_t S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
uint32_t maj = (a & b) ^ (a & c) ^ (b & c);
uint32_t t2 = S0 + maj;
h = g; g = f; f = e; e = d + t1;
d = c; c = b; b = a; a = t1 + t2;
}
m_h[0] += a; m_h[1] += b; m_h[2] += c; m_h[3] += d;
m_h[4] += e; m_h[5] += f; m_h[6] += g; m_h[7] += h;
}
uint32_t m_h[8];
uint8_t m_buf[64];
size_t m_bufLen;
uint64_t m_totalLen;
};
+254
View File
@@ -0,0 +1,254 @@
# 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;`,而该通道承载自由文本,
于是「echo」「error」这类以 e 开头的消息被静默吞掉。交谈子连接上没有心跳(心跳只在
主连接、且是 `[101][Heartbeat]` 多字节包,由主连接分发消费),这行是照搬其它 manager
的死防御,已删除。服务端**仍保留**前置空格规避:老客户端还带这个缺陷,多一个看不见的
空格好过静默丢消息。验证见本章末尾。
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` 因此直接写英文(德语系统看到的是英文而非乱码)。协议与服务端
逻辑不变。
**首字节 'e' 修复的验证(2026-10-25,Debug 实例 + 本机 Debug 客户端)**:验证时把
`McpChat.cpp` 的前置空格临时关掉(否则测不到客户端行为),`chat_open` 后
`chat_send "echo test"` 与 `"second line"` 各一条,再从服务端读客户端窗口文本
(`EnumWindows` → `WM_GETTEXT`):两条都完整出现在聊天记录里,`echo test` 无前导空格。
恢复前置空格后复测,显示为 `" echo test"`(多一个空格但不丢),两条路径都通过。
## 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') | 新客户端原样显示;老客户端靠前置空格仍能显示(`" echo test"`) |
| 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"
的后备字体);仅此一点无法由程序保证,缺少字体时显示为方框。
+448 -4
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"}
}
}
}
@@ -164,7 +165,7 @@ MCP 是 JSON-RPC 2.0。MVP 只需实现以下方法:
{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"list_online_hosts","arguments":{}}}
```
响应(结构化输出:`structuredContent` 承载主机数组,`content` 附带可读摘要):
响应(结构化输出:`structuredContent` 承载主机数组,`content` 是可读摘要 + 同一份结构的紧凑 JSON):
```json
{"jsonrpc":"2.0","id":3,"result":{
"structuredContent":{
@@ -174,10 +175,14 @@ MCP 是 JSON-RPC 2.0。MVP 只需实现以下方法:
"activeWindow":"WeChat","online":true,"group":"default","screen":"1:1920x1080","clientType":"EXE"}
]
},
"content":[{"type":"text","text":"共 1 台主机在线。"}],
"content":[
{"type":"text","text":"共 1 台主机在线。"},
{"type":"text","text":"{\"hosts\":[{\"id\":\"123\",\"name\":\"DESKTOP-ABC\",...}]}"}
],
"isError":false
}}
```
第二个文本块来自 §14:规范要求返回 `structuredContent` 时也把序列化 JSON 放进 TextContent,否则只读 `content` 的客户端拿不到 `id`。
#### 3.3.4 可选实现
@@ -231,6 +236,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` 一致。
@@ -256,6 +262,14 @@ Json::Value BuildHostJson(context* ctx, _ClientList* clientMap);
| `McpPort` | `6544` | MCP 监听端口;仅当 `McpEnabled=1` 时生效;未配置用默认 `6544` |
| `McpBind` | `127.0.0.1` | 监听地址;默认仅本机;可设 `0.0.0.0`(所有网卡)或内网 IP(如 `192.168.0.92`)以支持远程 |
| `McpToken` | 空(UI 默认随机值) | 静态 token;对话框内「token 必填、默认随机值」——首次打开若为空则预填随机并随保存持久化。运行时优先级:env `YAMA_MCP_TOKEN` → `McpToken` → 皆空则随机生成(见 §3.5) |
| `McpKeylog` | `0` | 键盘记录工具 `get_keylog` 的独立开关(见 §9.3);与 `McpReadonly` 无关,改动需重启生效 |
| `McpToolTimeoutMs` | `20000` | 工具等待客户端响应的默认超时(ms),clamp 到 `[1000, 600000]`;各工具自己的 `timeout_ms` 参数优先。**ini-only**(无设置界面控件),改动需重启生效 |
| `McpHttps` | `0` | `1` = 对外端口说 HTTPS(native TLS,见 §13),httplib 退到 `127.0.0.1:McpInternalPort`;`0` = 保持明文。经「MCP设置」对话框的「启用 HTTPS」复选框设置,改动需重启生效 |
| `McpCertPath` | 空(回退 `[tls] CertPath`) | MCP 专用证书(PEM)。面向公网客户端时应为公共 CA 证书(如 Let's Encrypt 的 `fullchain.pem`),不要复用设备端口的自签证书。对话框「证书路径」行可填/浏览;为空时按回退规则预填 `[tls]` 的值 |
| `McpKeyPath` | 空(回退 `[tls] KeyPath`) | 与 `McpCertPath` 配对的私钥,须为 PKCS#8(`-----BEGIN PRIVATE KEY-----`)。对话框「私钥路径」行可填/浏览 |
| `McpInternalPort` | 空(取 `McpPort+1`) | `McpHttps=1` 时 httplib 实际监听的回环端口,仅绑定 `127.0.0.1`。**ini-only**(对话框不暴露,自动取 `McpPort+1`) |
> 对话框里「证书路径/私钥路径」两行仅在勾选「启用 HTTPS」后可编辑;保存时校验两者非空且文件存在(加载失败会导致 MCP 监听 fail-closed,故提前挡住),格式仍以服务端实际加载为准。
> 与旧版「`McpPort=0` 即禁用」不同:启用与否改由独立的 `McpEnabled` 开关控制,`McpPort` 回归纯端口语义,二者解耦。
@@ -339,6 +353,11 @@ MCP 默认不启用,通过主对话框「扩展 → MCP设置」菜单项打
| 端口 | `McpPort` | `6544` | 数字编辑框,仅当启用时有效 |
| 绑定地址 | `McpBind` | `127.0.0.1` | 默认仅本机;可改 `0.0.0.0` / 内网 IP |
| Token | `McpToken` | 随机值 | 必填;为空时预填随机 token |
| 「启用 HTTPS」复选框 | `McpHttps` | 未勾选(`0`) | 勾选后本端口同时接受 TLS(§13);未勾选时下面两行置灰 |
| 证书路径 | `McpCertPath` | 空(回退 `[tls] CertPath`) | PEM;带「浏览」按钮。为空时按回退规则预填 `[tls]` 的值 |
| 私钥路径 | `McpKeyPath` | 空(回退 `[tls] KeyPath`) | PKCS#8;带「浏览」按钮 |
保存时若勾选了 HTTPS,证书/私钥必须非空且文件存在,否则弹提示并留在对话框(身份加载失败会让 MCP 监听 fail-closed,故提前挡住);HTTPS 改动与其它项一样重启生效。
#### 3.8.3 初始化与保存
@@ -426,6 +445,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`)
---
@@ -440,4 +460,428 @@ void CMcpSettingsDlg::OnBnClickedBtnSave()
- ✅ **生效方式**:MCP 启用/端口/绑定/token 的改动均需重启服务端生效,对话框保存后弹窗提醒「重启程序生效」。
- ✅ **取数方案**:C(抽公共函数 `BuildHostJson`,MCP 与 WebService 平级复用)。
- ✅ **返回字段**:全量,含实时信息(`rtt` / `activeWindow`),支持 AI 监督场景。
- ✅ **序列化**:`structuredContent` + `outputSchema`,`content` 附带可读摘要。
- ✅ **序列化**:`structuredContent` + `outputSchema`,`content` 附带可读摘要(2026-10-26 起再追加一份紧凑 JSON,见 §14)。
---
## 9. 增补(2026-10-25:N1–N5)
本轮在既有工具族(P2–P9)之上补齐「能找到主机、能一次查多台、输出不撑爆上下文、认证可追溯」四件事,全部为服务端改动,客户端零改动。
### 9.1 N1 离线主机可见
- 新增工具 `list_all_hosts`(`online` / `offline` 两个布尔过滤,默认都为 `true`),数据源是 `m_ClientMap`(主机列表历史记录,`GetAll()` 快照 + `m_cs` 保护),在线条目复用 `BuildHostJson`,离线条目由 `BuildOfflineHostJson` 生成,字段:`id` / `name` / `remark` / `ip` / `os` / `location` / `online` / `group` / `last_seen` / `install_time` / `authStatus`。
- `search_hosts` 的 `online` 参数:`true` = 仅在线,`false` = 仅离线(修复此前 `online=false` 永远返回空列表的问题),缺省 = 仅在线(与改动前一致,不改变既有调用方看到的结果)。两类都要请用 `list_all_hosts`。
- `authStatus` 是 `ClientValue::Authorized` 的三态枚举(`unauthorized` / `authorized_by_super` / `authorized_by_admin` / `forbidden`),不是布尔值。
- `get_host_detail` 对「在 `m_ClientMap` 里但当前离线」的 id 不再返回 `-32002`,改为返回该主机的最后记录(`online=false`),使 `list_all_hosts` 的结果可直接消费。
### 9.2 N2 批量只读调用
- 只读工具支持 `ids: []`(最多 50 个),与 `id` 二选一(inputSchema 用 `anyOf` 表达)。命中批量的工具:`get_host_detail` / `list_processes` / `list_windows` / `list_services` / `list_files` / `list_registry` / `get_client_log` / `get_activity_history` / `list_network_connections` / 全部 `host_list_*` / `host_get_hosts_file`。
- 写操作工具传 `ids` 直接 `-32602` 拒绝(不逐个执行,避免误操作扩散)。
- 返回:`{tool, total, succeeded, failed, results:[{id, ok, data|error, text}]}`;`content` 里是「共 N 台,成功 X 台,失败 Y 台」+ 最多 ~1200 字节的失败明细。
- `limit` / `offset` 对每台主机各自生效;批量是串行执行,单台超时会占用整批等待时间。
### 9.3 N3 `get_keylog`
- 复用客户端既有键盘记录链路:主连接下发 `COMMAND_KEYBOARD(169)` → 客户端建子连接 → 子连接回 `TOKEN_KEYBOARD_START(293)` 作为就绪包绑定 → 之后每约 1 秒推一包 `TOKEN_KEYBOARD_DATA(294)`。
- 服务端把击键流**累积**(不是一问一答),窗口 `duration_ms`(默认 4000,1000–15000)或字节上限 `max_bytes`(默认 64 KiB,1024–256 KiB)先到者结束;结束时 `EndManagedSession(..., cancelIo=true)` 关闭子连接 —— 与 MFC 关对话框同一路径,客户端据此停止记录。
- 复用 P8 的挂起会话表(新增 `PendingKind::Keylog`,仍受「单设备单飞行」约束),就绪包绑定、迟到包墓碑、子连接断开唤醒全部沿用 P8 逻辑;绑定后服务端回 `COMMAND_NEXT`,让客户端 `WaitForDialogOpen` 立即返回(本工具不开 UI)。
- 返回 `{id, duration_ms, bytes, lines, lineCount, truncated}`,文本按客户端代码页转 UTF-8(`GetClientEncoding`)。**注意**:客户端连上后会先把缓冲区里已有的历史记录推过来,所以结果既含历史也含窗口期内的新击键。
- 独立开关 `McpKeylog`(默认 `0`,不要求只读关)。工具只在开关打开时出现在 `tools/list`,关闭时直接调用返回 `-32006`。
- 隐私:击键内容只进本次响应;审计只记 `CALL_OK tool=get_keylog ms=… bytes=…`,不落任何正文。
### 9.4 N4 认证加固
- 静态 token 校验失败:返回 401,并按来源 IP 计数;60 秒窗口内失败 10 次即封禁该 IP 900 秒,封禁期内返回 429 + `Retry-After`。失败表上限 1024,满时先清理过期项。
- 环回来源(`127.0.0.1` / `::1`)**只记账不封禁**:内置 frpc 把 MCP 端口映射出去时是「本机连本机」,且这条转发没开 Proxy Protocol(httplib 不解析),服务端看到的源地址恒为环回。若按 IP 封禁,一次外部扫描就能把隧道后面所有客户端(包括自己)锁死 15 分钟。审计里这类封禁触发记为 `AUTH_BLOCK ... scope=proxy-source-exempt`。
- 审计文件 `<exe>\logs\mcp_audit.log`(追加写,5 MB 轮转为 `.1`),每行:时间戳(毫秒)、事件、来源 IP、详情。
- `AUTH_FAIL`:UA(截断/清洗)、body 大小、是否因此被封禁。
- `AUTH_BLOCK`:封禁生效。
- `CALL_OK` / `CALL_FAIL`:`tool=`、耗时 `ms=`、响应字节数 `bytes=`。
- `CALL_DENIED`:被策略拒绝的调用(`-32006`)另记一条,含 `tool=` 与固定原因文本,见 §10.8。
- 审计**不记录** token、密码、哈希、剪贴板内容或工具返回正文。
### 9.5 N5 列表输出治理
- 列表类工具统一 `limit` / `offset`:默认 `limit=100`,硬上限 `1000`,`offset` 默认 0;非正数按默认值处理。
- `structuredContent` 统一附 `total` / `totalAll` / `offset` / `limit` / `hasMore`,与 `McpMachine.cpp` 既有约定一致(`host_list_*` / `list_network_connections` 本来就是这样)。
- `content` 摘要统一为「共 N <单位>,本次返回第 a-b 条(还有更多,可用 offset 继续取)。」;`hasMore=false` 时不再出现「继续取」的误导提示;`offset` 越界时明确写「offset 超出范围,本次返回 0 条」。
- 实现集中在 `McpInternal.h/.cpp`:`PageWindow` / `ResolvePageWindow` / `ApplyPageWindow` / `WritePageFields` / `AppendPagingProps` / `PageSummary`。
- `list_files` 仍受服务端 `ParseFileList` 的 500 条硬限制(`total=500` 且原目录确有更多条目时表示截断,不是服务端分页)。客户端侧不截断、按需扩缓冲一次性回全量;本轮未加 `truncated` 标记(要加得改服务端 `ParseFileList` 的调用约定),仍靠「`total=500` 且 `hasMore`」判断。
---
## 10. 增补(2026-10-25:A 批加固 / B 批非破坏性能力)
A 批只改服务端传输、元数据与校验,不动任何既有工具语义;B 批新增三个工具(两个写主机库、一个远程搜索)。**客户端零改动。**
### 10.1 A1/A2 传输层加固(`CMcpServer::Start`)
httplib 默认值对 MCP 场景不合适,改为显式配置:
| 项 | 默认 | 现在 | 原因 |
|---|---|---|---|
| 请求体上限 | 不限(`SIZE_MAX`) | 2 MB(超出 413 `RequestEntityTooLarge`) | 只收 JSON 参数,文件内容走子连接分块,绝不进 HTTP body |
| 读超时 | 5s | 15s | 经 frp 隧道上传参数时,单次 recv 不该 5s 就断 |
| 写超时 | 5s | 60s | `get_screenshot` 大图 base64、慢链路下 5s 会写断响应 |
| 线程池 | `max(8, 核数-1)` | 固定 32 | `chat_wait`(最长 55s)与批量只读会长期占线程 |
读超时是 **socket 空闲读超时**,不是「处理时长上限」:`search_file` 阻塞 20s、`chat_wait` 阻塞 55s 都正常返回(已实测)。
### 10.2 A3 工具注解(`McpInternal::ApplyToolAnnotations`)
- `tools/list` 每个工具都带 `annotations`:`readOnlyHint` / `destructiveHint` / `idempotentHint` / `openWorldHint`,由 `McpInternal.cpp` 的 `kToolHints` 表按名登记,末尾统一补一次。
- 未登记的工具按规范默认值处理(`destructiveHint=true`),即**新增工具必须显式登记**,漏登记只会更保守,不会误标成只读。
- 只读工具的 `destructiveHint` 一律 `false`(按规范对只读工具无意义,避免客户端误报「破坏性」)。
- `openWorldHint=false` 只给「只读服务端本机状态」的工具(`list_online_hosts` / `search_hosts` / `list_all_hosts` / `get_host_detail` / `get_activity_history` / `get_audit_log` / `get_server_status`),其余都会触达外部主机。
### 10.3 A4 `get_host_detail` 字段补全
在线主机现在返回:`id` / `name` / `online` / `ip` / `publicIp` / `location` / `group` / `os` / `version` / `exeVersion` / `clientType` / `clientPath` / `systemBits` / `programBits` / `cpuCores` / `memoryGB` / `monitors` / `screen` / `user` / `isAdmin` / `pid` / `installTime` / `activeWindow` / `rtt` / `tls`;离线主机返回 `authStatus` / `last_seen` / `install_time` 等最后记录。
注意 `memoryGB` 是 **double**:客户端 `GetMemorySizeGB()` 上报的就是浮点字符串(如 `"27.800000000000001"` 的原始形态),不能按整数解析。服务端按 1 位小数规范化,并给 jsoncpp 写入器设 15 位有效数字,避免输出 17 位噪声。
### 10.4 B1 主机库写入:`host_set_remark` / `host_set_watch_level`
- 写的是服务端本机的 `_ClientList`(`MAP_NOTE` / `MAP_LEVEL`),**只影响主控端自己的展示**:不下发命令、不改远端状态。
- 门控:`McpReadonly=0` 即可(不要求 `McpManage`);在线/离线(历史记录)主机都能写,id 在主机库中存在即可。
- `host_set_remark`:`remark` 必填(空串 = 清除),**严格 GBK 转换**(emoji、`ö` 等不可表示字符报 `-32602`),长度上限 63 GBK 字节(主机库列 `char Note[64]`)。
- `host_set_watch_level`:`level` 0–3。重复写同一值幂等。
- 写后 `SaveToFile(GetDbPath())` 落库,并用 `LVM_REDRAWITEMS` 让在线列表那一行立刻刷新(MCP 线程不直接碰 `CListCtrl`)。
- 审计只记「set/cleared + 字节数」与 `level=`,**不记录备注正文**。
### 10.5 B2 远程文件搜索:`search_file`
**链路**(旧文件管理器,不是 SimplePlugins 版):
```
主连接 COMMAND_LIST_DRIVE → 客户端建子连接 → 子连接回 TOKEN_DRIVE_LIST
→ 服务端 OnDriveList 下发 COMMAND_SEARCH_FILE [根目录 \0][模式 \0](ANSI/GBK 两个 C 串)
→ N × TOKEN_SEARCH_FILE_LIST(分片)→ TOKEN_SEARCH_FILE_FINISH
```
协议来自 `client/FileManager.cpp`(`COMMAND_LIST_DRIVE` → `LoopFileManager` → `CFileManager`)。客户端工程是 MultiByte,所有字段都是 GBK,服务端用 `Utf8ToCpExact` 严格转换,不可表示即 `-32602`。
要点:
- **模式**:不含 `*` / `?` 时客户端当成 `*pattern*`(不区分大小写的子串),含通配符时走 `WildcardMatch`。
- **递归**:客户端只有递归搜索(深度 32,最多 10000 条,跳过隐藏/系统目录与重解析点)。`recursive=false` 由**服务端按「父目录 == 根目录」过滤**实现。
- **路径归一化**:客户端用 `wsprintf("%s\\*.*")` 枚举,根目录带尾部反斜杠会拼成 `C:\\*.*` 导致 `FindFirstFile` 失败、搜索秒回 0 条。服务端统一切成正斜杠→反斜杠并去尾斜杠(`C:\` → `C:`,客户端再拼回 `C:\*.*`)。
- **超时**:`timeout_ms` 默认 20000(1000–120000)。到点先下发 `COMMAND_FILES_SEARCH_STOP`,再等 5s 收尾;收不到 `FINISH` 也返回已收到的部分结果,`finished=false`。
- **收集上限**:5000 条 / 4 MB 原始包,超出即让客户端停搜并置 `truncated=true`(保护服务端内存,整盘搜索能命中几十万条)。
- **子连接身份校验**:`TOKEN_SEARCH_FILE_LIST` / `TOKEN_SEARCH_FILE_FINISH` 都按 `context*` 比对当前 pending 的子链接,旧搜索(已放弃)的尾包一律不受理,避免迟到的 FINISH 终止新搜索。
- **已知风险(客户端既有缺陷,仓库内已修)**:`client/FileManager.cpp` 的 `SearchFilesRecursive` 曾用无界 `wsprintf` 往 `char[MAX_PATH]` 里拼路径(`strPath`、`szFullPath`),全程没有长度检查。目录一深(累计路径超过 260)就栈溢出:Debug 客户端弹 `Run-Time Check Failure #2 - Stack around the variable 'strPath' was corrupted` 并挂住搜索线程,Release 客户端静默破坏栈。MFC 文件管理器的「搜索」走同一函数,**与 MCP 无关**。源码已于 2026-10-25 修掉(commit 8f718d9,入口/逐条目长度预判);**已部署的老客户端仍带这个缺陷**,所以 `tools/mcp_smoke.ps1` 的搜索用例仍是 opt-in(`-SearchPath`)。
- **无头路由**:MFC 对话框存在时搜索结果走 `OnReceiveComplete`;只有无头子连接(MCP 调用)才会进 `MessageHandle`,所以这两条 case 只影响 MCP。`TOKEN_SEARCH_FILE_LIST` 分支**绝不 CancelIO**(后面还有 FINISH 与剩余分片)。
- 输出:`{files:[{path,name,dir,size,modified}], finished, truncated, total, totalAll, offset, limit, hasMore}`。
### 10.6 A5 冒烟测试脚本
`tools/mcp_smoke.ps1`:只调只读工具(列表/详情/搜索 + 传输层负例),断言分页字段、注解、401/413、批量汇总。
```powershell
$env:YAMA_MCP_TOKEN = '<token>'
powershell -ExecutionPolicy Bypass -File tools\mcp_smoke.ps1 # 默认 6544(Release)
powershell -ExecutionPolicy Bypass -File tools\mcp_smoke.ps1 -Base http://127.0.0.1:6545/mcp
```
token 只从 `-Token` / env 读取,不落仓库、不打印;无在线主机时加 `-SkipHost`。退出码 0/1,可接 CI。
### 10.7 明确不做的两项
- `get_clipboard`:剪贴板常含口令/令牌/私钥,属"读即泄密",且客户端没有"只读不覆盖"的现成链路;已有 `remote_clipboard` 覆盖写。需要时用 `get_screenshot` + 人工确认。
- `close_window`:`operate_window` 的 `close` 动作已覆盖(同一 `COMMAND_WINDOW_CONTROL` 链路),不重复造工具。
### 10.8 D 批:拒绝也入审计
动机:所有策略拒绝(只读模式、`Mcp*` 开关关闭、主机不支持某能力)都返回 `-32006`,而审计里只有 `CALL_FAIL`——和「参数错」「主机离线」「超时」混在一起,事后分不清「没人调过」和「被策略拦下」。
- 实现放在 `tools/call` 的统一出口(`CMcpServer` 的 HTTP 处理器),不在 24 个 `-32006` 分支里逐个埋点:成功解析响应体后多取 `error.code` / `error.message`,`code == -32006` 就追加一条
```
<时间> CALL_DENIED ip=<来源> tool=<工具名> reason=<固定英文原因>
```
同一调用仍会留下原有的 `CALL_FAIL` 行,所以 `CALL_FAIL` 的统计口径不变。
- `reason` 全部是各分支写死的英文句子(如 `File transfer is disabled: requires McpFileTransfer=1`),不含调用参数或用户输入,落盘安全;审计依旧不记录 token、参数或返回正文。
- 其他错误码(`-32602` 参数、`-32002` 主机离线、`-32001` 超时等)不额外记事件,靠 `CALL_FAIL` 行即可。
- 验证(Debug 实例):把 `McpFileTransfer` 临时置 0 重启后调 `download_file`,审计立刻出现
`CALL_FAIL ... tool=download_file ms=1 bytes=114` 紧跟 `CALL_DENIED ... reason=File transfer is disabled: requires McpFileTransfer=1`;恢复 `McpFileTransfer=1` 重启后同一调用恢复 `CALL_OK` 且无 `CALL_DENIED`。冒烟脚本 20/20 通过(未指定 `-SearchPath` 时跳过 2 个搜索用例)。
---
## 11. 增补(C 批:读侧增强,不改客户端)
### 11.1 C1 `get_audit_log` 分页与过滤
改动前每次调用都返回镜像里的全部条目(环形缓冲上限 1000 条),调用方没法只看关心的部分,日志一多就会把工具返回值撑大。
- 新增入参:`type`(类型列子串,不区分大小写,如 `MCP` 能匹配 `MCP命令执行`)、`keyword`(正文子串,不区分大小写)、`limit` / `offset`(沿用统一分页,默认 100、上限 1000)。
- 过滤在分页之前生效:`total` 是命中条数、`totalAll` 是镜像里的全部条数;`hasMore` 针对命中的条目。摘要会补一句「过滤前共 N 条」,方便判断是不是过滤写错了。
- 读取仍在 `m_cs` 临界区内完成(UI 线程会并发写入),过滤循环里先做 GBK→UTF-8 转换再比对,避免拿两种编码互相比。
- outputSchema 补 `total/totalAll/offset/limit/hasMore`(与其它列表工具一致)。
- 注意 `get_audit_log` 读的是**主界面消息镜像**,不是 `logs\mcp_audit.log`;两者的条目内容和保留策略都不同(前者是 1000 条环形缓冲,后者是 5 MB 文件滚动)。
- 验证(Debug 实例):`limit=2` 两页分别返回第 1-2 / 3-4 条且 `hasMore=true`,`offset=999` 返回「offset 超出范围」;`type=mcp` 命中 `MCP命令执行`(大小写不敏感)、`type=提示` 命中「使用提示 / 提示信息」、`keyword=监听` 命中「监听端口: 6543成功」;冒烟脚本 23/23 通过(新增分页字段、条数上限、过滤未命中 3 项断言)。
### 11.2 C2 新工具 `get_server_status`
排查「改动到底生效没有」「为什么某个工具被拒」时,原先只能靠 `list_online_hosts` 加 `get_audit_log` 侧面推断;现在有一个服务端自身的状态快照。纯内存、只读、不建子连接。
返回(`structuredContent.status`):
| 字段 | 含义 |
|---|---|
| `app_name` / `version` | 品牌名与 `BRAND_VERSION`(当前 1.4.1) |
| `exe_build_time` | exe 文件的最后写入时间=链接时间(比 `__DATE__`/`__TIME__` 可靠,后者是编译单个 .cpp 的时间) |
| `uptime_sec` | 进程已运行秒数(`GetProcessTimes` 的创建时间起算,不是开机时间,也不受 MCP 启停影响) |
| `bind` / `port` | MCP 实际监听的地址与端口(`Start` 时记录,非从配置回读) |
| `switches` | `readonly` / `terminal` / `remote_control` / `file_transfer` / `manage` / `machine` / `machine_dangerous` / `keylog` / `chat` |
| `hosts` | `online` / `offline` 台数(与 `list_all_hosts` 同源) |
| `sessions` | `pending`(一次性/管理/键盘记录挂起) / `terminal` / `remote_control` / `file_transfer` / `chat` 在飞会话数 |
| `blocked_auth_ips` | 当前处于鉴权封禁期的来源 IP 数 |
- **不返回** token、`McpCmdWhitelist` 内容或任何配置原文;`switches` 只报布尔值。
- `sessions` 各项各取各自的锁、取完即放,是「大致同一时刻」的估算值,不能当一致性快照用。
- 工具注解登记为只读 + 非破坏性 + 幂等 + 不触达外部主机;`tools/list` 总数变为 53。
- 验证(Debug 实例):返回 `Yama v1.4.1,已运行 17 秒,监听 127.0.0.1:6545;在线主机 1 台、离线 3160 台`;`terminal_open` 期间 `sessions.terminal=1`、`terminal_close` 后回到 0;冒烟脚本 26/26 通过(新增 3 项:正常返回、版本/端口/开关齐全、不含 token)。
### 11.3 C3 主机列表过滤:`list_online_hosts` / `list_all_hosts`
这两个工具原先只有分页,想找「某个分组」「某个平台」的主机只能翻页或改用 `search_hosts`(后者不支持 `client_type`,且对在线/离线的取舍规则不同)。
- 新增三个可选入参(两个工具共用同一套实现):`group` / `os` / `client_type`,均为子串匹配、ASCII 不区分大小写、AND 组合,口径与 `search_hosts` 一致。
- 过滤在分页之前生效:`total` 为命中台数、`totalAll` 为过滤前总数(`list_online_hosts` 是全部在线数,`list_all_hosts` 是主机库总数);摘要改用「共 N 台主机匹配」并补一句过滤前规模,写错条件时一眼能看出来。
- `list_all_hosts` 摘要里的在线/离线拆分也按命中条目统计。
- **离线主机没有 `clientType`**(历史记录里不存这个字段),所以带 `client_type` 条件时离线主机不会命中——按平台筛历史主机用 `os`。
- 验证(Debug 实例):`client_type=exe` 命中 1 台(`EXE`/`os=Windows 11`),`client_type=lnx` 命中 0 台但 `totalAll` 仍为 1;`list_all_hosts` 带 `group=default` 命中 3161 台并正确拆分在线 1 / 离线 3160,`os=zzz` 命中 0 台;冒烟脚本 28/28 通过(新增过滤未命中、totalAll 不变 2 项断言)。
### 11.4 C4 `search_file` 结果侧过滤
`search_file` 的搜索条件(根目录 + 通配模式)由客户端执行,改不动;但把匹配项拿回服务端后可以再筛一遍,省掉 AI 端逐条比对。
- 新增四个可选入参,**都在服务端对已收集的匹配项做过滤**,不减少客户端侧搜索耗时:
- `min_size` / `max_size`:字节数,整数,闭区间;负数或非数字返回 `-32602`;两者都给出且 `min_size > max_size` 返回 `-32602`。
- `modified_after`:接受 `YYYY-MM-DD`(当天 00:00:00 之后)或 `YYYY-MM-DD HH:MM:SS`;格式不符返回 `-32602`。客户端返回的 `modified` 是定宽 `"YYYY-MM-DD HH:MM:SS"`,可直接字典序比较,所以两种写法都合法(`"2026-01-01" <= "2026-01-01 08:00:00"`)。
- `name_only`:布尔,命中项只保留 `path` / `name` 两个字段,适合只要文件清单时省 token。
- 过滤在分页之前:`total` 为命中条数、`totalAll` 为过滤前条数;摘要补一句「过滤前共 N 条(大小/修改时间/精简字段过滤在服务端进行,不减少客户端搜索耗时)」。
- 过滤只看服务端已收到的条目,所以仍受 `max_results` / `timeout_ms` 截断:客户端没搜完时,过滤结果也是部分的(`truncated` / `finished` 字段照旧反映这一点)。
- 验证(Debug 实例,根目录 `C:\Windows\Fonts`、`*.ttf`):基线 255 条;`min_size=1000000` → 39 条且 `totalAll=255`;`name_only=true` 每条只有 `path`/`name`;`modified_after=2026-01-01` → 165 条、`2026-06-03 00:00:00` → 130 条、`2027-01-01` → 0 条;`min_size=-5`、`min_size=10 & max_size=5`、`modified_after=2026/01/01`、`modified_after=2026-01-01 12:00` 均返回预期的 `-32602`。冒烟脚本 33/33 通过(新增 3 项:`min_size` 过滤后 `totalAll` 不变、`name_only` 精简字段、非法 `modified_after` 返回 `-32602`;后三项需带 `-SearchPath` 才执行)。
## 12. 错误码速查(E 批:冒烟与文档)
工具的失败分三类,AI 端应按 `code` 决定下一步,而不是读 `message` 文本。`message` 是给人看的英文说明,随实现变化,不作为契约。
| code | 含义 | 典型触发 | 建议动作 |
|---|---|---|---|
| `-32700` | Parse error | 请求体不是合法 JSON | 修正客户端序列化 |
| `-32600` | Invalid Request | 缺 `jsonrpc` / `method` / 非法 `tools/call` 结构 | 修正请求 |
| `-32601` | Method not found | `method` 不是 `initialize` / `tools/list` / `tools/call` 等 | 修正请求 |
| `-32602` | Invalid params | 未知工具名、缺必填参数、参数类型/取值非法、批量 `ids` 超过 50 个、`search_file` 过滤参数非法、文本无法转 GBK | 改参数重试,重试同样的请求不会成功 |
| `-32001` | Timeout | 等客户端就绪/等子连接/等搜索结果超时(`timeout_ms` 内没等到) | 可加大 `timeout_ms` 重试;持续出现看主机是否卡住 |
| `-32002` | Host offline / not found | 主机 id 不存在、主连接已断、会话 id 不存在或已关闭 | 先 `list_online_hosts` 刷新再选主机 |
| `-32003` | Busy | 该主机已有同类请求在飞(终端/截屏/文件/聊天会话),或同设备重复 `chat_open` | 等前一个结束或先 `*_close` |
| `-32004` | Send failed | 命令写入主连接失败(连接刚断) | 重试一次;仍失败按 `-32002` 处理 |
| `-32005` | Not supported on this host | 能力限制,改参数也修不好:需要 Windows 的工具用在 LNX/MAC/APK 主机上;`remote_open` 遇到多显示器(阶段一);主机无屏幕预览/控制能力位 | 换主机或换工具;不要改参数重试 |
| `-32006` | Policy refused | 只读模式 / 对应 `Mcp*` 开关关闭 / 主机不支持该能力(如 V2 文件传输) | **不要重试**:这是配置决定,需管理员改服务端配置 |
| `-32007` | Not in command whitelist | `exec_command` 的命令不在 `McpCmdWhitelist` 里,或词边界不匹配(`dir` 过、`dirx` 拒) | **不要重试**:换成白名单内的命令,或请管理员加白名单项 |
| `-32008` | Rejected by validation | 只覆盖「参数被校验拒绝、改参数可修」:`exec_command` 含 shell 元字符(Windows `&\|<>^`;Linux `&\|<>;` 与反引号、`$(` `${` `!`)或控制字符(含 `\r\n`);`terminal_exec` 含 `&`/`\|`/换行;路径/参数含非法字符 | 按 `message` 修正参数后重试 |
| `-32009` | Target not found | 远端路径/注册表键不存在(win32 `2`/`3`,由新客户端主动回报);`kill_network_connection` 的四元组在当前连接表里查不到(`dry_run` 传假四元组最常见) | 先用 `list_files`/`list_registry`(或 `host_list_network_state`)确认目标存在 |
| `-32010` | Access denied | 目标存在但权限不足(win32 `5`):非提权客户端的服务枚举(`OpenSCManager`)、受保护目录(如 `System Volume Information`)、受保护注册表键(如 `HKLM\SAM`) | **不要重试**:需客户端提权(管理员运行)或换目标 |
| `-32011` | Destination write failed | 文件传输的**目标端**已收到数据但写盘失败:`copy_files_c2c` / `upload_file` 的目标主机回了回执且 `status != 0`(`message` 带 status、首个 errno、实收文件数) | **不要原样重试**:按文案判断(errno 13/1→权限、2→路径不存在、28→磁盘满),先修目标端目录/权限 |
- **命令超时会销毁持久会话**(`terminal_exec`):等服务端收集到哨兵超时返回 `-32001`,会话随即被销毁并留 600 秒「墓碑」;对同一 `session_id` 再发命令返回 `-32002`,文案明确写 `Terminal session was destroyed after this command timed out (waited N ms); call terminal_open again`,与「id 写错」(`Terminal session not found: <id>`)区分开。
- **新客户端把失败改成结构化回报**(`TOKEN_SERVICE_ERROR=170` / `TOKEN_FILE_LIST_ERROR=171` / `TOKEN_REG_ERROR=172` / `TOKEN_DOWNLOAD_ERROR=173`,布局 `[token:1][win32 码:4 LE]`):`list_services`(未提权)、`list_files`/`list_registry`(路径/键不存在或拒绝访问)、`download_file`(远端路径全部不存在)都在客户端侧就失败并立即回报,服务端转译成 `-32009`/`-32010`,**亚秒级返回**,不再靠超时猜。老客户端不发这些包,成功路径报文一律不变,因此老客户端/老服务端的行为与改造前完全一致(老服务端把未知 token 走 `default` 丢弃)。
- **工具放弃后的「迟到首包」一律吸收,不会弹 MFC 窗口**:文件/服务/注册表/进程/日志/终端这几族的子连接都是「建成即发首包」。工具超时清理挂起后,客户端可能才把首包发上来,此时没有挂起会话,`MessageHandle` 只能把它当成人手点击,于是弹出文件管理器/服务管理器/注册表/进程管理器/日志/终端窗口(构造超时场景时实测出现过文件管理器窗口)。现在各等待函数在**放弃分支**登记「设备 → 该工具的首包 token」(`CMcpServer::MarkLateFirstPacketForTool`),包到达时 `TakeToolFirstPacket` 一次性吸收并关子连接:`list_files`/`download_file`/`upload_file`/`search_file` → `TOKEN_DRIVE_LIST`;`list_services`/`control_service` → `TOKEN_SERVERLIST`;`list_registry` → `TOKEN_REGEDIT`;`list_processes`/`kill_process` → `TOKEN_PSLIST`;`list_windows`/`operate_window` → `TOKEN_WSLIST`;`get_client_log` → `TOKEN_REPORT_LOG`;`get_activity_history` → `TOKEN_REPORT_ACTIVITY`(主连接,只丢包不关连接);`exec_command`/`terminal_open` → `TOKEN_SHELL_START` + `TOKEN_TERMINAL_START`。成功路径不登记,命中即消费,标记 5 分钟后过期。**已知代价**:同一主机在工具超时后 5 分钟内手动点开对应窗口,可能被这枚标记吞掉一次(再点即可)——比误弹窗口更可接受。
- **MCP 工具在飞时不弹客户端的老式提示框**:新客户端在失败分支同时发结构化 token 和老的 `ClientMsg`(只为兼容老服务端),后者会 `PostMessageA(WM_SHOWERRORMSG)` 在服务端 UI 上弹框。`TOKEN_CLIENT_MSG` 分支现在发现该设备有挂起请求/文件传输时就只记日志不弹框。实测 `list_services`(未提权)时客户端子连接已被服务端关掉,`ClientMsg` 根本发不出来,这条属兜底。
- **`download_file` 有停滞看门狗兜底**:60 秒没收到任何数据即失败,返回 `-32001` 且文案带 `File transfer stalled: no data received for 60s ...`。新客户端的 `TOKEN_DOWNLOAD_ERROR` 让这条路基本不再触发,看门狗只用来兜住「客户端卡住/老客户端」。
- `-32006` 会额外在审计日志里记一条 `CALL_DENIED`(§10.8),其余错误只体现在 `CALL_FAIL` 行。
- 批量调用(带 `ids[]`)**整体不报错**:每个 id 的结果单独带 `error`,顶层用 `succeeded` / `failed` / `skipped` 汇总;只有整批请求本身非法(超过 50 个 id、写操作传 `ids`)才返回顶层 `-32602`。
- 冒烟脚本 `tools/mcp_smoke.ps1` 覆盖了上表的可复现项:`-32601`(未知 method)、`-32602`(未知工具/缺参数/51 个 id)、`-32002`(不存在的主机)、`-32006`(任一开关关闭时自动挑一个关着的功能验证,并断言审计里出现 `CALL_DENIED`;全部开启时跳过)、`-32009`(新客户端的 `list_files`/`list_registry`/`download_file` 不存在路径负例)。其余码由各批次的功能验证覆盖(`-32001`/`-32003` 等需要构造竞态或超时,不进冒烟)。
- 本次验证(Debug 实例):冒烟 **40/40 通过**(原 37 项 + 3 条 `-32009` 负例);`-32010` 由 `list_services`(未提权客户端,win32=5)、`list_files "C:\System Volume Information"`、`list_registry "HKLM\SAM\SAM\Domains\Account"` 三条实测覆盖。
### 12.1 命令哨兵与输出清洗(测试报告 P1/P3/P4 的修复)
`exec_command` 与 `terminal_exec` 都靠哨兵判断「命令已执行完、退出码是多少」。哨兵有三种形态:
| 客户端 | 下发内容 | 退出码 |
|---|---|---|
| POSIX PTY(Linux,`RES_CLIENT_TYPE=LNX`) | 第一行 `PS1=`;第二行 `<cmd>`;第三行 `echo __MCP_DONE_<nonce>__$?` | 命令的真实退出码 |
| ConPTY(`is_pty=true`,新版 Windows 客户端) | 第一行 `@echo off & <cmd>`;第二行单独 `echo __MCP_DONE_<nonce>__%errorlevel%` | 命令的真实退出码 |
| 老 ShellManager 管道(`is_pty=false`) | 单行 `<cmd> 2>&1 && echo __MCP_DONE_<nonce>__0 || echo __MCP_DONE_<nonce>__1` | 仅 0 / 非 0 |
POSIX 形态与 Windows 的差别:
- **不能用 `@echo off & <cmd>` / `%errorlevel%`**:Linux 的 `bash -i` 把它们当字面量,哨兵永远不会出现,必然超时。
- **先发一行 `PS1=`**:交互式 bash 每读一行都打印提示符(`user@host:cwd$`),提示符会混进 stdout(Windows ConPTY 不会)。清空 `PS1` 后提示符消失。这一行的回显排在下发的命令行回显之前,会被「从缓冲区开头删到命令行回显结束」那一步一并切掉,不进入返回文本。
- **`$?` 是上一行的退出码**:`PS1=` 与命令各占一行,哨兵只取命令那一行的状态,未被 `PS1=` 干扰。
**为什么 PTY 要分两行下发**:`rem hello`、`cmd /c exit 0`、`if`、`for` 这类「吞行」命令会把同一行里的 `&& echo 哨兵` 一起吞掉(`rem`/`cmd /c` 把行内剩余文本当作自己的参数),哨兵永不出现,于是必然超时并销毁会话。哨兵独立成行后由 shell 自己执行,不再受命令行影响。老客户端只能维持单行形态:`client/ShellManager.cpp` 按「写入字节数」跳过回显,多写一行会吃掉上一行的输出。
**为什么用 `%errorlevel%`**:ConPTY 会把输入整行回显进输出流(80 列会折行)。回显文本里是字面 `%errorlevel%` 而不是数字,而 `FindSentinel` 只认「标记 + 数字」,折行回显再也不可能被误判成哨兵(评审 P3:`ver` 曾因回显里的 `__1` 被判成 `exit_code=1`),同时还能拿到真实退出码(如 `nosuchcmd` 的 9009)。
**输出清洗顺序**:剥 ANSI(OSC 序列以 `ESC\` 结尾时两字节一起吞,否则会残留 `\`)→ CRLF 归一 → 从缓冲区开头删到「我们下发的命令行回显」结束(顺带清掉 shell 启动画面与提示符)→ 删哨兵行回显 → **按 nonce 擦掉残留的哨兵文本** → 去首尾空行。最后一步是必需的:ConPTY 送回来的是**屏幕渲染流**(带光标移动/擦除序列),剥掉序列后同一行可能重复出现,哨兵会留下副本(实测不擦时 `rem hello` 只剩哨兵、`cmd /c echo abc` 成了 `abc__MCP_DONE_x__0`)。nonce 每条命令随机生成,命令的真实输出不可能包含它,所以按 nonce 擦除不会误伤业务输出。
**已知边界**:屏幕渲染流里「光标下移空行」会被剥成紧邻行(例如 `ping` 的统计块会贴在最后一条回复后面),不影响语义。
## 13. 增补(2026-10-26:MCP HTTPS / native TLS)
### 13.1 目标与取舍
公网 MCP 客户端(Claude Desktop、WorkBuddy 等)多数只接受 `https://` 端点,而 MCP 一直是明文 `httplib`。三条路里选了第三条:
| 方案 | 结论 |
|---|---|
| 在 vps 上用 nginx 反代加 TLS | 不行:vps 的 80/443/6544 都由 frps 持有,nginx 只在 8080,且反代会让 token 以明文经过 vps |
| 引入 OpenSSL / cpp-httplib 的 `CPPHTTPLIB_OPENSSL_SUPPORT` | 新增第三方依赖与证书/私钥加载路径,仓库已有 Schannel 实现 |
| **复用仓库既有的 Schannel 入站实现,在 MCP 端口上终结 TLS** | ✅ 零新依赖,`ServerTlsSession`/`ServerTlsIdentity` 已在设备端口跑通 |
### 13.2 结构:同端口嗅探 + 明文直通
```
客户端 ──TLS──▶ [McpTlsProxy] :McpPort ──明文──▶ httplib 127.0.0.1:McpInternalPort
客户端 ──明文─▶ │ 0x16 0x03 ? (只绑回环,不对外)
```
- `McpTlsProxy`(`McpTlsProxy.h/.cpp`)在 `McpBind:McpPort` 上监听,首包用 `MSG_PEEK` 判 TLS(首字节 `0x16` 且次字节 `0x03`,与设备端口 §5.2 同一套路):TLS 走 `ServerTlsSession::HandshakeWithCred` + `Decrypt`/`Encrypt`,否则按字节原样转发。
- 因此**同一端口两种用法并存**:本机既有的 `http://127.0.0.1:6544/mcp` 不用改,远端可以用 `https://host:6544/mcp`。
- `McpHttps=0` 时完全不启动前端,行为与改造前一致(httplib 直接监听 `McpBind:McpPort`)。
### 13.3 身份:第二份证书,独立 CNG 键名
`ServerTlsLoadIdentityFromPem(cert, key, L"YamaMcpTlsKey", id)` 构造进程内第二份入站身份,与设备端口的 `ServerTlsIdentity`(`YamaServerTlsKey`、通常自签 `CN=localhost`)并存:证书/私钥各读各的,持久化私钥用不同键名,互不覆盖。`HandshakeWithCred` 是新增的重载,设备端口仍用 `Handshake`(同一份逻辑,只是取凭据的方式不同)。
**fail-closed**:证书/私钥读不出来、CNG 导入失败、端口被占任一项失败,`McpServer::Start` 会把 httplib 一起停掉并返回 false——绝不允许「以为在跑 HTTPS、其实没在监听」。
### 13.4 实测(Debug 实例,自签证书)
| 场景 | 结果 |
|---|---|
| `https://127.0.0.1:6545/mcp`(`--cacert server.crt`)无 token | `401`,证书校验通过 |
| 同一端口 `http://127.0.0.1:6545/mcp` 无 token | `401`(明文直通未受影响) |
| TLS + token:`initialize` / `tools/list` / `tools/call get_server_status` | 正常,53 个工具 |
| 同一条 TLS 连接上连发两个请求(keep-alive) | 两次都 `200`,复用连接 |
| 错误 token | `401`(回环来源的鉴权封禁豁免仍生效) |
| 内部端口 `6546` | 只监听 `127.0.0.1` |
| `McpCertPath` 指向不存在的文件后重启 | MCP 整体不启动,无任何监听(fail-closed) |
| 公共 CA 的 ECDSA 证书(Let's Encrypt P-256 fullchain + PKCS#8 私钥) | 身份加载成功,TLS 无 token `401`、带 token `initialize`/`tools/list` 正常(53 工具) |
| 本地 CA 三级链(叶 + 中间,中间证书不在系统库) | 服务端下发 2 张证书,`openssl s_client -CAfile root.crt` 得 `Verify return code: 0` |
| 设备端口 `6543` TLS(回归) | 握手正常 |
| `McpHttps` 删除后重启(回归) | 明文明监听,无内部端口 |
### 13.5 Schannel 的一个坑(已修在共用层)
`ServerTlsSession` 原先把「首次收到的字节」直接喂给 `AcceptSecurityContext`。如果这批字节只是**半条 ClientHello**,Schannel 会先建出一个坏上下文,补齐后再送返回 `SEC_E_UNKNOWN_CREDENTIALS (0x80090301)`,握手必失败。设备端口因为累积了整包才分类、且客户端 ClientHello 通常一次到齐,一直没暴露;MCP 前端按 8 字节嗅探后接手,稳定触发。
现在 `HandshakeWithCred` 在首次 ASC 之前先凑齐**一整条 TLS 记录**(5 字节头 + 负载,上限 18432 字节,首字节非 `0x16` 或缺字节超时则 fail-closed),调用方给多少字节都行。这也顺带修好了设备端口在「ClientHello 被 TCP 分片」时的同类隐患。
### 13.6 部署公网证书
1. 把公共 CA 签发的证书链与私钥(PKCS#8)放到本机,例如 `Bin\certs\mcp-fullchain.pem` / `Bin\certs\mcp-key.pem`。证书支持 RSA 与 ECDSA(P-256/P-384/P-521),可以写成「叶证书 + 中间证书」的 fullchain(见 13.8)。
2. 「扩展 → MCP设置」勾选「启用 HTTPS」,在两行里填/浏览证书与私钥(也可直接改 ini:`McpHttps=1`、`McpCertPath=<证书>`、`McpKeyPath=<私钥>`),保存后重启 YAMA。注意「端口」填的是对外端口,httplib 自动退到 `127.0.0.1:McpPort+1`。
3. frp 的 `YAMA-MCP-*` 映射指向本机 `McpPort` 不变——TLS 在 YAMA 内终结,vps 只转发密文。
4. 证书续期后需重新拷贝 + 重启 YAMA(当前不做热加载)。
客户端配置形如:
```json
{
"mcpServers": {
"yama": {
"type": "http",
"url": "https://web.just-do-it.icu:6544/mcp",
"headers": { "Authorization": "Bearer <McpToken>" }
}
}
}
```
### 13.7 已知限制
- **按 IP 的鉴权封禁对远端不生效**:`IsAuthBlocked` 按来源 IP 计数,而经 frp 或本前端转发的请求来源都是 `127.0.0.1`,命中既有的「代理来源豁免」。因此远端的暴力尝试不受「10 次失败 / 60 秒 → 封 15 分钟」约束,真正的防线是 token 熵(32 hex ≈ 128 bit)与审计日志里的 `AUTH_FAIL` 记录。经 frp 暴露时改造前就已如此;但若改造前是把 `McpPort` 直接绑在公网地址(不经 frp),远端 IP 原本会被封禁,开启本前端后一律变成环回、不再封禁——按部署方式评估这一差异。要补需在本前端把真实来源 IP 以受信头注入 httplib 请求,属于后续工作。
- 证书不热加载:换/续证书需重启 YAMA。
- 只支持 HTTP/1.1(与 httplib 一致),不做 ALPN h2。
### 13.8 证书类型与证书链(2026-10-26 补齐)
早期实现只认 RSA:私钥一律按 `BCRYPT_RSAFULLPRIVATE_BLOB` 导出后再写入持久化键,遇到 ECDSA 证书(Let's Encrypt 自 2024 年起默认签发 P-256)会在导出处拿 `NTE_BAD_TYPE (0x8009000a)` 并报错退出。现在按**证书公钥类型**分两路落盘(`ServerTlsSession.cpp` 的 `BuildIdentity`):
| 证书公钥 | 落盘方式 |
|---|---|
| RSA | 导入 PKCS#8 为临时键 → 导出 `BCRYPT_RSAFULLPRIVATE_BLOB` → `NCryptCreatePersistedKey` + `NCryptSetProperty` + `NCryptFinalizeKey` |
| ECDSA(P-256/P-384/P-521) | 导入 PKCS#8 时在参数表里给出键名(`NCRYPTBUFFER_PKCS_KEY_NAME`),MS Software KSP 直接持久化 |
ECDSA 这条是 MS Software KSP 唯一可行的一条,其余几条均已实测不通:`NCryptCreatePersistedKey` 后写 EC 私钥 BLOB,`SetProperty` 返回 0 但 `Finalize` 给 `NTE_INVALID_PARAMETER (0x80090027)`;导入后再 `NCryptSetProperty(NCRYPT_NAME_PROPERTY)` 给 `NTE_NOT_SUPPORTED (0x80090029)`(不带键名即匿名临时键,Schannel 用不上);把临时键句柄经 `CERT_KEY_CONTEXT_PROP_ID` 挂到证书上,Schannel 报 `SEC_E_NO_CREDENTIALS (0x8009030e)`。`NCRYPTBUFFER_PKCS_KEY_NAME` 的值必须**含结尾 NUL**,少了同样报 0x80090027。曲线只支持具名 P-256/P-384/P-521,显式参数形式的曲线会带明确报错退出。
**证书链**:Schannel 的握手在进程外完成,建链时只查系统证书库——fullchain 里的中间证书塞进叶证书自带的内存库或 `paCred` 数组都不会被下发(实测只发叶证书,缺中间证书的客户端建链失败)。因此加载身份时把 fullchain 第 2 张起的证书补进「当前用户\中间证书颁发机构」库(`Cert:\CurrentUser\CA`,已在库中则跳过;.NET 的 `SslStreamCertificateContext` 也是这么做的),Schannel 建好链后随握手下发。证书文件因此可以、也建议写成「叶证书 + 中间证书」的 fullchain(Let's Encrypt 的 `fullchain.pem` 即如此)。副作用:进程所在账户的 CA 库里会多出这些中间证书(公开信息,留在库里无害)。
## 14. 增补(2026-10-26:结果外露 —— `content` 同时携带结构化 JSON)
### 14.1 问题
改造前,列表/查询类工具的 `content` 只有一句可读摘要(“共 1 台主机匹配。”),真正的载荷(`hosts[]`、`processes[]`、`files[]`、`session_id`……)只在 `structuredContent` 里。MCP 规范(Tools → Structured Content)明确建议:**返回 `structuredContent` 的工具应同时把序列化后的 JSON 放进一个 `TextContent` 块**,正是为了这种只把 `content` 交给模型的客户端。实测 WorkBuddy 就属这类:它把 `search_hosts` 的结果格式化成“共 1 台主机匹配”交给模型,`id` 完全不可见,于是后续 `get_host_detail` / `exec_command` / 终端 / 远程控制全部无从下手(用户侧表现为模型去猜 1–3100 的 id,而主机 id 是 64 位雪花值,如 `986530101822679521`,猜测不可能命中)。
### 14.2 实现
- `McpInternal::BuildResult` 统一收口:结果里 `structuredContent` 为非空对象/数组时,追加一个 `{type:"text", text:"<紧凑JSON>"}` 块到 `content` 末尾。所有工具(含 `McpMachine.cpp` / `McpChat.cpp` 的 `BuildStructuredResult` 漏斗)自动生效,新增工具无需额外处理;空 `{}`(`remote_mouse` 这类动作结果)不追加。
- 正文已经承载同一份载荷的工具用 `SetStructuredTextPayload(result, payload)` 只外露差异部分,避免同一内容在上下文里出现两三次:
| 工具 | 外露的文本块 |
|---|---|
| `exec_command` / `terminal_exec` | `{"exit_code":N}`(stdout 已在正文里) |
| `get_keylog` | `id` / `duration_ms` / `bytes` / `lineCount` / `truncated`(行内容已在正文里,最多 16 KB) |
| `get_activity_history` | `{"records":[…]}`(`activityHistory` 与 `records` 是同一份数据的两种形态) |
| `host_get_hosts_file` | `lines` + 元数据(不再重复 `content` 原文) |
- 控制键以 `$structuredTextPayload` 成员的形式挂在 result 上,`BuildResult` 消费后立即 `removeMember`,不会出现在响应里。
- 列表类工具本就有 `limit/offset` 分页,补出来的 JSON 与 `structuredContent` 同量级,不会失控。
### 14.3 验证
Debug 实例(`Bin\Yama_x64d.exe`,临时端口)实测:`list_all_hosts` 的 `content[1]` 含完整主机 JSON(`id` / `ip` / `last_seen` …),`get_server_status` 的 `content[1]` 是 `{"status":{…}}`,`search_hosts` 空结果时是 `{"hasMore":false,"hosts":[],…}`;`content[0]` 的既有摘要文案一字未改。
### 14.4 影响面
- 响应体积:列表类工具约翻倍(分页上限内),执行类工具只多一个退出码字段。
- 既有断言不受影响:摘要仍在 `content[0]`,内部批量工具(`ids` 批量调用)仍只读 `content[0].text` 并另取 `structuredContent`。
## 15. 增补(2026-10-26:`copy_files_c2c` 客户端间直传)
第 54 个工具:把文件从一台客户端**直接**发到另一台,服务端只做包中继,不落盘。复用 V2 文件传输的 C2C 通道(`FileChunkPacketV2.dstClientID != 0`),新增协议号 `COMMAND_C2C_SEND_FILES=174`(服务端给源端下路径清单)、`TOKEN_C2C_SEND_RESULT=175`(源端回传发送结果),以及能力位 `CLIENT_CAP_C2C_PATHS=0x0008`(老客户端因此被提前拒绝并提示升级)。
- 工具契约:`src_id` / `dst_id` / `paths[]` / `dst_dir` / 可选 `timeout_ms`;返回 `transfer_id` / `file_count` / `total_bytes` / `receiver_ack`。
- 开关:`McpFileTransfer=1 && McpReadonly=0`(会写远程),注解登记为破坏性 + 非只读,`McpInternal` 的 gating 表同步。
- 源端必须是 Windows 客户端(`-32005`);目标端可以是 Windows / Linux / macOS(2026-10-27 起)。POSIX 目标给绝对 POSIX `dst_dir`(`/tmp/recv`),服务端在建会话前校验形态,非法 `-32602`。
- `receiver_ack`:Linux 目标端落盘后会回一包 `TOKEN_C2C_RECV_RESULT=176`(能力位 `CLIENT_CAP_C2C_RECV_ACK=0x0010`),`true` 表示目标端确认写入、`total_bytes` 是实收值;写入失败统一 `-32011`(带 status/errno)。Windows/macOS 目标端不回执,仍为 `false`,需 `list_files` 复核。
- 实施中一个坑:服务端既有的 C2C 中继分支会在源端子连接上挂进度对话框,而 `NotifyProc` 对挂了 `hDlg` 的连接会把后续包交给对话框——源端最后那包结果就被当 V1 文件块吃掉,工具只能超时。现按「该 host 是否有 MCP 的 C2C 会话」跳过对话框,MFC 手动 C2C 不变。
- 协议细节、落盘路径语义(`dst_dir` + 相对公共父目录,Windows 与 POSIX 两种目标端)、回执与错误码映射(含 `-32011`)、限制与实测见 [Mcp_FileTransfer_Design.md](./Mcp_FileTransfer_Design.md) §14。
## 16. 增补(2026-10-27:`download_file` / `upload_file` 支持 Linux/macOS 主机)
此前两个工具把 LNX/MAC 目标端直接拒掉(`-32005`)。现在放开,改动集中在服务端的路径门禁与 POSIX 接收端:
- **`upload_file` 不需要客户端新指令**:Linux/macOS 的文件接收走 `common/FileTransferV2.h`,`dstClientID != 0` 的包按 C2C 语义落盘,目录由包里的 name 派生。服务端按 `RES_CLIENT_TYPE` 校验 `remote_dir`:POSIX 目标必须是绝对 `/…`、不含 `\`、不含 `..` 段(`-32602`);Windows 目标行为不变。
- **`download_file`**:POSIX 文件管理器(`common/FileManager.h`)补齐两块——每个文件末尾发 `FileCompletePacketV2`(流式 SHA-256,新增 `common/sha256_posix.h`;读失败/截断不发,不谎报校验通过),以及下载失败时回 `TOKEN_DOWNLOAD_ERROR`(errno→win32,服务端转成 `-32009`/`-32010`,不用等停滞看门狗)。
- **`upload_file` 的 `receiver_ack`**:Linux 目标端会回 `TOKEN_C2C_RECV_RESULT=176`,服务端在发送完成后等 ≤5 s,`true` 表示已确认写入;回执报错 `-32011`;声明会回执却不回(且传输含字节)`-32001`。Windows/macOS 目标端仍恒为 `false`。
- **空文件**:worker 对 0 字节文件只发完成包(无路径字段),POSIX 接收端无从建文件。服务端只对 POSIX 目标补一个长度 0 的末块,接收端据此建空文件;Windows 目标的空文件仍不落地(V2 协议既有边界,未改)。
- 顺带修掉一个下载完成判定的边界:条目顺序由客户端决定,目录可能排在文件之后(如空子目录),`OnFileChunkV2` 改为按 `filesDone + directoryCount >= totalFiles` 判完成,不再出现「文件全部收完还干等超时」。
- 协议细节、POSIX 路径规则、错误码新语义与实测(含 3 MB 二进制、中文名、空文件、空目录的 SHA-256 往返)见 [Mcp_FileTransfer_Design.md](./Mcp_FileTransfer_Design.md) §15。
## 17. 增补(2026-10-27:档 1 工具支持 Linux 客户端)
Linux 客户端(`LNX`)早已实现下面这些工具的**线上协议**,只是服务端按客户端类型一律拒绝。本次只放开服务端的判定,**不改 Linux 客户端、不加能力位**:
| 工具 | 线上协议(已存在) | 服务端改动 |
|---|---|---|
| `kill_process` | 主连接 `COMMAND_SYSTEM` → 子连接 `TOKEN_PSLIST` → `COMMAND_KILLPROCESS` + PID 数组 → 刷新列表(`linux/SystemManager.h`,`kill(SIGKILL)`,忽略 `pid<=1`) | 只拒绝 `MAC`/`APK` |
| `exec_command` | `COMMAND_SHELL` → `TOKEN_TERMINAL_START` → PTY(`common/PTYHandler.h`,`bash -i`) | 只拒绝 `MAC`;POSIX 白名单 / 元字符集 / 哨兵(§12.1) |
| `terminal_open` / `terminal_exec` / `terminal_close` | 同上,`CMD_TERMINAL_RESIZE` + `COMMAND_NEXT` 启动读线程 | 只拒绝 `MAC`;`posix` 透传到哨兵与编码(UTF-8) |
| `remote_open` / `remote_close` / `remote_mouse` / `remote_keyboard` / `remote_clipboard` | `COMMAND_SCREEN_SPY` → `TOKEN_BITMAPINFO` → `COMMAND_SCREEN_CONTROL` + `MSG64_LNX`(`linux/ScreenHandler.h`,XTest 注入);剪贴板 `COMMAND_SCREEN_SET_CLIPBOARD` | 只拒绝 `MAC`;输入事件改为**一条一包**(见下) |
要点:
- **POSIX 默认白名单是独立的一份**(`kDefaultCmdWhitelistPosix`):同名的 POSIX 命令语义与 Windows 不同(`find` 能 `-exec`、`hostname` 能改名、`sort -o` 能写文件),因此只收「参数也基本只读」的命令。`env` **刻意不收**——`env <程序>` 等于执行任意命令,会让白名单形同虚设。管理员显式配置 `McpCmdWhitelist` 时两种平台共用配置(配置者自负其责)。
- **元字符集按平台分开**:Linux 拒绝 `& | < > ;` 与反引号、`$(` `${` `!`(`!` 在交互式 bash 里触发历史展开);`^` 在 POSIX 里不是元字符,因此 `grep -v ^# /etc/hosts` 这类只读命令在 Linux 上可用,Windows 上仍按原规则拒绝。
- **输入事件一条一包**:协议允许 `[COMMAND_SCREEN_CONTROL][MSG64*N]` 批量,Windows 客户端(`CScreenManager::ProcessCommand`)也支持批量;但 `linux/ScreenHandler.h` 只处理包内第一条,批量会让 `key_press` 只按下不抬起(X11 自动重复)、`click` 只按下、`type` 只打首字符。服务端因此按消息拆包(`SendScreenCtrlEvents`),对 Windows 完全等价(它本来就一条一条处理),新老 Linux 客户端也都不用升级。
- **`remote_keyboard` 的 `type` 仍是 ASCII-only**:Linux 侧 `VKtoKeySym` 把 VK 映射为 keysym 后走 XTest,IME 组合输入做不到;非 ASCII 走 `remote_clipboard` + `Ctrl+V`(Linux 客户端把服务端下发的 GBK 转回 UTF-8 再调 `xclip`/`xsel`,需要 X11 桌面)。
- **限制**:纯 Wayland 会话无法抓屏/注入(要 X11 或 XWayland);多显示器仍按 §7.2 拒绝(Linux 客户端心跳里 `RES_RESOLUTION` 依赖 `xrandr`,没有 `xrandr` 的系统上报 `0:0*0`,按「无法判定」放行);`remote_*` 需要安装 `libX11` + `libXtst`,剪贴板需要 `xclip`/`xsel`。
- **验收**(Debug 实例 + WSL Ubuntu 24.04 客户端,WSLg `DISPLAY=:0`):`exec_command` 真实退出码(`ls` 不存在路径 → 2)、`-32007`/`-32008` 负例、`grep -v ^#` 放行、输出无提示符噪声;持久终端 `cd`/环境变量保持、`false` → 1、`;` 串联取末条、`close` 幂等;`kill_process` 杀死自己起的 `sleep` 且 `remaining` 为空、`pid 1` 被跳过;`remote_open` 返回 3840x1140、`remote_mouse` 归一化 (0.5,0.5) 落在 (1920,570)、`xev` 观测到按键/按钮成对、剪贴板中文往返 UTF-8 一致。Windows 客户端同批工具回归无变化。
+207 -4
View File
@@ -1,6 +1,6 @@
# YAMA MCP 文件传输功能设计(download_file / upload_file)
# YAMA MCP 文件传输功能设计(download_file / upload_file / copy_files_c2c)
> **状态**:设计定稿(经专家审查修订,结论见 §13)。`download_file`(P1)已实施并验收;`upload_file`(P2)已实施(详见 §7,评审修订见 §13.1)。`download_file` 采用 **V2 文件传输协议**(`CMD_DOWN_FILES_V2` + 流式子连接 + SHA-256 校验),`upload_file` 复用服务端既有 `FileBatchTransferWorkerV2`(主连接同步驱动)。两者共享同一套「文件会话」注册表。
> **状态**:设计定稿(经专家审查修订,结论见 §13)。`download_file`(P1)已实施并验收;`upload_file`(P2)已实施(详见 §7,评审修订见 §13.1)。`copy_files_c2c`(P3,客户端间直传、服务端只中继)已实施(见 §14)。`download_file` 采用 **V2 文件传输协议**(`CMD_DOWN_FILES_V2` + 流式子连接 + SHA-256 校验),`upload_file` 复用服务端既有 `FileBatchTransferWorkerV2`(主连接同步驱动),`copy_files_c2c` 复用 V2 的 C2C 中继(`dstClientID != 0`)。三者共享同一套「文件会话」注册表。
> **读者**:MCP 后续功能研发/评审人员。
> **关联文档**:[Mcp_Phase2_Design.md](./Mcp_Phase2_Design.md)(双模式无头驱动机制)、[FILE_TRANSFER_V2.md](./FILE_TRANSFER_V2.md)(V2 协议清单)、[Mcp_Design.md](./Mcp_Design.md)(Phase 1 协议/架构/配置)。
@@ -175,7 +175,7 @@ MCP工具线程 服务端 MessageHandle
- 发 `CMD_DOWN_FILES_V2` 前把 `local_dir` 规范化为绝对路径并 `CreateDirectory`;`targetDir` 用 ANSI(MBCS 构建本机路径)。
- 每收到一个 chunk,校验其 `filename` 规范化后**前缀必须在 `local_dir` 内**(防 `..` 穿越,呼应 `FILE_TRANSFER_V2.md §8.3` 已识别的风险);逃逸则置 `error` 并 `CancelIO`。
- 编码:`remote_path` 走 UTF-8→ANSI(936)(Windows 客户端,复用 `McpServer.cpp` 既有 `ToAnsi`,与 `list_files` 一致)。
- 编码:`remote_path` 走 UTF-8→ANSI(936)(复用 `McpServer.cpp` 既有 `ToAnsi`,与 `list_files` 一致)。POSIX 目标端的路径规则见 §15。
### 6.5 超时与并发
@@ -248,7 +248,7 @@ MCP工具线程 主连接 (ctx→Send2Client)
- V2 无接收方→发送方 ACK:客户端 `HandleFileCompleteV2` 校验失败只打日志(`RecvFileChunkV2` 返回 8,`KernelManager.cpp:1381` 不回传主控)。
- **P2 的 `output.files[].sha256` 恒为空串**:`FileBatchTransferWorkerV2` 内部会为每个文件自算 SHA-256 并写入 `COMMAND_FILE_COMPLETE_V2` 包发给客户端,但该值**不回传调用方**;服务端侧又无导出的 SHA-256 工具函数可自行复算。故 P2 输出不填 sha256(延后 P3:worker 回传哈希,或服务端引入 SHA-256 工具)。传输完整性仍依赖客户端本地 `HandleFileCompleteV2` 校验(与 GUI upload / C2C 同权,属 V2 协议既有边界,非 MCP 引入)。
- 若未来需要「接收方验真回执」,需新增反向 ACK 包(协议扩展,进 P3)。
- 若未来需要「接收方验真回执」,需新增反向 ACK 包(协议扩展,进 P3)——**Linux 目标端的 `receiver_ack` 已实现**,复用 §14 的 176 回执(见 §15),Windows 目标端仍为 `false`。
### 7.6 overwrite 语义
@@ -309,6 +309,8 @@ int n = RecvFileChunkV2((char*)szBuffer, ulLength, m_conn, nullptr, m_hash, m_hm
| (P2)`server/2015Remote/McpServer.h` | `FileTransferSession.tool` 增 `"upload_file"`;新增 `BeginFileUpload(id)`(单设备单传输互斥标记) |
| (P2)`server/2015Remote/McpServer.cpp` | `upload_file` schema/实现:无头回调 `UploadSendChunkHeadless` + `CollectLocalFiles` 收集 + overwrite 预检(复用 `list_files` 链路)+ 驱动 `FileBatchTransferWorkerV2`(复用主连接,无子连接路由) |
| (P2)`client/KernelManager.cpp` | `COMMAND_SEND_FILE_V2` 分支加懒初始化 `InitFileUpload`(`g_status` 由 0 置 1,见 §7.8) |
| (2026-10-27)`common/FileTransferV2.h` | POSIX 接收端:发送 `FileCompletePacketV2`(含流式 SHA-256)、下载失败回 `TOKEN_DOWNLOAD_ERROR`(errno→Win32 映射);见 §15 |
| (2026-10-27)`common/sha256_posix.h` | 新增:POSIX 侧最小流式 SHA-256(Windows 侧仍走 BCrypt,见 `common/VerifyV2.h`) |
**客户端**:`UploadToRemoteV2` / `RecvFileChunkV2` / `FileBatchTransferWorkerV2` 均已存在、未改动;仅 `COMMAND_SEND_FILE_V2` 分支新增懒初始化(见 §7.8)。
@@ -394,3 +396,204 @@ int n = RecvFileChunkV2((char*)szBuffer, ulLength, m_conn, nullptr, m_hash, m_hm
| U7 | 实施验证发现:客户端主连接 `g_status==0`,`RecvFileChunkV2` 逐 chunk `return -1`(上传落盘 0 字节/截断) | 客户端 `COMMAND_SEND_FILE_V2` 分支加懒初始化(§7.8):`static` 一次 + 永久引用计数、析构不 `Uninit`;与 `FileManager.cpp:40` 参数一致,独立评审确认无稳定性风险 |
**判定**:7 项均已写入 §7 对应小节,无阻塞项,**定稿**。
### 13.2 实施后修复记录(2026-10-25)
| # | 问题 | 修复 |
|---|---|---|
| R1 | **纯目录树下载必超时**:完成判定 `filesDone >= totalFiles - directoryCount` 只在 `OnFileCompleteV2` 里跑,而客户端对目录项不发 `COMMAND_FILE_COMPLETE_V2`。空目录/只有子目录的树期望文件数为 0,永远等不到 COMPLETE → 只能干等 `timeout_ms`(默认 600s)后报 `1002` | `OnFileChunkV2` 的目录分支里,`directoryCount >= totalFiles`(即全部条目都是目录)时直接置 `done` + notify。实测空目录 0.2s 返回、3 文件目录树回归正常 |
| R2 | **断线无清理 → 悬空子连接指针**:`FileTransferSession.fmSubCtx / streamSubCtx` 是裸 `context*`,`OfflineProc` 只清了终端/远程控制/聊天,没有文件传输的钩子(§6.5 声称的「断线擦会话」实现缺失)。客户端传输中掉线后 connection 被连接池回收,工具线程超时路径仍对其 `CancelIO()` → 悬空指针/误取消他人连接 | 新增 `m_FileXferContextToDevice` 反查表(受 `m_FileXferMutex` 保护,`ClearFileTransfer` 同步擦除),`OfflineProc` 增 `OnFileTransferContextClosed`:清指针并移除反查项;**流式子连接**断开即判失败(`error=1003`,立即唤醒工具线程),文件管理器子连接断开只清指针(数据走流式子连接,不判失败)。实测传输中杀掉客户端:1s 返回 `Connection lost`(原来要等满 `timeout_ms`),服务端存活;重启客户端后连续两次下载、一次上传均正常 |
---
## 14. 增补(2026-10-26):C2C 直传 `copy_files_c2c`
### 14.1 动机
运维里经常要在**两台客户端之间**拷文件。此前的变通流程是「`download_file` 拉到主控本机 → `upload_file` 再推上去」,数据在服务端磁盘上落一遍、两倍耗时。文件传输 V2 本身已经支持 C2C:`FileChunkPacketV2.dstClientID != 0` 时,服务端把包**原样中继**给目标客户端,目标端在自己的主连接上 `RecvFileChunkV2` 落盘,服务端不解析、不落盘。
但客户端现有的 C2C 入口只有一个 `COMMAND_CLIPBOARD_V2`(Ctrl+V),文件来源固定是本端剪贴板/资源管理器选中项,服务端无法指定路径。因此新增一条「服务端给源端一份显式路径清单」的命令。
### 14.2 协议(`common/commands.h` / `common/file_upload.h`)
```cpp
CLIENT_CAP_C2C_PATHS 0x0008 // LOGIN_INFOR 能力位,仅 Windows 客户端置位(源端)
CLIENT_CAP_C2C_RECV_ACK 0x0010 // 作为目标端会回执落盘结果,目前仅 Linux 客户端置位(macOS 不置位)
COMMAND_C2C_SEND_FILES = 174, // 服务端 → 源客户端主连接
TOKEN_C2C_SEND_RESULT = 175, // 源客户端 → 服务端(源端自开的传输子连接上)
TOKEN_C2C_RECV_RESULT = 176, // 目标客户端 → 服务端(目标端主连接上)
```
| 包 | 布局 | 说明 |
|---|---|---|
| `C2CSendFilesPacket` | `cmd(1) transferID(8) srcClientID(8) dstClientID(8) hash(64) hmac(16) flags(1)` = 106 B | 后接 `dst_dir\0`,再是 `path1\0 … pathN\0`,以额外一个 `\0` 结束(ANSI/936) |
| `C2CSendResultPacket` | `cmd(1) transferID(8) dstClientID(8) status(4) win32err(4) workerRc(4) fileCount(4) totalBytes(8)` = 41 B(`#pragma pack(1)`) | 175:`status` 0=全部发出、`FEV2_FILE_NOT_FOUND`/`FEV2_ACCESS_DENIED`(带首个 win32 码)、1001=发送线程失败(看 `workerRc`)。176:`status` 0=全部落盘成功,否则为映射后的 `FEV2_*`;`win32err` 位置放**首个 errno**;`workerRc` 恒 0 |
老客户端不认识 174(服务端按 `CLIENT_CAP_C2C_PATHS` 提前拒绝,`-32005` 提示升级);老服务端不认识 175/176,走 `default` 丢弃,无兼容风险。回执用**独立的 176**而不是复用 175:同一台主机可能同时是 A 传输的目标端和 B 传输的源端,复用会让服务端把回执误当成源端结果去 latch `done`。
### 14.3 客户端(`client/KernelManager.cpp`)
1. `OnC2CSendFiles`:解析 `dst_dir` 与路径清单 → `ExpandEnvironmentStringsA` 展开 `%VAR%` → 目录按 `CollectFilesRecursiveV2` 同语义**递归展开,且目录项本身也入列**(目标端据此建空目录)→ 统计 `fileCount/totalBytes`。
2. `EnsureV2TransferInited()`:`FileBatchTransferWorkerV2` 依赖进程级的 `InitFileUpload`(`g_status==1`),否则直接返回 -1。源端可能从未打开文件管理器、也没接收过上传,所以发送前显式初始化;与接收分支共用同一份 `static` 一次性初始化(`InitFileUpload`/`UninitFileUpload` 成对,重复 Init 会重置状态)。
3. 新开一个 `EnableSubConnAuth()` 的子连接 → `FileBatchTransferWorkerV2(files, targetDir=dst_dir, …, opts{dstClientID=dst, enableResume=false})`,回调即 `Send2Server`。子连接经 `TOKEN_CONN_AUTH` 校验后,服务端把它钉成源主连接的 clientID。
4. 发送结束后**在同一条子连接上**回 `C2CSendResultPacket`,然后关闭子连接。任何早退分支(路径非法/全部不可访问/连不上服务端)都先回一包结果——否则工具侧只能干等超时。
### 14.4 服务端
- **会话**:`BeginC2CTransfer(src, dst, transferID)` 把会话键在**源**设备上(`tool="copy_files_c2c"`、`dstClientID`),与 `m_Pending`、目标端文件会话双向互斥;`WaitC2CDone` 只等源端那包结果,**没有停滞看门狗**(源端全程只在最后回一包,大文件中途静默是正常的),只有总超时。
- **中继**:完全复用 `COMMAND_SEND_FILE_V2` / `COMMAND_FILE_COMPLETE_V2` 的 `dstClientID != 0` 分支,零改动。
- **必须抑制源端的进度对话框**(实施中踩到的坑):该分支原本会在源端子连接上挂一个 `CDlgFileSend` 显示进度。而 `NotifyProc` 对**挂了 `hDlg` 的连接**会把后续包交给对话框的 `OnReceiveComplete`——源端最后那包 175 就被当成 V1 文件块解析(服务端 trace 里是 `RecvFileChunk failed: 3`),MCP 侧只会超时。现在用 `IsC2CTransferPending(src, dst)` 判定:MCP 发起的 C2C 不建对话框,包照常落到 `MessageHandle`;MFC 手动 C2C(Ctrl+V / 文件管理器)行为完全不变。
- **落盘位置**:目标端收到的目录是 `dst_dir`,文件名取各路径**相对公共父目录**的部分(库内 `GetCommonRoot` 语义)。例如发 `D:\data\a.txt` 与 `D:\data\sub\`,目标是 `C:\backup`,则得到 `C:\backup\a.txt`、`C:\backup\sub\b.bin`;`dst_dir` 不存在时由接收端自动创建。
- **Windows 目标**:`dst_dir` 必须是绝对 Windows 路径(`C:\backup`),服务端补尾部 `\` 后交给源端拼接。
- **Linux/macOS 目标**:`dst_dir` 必须是绝对 POSIX 路径(`/home/user/incoming`、`/tmp/recv`),不得含 `\`。源端仍然只是把 `dst_dir` 与相对路径**纯字符串拼接**(`targetDir + relPath`,库内不经过任何 Windows 路径 API),因此得到 `"/tmp/recv\sub\b.bin"`;POSIX 接收端 `GetTargetDir()` 为空时会把 `\` 归一化成 `/`、去盘符、补前导 `/` 再 `MakeDirs`,正好落到 `/tmp/recv/sub/b.bin`。这条路径不需要改 Windows 客户端。
- 目标端类型来自 `RES_CLIENT_TYPE`(`LNX`/`MAC` 视为 POSIX),服务端在**建会话前**校验形态,不合法直接 `-32602`。
- **目标端回执**:目标端声明 `CLIENT_CAP_C2C_RECV_ACK`(当前只有 Linux)时,服务端在源端结果之后再 `WaitC2CReceiver`(≤5 s,250 ms 切片)等一包 176;没有该能力位的目标端(Windows、macOS、老客户端)直接跳过,不增加任何延迟。回执状态记在 `FileTransferSession` 的 `recv*` 字段,与源端的 `done/status` 互不覆盖。
### 14.5 工具契约
入参:`src_id`、`dst_id`(必填,且不得相同)、`paths`(必填,文件或目录,1..N,源端 Windows 绝对路径)、`dst_dir`(必填,绝对路径;Windows 目标用 `C:\x`,Linux/macOS 目标用 `/x`)、`timeout_ms`(默认 600000,上限 3600000)。
出参(`structuredContent`):`transfer_id`、`src_id`、`dst_id`、`dst_dir`、`file_count`、`total_bytes`、`receiver_ack`。
`receiver_ack` 三种取值:
- `true` 且 `status==0`:目标端已确认全部条目落盘(`file_count`/`total_bytes` 是**目标端实收**值,与源端统计一致)。
- `false`:目标端不支持回执(Windows/macOS/老客户端),或目标端中途断线——源端只保证「包已全部发出」,请用 `list_files` 复核。
- 目标端回执报错时工具**不返回** `structuredContent`,而是下面的 `-32011` 错误。
| 码 | 触发 |
|---|---|
| `-32602` | 缺参 / id 非法 / 源目标相同 / `paths`、`dst_dir` 含 `..` 段或内嵌 NUL / 编码无法转 936 / POSIX 目标的 `dst_dir` 不是绝对 `/…` 或含 `\` |
| `-32002` | 源或目标主机不在线 |
| `-32003` | 源或目标已有在飞传输(单设备单传输) |
| `-32004` | 命令下发失败 |
| `-32005` | 源端是老客户端(无 `CLIENT_CAP_C2C_PATHS`)、或源端是 Linux/macOS(目标端可以是 Linux/macOS) |
| `-32006` | `McpFileTransfer=0` 或 `McpReadonly=1`(改远程);任一端不支持 V2 |
| `-32009` / `-32010` | 源端路径不存在(win32 2/3)/ 拒绝访问(win32 5) |
| `-32011` | **目标端写入失败**:收到 176 回执且 `status != 0`;文案带 status、首个 errno(13/1→权限、2→路径不存在、28→磁盘满)与实收文件数 |
| `-32001` | 等源端结果超时(传输可能仍在进行);或**支持回执的目标端在源端完成后 5 s 内没有回执**(对 `total_bytes>0` 的传输才判失败;全空文件传输没有数据块、目标端无从学到 `totalFiles`,按无回执处理) |
### 14.6 限制
- **回执只覆盖 Linux 目标端**:Windows 目标端(V2 接收实现里没有回执通道)与 macOS(`macos/main.mm` 的客户端对象是函数内局部变量,没有全局主连接句柄)仍是 `receiver_ack:false`,只能确认「包已全部发出」,要确认落盘请用 `list_files` 核对目标端。
- **不做断点续传**(`enableResume=false`):C2C 的续传查询/应答会多两跳,v1 从简;失败即整包重发。
- **源端必须是 Windows 客户端**(`CLIENT_CAP_C2C_PATHS` 只有 Windows 置位);目标端可以是 Windows / Linux / macOS。
- **POSIX 目标的路径限制**:`dst_dir` 与文件名的 UTF-8 → ANSI 转换固定用 CP936(协议字段没有编码标志位),GBK 无法表示的字符(如 `ö`、`ß`)会变成 `?`;POSIX 目标的 `dst_dir` 必须是绝对 `/…` 且不含 `\`;Linux 侧文件名按收到的字节原样落盘(大多是 GBK 字节),在 UTF-8 环境里 `ls` 会显示为乱码但内容与 SHA-256 正确。要根治需要为 V2 名字字段引入 UTF-8 标志位,本次不做。
- **空文件不会被创建**(协议现状,与目标端类型无关):worker 对 0 字节文件不发数据块,只发 `FileCompletePacketV2`,接收端没有对应分支去 `open(O_CREAT)`。空**目录**会创建。
- 一次只允许一对主机间的单个传输(源、目标各自都要求空闲),避免与 `download_file`/`upload_file` 抢同一主机的连接。
### 14.7 验证(Debug 实例 + 两个 Debug 客户端副本,同一台机器不同目录 → 不同 client_id)
数据确实走「源客户端子连接 → 服务端中继 → 目标客户端主连接」:
| 用例 | 结果 |
|---|---|
| 发 2 个文件(其一中文名)+ 1 个目录(含 3 MB 二进制与空子目录) | 3 个文件 SHA-256 全对,空目录被创建,`file_count=3`、耗时 3.2s |
| `dst_dir` 不存在(`…\recv\fresh\nested`) | 自动创建,文件到位 |
| `src_id == dst_id` / 源路径不存在 / 目标离线 / `dst_dir` 含 `..` | `-32602` / `-32009`(win32=3) / `-32002` / `-32602` |
| `tools/mcp_smoke.ps1`(含主机类工具,41 项) | 全通过;新增 `copy_files_c2c` 同主机 `-32602`、目标离线 `-32002` 两项 |
### 14.8 增补(2026-10-27):Linux 作为目标端 + 落盘回执
改动面:服务端门禁按目标端类型校验 `dst_dir`(§14.4);Linux 接收端 `common/FileTransferV2.h` 统计每个
`transferID` 的定案条目,全部定案后从主连接回一包 `TOKEN_C2C_RECV_RESULT`(176);服务端新增
`OnC2CRecvResult` / `WaitC2CReceiver`,在源端结果之后等回执并把它变成 `receiver_ack` 或 `-32011`。
接收端记账要点(都在 `FileTransferV2.h` 的 `RecvProgress` 里):
- 条目定案有三个来源:**目录项包**(`FFV2_DIRECTORY`,无 LAST_CHUNK)、**最后一块数据**、**空文件的完成包**;
源端重发(最多 3 次)与「最后一块 + 完成包」都会重复命中同一 `fileIndex`,用 `doneFiles`/`doneDirs` 去重。
- `totalFiles` 只能从数据块/目录包学到(`FileCompletePacketV2` 没有该字段);目录项也计入 `totalFiles`,
所以判据是 `doneFiles + doneDirs >= totalFiles`。
- `errno` 只在失败瞬间有效,open 失败处紧接着就有 `Mprintf`,因此在失败点立刻取值再传递;
`fstat` 复核最终大小,大小不符记 `EIO`。
- 回执在锁外发送;`reply->IsConnected()` 失败只记日志,不影响已落盘的文件。
验证(Debug 实例 6543/6546,WSL Ubuntu 24.04 里新编译的 `linux/ghost` 以 yuan(1000) 运行):
| 用例 | 结果 |
|---|---|
| Windows → Linux,`dst_dir=/tmp/yama_c2c/recv`,2 个文件(其一中文名)+ 目录(含 3 MB 二进制与空子目录) | 3 个文件 SHA-256 全对、`sub/empty` 空目录已建,`receiver_ack:true`、`file_count=3`、`total_bytes=3147539`(与源端一致),耗时 3.2 s |
| `dst_dir=/tmp/yama_c2c/fresh/nested`(不存在) | 自动创建,`receiver_ack:true` |
| POSIX 目标给 `dst_dir=C:\tmp\x` | `-32602` "use an absolute POSIX path such as /home/user/incoming" |
| POSIX 目标给不可写位置 `/proc/yama_c2c` | `-32011` "no such file or directory (status=3, errno=2, files=1)" |
| 只发一个 0 字节文件 | 成功返回、`receiver_ack:false`(无数据块 → 接收端学不到 `totalFiles` → 不回执),**不误报** `-32001` |
| 只发一个空目录 | 目录包携带 `totalFiles` → 回执到达,`receiver_ack:true`、`file_count=0`,目录已创建 |
| Windows → Windows 回归(原 c2c_test 用例) | 全部与改动前一致,`receiver_ack:false`,耗时 3.2 s(未增加等待) |
| `upload_file`/`download_file`(`dstClientID=0`) | 不进回执分支(`FinishC2CItem` 首行即 `dstClientID==0` 返回),行为不变 |
---
## 15. 增补(2026-10-27):`download_file` / `upload_file` 支持 Linux/macOS 主机
§6/§7 的原始实现只允许 Windows 目标端(LNX/MAC 直接 `-32005`)。本次打通:
- **`upload_file`(主控 → 目标端)**:不需要客户端新指令。POSIX 接收端本来就实现了 `COMMAND_SEND_FILE_V2`
(`common/FileTransferV2.h`),`dstClientID != 0` 的包按 C2C 语义处理,目标目录由包里的 name 派生
(§14.4 的 POSIX 规则)。服务端只放开门禁 + 按目标端类型校验 `remote_dir` 形态。
- **`download_file`(目标端 → 主控)**:走客户端文件管理器子连接的 `CMD_DOWN_FILES_V2`,Linux/macOS 的
文件管理器在 `common/FileManager.h` 里(与 Windows `client/FileManager.cpp` 同构)。缺的两块在 POSIX 接收侧补齐:
### 15.1 接收端改动(`common/FileTransferV2.h`,Linux 与 macOS 共用)
1. **发送 `FileCompletePacketV2`**(`SendFilesV2` 每个文件末尾):`cmd(1) transferID(8) srcClientID(8)
dstClientID(8) fileIndex(4) fileSize(8) sha256(32)`,SHA-256 边读边算(新增 `common/sha256_posix.h`,
自包含流式实现;Windows 侧继续用 BCrypt)。服务端 `OnFileCompleteV2` 凭它计 `filesDone` 并校验摘要——
没有它 MCP 的下载会话永远等不到完成判定。
- 读失败 / 文件在传输中被截断(短读):仍把末块发出去,但**不发**完成包(不谎报校验通过),服务端按
`fileSize` 收不全而失败。
- 发送失败(`Send2Server` 返回 false)同样不发完成包。
2. **下载失败回 `TOKEN_DOWNLOAD_ERROR`**:`[cmd:1][win32err:4 LE]`,与 Windows `CFileManager::SendDownloadError`
一致。触发点:`remote_paths` 为空(win32 87)、所有路径 stat 失败 / 展开后无文件(首个 errno 映射
`ENOENT/ENOTDIR→2/3`、`EACCES/EPERM→5`,其余→2)。服务端据此立即失败,不用等停滞看门狗。
### 15.2 服务端改动(`server/2015Remote/McpServer.cpp`)
- `BuildDownloadFile` / `BuildUploadFile`:`RES_CLIENT_TYPE` 为 `LNX`/`MAC` 时按 POSIX 校验路径:
**必须以 `/` 开头、不得含 `\`(会被客户端 `WinPathToLinux` 归一化成 `/`,语义会漂)、不得含 `..` 段**,
否则 `-32602` 并给出示例;`upload_file` 的 `remote_dir` 单独给 `/` 是合法的(写到根目录,通常因权限回 `-32011`)。
Windows 目标端行为与之前逐字节一致。
- `BeginFileUpload(device_id, transfer_id)` 现在登记 `dstClientID`/`transferID`,`OnC2CRecvResult` 同时匹配
`copy_files_c2c` 与 `upload_file` 的会话(键分别是源端与目标端,都用 `dstClientID + transferID` 定位)。
`upload_file` 因此也能拿到真实回执:Linux 目标端声明 `CLIENT_CAP_C2C_RECV_ACK`,发送完成后等 ≤5 s,
`receiver_ack` 参与输出。
- **空文件(仅 POSIX 目标)**:`FileBatchTransferWorkerV2` 对 0 字节文件不发数据块,只发完成包,而完成包
没有路径字段,POSIX 接收端无从建文件(会「回执成功但文件不存在」)。服务端在驱动 worker 前,为每个
0 字节文件补一个长度 0 的 `FFV2_LAST_CHUNK` 块(名字拼法与 worker 一致:`targetDir + relPath`),
接收端据此 `open(O_CREAT)`;随后 worker 的完成包只用于去重。**Windows 目标端不注入**——保持原有行为
(Windows 目标端的空文件仍不会被创建,属 V2 协议既有边界,见 §14.6)。
- 下载完成判定(F4 的补强):条目顺序由客户端决定,目录可能排在**最后**(如空子目录),所以
`OnFileChunkV2` 的目录分支现在按 `filesDone + directoryCount >= totalFiles` 判完成。此前只比目录数,
目录排在文件之后时整次下载会干等到超时(实测 4 个文件全部 COMPLETE 后仍卡 60 s)。
### 15.3 工具契约变化
| 工具 | 变化 |
|---|---|
| `download_file` | 支持 LNX/MAC 目标端(`remote_path` 用绝对 POSIX 路径);新增错误来源 `-32009`/`-32010`(来自客户端 `TOKEN_DOWNLOAD_ERROR`) |
| `upload_file` | 支持 LNX/MAC 目标端(`remote_dir` 用绝对 POSIX 路径);输出新增 `receiver_ack`(boolean);新增 `-32011`(目标端回执报写入失败)与 `-32001`(声明会回执却不回,且传输含字节) |
`upload_file` 的错误补充(其余码与 §7.7 一致):
| 码 | 触发 |
|---|---|
| `-32011` | 目标端回了 176 且 `status != 0`;文案带 status、首个 errno、实收文件数(13/1→权限、2→路径不存在、28→磁盘满) |
| `-32001` | 传输完成但支持回执的目标端在 5 s 内没有回执(目标端可能中途掉线);全 0 字节的传输不判失败(接收端学不到 `totalFiles`,无从回执) |
`receiver_ack` 语义与 §14.5 一致:`true` 只可能来自 Linux 目标端;Windows 目标与 macOS 目标恒为 `false`
(macOS 编译侧 `macos/main.mm` 没有全局主连接句柄,本次未接线),要确证落盘请用 `list_files` 复核。
### 15.4 验证(Debug 实例 6543/6546,WSL Ubuntu 24.04 的 `linux/ghost` 以 yuan(1000) 运行)
源目录含:`a.txt`(12 B)、`empty.txt`(0 B)、`sub/b.bin`(3 MB)、`emptydir/`、`中文名.txt`(14 B)。
| 用例 | 结果 |
|---|---|
| `upload_file` → `/tmp/yama_mcp/final` | 4 文件 + 空目录到位,SHA-256 全对(`ddda4069…`/`e3b0c442…`/`834dcf1d…`/`b2a71864…`),`receiver_ack:true`,`total_bytes=3145754` |
| 同上 `overwrite=false` 重传 | 全部跳过(`skipped=4`),不发包 |
| `download_file` 整目录 | 4 文件 + 空目录,SHA-256 全对,`total_bytes=3145754` |
| 单文件 / 单文件中文名 / 只含空子目录的目录 | 均成功(后者 0.2 s 级返回,不再等超时) |
| `download_file` 不存在的路径 | `-32009`(errno 2 → win32 2) |
| `remote_path` 给 `C:\tmp\x` 或含 `..` | `-32602` |
| `upload_file` 到 `/` 或 `/root/yama_x`(非 root) | `-32011`(errno 13/2) |
| Windows 目标端 `upload_file` / `download_file` / `copy_files_c2c` 回归 | 与改动前一致(Windows 目标的空文件仍不落地,`receiver_ack` 仍为 `false`) |
注:WSL 重启后 Linux 客户端的 machine-id 会变,`id` 随之改变,测试脚本以运行时 `list_online_hosts` 为准。
+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 工具,服务端无残留子连接。
+15 -5
View File
@@ -1,7 +1,7 @@
# MCP 远程控制(Remote Control)设计文档
> 版本:v1(设计基线) 状态:待开发 关联:`docs/Mcp_Design.md`、`docs/Mcp_Terminal_Design.md`
> 定位:本文件是「AI 远程控制一台 Windows 客户端(像人一样点鼠标、敲键盘、看画面完成任务)」功能的**唯一参照设计**,后续开发一律以本文为准,改需求先改本文。
> 定位:本文件是「AI 远程控制一台 Windows 或 Linux 客户端(像人一样点鼠标、敲键盘、看画面完成任务)」功能的**唯一参照设计**,后续开发一律以本文为准,改需求先改本文。Linux 支持范围与限制见 §6.5、§12.1。
---
@@ -172,6 +172,7 @@ AI 无法「看懂」视频流。把 25fps 的远程画面直接丢给视觉模
- **包格式**:`[cmd:1][MSG64:48]`,可批量重复(`commands.h` `COMMAND_SCREEN_CONTROL=20`,`MSG64` 1581–1623)。
- **MSG64 布局**:`{uint64 hwnd, message, wParam, lParam, time; POINT pt;}` = 48 字节(`_WIN64` 下 `MYMSG` 即 `MSG`;客户端亦接受 28 字节 `MSG32`,由 `ulLength % 28/48` 判定)。
- **一条一包(重要)**:协议允许一包多消息,Windows 客户端也支持(`ProcessCommand` 按 `ulLength % 48 / % 28` 算出条数后逐条处理);但 Linux 客户端(`linux/ScreenHandler.h` `OnReceive`)**只处理包内第一条**。服务端因此统一按「一条 MSG64 一个 `COMMAND_SCREEN_CONTROL` 包」下发(`SendScreenCtrlEvents`):批量下发会让 Linux 上的 `key_press` 只按下不抬起(X11 自动重复)、`click` 只按下、`type` 只打出首字符。对 Windows 客户端完全等价。
- **客户端解码**:`ScreenManager.cpp:1175` → `ProcessCommand(1727)` → `SendInput`:
- 鼠标:坐标取 `LOWORD/HIWORD(lParam)`,`WM_MOUSEMOVE`→`MOUSEEVENTF_MOVE`,`WM_LBUTTONDOWN/UP`→`LEFTDOWN/LEFTUP`,`WM_LBUTTONDBLCLK`→额外 `LEFTDOWN`,`WM_MBUTTONDOWN/UP`,`WM_MOUSEWHEEL`→`MOUSEEVENTF_WHEEL`(`mouseData=GET_WHEEL_DELTA_WPARAM`)。
- 键盘:`wVk=(WORD)wParam`,`wScan=(lParam>>16)&0xFF`,`KEYEVENTF_EXTENDEDKEY` 由 `(lParam>>24)&1`。
@@ -205,6 +206,16 @@ AI 无法「看懂」视频流。把 25fps 的远程画面直接丢给视觉模
- 随后 `remote_keyboard` 注入 `Ctrl+V` 粘贴、`Enter` 发送。
- **编码注意(已核实)**:`UpdateClientClipboard` 用 `SetClipboardData(CF_TEXT,...)`——ANSI/GBK 格式(`CF_TEXT`,非 `CF_UNICODETEXT`)。MVP 下中文可经 `ToAnsi(utf8, 936)` 转 GBK 后直发(与终端命令同模式);但 emoji/非 GBK 字符会丢、部分新式聊天软件粘贴偏好 Unicode。更稳做法是复用 `COMMAND_C2C_TEXT`(90) 的 UTF-8→Unicode→`CF_UNICODETEXT` 逻辑(`KernelManager.cpp:1573-1587`,且已内置「设完剪贴板后自动模拟 Ctrl+V」),或新增一个 UTF-8 设剪贴板变体。见 §17 实验案例。
### 6.5 Linux 客户端(`RES_CLIENT_TYPE=LNX`)
服务端路径与 Windows 完全一致(`COMMAND_SCREEN_SPY` → `TOKEN_BITMAPINFO` → `COMMAND_SCREEN_CONTROL`),差异都在客户端(`linux/ScreenHandler.h`,本轮**未改客户端**):
- **注入**:走 XTest(`XTestFakeMotionEvent` / `XTestFakeButtonEvent` / `XTestFakeKeyEvent`),需要 `libXtst` 与可用的 X 连接(X11 或 XWayland)。
- **按键映射**:`VKtoKeySym` 把 Windows VK 映射为 X11 keysym 后 `XKeysymToKeycode`。支持 A–Z、0–9、小键盘、F1–F12、方向键/编辑键、修饰键(`VK_SHIFT→Shift_L`、`VK_CONTROL→Control_L`、`VK_MENU→Alt_L`、`VK_LWIN→Super_L`)与 OEM 标点;**F13–F24 与 `VK_APPS` 无映射**(消息被忽略,不报错)。
- **滚轮**:客户端收到 `WM_MOUSEWHEEL` 后按 120 的倍数换算成 Button4/Button5 的按放对,单条消息即可(服务端 `scroll` 只发一条)。
- **剪贴板**:服务端按 GBK 下发(与 Windows 相同),Linux 客户端 `ClipboardHandler::SetTextRaw` 检测编码并用 iconv 转 UTF-8 后写 `xclip -selection clipboard`;需要 `xclip` 或 `xsel`。非 GBK 字符(emoji)在服务端就已变成 `?`,Linux 侧无法挽回。
- **分辨率**:`TOKEN_BITMAPINFO` 的尺寸取自 root window,与服务端归一化坐标一致;多显示器判定依赖客户端心跳的 `RES_RESOLUTION`(`xrandr` 才能拿到显示器数),无 `xrandr` 时上报 `0:0*0`,服务端按「无法判定」放行。
---
## 7. 坐标约定与映射
@@ -295,10 +306,8 @@ remote_open ──► 建立子连接 ──► [remote_mouse/remote_keyboard ×
| -32002 | 设备/会话不存在 | `id` 无在线主机、`session_id` 不存在或不匹配 |
| -32003 | 设备/会话忙 | 已有控制会话、人类远程桌面占用、`get_screenshot` 在飞 |
| -32004 | 发送失败 | 注入命令发送失败 |
| -32005 | 能力不支持 | 客户端无 `CLIENT_CAP_SCREEN_PREVIEW`(Observe)/ 不支持屏幕控制(Act) |
| -32005 | 能力不支持 | 客户端无 `CLIENT_CAP_SCREEN_PREVIEW`(Observe)/ 不支持屏幕控制(Act)/ **多显示器主机(阶段一)** |
| -32006 | 被开关禁用 | `McpRemoteControl=0` 或 `McpReadonly=1` |
| -32008 | 非法/被拒参数 | 多显示器未支持时的 `remote_open` 降级拒绝(阶段一) |
---
## 11. 配置项
@@ -317,8 +326,9 @@ remote_open ──► 建立子连接 ──► [remote_mouse/remote_keyboard ×
### 12.1 阶段一(本期)
- **单显示器**:Observe 抓主屏,坐标空间与虚拟桌面重合;多显示器 `remote_open` 显式报错(`-32008`)。
- **单显示器**:Observe 抓主屏,坐标空间与虚拟桌面重合;多显示器 `remote_open` 显式报错(`-32005`,能力限制而非参数错误)。
- 注入基于**绝对坐标** `SendInput`,要求客户端处于可注入的桌面会话(已登录、非锁屏/非 UAC 安全桌面);锁屏/UAC 提示场景注入无效(客户端 `SendInput` 限制),设计文档记录为已知限制。
- **Linux 专属限制**(§6.5):纯 Wayland 会话不支持(需 X11/XWayland);需 `libX11`+`libXtst`,剪贴板需 `xclip`/`xsel`;F13–F24、`VK_APPS` 无 keysym 映射;非 ASCII 文本仍只能走剪贴板。
- **代聊实验使能项**:窗口抓屏(`COMMAND_SCREEN_WINDOW`)、UTF-8 剪贴板、窗口聚焦随阶段一落地(§17)。
### 12.2 阶段二(后续)
+166
View File
@@ -0,0 +1,166 @@
# YAMA MCP 服务测试报告
- 日期:2026-10-25(两轮:本机回环 + 虚拟机复测)
- 环境:
- 第1轮:Debug 服务端 `Yama_x64d.exe` + 本机被控端 `ghost.exe`(Windows 11,双显示器)
- 第2轮:同一 Debug 服务端 + VirtualBox 虚拟机被控端(`DESKTOP-A55C0OI`,Windows 10 19045,单显示器 1718x920,clientType=MDLL)+ 重启后的本机被控端
- 配置:`Bin\settings.ini`(McpEnabled=1,McpPort=6545,McpBind=127.0.0.1,McpReadonly=0,全部 `Mcp*` 开关开启)
- 方法:Python 直连 `http://127.0.0.1:6545/mcp`(JSON-RPC 2.0),辅以 `tools/mcp_smoke.ps1`、审计日志、`get_client_log`、代码审读交叉验证
- 敏感操作约束:删除类操作仅针对本次自建的临时文件/目录(本机 `%TEMP%\yama_mcp_test`、VM 同名目录),测试后已全部清理
---
## 0. 复核与处置(同日二次复核)
复核方式:逐条回到源码确认现象与根因,再在 Debug 实例(`Bin\Yama_x64d.exe` + 本机 `ghost.exe`,Windows 11 双屏 ConPTY 客户端)上端到端复现与验证修复。复核用的客户端配置临时改为直连本机(`x64\Debug\settings.ini`:`master=127.0.0.1`、`ghost=6543`、`UseFrp=0`,原文件备份为 `settings.ini.bak_mcptest`);修复后在 Debug 实例上 `tools/mcp_smoke.ps1 -SearchPath C:\Windows\Fonts` **37/37 通过**。
| 编号 | 复核结论 | 处置 | 验证证据(修复后实测) |
|---|---|---|---|
| P1 | 属实 | **已修**。ConPTY 下哨兵改为独立一行(`@echo off & <cmd>` + 单独 `echo __MCP_DONE_<nonce>__%errorlevel%`);会话因超时被销毁后留 600s 墓碑,报错文案区分「被销毁」与「id 写错」。老客户端(非 PTY)保持单行 `&&` 形态,行为不变。 | `rem hello` → exit 0(原 100% 超时);`cmd /c exit 0` → exit 0;`cmd /c echo abc` → `abc`。超时路径:`ping -n 40` 配 `timeout_ms=3000` → `-32001`,随后同一 session → `-32002 "Terminal session was destroyed after this command timed out (waited 3000 ms); call terminal_open again"`;假 id → `-32002 "Terminal session not found: <id> (call terminal_open first)"`;销毁后 `terminal_open` 立即成功 |
| P2 | 属实(结论成立),但「10 个纯本地 DB 读取」的**表述有误**——被挡的是经主连接向目标机取数据的远程机器管理工具(`host_list_processes/windows/network_state/scheduled_tasks/services/…`、`host_get_hosts_file` 等,都走 `BeginPending`),属 single-flight 设计;纯服务端本地工具(`get_server_status`、`get_audit_log`、`host_set_remark` 等)不受影响 | **已修**(选了「快速失败」):文件传输加 60s 停滞看门狗,`timeout_ms` 内只要持续有数据就不受影响;默认超时保持 600s(避免误杀大文件)。互斥豁免未做——远程工具之间互斥本身就是有意的。 | 不存在路径 `C:/no_such_dir_zzz_mcp` → **60096ms** 失败,`-32001 "File transfer stalled: no data received for 60s (the remote path is probably missing or inaccessible; verify it with list_files first)"`(原为 `ms=600004`);挂起期间 `get_server_status` 2120ms OK、`get_audit_log` 20ms OK,远程 `list_files` 仍 `-32003`;失败后主机立刻释放,冒烟脚本随即 37/37 通过。**2026-10-25 二次修**:新客户端在建立传输子链接前就回 `TOKEN_DOWNLOAD_ERROR`(173),`download_file` 不存在路径现在 **0.07s → `-32009`**(`Remote path does not exist: ... (win32=3)`),60s 停滞看门狗降级为兜底 |
| P3 | 属实 | **已修**。`%errorlevel%` 在回显文本里是字面模板而非数字,`FindSentinel` 改为「从后往前找第一个『标记+数字』」,不再依赖行首。 | `ver` → exit 0(原 1);`nosuchcmd_zzz` → 9009;`cmd /c exit 0` → 0;`set NOVAR` → 1 |
| P4 | 属实 | **已修**。清洗改为三段:删到「命令行回显」结束(顺带清掉 shell 启动画面/提示符)→ 删哨兵行回显 → 按 nonce 擦掉渲染残留的哨兵文本;另修 `StripAnsi` 对 `OSC…ESC\` 的收尾(会残留 `\`)。设计见 `docs/Mcp_Design.md` §12.1。 | 上述命令的 stdout 全部无 `@echo off`、无 `__MCP_DONE_*`、无提示符/空行;`type` 报错文本无残留反斜杠 |
| P5 | 属实 | **已修**(`McpInternal.cpp` 注解表 `get_activity_history` → `openWorld=true`,附代码注释说明它经 `COMMAND_QUERY_ACTIVITY` 触达远程主机) | 代码审查 + 与 §10.2 口径一致 |
| P6 | 属实(`OpenSCManager` 权限不足,客户端失败分支回普通消息包) | **已修**:新增 `TOKEN_SERVICE_ERROR`(170),客户端 `SendServicesList` 失败时回 `[170][win32:4]`(并保留原 `ClientMsg`,老服务端行为不变);服务端转译成 `-32010`,文案点明需要管理员权限 | 非提权客户端 `list_services` → **268ms `-32010`**(`Failed to enumerate services: access denied (win32=5). service enumeration requires the client to run elevated (administrator)`;原为 20s `-32001`) |
| P7 | 属实 | **已修**(文档):`docs/Mcp_Design.md` §12 补齐 `-32007`/`-32008`/`-32009` 并注明 `-32008` 的四类语义 | 文档核对 |
| P8 | 属实 | **已修**:新增 `TOKEN_FILE_LIST_ERROR`(171) / `TOKEN_REG_ERROR`(172),客户端失败分支回 `[token][win32/lstatus:4]`;服务端按 `2/3 → -32009`、`5 → -32010` 转译,空目录/空键仍返回成功空列表 | `list_files C:\no_such_dir_xyz` → **0.22s `-32009`**、`list_files C:\System Volume Information` → **0.06s `-32010 (win32=5)`**;`list_registry HKLM\Software\NoSuchKeyXYZ` → **0.10s `-32009`**、`HKLM\SAM\SAM\Domains\Account` → **0.08s `-32010`**;空目录/正常目录/正常键返回不变 |
**结论**:报告的问题清单与根因分析全部成立(仅 P2 有一处表述需要更正);P1/P3/P4(同一处哨兵机制)与 P5/P7、P2 的「长时间锁定」已在服务端修复并端到端验证,P6/P8 已在放开「客户端可小改」后按结构化失败回报修复(见上表,均为亚秒级返回)。
---
53 个工具全部可达,冒烟脚本 32/32 通过。功能面整体质量良好;VM 复测轮验证了第1轮受条件所限未能覆盖的远程控制族(11/11)、跨机文件往返、真实 kill 目标校验,并把第1轮两大疑难问题(exec_command 超时、list_services 超时)推进到根因定性。
最终问题清单:**2 个高优先级**(哨兵机制对吞行命令必然超时并销毁会话;download_file 失败路径长时间锁定主机)、**3 个中优先级**(exit_code 不可靠、stdout 内部实现泄漏、get_activity_history 注解错误)、**3 个低优先级**(list_services 权限失败无解释、错误码缺漏/-32008 复用、路径类工具静默空结果)。每条问题的逐条复核结论、处置与修复后实测证据见 §0。
## 2. 问题清单
### P1(高):哨兵机制——「吞行」命令 100% 超时,且销毁持久会话
哨兵方案:发送 `@echo off & <cmd> 2>&1 && echo __MCP_DONE_<nonce>__0 || echo __MCP_DONE_<nonce>__1`,服务端扫描输出定位哨兵取退出码(`McpServer.cpp:2721/3027` 发送、`FindSentinel :6195` 匹配)。
缺陷:**任何会消费行内剩余文本的命令都会把哨兵一起「吞掉」**,导致哨兵永远不出现:
| 命令 | 结果 | 机制 |
|---|---|---|
| `rem hello` | 超时 | `rem` 把整行剩余部分当注释,`&& echo 哨兵` 不执行 |
| `cmd /c exit 0` | 超时(2/2 会话复现) | `cmd /c` 把 `&& echo 哨兵` 一并传给子进程,子进程 `exit` 即退 |
| `if`/`for` 同理 | 预期同 | 同类吞行语句 |
后果链:20s 等待 → `-32001 Timeout waiting for command output`;**持久终端路径上 `WaitTermCommand` 超时直接销毁会话**(`McpServer.cpp:6400` 附近),后续所有 `terminal_exec` 报 `-32002 "Terminal session not found, not ready, or busy"`——报错文案无法区分「会话已被超时销毁」与「id 写错」。
- 正常对照:`whoami` 35/35 成功(62-217ms)、`set NOVAR`(失败有哨兵)正确返回 exit=1、`cmd /c echo abc`/`cmd /c ver`(子进程有输出)成功。
- 建议:
1. 哨兵改为独立行下发(先发命令行,再单独发 `echo __MCP_DONE_...__0 || echo ...` 第二行,或用 `(%cmd%) & (echo sentinel)` 子shell包裹);
2. 会话被超时销毁后,`terminal_exec` 对该 session_id 返回专门的错误文案(如 "session destroyed after timeout; re-open");
3. 文档标注 `exec_command`/`terminal_exec` 不支持 `rem`、`cmd /c` 等吞行命令。
**复核(2026-10-25)**:属实。已按建议 1、2 修复并验证(PTY 下哨兵独立成行;超时销毁会话留墓碑 + 专用文案),文档见 `docs/Mcp_Design.md` §12.1。老客户端(非 PTY)仍为单行形态,故「吞行命令」限制只适用于老客户端。
### P2(高):`download_file` 对不存在路径无快速失败,默认 600 秒锁定整台主机
- 不存在的远程路径会等满默认 `timeout_ms=600000`(实测审计日志 `ms=600004`),期间该主机**所有**远程机器管理工具 `-32003`(single-flight 跨工具互斥),含 `host_list_processes/windows/network_state/scheduled_tasks/services`、`host_get_hosts_file` 等**经主连接向目标机取数据**的工具。一次误路径 = 10 分钟整机不可管理。(初版报告把这批工具写成「10 个纯本地 DB 读取」,属表述错误:它们都要触达目标主机,被互斥挡住是设计;纯服务端本地工具如 `get_server_status` / `get_audit_log` / `host_set_remark` 不受影响,二次复核已实测确认。)
- **timeout_ms 参数本身工作正常**(显式 8000 → 实测 8031ms 终止),问题是默认值过长 + 缺路径检测。
- 建议任选:客户端枚举路径时快速失败(最优);或下调默认超时(如 60s);或本地读取类工具豁免 BeginPending 互斥。
### P3(中):`exit_code` 不可靠(哨兵匹配到回显模板)
- `ver`(成功命令)返回 `exit_code=1`。根因:ConPTY 80 列回显折行使**回显的命令模板**中 `|| echo __MCP_DONE_<nonce>__1` 片段落到行首,`FindSentinel`(`McpServer.cpp:6195`)要求哨兵前是 `\n`/`\r`,于是 rfind 命中的是回显片段而非真实执行的哨兵。
- 影响:依赖 exit_code 的自动化会把成功当失败。与 P1 同根(哨兵与回显混在同一输出流)。
- 建议:随 P1 一起修(独立行哨兵可同时解决);短期可在 FindSentinel 中排除与已发送命令行重叠的匹配位置。
**复核(2026-10-25)**:属实。已随 P1 修复:`%errorlevel%` 回显是字面模板、`FindSentinel` 改为从后往前找「标记+数字」,实测 `ver`→0、`nosuchcmd_zzz`→9009。
### P4(中):`stdout` 泄漏内部实现(回显命令行 + 哨兵文本)
- `terminal_exec`/`exec_command` 返回的 stdout 中可见 `@echo off & ...` 命令回显、`__MCP_DONE_<nonce>__0/1` 哨兵字样(多例复现,如 `cmd /c echo abc` 的 stdout 含 `__0 || echo __MCP_DONE_2c0fbce0__1\nabc`)。
- 原因:ConPTY 回显折行后 `StripEchoedCommand` 的整行匹配失效;哨兵截断点之后的清洗也不覆盖片段。
- 影响:输出不可直接展示给最终用户;nonce 泄漏无安全风险(一次性),但属于实现细节泄漏。
- 建议:清洗逻辑改为「剔除从行首到哨兵行之前的全部回显块」,而非精确整行匹配。
**复核(2026-10-25)**:属实。已修:删到命令行回显结束 → 删哨兵行回显 → 按 nonce 擦掉渲染残留的哨兵文本;另修 `StripAnsi` 对 `OSC…ESC\` 收尾会残留 `\` 的问题。设计见 `docs/Mcp_Design.md` §12.1。
### P5(中):`get_activity_history` 注解登记错误
- `McpInternal.cpp:333` 登记 `openWorldHint=false`,但该工具经 `ctx->Send2Client(COMMAND_QUERY_ACTIVITY)` 触达远程主机(`McpServer.cpp:2249`),与代码注释及 `docs/Mcp_Design.md` §10.2 口径矛盾。一行修复。
**复核(2026-10-25)**:属实,已改 `openWorld=true` 并加注释说明理由。
### P6(低):`list_services` 在非提权被控端上 20s 超时且无解释
- 第1轮本机被控端(非提权):3/3 超时。客户端日志定位根因:`ServicesManager.cpp:31 Get service list failed`——`OpenSCManager(SC_MANAGER_ALL_ACCESS)` 权限不足,失败分支回传普通消息包而非 `TOKEN_SERVERLIST`,服务端等满 20s。
- 第2轮 VM 被控端(权限足够):**成功**(服务列表正常返回)——反证根因即权限。
- 建议:客户端失败分支回传带失败标记的 `TOKEN_SERVERLIST`,服务端转译为 `-32005`/明确错误文本;文档标注需要管理员权限。
**复核(2026-10-25)**:属实(`OpenSCManager` 权限不足 → 客户端失败分支回普通消息包,服务端只能等到超时)。修它要改客户端,按「暂不动客户端」原则搁置。
### P7(低):错误码表缺 -32007/-32008/-32009,且 -32008 复用多种语义
- `docs/Mcp_Design.md` §12 只登记到 -32006。-32008 同时用于:元字符、`&|`/控制字符、老客户端格式、多显示器不支持(4 处)。后者语义近 `-32005 Not supported`。
**复核(2026-10-25)**:属实。`docs/Mcp_Design.md` §12 已补齐 `-32007`/`-32008`/`-32009`,`-32008` 行内注明其四类语义(修正参数 vs 能力限制的处理方式不同)。
### P8(低):路径类工具对不存在路径静默返回空
- `list_registry`(注册表,两轮均复现)与 `list_files`(文件列表)对不存在的路径均返回空列表 + `isError:false`,无法区分「为空」与「不存在」。建议返回错误或加 `exists:false`。
**复核(2026-10-25)**:属实,但服务端拿到的响应与「空目录/空键」完全一致,无法在服务端区分;需客户端回报错误码 → 按「暂不动客户端」原则搁置。
### 观察项(不计入问题)
- `host_list_network_state` 的 state 为本地化文本("连接"),按 `ESTABLISHED` 过滤会失配;`kill_network_connection` 内部已归一化(stateName=ESTABLISHED, killable:true),dry_run 对真实四元组校验通过。
- `remote_open` 双显示器拒绝(-32008)文案清晰、即时;VM 单屏下全链路正常。
- 第1轮 exec_command 11/12 超时在两台被控端重启后均未复现(VM 5/5、重启后本机 5/5+30/30 连发通过);当时环境长时间运行+大量会话开关,疑与资源/状态积累有关,未能复现定位。鉴于 P1/P3 已证哨兵机制脆弱,建议优先落实哨兵改造后观察。
## 3. 通过项(摘要)
| 领域 | 结果 |
|---|---|
| 传输层 | 401/413/404、-32700/-32600/-32601、ping、status 不泄露 token —— 全过 |
| 冒烟脚本 | 32/32 PASS |
| 主机列表/分页/过滤 | 分页 clamp、越界、group/os/client_type、totalAll 保留 —— 全过 |
| 批量工具 | ids>51 拒、写工具拒批量 —— 全过 |
| exec 安全门 | 白名单+词边界(`dir` 过/`dirx` 拒/`echo` 拒)、`&`/CRLF -32008、空命令 -32602 —— 全过 |
| 文件传输 V2 | 上传 11 项(中文文件名、1MB SHA-256、620 文件递归、overwrite 跳过)、下载 SHA-256、**跨机往返(本机↔VM)SHA 一致** —— 全过 |
| search_file | min_size/name_only/子串/非法时间 -32602 —— 全过 |
| 服务端本机工具 | audit 分页+过滤、status 一致性、`host_set_remark` GBK 边界(63B 过/66B 拒/emoji 拒)—— 全过 |
| 只读主机工具(双端) | get_screenshot(JPEG magic 双端过)、get_keylog、list_registry 子键、list_windows、get_activity_history —— 全过 |
| **remote 控制族(VM,第2轮新增)** | open→mouse(move/click/scroll)→keyboard(type/key_press)→clipboard→close→幂等→死会话拒绝 —— **11/11** |
| chat(双端) | 本机 6/6 + VM 4/4(open/send/wait timed_out/close)—— 全过 |
| 终端持久会话 | open/exec/close 生命周期、echo/whoami/cmd /c echo 等有输出命令 —— 全过(异常见 P1/P3/P4) |
| 写工具 | watch_level 1↔0 往返、非法值拒绝 —— 过 |
| kill_network_connection | dry_run 假四元组 -32009、**真实四元组校验通过**(VM 实测)—— 过 |
## 4. 修复优先级建议
1. **哨兵改造**(P1/P3/P4 同根一次修):独立行哨兵 + 回显块整体剔除 + 超时销毁会话的专用错误文案;
2. P2:download 快速失败或默认超时下调 + 本地读取豁免互斥;
3. P5:一行注解修复;
4. P6:客户端服务枚举失败结构化回传;
5. P7/P8 随批次顺手处理。
**复核后状态**:1 → 已修(§0 P1/P3/P4);2 → 已修「停滞 60s 快速失败」,默认超时未下调、互斥豁免未做(远程工具互斥是有意设计,本地工具本就不受限);3 → 已修;4 → 已修(`TOKEN_SERVICE_ERROR` → `-32010`);5 → P7 已修(文档),P8 已修(`TOKEN_FILE_LIST_ERROR`/`TOKEN_REG_ERROR` → `-32009`/`-32010`)。
## 附录 A:错误码实测一览
| 码 | 场景 | 实测 |
|---|---|---|
| -32001 | 等待超时 | 吞行命令、非提权 list_services、download 600s/8s 均复现(复核后:吞行命令不再超时;download 停滞 60s 即失败并说明原因) |
| -32002 | 离线/不存在 | 不存在 id 复现;会话销毁后 terminal_exec 文案混用(见 P1)→ 复核后已拆成「被超时销毁」与「id 写错」两种文案 |
| -32003 | 单设备互斥 | 挂起期间跨工具复现(含远程机器管理工具;**纯服务端本地工具不受影响**,复核已实测) |
| -32005 | 不支持 | 代码审查确认(无 LNX/MAC 主机可测) |
| -32006 | 策略拒绝 | 冒烟历史覆盖(McpKeylog=0 → CALL_DENIED) |
| -32007 | 白名单拒绝 | `echo`/`set` 复现 |
| -32008 | 元字符/&\|/老格式/多显示器 | 双屏 `remote_open`、`dir & whoami` 复现 |
| -32009 | kill 目标不存在 | dry_run 复现;真实四元组通过 |
| -32602 | 参数错误 | 备注 66B、level=99、非法时间等复现 |
## 附录 B:审计日志行为
- `CALL_OK`/`CALL_FAIL` 含 `tool= ms= bytes=`;600s 挂起精确记录 `ms=600004`;`get_audit_log` 过滤与实际一致。
## 附录 C:测试残留与清理
- 全部测试数据(本机 `%TEMP%\yama_mcp_test\src|vm_target|dl_vm` 与 VM 同名目录)测试后已删除/验证删除。
- `settings.ini` 未做修改(本轮未动开关),第1轮已恢复备份。
- VM 会话中因超时被销毁的终端已随服务端状态清理;我启动的本机 ghost.exe 已关闭,Debug 服务端保持用户启动状态。
+27 -6
View File
@@ -1,8 +1,8 @@
# 传输层单向 TLS 加密设计(按需加密)
> 版本:v0.5 · 状态:**Go 服务端 + Windows 客户端已实现并验证;信任锚改存注册表;MFC 主控端(阶段 3)未施工** · 日期:2026-10-14
> 版本:v0.7 · 状态:**Go 服务端 + Windows/Linux 客户端已实现并验证;Linux 客户端支持下发即时热切换;MFC 主控端见 `TransportTLS_MFCServer_Design.md`;macOS/Android 未接入** · 日期:2026-10-28(Linux 客户端接入 + 热切换)
> 目标:让 YAMA 设备端口(TCP 6543)在继续兼容老客户端(明文/XOR)的同时,允许新客户端在拿到证书后按需开启**单向 TLS** 加密传输。
> 本期范围:**Go 服务端(`server/go`)+ Windows 客户端**;MFC 服务端(`server/2015Remote`)延后。
> 本期范围:**Go 服务端(`server/go`)+ Windows 客户端 + Linux 客户端**。
>
> 需求原文(三点,逐一对应下文):
> 1. 新客户端**默认不加密**,行为与老客户端完全一致;
@@ -23,8 +23,8 @@
- 不做 **mTLS / 客户端证书**:单向 TLS 不验证客户端证书,客户端身份仍由隧道内的现有登录(`PwdHmac` V1 / `ECDSA` V2)承担。
- 不做传输层 PSK(`YAMA_TRANSPORT_KEY`)方案——本设计改用证书,更贴合「颁发证书」的运维模型。
- 不改应用层协议(flag 帧格式 / XOR / zstd),不做「TLS 内去掉 XOR」的二次精简(后续可选)。
- 不做加密开关的运行时热切换(证书只在客户端启动时读取一次,改配置需重启——这正是需求)。
- 不做 Linux / macOS / Android 客户端的 TLS 接入(本文以 Windows MFC 客户端为主,其余平台同样式跟进)。
- Windows 客户端**不做**加密开关的运行时热切换(证书只在进程启动时读取一次,改配置需重启——这正是需求)。Linux 客户端例外:服务端下发 166/167 后立即重载信任锚并重连切换(§6.6),语义差异见该节。
- macOS / Android 客户端的 TLS 接入不在本期(Linux 客户端已按同一模式接入,见 §6.6)。
- 不做 **MFC 服务端(`server/2015Remote`)的 TLS 接入**——本期只做 Go 服务端(`server/go`),MFC 主控端延后到阶段 3。
## 2. 现状与复用
@@ -190,6 +190,8 @@ func (s *Server) wrapTLS(conn net.Conn) net.Conn {
启动时(连接前)按优先级找信任锚:① 注册表 `Software\<exehash>\settings\tls_cert`(REG_SZ 存 PEM 正文)→ ② `settings.ini` `[settings] tls_cert` 路径 → ③ exe 同目录 `yama-ca.pem`。找到即走 TLS,否则明文。实现:`client/TlsChannel.cpp` 的 `ReadTrustAnchor()` + `TlsEnabled()`(`std::call_once` 惰性加载、线程安全、幂等)。
Linux 无注册表,信任锚按:① `$XDG_CONFIG_HOME/ghost/yama-ca.pem`(默认 `~/.config/ghost/yama-ca.pem`)→ ② 程序同目录 `yama-ca.pem`。文件**存在即视为已配置**:读取/解析失败一律拒绝连接(fail-closed)。实现:`client/TlsChannelLinux.cpp`。
### 6.2 TLS 栈选型(已定:Schannel)
- **已选 Schannel(Windows 原生 SSPI)**:零第三方依赖/零额外 DLL 部署,`secur32.lib`/`crypt32.lib` 均为系统库(`secur32.lib` 已在 `CFFmpegH264Encoder.cpp:38` 链接)。
@@ -223,6 +225,22 @@ Schannel 流模式(`ISC_REQ_STREAM`)下,`DecryptMessage` 会把输入的
`STREAM_HEADER/DATA/TRAILER` 三段布局,本就正确。这一处是联调阶段实际踩到的、唯一的方向性
不对称 bug,已修复。
### 6.6 Linux 客户端实现(OpenSSL,2026-10-28)
- **选型**:OpenSSL(`libssl`)。Linux 构建早已因 `libsign.a` 链接 `libcrypto`,只多链一个 `OpenSSL::SSL`,不引入新的运行时依赖包(同一 OpenSSL 3 包提供 `libcrypto.so.3` / `libssl.so.3`)。
- **代码组织**:`client/TlsChannel.h` 按平台分派(`_WIN32` → Schannel,`__linux__ && !__ANDROID__` → OpenSSL),Windows 分支内容不变;实现文件为 `client/TlsChannelLinux.cpp`。`YAMA_TLS_CHANNEL` 宏标注「本平台有 TLS 通道」,`IOCPClient` 用它替代原先的 `#ifdef _WIN32`,因此主连接与子连接共用同一接线点。macOS/Android 不定义该宏,维持明文。
- **语义对齐**:`TLS 1.2` 钉扎(min=max,与 `SP_PROT_TLS1_2_CLIENT` 及两套服务端一致);单向 TLS、不提供客户端证书、不校主机名、不做吊销检查;`SSL_VERIFY_PEER` + 只含信任锚的 `X509_STORE`(不含系统根库,严格钉扎),握手内完成链校验,失败即断开(fail-closed)。
- **缓冲差异**:OpenSSL 自己管理记录缓冲,不需要 Schannel 的 `m_raw`/`m_pending`;一次 `SSL_read` 交付不完的明文留在 `SSL` 内部,接收线程在 `select` 前用 `SSL_pending() || SSL_has_pending()` 优先消费,否则剩余字节会被 2 秒 `select` 超时卡住。
- **下发/撤销**:`COMMAND_TLS_ENABLE`(166) 的 PEM 正文写入 `~/.config/ghost/yama-ca.pem`(目录 0700、文件 0600、临时文件 + rename 原子替换);`COMMAND_TLS_DISABLE`(167) 删除该文件(含程序目录同名回退文件)。写入前先用 OpenSSL 解析一遍,不是合法证书就整包拒绝并保留原状态。
- **热切换(与 Windows 的唯一语义差异)**:落盘后立即 `TlsReload()` 重建 `SSL_CTX` 并更新开关,然后断开主连接、由外层重连循环用新传输方式重连——**主控端菜单点下去几秒内就生效**,不需要重启客户端(Windows 客户端仍需重启进程)。
- 状态不再是 `std::call_once`,而是 `g_stateMtx` 保护的 `{g_tlsEnabled, g_tlsError, g_tlsCtx}`;`TlsEnabled()/TlsLoadError()/TlsReload()/Handshake()` 都在这把锁下读写。
- **已建立的连接不受影响**:`SSL_new` 会递增 `SSL_CTX` 引用计数,`TlsReload` 释放旧 ctx 后旧的 `SSL` 仍然安全(已用「连接保持打开时撤销锚」验证)。
- **只在传输方式真的变了(明文↔TLS)时才重连**;仅换锚(例如证书轮换,仍是 TLS)不打断现有会话,新锚从下一条新连接生效。
- 热重载遇到坏锚时**保留原状态**并记日志,不把正在工作的客户端打死(下次启动仍按 fail-closed 语义)。
- 重连由 `DataProcess`(接收线程)只置 `g_needReconnect` 标志,由主心跳线程 `Disconnect()` 后走外层重连循环——避免在接收线程里关 socket 与主线程发送竞争。
- **代价**:此刻若正处于远程桌面/文件传输会话,主连接重建会中断该会话(子连接随之失效)。这是「立即生效」的固有代价。
- **上报**:登录 `szReserved[19]`(`RES_TLS`)填 `TlsEnabled() ? 1 : 0`,主控端主机信息显示 Y/N。热切换后重连会重新登录,登录前用 `RefreshLoginTls()` 刷新该字段,主控端在线列表的 TLS 列随之翻转。
## 7. 兼容矩阵
| 客户端 | 服务端行为 | 结果 |
@@ -286,7 +304,9 @@ Set-ItemProperty -Path 'HKCU:\Software\<exehash>\settings' -Name 'tls_cert' -Val
兼容旧方式:把信任锚复制到客户端目录并命名为 `yama-ca.pem`(或经 `settings.ini` `[settings] tls_cert` 指向),重启客户端。
移除注册表值(或删除文件)并重启即退回明文。**远程下发/撤销信任锚属后续工作,本期仅支持本地写注册表。**
Linux 客户端:把信任锚放到 `~/.config/ghost/yama-ca.pem`(或程序同目录 `yama-ca.pem`),重启客户端生效。MFC 主控端的「启用/停用 TLS 传输」指令对选中主机下发时也会写/删该文件,**且 Linux 客户端会立即热切换并重连**(无需重启,见 §6.6);Windows 客户端仍需重启。
移除注册表值(或删除文件)并重启即退回明文。远程下发/撤销:Windows 经 `COMMAND_TLS_ENABLE/DISABLE` 写注册表(重启生效),Linux 写/删上述配置文件(立即生效)。
## 10. 测试计划
@@ -302,6 +322,7 @@ Set-ItemProperty -Path 'HKCU:\Software\<exehash>\settings' -Name 'tls_cert' -Val
- **阶段 1(Go 服务端,本期优先)**:`Config` + `tls.Config` + `acceptLoop` 检测回放;明文路径零改动。可独立上线、独立验证——用 `openssl s_client` 或 Go 测试客户端即可联调 TLS 链路,无需真实客户端配合。
- **阶段 2(Windows 客户端)**:证书检测 + TLS 栈 + fail-closed。
- **阶段 2b(Linux 客户端)**:OpenSSL 实现,复用同一接线点与协议语义(2026-10-28 完成)。
- **阶段 3(MFC 服务端 `server/2015Remote`,延后)**:与 Go 服务端同款的 TLS 检测 + 解包接入。设计稿见 `docs/TransportTLS_MFCServer_Design.md`。
- **回滚**:服务端清空 `YAMA_TLS_CERT/KEY` 即回到纯明文;客户端删除注册表 `tls_cert` 值(或 `yama-ca.pem` 文件)即回明文。
@@ -310,4 +331,4 @@ Set-ItemProperty -Path 'HKCU:\Software\<exehash>\settings' -Name 'tls_cert' -Val
1. ~~客户端 TLS 栈最终选型~~ → **已定 Schannel**(见 §6.2,2026-10-13 落地)。
2. ~~信任锚文件固定名(`yama-ca.pem`)是否需可配置~~ → **已改为注册表 `tls_cert` 值优先、文件回退**(见 §6.1/§9.3,2026-10-14)。
3. 是否同步把「TLS 内去掉 XOR」列为后续精简项(当前保留 XOR,换取零协议改动)。
4. Linux / macOS / Android 客户端的 TLS 接入排期。
4. ~~Linux / macOS / Android 客户端的 TLS 接入排期~~ → **Linux 已接入(OpenSSL,2026-10-28)**;macOS / Android 待定(macOS 需 Security.framework 或自带 OpenSSL,Android 需在 NDK 内构建 OpenSSL)。
+4 -2
View File
@@ -28,6 +28,7 @@ set(SOURCES
main.cpp
../client/Buffer.cpp
../client/IOCPClient.cpp
../client/TlsChannelLinux.cpp # Linux 客户端单向 TLS(OpenSSL),见 client/TlsChannel.h
../client/sign_shim_unix.cpp
)
add_executable(ghost ${SOURCES})
@@ -45,9 +46,10 @@ target_link_libraries(ghost PRIVATE "${CMAKE_SOURCE_DIR}/lib/libzstd.a")
# 该库由 SimplePlugins 仓库本地构建后放置于 lib/,构建机需先准备好
target_link_libraries(ghost PRIVATE "${CMAKE_SOURCE_DIR}/lib/libsign.a")
# libsign.a 内部使用 OpenSSL HMAC,需要在最终可执行链接 libcrypto
# libsign.a 内部使用 OpenSSL HMAC,需要在最终可执行链接 libcrypto;
# 客户端传输层 TLS(client/TlsChannelLinux.cpp)另需 libssl。
find_package(OpenSSL REQUIRED)
target_link_libraries(ghost PRIVATE OpenSSL::Crypto)
target_link_libraries(ghost PRIVATE OpenSSL::Crypto OpenSSL::SSL)
# 链接 dl 库(dlopen/dlsym 用于运行时加载 X11)
target_link_libraries(ghost PRIVATE dl)
+50 -1
View File
@@ -25,8 +25,10 @@ SimpleRemoter 的 Linux 客户端,支持远程桌面、远程终端、文件
| 系统信息采集 | main.cpp | `LoginServer.cpp` | ✅ 完整 |
| 守护进程 | daemonize() | Windows 服务 | ✅ 完整 |
| 剪贴板同步 | `ClipboardHandler.h` | `ScreenManager.cpp` | ✅ 服务端↔Linux |
| V2 文件传输 | `FileTransferV2.h` | `file_upload.h` | ✅ 服务端↔Linux |
| V2 文件传输 | `FileTransferV2.h` | `file_upload.h` | ✅ 服务端↔Linux(含 MCP `upload_file`/`download_file`:发送完成包带流式 SHA-256,路径不存在/无权限回 `TOKEN_DOWNLOAD_ERROR`) |
| C2C 文件接收 | `FileTransferV2.h` | `file_upload.h` | ✅ Windows/MCP → Linux(目标目录由服务端 `dst_dir` 指定,落盘后回执) |
| 配置持久化 | `LinuxConfig` | INI 文件 | ✅ 完整 |
| MCP 远程管理 | 复用 `SystemManager.h` / `PTYHandler.h` / `ScreenHandler.h` | 服务端 MCP | ✅ 档 1:`kill_process`、`exec_command`、`terminal_open/exec/close`、`remote_open/close/mouse/keyboard/clipboard`(服务端放开门禁,客户端协议本已实现) |
### 未实现
@@ -160,6 +162,53 @@ make -j$(nproc)
kill $(cat ~/.config/ghost/ghost.pid)
```
## 远程升级
服务端选中一台 Linux 主机后点「升级程序」,即可把新的 `ghost` 推下去并自动重启。
### 服务端准备
按以下优先级取 ELF,前一级拿不到才看下一级:
| 顺序 | 来源 | 说明 |
|-----|------|------|
| 1 | `settings.ini` 的 `[settings] LinuxClientPath` | 显式指定。配了但读不到会直接报错,不会偷偷换成别的版本 |
| 2 | 服务端**程序目录**下的 `ghost_linux_amd64` | 换个文件即可,不必重编服务端 |
| 3 | 服务端 `res\ghost_linux` | 项目通用的外部资源目录 |
| 4 | 内嵌资源 `IDR_LINUX_GHOST` | 编译进服务端 exe(构建时取 `linux/ghost`),磁盘上什么都不用放 |
```ini
[settings]
LinuxClientPath=C:\build\ghost
```
第 4 级是编译时的快照,想换版本要么放到第 1~3 级,要么重编服务端。
只接受 64 位 x86_64 ELF(`ELFCLASS64` + `EM_X86_64`),其它文件会在下发前被拒绝并提示。
### 下发格式
```
[COMMAND_UPDATE:1][size:8 LE][ELF:size][md5:32 ASCII 小写 hex]
```
Windows 客户端的同名命令没有摘要(走内存加载器/更新器),LNX 多出 32 字节 MD5。
### 客户端行为
1. 校验长度、ELF magic、`e_machine` 与本机自身 ELF 头一致、MD5 匹配;
2. 在自身所在目录写临时文件 `.<名字>.new.<pid>`(0755)并 `fsync`;
3. 用 `rename()` 原子替换正在运行的二进制(Linux 允许替换执行中的 inode),
旧版本保留为 `<名字>.old`;
4. `fork` + `setsid` + 关闭继承的 fd + 等待老进程退出,再用**原始命令行** `execv` 新版本;
老进程以 `g_bExit = S_CLIENT_UPDATE` 正常退出,服务端立刻看到断线重连。
前提:客户端所在目录对运行用户可写(否则报「cannot create ...: Permission denied」)。
任何一步失败都不会退出进程,原因会写进客户端日志并发到服务端消息栏
(`Linux client update failed`)。
回滚:把 `ghost.old` 拷回 `ghost` 并重启即可(它会在下次升级时被覆盖)。
## 常见问题
### Q: 远程桌面功能不工作
+330 -4
View File
@@ -18,6 +18,7 @@
#include <iostream>
#include <stdexcept>
#include <cstdio>
#include <ctime>
#include <memory>
#include <array>
#include <regex>
@@ -37,8 +38,12 @@
#include "common/posix_net_helpers.h"
#include "common/sub_conn_thread.h"
#include "LinuxConfig.h"
#include <openssl/evp.h>
#include <cctype>
#include <vector>
int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength);
static void ApplySelfUpdate(const PBYTE szBuffer, ULONG ulLength);
// 远程地址:当前为写死状态,如需调试,请按实际情况修改
CONNECT_ADDRESS g_SETTINGS = { FLAG_GHOST, "91.99.165.207", "443", CLIENT_TYPE_LINUX };
@@ -46,6 +51,16 @@ CONNECT_ADDRESS g_SETTINGS = { FLAG_GHOST, "91.99.165.207", "443", CLIENT_TYPE_L
// 全局状态
State g_bExit = S_CLIENT_NORMAL;
static std::atomic<bool> g_needResendLogin(false); // 分组变更后需要重发登录信息
// 传输层热切换(服务端 COMMAND_TLS_ENABLE/DISABLE 改了信任锚)后需要重建连接。
// DataProcess 跑在接收线程上,直接关 socket 会和主线程的发送竞争,所以只置标志,
// 由主心跳循环择机 Disconnect 并重连。
static std::atomic<bool> g_needReconnect(false);
// 自升级(COMMAND_UPDATE):fork+execv 重启自己时需要原始命令行,
// 失败回报需要主连接(DataProcess 的 user 参数为 NULL,只能靠全局)。
static int g_argc = 0;
static char** g_argv = nullptr;
static IOCPClient* g_pMainClient = nullptr;
// 上次收到 HeartbeatACK 的 wall-clock 时间戳(ms),0 表示新连接刚建立尚未喂初值。
// 心跳循环用它检测应用层超时:TCP send() 永远不会因半死连接报错(数据塞进 SNDBUF
@@ -367,6 +382,28 @@ void* FileManagerThread(void* /*param*/)
return NULL;
}
// 信任锚已落盘/已删除:热重载 TLS 状态,必要时请求主循环重建连接。
// 只在传输方式真正变化(明文↔TLS)时重连;仅换证书(仍是 TLS)不打断现有会话,
// 新锚从下一条新连接开始生效。
static void ApplyTlsAnchorChange(void* user)
{
bool before = TlsEnabled();
std::string err;
if (!TlsReload(err)) {
Mprintf("** [%p] TLS reload failed: %s (keeping current transport) ***\n", user, err.c_str());
return;
}
bool after = TlsEnabled();
if (before == after) {
Mprintf("** [%p] TLS trust anchor updated, transport unchanged (%s) ***\n",
user, after ? "TLS" : "plaintext");
return;
}
g_needReconnect.store(true);
Mprintf("** [%p] TLS transport switched to %s, reconnecting ***\n",
user, after ? "TLS" : "plaintext");
}
int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
{
if (szBuffer == nullptr || ulLength == 0)
@@ -445,8 +482,8 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
FileTransferV2::HandleC2CPrepare(szBuffer, ulLength, nullptr);
Mprintf("** [%p] C2C Prepare received ***\n", user);
} else if (szBuffer[0] == COMMAND_SEND_FILE_V2 || szBuffer[0] == COMMAND_FILE_COMPLETE_V2) {
// V2 文件接收
int result = FileTransferV2::RecvFileChunkV2(szBuffer, ulLength, g_myClientID);
// V2 文件接收;g_pMainClient 用于 C2C 落盘回执(DataProcess 的 user 恒为 NULL)
int result = FileTransferV2::RecvFileChunkV2(szBuffer, ulLength, g_myClientID, g_pMainClient);
if (result != 0) {
Mprintf("** [%p] V2 File recv error: %d ***\n", user, result);
}
@@ -470,6 +507,36 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
// 标记需要重发登录信息(让服务端更新分组显示)
g_needResendLogin.store(true);
Mprintf("** [%p] Group changed to: %s ***\n", user, groupName.c_str());
} else if (szBuffer[0] == COMMAND_TLS_ENABLE) {
// 服务端下发信任锚证书(载荷与 Windows 一致:szBuffer+1 起为 PEM 正文)。
// Windows 写注册表 settings\tls_cert;Linux 写 ~/.config/ghost/yama-ca.pem。
// 与 Windows 不同:Linux 落盘后热重载并重连,立即切换(Windows 仍需重启进程)。
if (ulLength > 1) {
std::string pem((char*)szBuffer + 1, ulLength - 1);
std::string err;
if (TlsTrustAnchorSave(pem, err)) {
Mprintf("** [%p] TLS trust anchor received and saved ***\n", user);
ApplyTlsAnchorChange(user);
} else {
Mprintf("** [%p] TLS trust anchor save failed: %s ***\n", user, err.c_str());
}
} else {
// 没有证书正文就等于「启用但没有锚」——不该悄悄忽略,留一行便于排查。
Mprintf("** [%p] COMMAND_TLS_ENABLE without a certificate payload, ignored\n", user);
}
} else if (szBuffer[0] == COMMAND_TLS_DISABLE) {
// 撤销信任锚:删除配置文件并热重载,当前连接若是 TLS 就重连回明文。
std::string err;
if (TlsTrustAnchorRemove(err)) {
Mprintf("** [%p] TLS trust anchor removed ***\n", user);
ApplyTlsAnchorChange(user);
} else {
Mprintf("** [%p] TLS trust anchor removal: %s ***\n", user, err.c_str());
}
} else if (szBuffer[0] == COMMAND_UPDATE) {
// 服务端"升级程序"菜单下发新版本 ELF
Mprintf("** [%p] Received 'UPDATE' command (%u bytes) ***\n", user, (unsigned)ulLength);
ApplySelfUpdate(szBuffer, ulLength);
} else {
Mprintf("** [%p] Received unimplemented command: %d ***\n", user, int(szBuffer[0]));
}
@@ -585,6 +652,21 @@ std::string getLinuxDistro()
return "Linux";
}
// 进程启动时刻(墙钟)。在程序加载时记录一次:升级走 fork+execv 会重新加载本进程
// 镜像,于是升级后重新计时,与 Windows 的 GetProcessTimes(创建时间) 语义一致。
// 刻意不用 /proc/self/stat 的 starttime + /proc/stat 的 btime:btime 是开机时按当时
// 墙钟算的,之后 NTP 校时/休眠都不会修正它,算出来的启动时刻可能偏出几小时
// (WSL2 实测偏 1.8h)。这里是本进程自己读到的墙钟,不受此影响。
static const std::time_t g_processStartTime = std::time(nullptr);
// 进程启动时间("YYYY-MM-DD HH:MM:SS",北京时间):与 Windows 客户端的
// getProcessTime() 一致,是进程创建时刻而非本次登录时刻。
std::string getProcessStartTime()
{
// 服务端按北京时间解释这个字符串(见服务端 GetElapsedTime),沿用既有约定
return ToPekingTimeAsString(&g_processStartTime);
}
// 获取 CPU 核心数
int getCPUCores()
{
@@ -806,11 +888,241 @@ static void setupSignals()
signal(SIGPIPE, SIG_IGN); // 写入已关闭的 socket 时忽略
}
// ============== 客户端自升级(COMMAND_UPDATE) ==============
// 服务端 -> Linux 客户端载荷布局(Windows 的 COMMAND_UPDATE 没有摘要,LNX 有):
// [cmd:1][size:8 LE][ELF payload:size][md5:32 ASCII 小写 hex]
// 摘要只用于发现传输/落盘损坏:主通道本身已有掩码 + 可选 TLS。
//
// 关键约束:
// - 正在运行的 ELF 不能 O_TRUNC / 原地覆盖(ETXTBSY),必须先写同目录临时文件
// (同一文件系统,rename 才是原子的);
// - Linux 允许 rename() 覆盖正在执行的 inode,老进程继续跑完自己那份,
// 新进程用新 inode;
// - fork 子进程 -> setsid -> 关掉继承的 fd -> 等老进程退出 -> execv,
// 否则服务端会看到同一 clientID 两条连接并存,且新进程写 PID 文件前可能
// 被 isAlreadyRunning() 误判。
// 升级失败一律不退出进程:报错(ClientMsg 报到服务端消息栏 + 写客户端日志)后
// 继续用当前版本。
static const size_t kUpdateMd5HexLen = 32;
// MD5 小写 hex;与 Windows 侧 common/md5.h CalcMD5FromBytes 输出一致
static std::string md5HexOf(const unsigned char* data, size_t len)
{
unsigned char digest[EVP_MAX_MD_SIZE];
unsigned int digestLen = 0;
std::string hex;
EVP_MD_CTX* ctx = EVP_MD_CTX_new();
if (!ctx) return hex;
if (EVP_DigestInit_ex(ctx, EVP_md5(), nullptr) == 1 &&
EVP_DigestUpdate(ctx, data, len) == 1 &&
EVP_DigestFinal_ex(ctx, digest, &digestLen) == 1) {
static const char kHex[] = "0123456789abcdef";
hex.reserve(digestLen * 2);
for (unsigned int i = 0; i < digestLen; ++i) {
hex.push_back(kHex[digest[i] >> 4]);
hex.push_back(kHex[digest[i] & 0x0F]);
}
}
EVP_MD_CTX_free(ctx);
return hex;
}
// 自身 ELF 头的 e_machine(偏移 18,ELF32/ELF64 相同),用于拒绝架构不符的包
static int selfElfMachine()
{
std::ifstream f("/proc/self/exe", std::ios::binary);
unsigned char hdr[20] = {};
if (!f.read((char*)hdr, sizeof(hdr))) return -1;
if (hdr[0] != 0x7f || hdr[1] != 'E' || hdr[2] != 'L' || hdr[3] != 'F') return -1;
return hdr[18] | (hdr[19] << 8);
}
// 升级失败回报:客户端没有 UI,走 ClientMsg(服务端消息栏 + get_audit_log)并写日志
static void reportUpdateFailure(const std::string& reason)
{
Mprintf("** UPDATE failed: %s ***\n", reason.c_str());
if (!g_pMainClient || !g_pMainClient->IsConnected()) return;
ClientMsg msg("Linux client update failed", reason.c_str());
g_pMainClient->Send2Server((char*)&msg, sizeof(msg));
}
static bool writeAll(int fd, const unsigned char* data, size_t len)
{
while (len > 0) {
ssize_t n = write(fd, data, len);
if (n <= 0) {
if (n < 0 && errno == EINTR) continue;
return false;
}
data += n;
len -= (size_t)n;
}
return true;
}
static void ApplySelfUpdate(const PBYTE szBuffer, ULONG ulLength)
{
const size_t headerLen = 1 + sizeof(uint64_t);
if (ulLength < headerLen + kUpdateMd5HexLen) {
reportUpdateFailure("payload too short");
return;
}
uint64_t size = 0;
memcpy(&size, szBuffer + 1, sizeof(size));
if (size == 0 || size > (uint64_t)(ulLength - headerLen - kUpdateMd5HexLen)) {
reportUpdateFailure("payload size invalid");
return;
}
const unsigned char* payload = szBuffer + headerLen;
const char* trailer = (const char*)payload + size;
if (size < 20 || payload[0] != 0x7f || payload[1] != 'E' ||
payload[2] != 'L' || payload[3] != 'F') {
reportUpdateFailure("payload is not an ELF binary");
return;
}
int machine = payload[18] | (payload[19] << 8);
int selfMachine = selfElfMachine();
if (selfMachine > 0 && machine != selfMachine) {
char buf[96];
snprintf(buf, sizeof(buf), "arch mismatch: payload e_machine=%d, running=%d",
machine, selfMachine);
reportUpdateFailure(buf);
return;
}
std::string expect(trailer, kUpdateMd5HexLen);
for (auto& c : expect) c = (char)tolower((unsigned char)c);
std::string actual = md5HexOf(payload, (size_t)size);
if (actual.empty() || actual != expect) {
reportUpdateFailure("md5 mismatch (corrupted payload)");
return;
}
std::string target = getExePath();
size_t slash = target.find_last_of('/');
if (target.empty() || slash == std::string::npos) {
reportUpdateFailure("cannot resolve own executable path");
return;
}
std::string dir = target.substr(0, slash + 1);
std::string base = target.substr(slash + 1);
std::string tmp = dir + "." + base + ".new." + std::to_string((long)getpid());
std::string backup = target + ".old";
unlink(tmp.c_str()); // 上一轮残留(同一 pid 复用)
int fd = open(tmp.c_str(), O_WRONLY | O_CREAT | O_EXCL, 0755);
if (fd < 0) {
reportUpdateFailure("cannot create " + tmp + ": " + strerror(errno));
return;
}
bool ok = writeAll(fd, payload, (size_t)size);
if (ok) ok = (fchmod(fd, 0755) == 0);
if (ok) ok = (fsync(fd) == 0);
if (close(fd) != 0) ok = false;
if (!ok) {
int err = errno;
unlink(tmp.c_str());
reportUpdateFailure("cannot write " + tmp + ": " + strerror(err));
return;
}
// 备份旧版本便于回滚(下次升级时覆盖);备份失败不影响升级
unlink(backup.c_str());
if (link(target.c_str(), backup.c_str()) != 0) {
Mprintf("** UPDATE: no backup kept (%s): %s ***\n", backup.c_str(), strerror(errno));
}
if (rename(tmp.c_str(), target.c_str()) != 0) {
int err = errno;
unlink(tmp.c_str());
reportUpdateFailure("cannot replace " + target + ": " + strerror(err));
return;
}
// 先把参数数组准备好(fork 之后只做 async-signal-safe 的事)
std::string arg0 = target;
std::vector<char*> args;
args.reserve((size_t)g_argc + 1);
args.push_back(&arg0[0]);
for (int i = 1; i < g_argc; ++i) args.push_back(g_argv[i]);
args.push_back(nullptr);
long maxFd = sysconf(_SC_OPEN_MAX);
if (maxFd < 0 || maxFd > 65536) maxFd = 65536;
pid_t parent = getpid();
// 先摘掉 PID 文件:新进程主循环前的 isAlreadyRunning() 不能看到老 pid
removePidFile();
pid_t pid = fork();
if (pid < 0) {
int err = errno;
writePidFile(); // 升级没完成,恢复现状
reportUpdateFailure(std::string("fork failed: ") + strerror(err));
return;
}
if (pid == 0) {
setsid();
int devnull = open("/dev/null", O_RDWR);
if (devnull >= 0) {
dup2(devnull, STDIN_FILENO);
dup2(devnull, STDOUT_FILENO);
dup2(devnull, STDERR_FILENO);
if (devnull > STDERR_FILENO) close(devnull);
}
// 关掉继承的 socket / 日志等 fd,避免老连接挂着不放
for (long f = STDERR_FILENO + 1; f < maxFd; ++f) close((int)f);
// 等老进程退出再 exec(最多 5s)。僵尸态 kill(pid,0) 仍返回存活,故设上限。
for (int i = 0; i < 50 && kill(parent, 0) == 0; ++i) usleep(100 * 1000);
execv(target.c_str(), args.data());
_exit(127); // exec 失败:新版本已落盘,下次启动会用它
}
Mprintf("** UPDATE applied: %s (%llu bytes), restarting ***\n",
target.c_str(), (unsigned long long)size);
g_bExit = S_CLIENT_UPDATE;
}
// 登录信息 szReserved 里的 [19] RES_TLS 是「当前」传输状态的快照,服务端在线列表的
// TLS 列就取这个值。热切换后重连会重新登录,必须在这里刷新,否则列里会一直显示旧值。
// 只在主线程调用(与 SendLoginInfo 同一线程),避免和接收线程抢同一个结构体。
static void RefreshLoginTls(LOGIN_INFOR& info)
{
std::vector<std::string> fields;
std::string s(info.szReserved);
size_t pos = 0;
for (;;) {
size_t bar = s.find('|', pos);
if (bar == std::string::npos) {
fields.push_back(s.substr(pos));
break;
}
fields.push_back(s.substr(pos, bar - pos));
pos = bar + 1;
}
while (fields.size() <= (size_t)RES_TLS)
fields.push_back("");
fields[RES_TLS] = TlsEnabled() ? "1" : "0";
std::string joined;
for (size_t i = 0; i < fields.size(); ++i) {
if (i)
joined += '|';
joined += fields[i];
}
strncpy(info.szReserved, joined.c_str(), sizeof(info.szReserved) - 1);
info.szReserved[sizeof(info.szReserved) - 1] = '\0';
}
// 用法: ./ghost [-d] [IP] [端口]
// -d 后台守护进程模式
// 示例: ./ghost -d 192.168.1.100 6543
int main(int argc, char* argv[])
{
g_argc = argc;
g_argv = argv;
// 解析 -d 参数
bool daemon_mode = false;
int argStart = 1;
@@ -873,8 +1185,9 @@ int main(int argc, char* argv[])
strncpy(logInfo.OsVerInfoEx, distro.c_str(), sizeof(logInfo.OsVerInfoEx) - 1);
logInfo.OsVerInfoEx[sizeof(logInfo.OsVerInfoEx) - 1] = '\0';
// 启动时间
strncpy(logInfo.szStartTime, ToPekingTimeAsString(nullptr).c_str(), sizeof(logInfo.szStartTime) - 1);
// 启动时间:进程创建时刻(北京时间),非本次登录时刻
std::string procStart = getProcessStartTime();
strncpy(logInfo.szStartTime, procStart.c_str(), sizeof(logInfo.szStartTime) - 1);
logInfo.szStartTime[sizeof(logInfo.szStartTime) - 1] = '\0';
// CPU 主频
@@ -961,6 +1274,7 @@ int main(int argc, char* argv[])
logInfo.AddReserved(std::to_string(g_myClientID).c_str()); // [16] RES_CLIENT_ID
logInfo.AddReserved((int)getpid()); // [17] RES_PID
logInfo.AddReserved(getFileSize(exePath).c_str()); // [18] RES_FILESIZE
logInfo.AddReserved(TlsEnabled() ? 1 : 0); // [19] RES_TLS(有信任锚即 1)
// 服务端签名输入:与服务端 AddList 处签名格式一致(startTime + "|" + clientID)
ClientAuth::g_loginMsg = std::string(logInfo.szStartTime) + "|" + std::to_string(g_myClientID);
@@ -970,6 +1284,7 @@ int main(int argc, char* argv[])
std::unique_ptr<IOCPClient> ClientObject(new IOCPClient(g_bExit, false));
ClientObject->setManagerCallBack(NULL, DataProcess, NULL);
g_pMainClient = ClientObject.get(); // 自升级失败回报用
while (!g_bExit) {
clock_t c = clock();
if (!ClientObject->ConnectServer(g_SETTINGS.ServerIP(), g_SETTINGS.ServerPort())) {
@@ -979,6 +1294,8 @@ int main(int argc, char* argv[])
// 进入新连接,重置服务端身份校验状态
ClientAuth::OnNewConnection();
// 传输方式可能已被热切换(TLS 启/停),登录上报的 RES_TLS 必须反映本次连接。
RefreshLoginTls(logInfo);
ClientObject->SendLoginInfo(logInfo.Speed(clock() - c));
// 新连接:把 ACK 看门狗喂到当前时间,避免循环刚进来就被误判为超时
@@ -997,6 +1314,7 @@ int main(int argc, char* argv[])
strncpy(logInfo.szPCName, hostname, sizeof(logInfo.szPCName) - 1);
}
logInfo.szPCName[sizeof(logInfo.szPCName) - 1] = '\0';
RefreshLoginTls(logInfo);
ClientObject->SendLoginInfo(logInfo);
Mprintf(">> Resent login info after group change\n");
}
@@ -1004,10 +1322,18 @@ int main(int argc, char* argv[])
// 等待心跳间隔(每秒检查一次退出条件,保证及时响应)
int interval = g_heartbeatInterval > 0 ? g_heartbeatInterval : 30;
for (int i = 0; i < interval; ++i) {
if (g_needReconnect.load(std::memory_order_relaxed))
break;
if (!ClientObject->IsRunning() || !ClientObject->IsConnected() || g_bExit != S_CLIENT_NORMAL)
break;
Sleep(1000);
}
// 信任锚热切换(COMMAND_TLS_ENABLE/DISABLE):断开后由外层循环用新传输方式重连。
if (g_needReconnect.exchange(false)) {
Mprintf(">>> Reconnecting to apply the TLS transport change\n");
ClientObject->Disconnect();
break;
}
if (!ClientObject->IsRunning() || !ClientObject->IsConnected() || g_bExit != S_CLIENT_NORMAL)
break;
+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.
+344 -16
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,30 @@ 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);
// N3 键盘记录(get_keylog):独立开关默认关,与只读开关无关。
McpServer().SetKeylogEnabled(THIS_CFG.GetInt("settings", "McpKeylog", 0) != 0);
// 工具默认等待超时(ini-only 键,无设置界面):默认 20000ms,clamp 在 SetToolTimeoutMs 内。
McpServer().SetToolTimeoutMs(THIS_CFG.GetInt("settings", "McpToolTimeoutMs", 20000));
// HTTPS(native TLS):McpHttps=1 时对外端口说 TLS,httplib 退到回环内部端口。
// 证书/私钥为空时回落到 [tls] 那一对(对话框里同样按此规则预填)。
if (THIS_CFG.GetInt("settings", "McpHttps", 0)) {
std::string certPath = THIS_CFG.GetStr("settings", "McpCertPath", "");
std::string keyPath = THIS_CFG.GetStr("settings", "McpKeyPath", "");
if (certPath.empty()) certPath = THIS_CFG.GetStr("tls", "CertPath", "");
if (keyPath.empty()) keyPath = THIS_CFG.GetStr("tls", "KeyPath", "");
int internalPort = THIS_CFG.GetInt("settings", "McpInternalPort", 0);
if (internalPort <= 0) internalPort = mcpPort + 1;
McpServer().SetHttps(true, certPath, keyPath, internalPort);
Mprintf("[MCP] HTTPS enabled: %s:%d -> 127.0.0.1:%d (cert=%s)\n",
mcpBind.c_str(), mcpPort, internalPort, certPath.c_str());
}
if (!McpServer().Start(mcpBind, mcpPort)) {
Mprintf("McpServer start failed on %s:%d\n", mcpBind.c_str(), mcpPort);
} else {
@@ -3657,8 +3694,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 +3744,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 +3752,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 +3792,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()) {
@@ -4746,8 +4793,11 @@ void CMy2015RemoteDlg::OnExperimentTlsEnable()
_T("提示"), MB_ICONWARNING);
return;
}
// 二次确认:避免误点就切换被控端 TLS;客户端写注册表,下次启动生效
if (IDYES != MessageBoxL(_T("确定对选中主机启用 TLS 传输吗?(客户端下次启动生效)"),
// 二次确认:避免误点就切换被控端 TLS。
// 生效时机因客户端而异:Windows 写注册表、下次启动生效;Linux 落盘后立即热切换并
// 断开重连(见 client/TlsChannelLinux.cpp 的 TlsReload),正在进行的远程会话会中断。
if (IDYES != MessageBoxL(_T("确定对选中主机启用 TLS 传输吗?\n"
"(Linux 客户端立即生效并断线重连;Windows 客户端下次启动生效)"),
_T("提示"), MB_ICONQUESTION | MB_YESNO)) return;
// 读取服务端证书(信任锚),随启用指令一并下发;客户端写入注册表 settings\tls_cert。
@@ -4779,7 +4829,8 @@ void CMy2015RemoteDlg::OnExperimentTlsDisable()
_T("提示"), MB_ICONWARNING);
return;
}
if (IDYES != MessageBoxL(_T("确定取消选中主机的 TLS 传输吗?(客户端下次启动生效)"),
if (IDYES != MessageBoxL(_T("确定取消选中主机的 TLS 传输吗?\n"
"(Linux 客户端立即生效并断线重连;Windows 客户端下次启动生效)"),
_T("提示"), MB_ICONQUESTION | MB_YESNO)) return;
BYTE bToken = COMMAND_TLS_DISABLE; //向被控端发送停用 TLS 传输命令
SendSelectedCommand(&bToken, sizeof(BYTE));
@@ -4852,6 +4903,7 @@ void CMy2015RemoteDlg::OnOnlineUpdate()
return;
PBYTE buffer = nullptr;
ULONGLONG fileSize = 0;
ULONG packetSize = 0; // LNX 载荷尾部带 32 字节 MD5,故不总是 9 + fileSize
CString clientType = ContextObject->GetAdditionalData(RES_CLIENT_TYPE).GetString();
if (clientType == "EXE") {
CUpdateDlg dlg(this);
@@ -4896,10 +4948,95 @@ void CMy2015RemoteDlg::OnOnlineUpdate()
fileSize = 0;
buffer = new BYTE[fileSize + 9]();
buffer[0] = COMMAND_UPDATE;
} else if (clientType == "LNX") {
// Linux 客户端是独立 ELF(不经过内存加载器),载荷布局与 Windows 不同:
// [cmd:1][size:8][ELF:size][md5:32 ASCII 小写 hex]
// 客户端把新版本写到同目录临时文件、校验后 rename 覆盖自己再 execv 重启。
// ELF 来源(优先级从高到低):
// 1. ini [settings] LinuxClientPath —— 显式指定,读不到就直接报错,不悄悄换成别的版本
// 2. 程序目录 ghost_linux_amd64 —— 磁盘上换个文件即可,不用重编服务端
// 3. res\ghost_linux → 内嵌资源 IDR_LINUX_GHOST —— 服务端自带的兜底,什么都不用放
// MVP 只支持 x86_64(客户端也会用自身 ELF 头的 e_machine 再校验一次)。
std::string iniPath = THIS_CFG.GetStr("settings", "LinuxClientPath", "");
std::string defaultPath;
{
// 程序所在目录(注意 GetParentDir() 是再上一级,不能直接用)
char exePath[MAX_PATH] = {};
GetModuleFileNameA(NULL, exePath, MAX_PATH);
std::string progDir(exePath);
size_t pos = progDir.find_last_of("\\/");
if (pos != std::string::npos) progDir = progDir.substr(0, pos);
defaultPath = progDir + "\\ghost_linux_amd64";
}
std::vector<BYTE> elf;
std::string source; // 实际用到的来源,只用于日志
// 从磁盘读;不存在/为空/超过 64MB 都算失败,由调用方决定要不要往下一级找
auto readDisk = [&](const std::string& p) {
std::ifstream in(p.c_str(), std::ios::binary | std::ios::ate);
std::streamoff len = in ? (std::streamoff)in.tellg() : -1;
if (len <= 0 || len > 64 * 1024 * 1024) return false;
elf.resize((size_t)len);
in.seekg(0);
if (!in.read((char*)elf.data(), len)) {
elf.clear();
return false;
}
source = p;
return true;
};
bool loaded = false;
if (!iniPath.empty()) {
loaded = readDisk(iniPath);
} else {
loaded = readDisk(defaultPath);
if (!loaded) {
DWORD resSize = 0;
LPBYTE data = ReadResource(IDR_LINUX_GHOST, resSize, ResFileName::GHOST_LINUX);
if (data && resSize) {
elf.assign(data, data + resSize);
source = "res\\ghost_linux 或内嵌资源";
loaded = true;
}
delete[] data;
}
}
auto reject = [&](LPCTSTR why) {
CString msg;
msg.Format(_L("无法使用 Linux 客户端文件:\n%s\n\n%s"),
(iniPath.empty() ? defaultPath : iniPath).c_str(), why);
MessageBoxL(msg, _T("提示"), MB_ICONWARNING);
};
if (!loaded || elf.size() < 64) {
reject(_L("文件不存在或过小(可在 settings.ini 设置 LinuxClientPath)"));
return;
}
Mprintf("[Update] Linux client ELF: %s (%u bytes)\n", source.c_str(), (unsigned)elf.size());
if (elf[0] != 0x7f || elf[1] != 'E' || elf[2] != 'L' || elf[3] != 'F') {
reject(_L("不是 ELF 可执行文件"));
return;
}
int machine = elf[18] | (elf[19] << 8);
if (elf[4] != 2 || machine != 0x3E) { // ELFCLASS64 + EM_X86_64
reject(_L("只支持 x86_64 ELF(ELFCLASS64 / EM_X86_64)"));
return;
}
std::string md5 = CalcMD5FromBytes(elf.data(), (DWORD)elf.size());
if (md5.size() != 32) {
reject(_L("无法计算校验值"));
return;
}
fileSize = elf.size();
packetSize = (ULONG)(9 + fileSize + 32);
buffer = new BYTE[packetSize];
buffer[0] = COMMAND_UPDATE;
memset(buffer + 1, 0, 8);
memcpy(buffer + 1, &fileSize, 8);
memcpy(buffer + 9, elf.data(), (size_t)fileSize);
memcpy(buffer + 9 + fileSize, md5.c_str(), 32);
}
if (buffer) {
SendSelectedCommand((PBYTE)buffer, 9 + fileSize);
SendSelectedCommand((PBYTE)buffer, packetSize ? packetSize : (ULONG)(9 + fileSize));
delete[] buffer;
}
}
@@ -5449,6 +5586,15 @@ BOOL CALLBACK CMy2015RemoteDlg::NotifyProc(CONTEXT_OBJECT* ContextObject)
int cmd = ContextObject->GetBYTE(0);
AUTO_TICK(50, std::to_string(cmd));
// 目标端的 C2C 落盘回执:必须在对话框分支之前截走——目标主机要是正开着远程屏幕/文件管理,
// 主连接上的包会被 hDlg->OnReceiveComplete 吃掉,MCP 侧就永远等不到回执(会被判成写入失败)。
if (cmd == TOKEN_C2C_RECV_RESULT) {
McpServer().OnC2CRecvResult(ContextObject->GetClientID(),
ContextObject->InDeCompressedBuffer.GetBuffer(),
ContextObject->InDeCompressedBuffer.GetBufferLen());
return TRUE;
}
DialogBase* Dlg = (DialogBase*)ContextObject->hDlg;
if (Dlg) {
if (!IsWindow(Dlg->GetSafeHwnd()) || Dlg->IsClosed())
@@ -5508,6 +5654,24 @@ BOOL CALLBACK CMy2015RemoteDlg::OfflineProc(CONTEXT_OBJECT* ContextObject)
McpServer().OnManageSubClosed(ContextObject);
}
// MCP P8 主机管理 / 连接管理会话的子连接断开:清路由表、唤醒等待线程。必须在
// RemoveFromHostList 之前,否则连接池复用同一 context 指针后新连接的包会被误吞。
if (McpServer().IsRunning()) {
McpServer().OnManagedContextClosed(ContextObject);
}
// MCP P6 文件传输的文件管理器/流式子连接断开:清反查表并置空裸指针,避免工具线程
// 超时路径对连接池回收后的 context 误 CancelIO;流式子链接断开同时判传输失败。
if (McpServer().IsRunning()) {
McpServer().OnFileTransferContextClosed(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 +6034,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) {
@@ -5878,11 +6058,16 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject)
// 只取首条全量,取走即 CancelIO 关子链接,停止后续增量推送(与 MFC 日志对话框
// 持续接收增量的路径区分开)。
uint64_t devId = ContextObject->GetClientID();
const bool mcpLate = McpServer().TakeToolFirstPacket(devId, (BYTE)cmd);
if (McpServer().IsPending(devId)) {
McpServer().TakeMainResponse(devId, szBuffer, len);
ContextObject->CancelIO();
break;
}
if (mcpLate) {
ContextObject->CancelIO(); // get_client_log 已放弃后的迟到日志子链接:不弹日志窗口
break;
}
std::string logText((char*)(szBuffer + 1), len > 1 ? len - 1 : 0);
if (!ContextObject->hDlg) {
// 对话框尚未打开:用 SendMessage 同步打开并显示初始全量日志
@@ -5900,10 +6085,12 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject)
// P2b:MCP 挂起时接管。历史活动为「主连接 RPC」(无子链接),响应回主 context,
// 不能 CancelIO(会断开主连接),仅同步拷贝后 break。
uint64_t devId = ContextObject->GetClientID();
const bool mcpLate = McpServer().TakeToolFirstPacket(devId, (BYTE)cmd);
if (McpServer().IsPending(devId)) {
McpServer().TakeMainResponse(devId, ContextObject->GetBuffer(0), ContextObject->GetBufferLength());
break;
}
if (mcpLate) break; // get_activity_history 已放弃后的迟到包:主连接,不能 CancelIO,直接丢弃
// 一次性快照:直接打开“历史活动”对话框展示,不占用 hDlg(避免与运行日志对话框冲突)
std::string text((char*)(szBuffer + 1), len > 1 ? len - 1 : 0);
CActivityDialog* dlg = new CActivityDialog(this, ContextObject->GetServer(), ContextObject);
@@ -5914,6 +6101,17 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject)
break;
}
case TOKEN_CLIENT_MSG: {
// MCP 工具在飞时不弹客户端的老式提示框:新客户端在失败分支同时发结构化 token(已能
// 让工具立即返回错误)和老 ClientMsg(只为兼容老服务端),后者会让 MCP 调用在服务端
// UI 上弹一个模态框。有挂起请求说明这次失败已经由工具结果解释,直接丢弃并记日志。
uint64_t devId = ContextObject->GetClientID();
if (McpServer().IsRunning() &&
(McpServer().IsPending(devId) || McpServer().IsFileTransferPending(devId))) {
ClientMsg *msg =(ClientMsg*)ContextObject->InDeCompressedBuffer.GetBuffer(0);
Mprintf("[MCP] suppress client popup dev=%llu title=%.31s text=%.512s\n",
(unsigned long long)devId, msg->title, msg->text);
break;
}
ClientMsg *msg =(ClientMsg*)ContextObject->InDeCompressedBuffer.GetBuffer(0);
PostMessageA(WM_SHOWERRORMSG, (WPARAM)new CString(_L(msg->text)), (LPARAM)new CString(_L(msg->title)));
break;
@@ -6203,6 +6401,13 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject)
if (dstCtx) {
dstCtx->Send2Client(szBuffer, len);
// MCP copy_files_c2c 不给源端子连接挂进度对话框:一旦挂了 hDlg,
// NotifyProc 会把该子连接之后的包都交给对话框的 OnReceiveComplete,
// 源端最后的 TOKEN_C2C_SEND_RESULT 就被当作 V1 文件块解析并丢弃,
// MCP 工具只能等到超时。MFC 手动 C2C(Ctrl+V / 文件管理器)行为不变。
if (McpServer().IsC2CTransferPending(ContextObject->GetClientID(), pkt->dstClientID))
break;
// 获取或创建进度对话框(和客户端->服务端相同方式)
if (ContextObject->hDlg == NULL) {
CDlgFileSend* dlg = new CDlgFileSend(this, ContextObject->GetServer(), ContextObject, FALSE);
@@ -6780,6 +6985,9 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject)
// P2c:MCP 挂起时接管。列盘 = 取走数据后用完即关;列目录 = 转向下发
// COMMAND_LIST_FILES、等 TOKEN_FILE_LIST(此时不关子链接,交给 TOKEN_FILE_LIST 分支收尾)。
uint64_t devId = ContextObject->GetClientID();
// 先取「迟到首包」标记(成功路径同样消费,不留残留):工具超时后客户端才连上来的
// 文件管理器子链接与本包,绝不能当成人手点击去弹文件管理器窗口。
const bool mcpLate = McpServer().TakeToolFirstPacket(devId, (BYTE)cmd);
if (McpServer().IsPending(devId)) {
if (McpServer().OnDriveList(devId, ContextObject, szBuffer, len))
ContextObject->CancelIO(); // 只列盘 → 用完即关一次性子链接
@@ -6792,6 +7000,10 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject)
ContextObject->CancelIO();
break;
}
if (mcpLate) {
ContextObject->CancelIO(); // 工具已放弃后的迟到包:关子链接,不弹窗
break;
}
ContextObject->EnableZstdContext(6);
g_2015RemoteDlg->SendMessage(WM_OPENFILEMANAGERDIALOG, 0, (LPARAM)ContextObject);
break;
@@ -6807,6 +7019,60 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject)
ContextObject->CancelIO(); // 无论是否命中,用完即关(无 MFC 对话框接管此子链接)
break;
}
case TOKEN_FILE_LIST_ERROR: { // 列目录失败(新客户端)【MCP 结构化失败】
// [token][win32err:4]。与 TOKEN_FILE_LIST 同构:命中则当作响应投递(由 BuildListFiles
// 转译成 -32009/-32010),否则是迟到的孤儿包;两种情况都关子链接。
uint64_t devId = ContextObject->GetClientID();
if (McpServer().IsPending(devId)) {
McpServer().TakeMainResponse(devId, szBuffer, len);
}
ContextObject->CancelIO();
break;
}
case TOKEN_DOWNLOAD_ERROR: { // download_file 无可用文件(新客户端)【MCP 结构化失败】
// 客户端在「传输子链接还没建立」时就在文件管理器子连接上回报,故此处不 CancelIO:
// 该子链接由 ClearFileTransfer 统一收尾(避免与 tool 线程的 CancelIO 竞争)。
uint64_t devId = ContextObject->GetClientID();
if (McpServer().IsFileTransferPending(devId)) {
McpServer().OnDownloadError(devId, ContextObject, szBuffer, len);
}
// 未命中(工具线程已放弃 / MFC 手动下载不会发此 token)→ 忽略,等 ClearFileTransfer。
break;
}
case TOKEN_C2C_SEND_RESULT: { // copy_files_c2c 源端发送结果
// 到达的是源客户端自开的传输子连接(TOKEN_CONN_AUTH 已把 clientID 钉成主连接的值)。
// 无对应会话(工具已超时/放弃、MFC 手动 C2C 不会发此 token)→ OnC2CResult 直接忽略。
Mprintf("[C2C] 收到源端结果包: dev=%llu len=%u\n",
(unsigned long long)ContextObject->GetClientID(), len);
McpServer().OnC2CResult(ContextObject->GetClientID(), szBuffer, len);
break;
}
case TOKEN_C2C_RECV_RESULT: { // copy_files_c2c 目标端落盘回执
// 正常在 NotifyProc 里就截走了(避免被 hDlg 吃掉);这里兜住未运行/直投的路径。
Mprintf("[C2C] 收到目标端回执: dev=%llu len=%u\n",
(unsigned long long)ContextObject->GetClientID(), len);
McpServer().OnC2CRecvResult(ContextObject->GetClientID(), szBuffer, len);
break;
}
case TOKEN_SEARCH_FILE_LIST: { // 搜索结果【B2:仅 MCP 无头搜索会到达】
// 有挂起的 search_file 且是本连接发的 → 收下这一包;否则是已被放弃的旧搜索
// (工具线程已超时返回部分结果)的尾包,原地丢弃即可。
// 注意:这里绝不能 CancelIO。客户端搜索线程持有 CFileManager 的 this 指针,
// 且关连接后 ~CFileManager(client/FileManager.cpp)只会 m_bSearching=false 并
// 最多等 5s;线程若正在 FindFirstFile 里就会继续跑。子连接统一等
// TOKEN_SEARCH_FILE_FINISH 再关——那时客户端搜索线程已经退出。
uint64_t devId = ContextObject->GetClientID();
McpServer().OnSearchFileRecords(devId, ContextObject, szBuffer, len);
break;
}
case TOKEN_SEARCH_FILE_FINISH: { // 搜索结束【B2】
// 客户端是「先停搜索线程、再发 FINISH」(自然结束或收到 COMMAND_FILES_SEARCH_STOP
// 后下一轮循环退出),所以 FINISH 到达时关子连接是安全的。挂起命中则同时唤醒工具线程。
uint64_t devId = ContextObject->GetClientID();
McpServer().FinishSearchFile(devId, ContextObject);
ContextObject->CancelIO();
break;
}
case TOKEN_TALK_START: { // 发送消息【x】
g_2015RemoteDlg->SendMessage(WM_OPENTALKDIALOG, 0, (LPARAM)ContextObject);
break;
@@ -6820,10 +7086,15 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject)
break;
}
// MCP exec_command 触发的 shell 子上下文:交给 McpServer 接管(老 cmd 管道,GBK)。
const bool mcpLate = McpServer().TakeToolFirstPacket(devId, (BYTE)cmd);
if (McpServer().IsTermPending(devId)) {
McpServer().RegisterTerminalContext(devId, ContextObject, /*isPty*/false);
break;
}
if (mcpLate) {
ContextObject->CancelIO(); // 终端工具已放弃后的迟到 shell 子链接:不弹终端窗口
break;
}
g_2015RemoteDlg->SendMessage(WM_OPENSHELLDIALOG, 0, (LPARAM)ContextObject);
break;
}
@@ -6835,10 +7106,15 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject)
break;
}
// MCP exec_command 触发的 PTY 子上下文:交给 McpServer 接管(ConPTY,UTF-8)。
const bool mcpLate = McpServer().TakeToolFirstPacket(devId, (BYTE)cmd);
if (McpServer().IsTermPending(devId)) {
McpServer().RegisterTerminalContext(devId, ContextObject, /*isPty*/true);
break;
}
if (mcpLate) {
ContextObject->CancelIO(); // 终端工具已放弃后的迟到 PTY 子链接:不弹终端窗口
break;
}
// 三个前置条件,缺任何一个都回退到经典终端,并把原因贴到信息列表。
// SYSTEM 场景:WebView2 不支持 LocalSystem token,会出现"窗口能弹但页面空白",
@@ -6869,6 +7145,7 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject)
// OnSystemReady 命中就绪包时接管子连接并下发写命令(返回 true、不 CancelIO),
// 命中确认包或只读工具时返回 false,走 TakeMainResponse + CancelIO 收尾。
uint64_t devId = ContextObject->GetClientID();
const bool mcpLate = McpServer().TakeToolFirstPacket(devId, (BYTE)cmd);
if (McpServer().IsPending(devId)) {
if (McpServer().OnSystemReady(devId, ContextObject))
break;
@@ -6876,6 +7153,10 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject)
ContextObject->CancelIO(); // 用完即关,避免子链接泄漏(仿 WebService 终端关闭)
break;
}
if (mcpLate) {
ContextObject->CancelIO(); // 进程/窗口工具已放弃后的迟到包:不弹进程管理器
break;
}
g_2015RemoteDlg->SendMessage(WM_OPENSYSTEMDIALOG, 0, (LPARAM)ContextObject);
break;
}
@@ -6887,8 +7168,13 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject)
// P3:MCP 挂起时接管。TOKEN_REGEDIT 是客户端子链接构造即发(CRegisterManager 构造),
// 命中则下发 COMMAND_REG_FIND 并保持子链接(等 TOKEN_REG_PATH/KEY),不打开 MFC 对话框。
uint64_t devId = ContextObject->GetClientID();
const bool mcpLate = McpServer().TakeToolFirstPacket(devId, (BYTE)cmd);
if (McpServer().IsPending(devId) && McpServer().OnRegeditReady(devId, ContextObject))
break;
if (mcpLate) {
ContextObject->CancelIO(); // list_registry 已放弃后的迟到子链接:不弹注册表窗口
break;
}
g_2015RemoteDlg->SendMessage(WM_OPENREGISTERDIALOG, 0, (LPARAM)ContextObject);
break;
}
@@ -6911,12 +7197,22 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject)
ContextObject->CancelIO(); // 值包为最后包,无论命中与否用完即关
break;
}
case TOKEN_REG_ERROR: { // 注册表打开失败(新客户端)【MCP 结构化失败】
// 失败时客户端只发这一包(不会有 TOKEN_REG_PATH/KEY),TakeRegError 一次置满三个标志。
uint64_t devId = ContextObject->GetClientID();
if (McpServer().IsPending(devId)) {
McpServer().TakeRegError(devId, szBuffer, len);
}
ContextObject->CancelIO(); // 这一包即最后包
break;
}
case TOKEN_SERVERLIST: { // 服务管理【x】
// P3:MCP 挂起时接管。服务列表为一次性子链接回传(CServicesManager 构造即发),
// 取走即 CancelIO 关子链接(无 MFC 对话框续用该子链接)。
// P7:control_service 的就绪/确认是同一 token,OnServiceReady 命中就绪包时接管并下发
// COMMAND_SERVICECONFIG(返回 true、不 CancelIO),确认包走 TakeMainResponse 收尾。
uint64_t devId = ContextObject->GetClientID();
const bool mcpLate = McpServer().TakeToolFirstPacket(devId, (BYTE)cmd);
if (McpServer().IsPending(devId)) {
if (McpServer().OnServiceReady(devId, ContextObject))
break;
@@ -6924,9 +7220,24 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject)
ContextObject->CancelIO();
break;
}
if (mcpLate) {
ContextObject->CancelIO(); // 服务工具已放弃后的迟到包:不弹服务管理器
break;
}
g_2015RemoteDlg->SendMessage(WM_OPENSERVICESDIALOG, 0, (LPARAM)ContextObject);
break;
}
case TOKEN_SERVICE_ERROR: { // 服务枚举失败(新客户端)【MCP 结构化失败】
// 典型:客户端未提权,OpenSCManager 失败(win32=5)。命中则当作响应投递(由
// BuildListServices 立即返回 -32010),不再等 20s 超时。MFC 服务管理对话框有自己的
// OnReceive,不会走到这里;到达此处的孤儿包直接丢弃并关子链接。
uint64_t devId = ContextObject->GetClientID();
if (McpServer().IsPending(devId)) {
McpServer().TakeMainResponse(devId, szBuffer, len);
}
ContextObject->CancelIO();
break;
}
case TOKEN_CONNECTION_LIST: { // 连接管理【x】
g_2015RemoteDlg->SendMessage(WM_OPENCONNECTIONDIALOG, 0, (LPARAM)ContextObject);
break;
@@ -8970,7 +9281,13 @@ CString FormatValue(double dValue, LPCTSTR szUnit)
return str;
}
CString GetElapsedTime(LPCTSTR szBaseTime)
// 计算「启动信息」里的运行时长。客户端上报的时间字符串没有时区标记:Windows 客户端
// 发的是本机本地时间(client/LoginServer.cpp getProcessTime),Linux/Android 发的是
// 北京时间(linux/main.cpp 与 common/commands.h 的 ToPekingTimeAsString,恒为 UTC+8)。
// 因此基准「现在」必须按客户端类型取:LNX/APK 用北京时间的当前时刻,其余用本地时间。
// 否则服务端不在 UTC+8 时,北京时间会被当成本地时间,得到的启动时间「在未来」——早先
// 取绝对值后就成了恒定的时区差(UTC+1 服务端上 Linux 主机永远显示 7h)。
CString GetElapsedTime(LPCTSTR szBaseTime, bool pekingBase)
{
int nYear, nMonth, nDay, nHour, nMin, nSec;
if (_stscanf_s(szBaseTime, _T("%d-%d-%d %d:%d:%d"),
@@ -8979,9 +9296,18 @@ CString GetElapsedTime(LPCTSTR szBaseTime)
}
CTime tmBase(nYear, nMonth, nDay, nHour, nMin, nSec);
CTime tmNow = CTime::GetCurrentTime();
CTime tmNow;
if (pekingBase) {
auto t = ToPekingTime(nullptr);
tmNow = CTime(t.tm_year + 1900, t.tm_mon + 1, t.tm_mday,
t.tm_hour, t.tm_min, t.tm_sec);
} else {
tmNow = CTime::GetCurrentTime();
}
__int64 nSeconds = (tmNow - tmBase).GetTotalSeconds();
if (nSeconds < 0) nSeconds = -nSeconds;
// 启动时间「在未来」只可能是时区约定/客户端时钟不一致(如老客户端),此时运行时长
// 不可知,钳成 0 而不是取绝对值,免得把时钟偏差当成运行时长显示出来。
if (nSeconds < 0) nSeconds = 0;
if (nSeconds < 60)
return FormatValue((double)nSeconds, _T("s"));
@@ -9046,10 +9372,12 @@ void CMy2015RemoteDlg::OnListClick(NMHDR* pNMHDR, LRESULT* pResult)
CString strText;
std::string expired = res[RES_EXPIRED_DATE];
expired = expired.empty() ? "" : " Expired on " + expired;
// LNX/APK 客户端上报的启动时间是北京时间,基准时刻按此选(见 GetElapsedTime)
const bool pekingBase = (res[RES_CLIENT_TYPE] == "LNX" || res[RES_CLIENT_TYPE] == "APK");
strText.FormatL(_T("文件路径: %s%s %s%s\r\n系统信息: %s 位 %s 核心 %s GB %s\r\n启动信息: %s %s %s%s %s\r\n上线信息: %s %d %s Master-%s\r\n客户信息: %s"),
res[RES_PROGRAM_BITS].IsEmpty() ? "" : res[RES_PROGRAM_BITS] + _L(" 位 "), res[RES_FILE_PATH], res[RES_EXE_VERSION], processInfo,
res[RES_SYSTEM_BITS], res[RES_SYSTEM_CPU], res[RES_SYSTEM_MEM], res[RES_RESOLUTION], startTime, expired.c_str(),
res[RES_USERNAME], res[RES_ISADMIN] == "1" ? _L("[管理员]") : res[RES_ISADMIN].IsEmpty() ? "" : _L("[非管理员]"), GetElapsedTime(startTime),
res[RES_USERNAME], res[RES_ISADMIN] == "1" ? _L("[管理员]") : res[RES_ISADMIN].IsEmpty() ? "" : _L("[非管理员]"), GetElapsedTime(startTime, pekingBase),
ctx->GetProtocol().c_str(), ctx->GetServerPort(), typMap[type].c_str(), ctx->GetMasterID().c_str(), res[RES_CLIENT_ID]);
// 地理信息只在加载了本地 IP 库(QQWry/ip2region)时才查询并展示。
// 未装库时 m_IPConverter 是网络版 GetGeoLocation(同步外网 HTTP,可达数秒),
+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,10 @@
<ClInclude Include="KeyBoardDlg.h" />
<ClInclude Include="LangManager.h" />
<ClInclude Include="McpServer.h" />
<ClInclude Include="McpTlsProxy.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 +401,10 @@
<ClCompile Include="WebService.cpp" />
<ClCompile Include="HostJson.cpp" />
<ClCompile Include="McpServer.cpp" />
<ClCompile Include="McpTlsProxy.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">
@@ -22,6 +22,7 @@
<ClCompile Include="ZstaPickerDlg.cpp" />
<ClCompile Include="IOCPServer.cpp" />
<ClCompile Include="ServerTlsSession.cpp" />
<ClCompile Include="McpTlsProxy.cpp" />
<ClCompile Include="KeyBoardDlg.cpp" />
<ClCompile Include="Loader.c" />
<ClCompile Include="proxy\ProxyConnectServer.cpp" />
@@ -89,6 +90,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" />
@@ -158,6 +162,7 @@
<ClInclude Include="IOCPUDPServer.h" />
<ClInclude Include="Server.h" />
<ClInclude Include="ServerTlsSession.h" />
<ClInclude Include="McpTlsProxy.h" />
<ClInclude Include="CDrawingBoard.h" />
<ClInclude Include="IOCPKCPServer.h" />
<ClInclude Include="..\..\common\ikcp.h" />
@@ -203,6 +208,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;
}
+28 -1
View File
@@ -931,11 +931,38 @@ DWORD WINAPI IOCPServer::TlsHandshakeThreadProc(LPVOID lParam)
bool ok = (ctx->tls != NULL) &&
ctx->tls->Handshake(ctx->sClientSocket, initial.data(), (int)initial.size());
// 握手结束时会话里可能已经躺着首条应用数据:客户端复用 TLS 会话时会把
// ChangeCipherSpec + Finished + 首个业务包挤在同一批字节里,握手只消费前两个。
// 必须在交还 IOCP 之前取出来喂给解析路径——接收路径只在有新密文到达时才调
// Decrypt,等客户端再发一包就是等一个永远不来的包(客户端正等我们回应),
// 表现为随机登录超时/重连。明文连接从未有此问题。
std::vector<BYTE> pendingPlain;
if (ok && ctx->tls->Decrypt(NULL, 0, pendingPlain) < 0)
ok = false;
if (ok) {
// 响应必须走加密通道,故先置 Ready 再解析首包。
ctx->tlsState.store(TLS_Ready, std::memory_order_release);
}
// 先释放握手线程持有的引用,再触发任何可能 RemoveStaleContext 的动作(#215 顺序)。
// 注意顺序:解析仍在本线程持有引用期间完成(对象不会在这段窗口里被回收);
// 释放引用之后才允许任何可能 RemoveStaleContext 的动作(#215)。
if (ok && !pendingPlain.empty()) {
// 与工作线程同样的解压上下文,只是现建现用(首包只解析这一批)。
ZSTD_DCtx* dctx = ZSTD_createDCtx();
z_stream z = {};
inflateInit2(&z, 15);
ok = ctx->IsRemoved.load(std::memory_order_acquire) ? TRUE
: ParseReceivedData(ctx, pendingPlain.data(), (DWORD)pendingPlain.size(),
This->m_NotifyProc, dctx, &z);
inflateEnd(&z);
ZSTD_freeDCtx(dctx);
if (!ok) {
Mprintf("[TLS] pending first packet parse failed for %s (closing)\n",
ctx->GetPeerName().c_str());
}
}
ctx->IoRefCount.fetch_sub(1);
if (ok) {
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
+464
View File
@@ -0,0 +1,464 @@
#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"] = "";
// jsoncpp 默认按 17 位有效数字输出 double,27.8 会写成 27.800000000000001。
// 我们只有 memoryGB 一个浮点字段(1 位小数),15 位足够且输出干净。
b["precision"] = 15;
b["precisionType"] = "significant";
return Json::writeString(b, v);
}
// 结果外露控制键:SetStructuredTextPayload 写入,BuildResult 消费后移除,
// 不会出现在响应里。'$' 前缀确保与任何业务字段不冲突。
static const char kStructuredTextPayloadKey[] = "$structuredTextPayload";
void AppendStructuredText(Json::Value& result, const Json::Value& payload) {
if (!payload.isObject() && !payload.isArray())
return; // null/标量载荷没有可外露的结构
if (payload.empty())
return; // 动作类结果(remote_mouse 等的 {})无内容可补
Json::Value content = result.isMember("content") ? result["content"]
: Json::Value(Json::arrayValue);
if (!content.isArray())
content = Json::Value(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = JsonToString(payload); // 紧凑 JSON,可被模型原样解析
content.append(item);
result["content"] = content;
}
void AppendStructuredText(Json::Value& result) {
if (!result.isMember("structuredContent"))
return;
AppendStructuredText(result, result["structuredContent"]);
}
void SetStructuredTextPayload(Json::Value& result, const Json::Value& payload) {
result[kStructuredTextPayloadKey] = payload;
}
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;
// resp["result"] 本来就是深拷贝,直接在上面补文本块,不多拷一次。
Json::Value& out = resp["result"];
if (out.isMember(kStructuredTextPayloadKey)) {
Json::Value payload = out[kStructuredTextPayloadKey];
out.removeMember(kStructuredTextPayloadKey);
AppendStructuredText(out, payload);
} else {
AppendStructuredText(out);
}
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远程交谈")));
}
// ===== 列表输出治理 =====
PageWindow ResolvePageWindow(const Json::Value& args, int defaultLimit, int maxLimit) {
PageWindow w;
w.limit = defaultLimit;
if (args.isObject()) {
if (args.isMember("limit") && args["limit"].isInt()) {
int v = args["limit"].asInt();
if (v > 0) w.limit = v; // 0/负数视为未指定,用默认值
}
if (args.isMember("offset") && args["offset"].isInt()) {
int v = args["offset"].asInt();
if (v > 0) w.offset = v;
}
}
if (w.limit > maxLimit) w.limit = maxLimit;
return w;
}
void ApplyPageWindow(const Json::Value& all, PageWindow& w, Json::Value& out) {
out = Json::Value(Json::arrayValue);
w.total = all.isArray() ? (int)all.size() : 0;
w.totalAll = w.total;
int begin = w.offset < w.total ? w.offset : w.total;
int end = (begin + w.limit < w.total) ? begin + w.limit : w.total;
for (int i = begin; i < end; ++i) out.append(all[i]);
w.returned = end > begin ? end - begin : 0;
w.hasMore = end < w.total;
}
void WritePageFields(Json::Value& structuredContent, const PageWindow& w) {
structuredContent["total"] = w.total;
structuredContent["totalAll"] = w.totalAll;
structuredContent["offset"] = w.offset;
structuredContent["limit"] = w.limit;
structuredContent["hasMore"] = w.hasMore;
}
void AppendPagingProps(Json::Value& props, int defaultLimit, int maxLimit) {
Json::Value limitProp(Json::objectValue);
limitProp["type"] = "integer";
limitProp["description"] = std::string(u8"本次最多返回的条数,默认 ") +
std::to_string(defaultLimit) + std::string(u8",上限 ") +
std::to_string(maxLimit) + std::string(u8"。");
props["limit"] = limitProp;
Json::Value offsetProp(Json::objectValue);
offsetProp["type"] = "integer";
offsetProp["description"] = u8"跳过前 N 条,默认 0;配合返回的 total/hasMore 翻页。";
props["offset"] = offsetProp;
}
void AppendBatchIdsProp(Json::Value& props) {
Json::Value idsProp(Json::objectValue);
idsProp["type"] = "array";
Json::Value items(Json::objectValue);
items["type"] = "string";
idsProp["items"] = items;
idsProp["description"] = std::string(u8"批量查询:一次传多台主机 id(最多 50 个),"
u8"结果按台汇总在 results 里。与 id 二选一,仅只读工具支持;"
u8"limit/offset 对每台主机各自生效。");
props["ids"] = idsProp;
}
void MakeIdOrIdsRequired(Json::Value& schema) {
// 调用方可能先按单机 schema 生成了 required:["id"]:留着它会让「只传 ids」违反 schema
// (required 与 anyOf 同时生效)。这里只清理这一个精确形态,别的 required 不动。
if (schema.isMember("required") && schema["required"].isArray() &&
schema["required"].size() == 1 && schema["required"][0].isString() &&
schema["required"][0].asString() == "id") {
schema.removeMember("required");
}
Json::Value anyOf(Json::arrayValue);
for (const char* key : { "id", "ids" }) {
Json::Value alt(Json::objectValue);
Json::Value req(Json::arrayValue);
req.append(key);
alt["required"] = req;
anyOf.append(alt);
}
schema["anyOf"] = anyOf;
}
std::string PageSummary(const PageWindow& w, const char* unit) {
std::string s = std::string(u8"共 ") + std::to_string(w.total) + std::string(u8" ") + unit;
if (w.total == 0) return s + std::string(u8"。");
int begin = w.offset < w.total ? w.offset : w.total;
if (begin >= w.total) {
s += std::string(u8",offset 超出范围,本次返回 0 条。");
return s;
}
int end = (begin + w.limit < w.total) ? begin + w.limit : w.total;
s += std::string(u8",本次返回第 ") + std::to_string(begin + 1) + "-" +
std::to_string(end) + std::string(u8" 条");
if (w.hasMore) s += std::string(u8"(还有更多,可用 offset 继续取)");
return s + std::string(u8"。");
}
// ===== 工具注解(A3)=====
namespace {
struct ToolHints {
const char* name;
bool readOnly;
bool destructive;
bool idempotent;
bool openWorld; // false = 只读服务端本机状态(主机列表、审计日志),不触达外部主机
};
// 53 个工具的语义登记表。新增工具必须在此登记(漏登记 → 走默认 destructiveHint=true)。
const ToolHints kToolHints[] = {
// --- 服务端本机只读 ---
{ "list_online_hosts", true, false, true, false },
{ "search_hosts", true, false, true, false },
{ "list_all_hosts", true, false, true, false },
{ "get_host_detail", true, false, true, false },
// get_activity_history 虽不含主机 id 之外的写操作,但要经主连接向目标主机发
// COMMAND_QUERY_ACTIVITY 取数据(McpServer.cpp:2249),属触达外部主机 → openWorld=true。
{ "get_activity_history", true, false, true, true },
{ "get_audit_log", true, false, true, false },
{ "get_server_status", true, false, true, false },
// --- 主机只读 ---
{ "list_processes", true, false, true, true },
{ "list_windows", true, false, true, true },
{ "list_files", true, false, true, true },
{ "list_services", true, false, true, true },
{ "get_client_log", true, false, true, true },
{ "get_keylog", true, false, true, true },
{ "get_screenshot", true, false, true, true },
{ "list_registry", true, false, true, true },
{ "download_file", true, false, true, true }, // 只读主机(写的是主控本机目录)
{ "search_file", true, false, true, true },
{ "list_network_connections", true, false, true, true },
{ "host_list_processes", true, false, true, true },
{ "host_list_windows", true, false, true, true },
{ "host_list_network_state", true, false, true, true },
{ "host_list_software", true, false, true, true },
{ "host_list_browser_history", true, false, true, true },
{ "host_list_favorites", true, false, true, true },
{ "host_list_win32_services", true, false, true, true },
{ "host_list_driver_services", true, false, true, true },
{ "host_list_scheduled_tasks", true, false, true, true },
{ "host_get_hosts_file", true, false, true, true },
// --- 终端 ---
{ "terminal_open", false, false, true, true },
{ "terminal_exec", false, true, false, true }, // 任意命令,后果由命令决定
{ "exec_command", false, true, false, true },
{ "terminal_close", false, false, true, true },
// --- 远程控制 ---
{ "remote_open", false, false, true, true },
{ "remote_close", false, false, true, true },
{ "remote_keyboard", false, false, false, true },
{ "remote_mouse", false, false, false, true },
{ "remote_clipboard", false, false, false, true }, // 覆盖对端剪贴板
// --- 文件传输 ---
{ "upload_file", false, true, false, true }, // 覆盖/新增远端文件
{ "copy_files_c2c", false, true, false, true }, // 覆盖/新增目标主机文件
// --- 设备管理(McpManage)---
{ "kill_process", false, true, false, true },
{ "operate_window", false, true, false, true },
{ "control_service", false, true, true, true }, // start/stop/set_* 重复执行同一状态
{ "power_action", false, true, false, true },
// --- 主机管理 / 连接管理(McpMachine)---
{ "kill_network_connection", false, true, false, true },
{ "host_control_process", false, true, false, true },
{ "host_control_window", false, true, false, true },
{ "host_control_service", false, true, true, true },
{ "host_control_task", false, true, false, true },
{ "host_set_remark", false, false, true, false }, // 只写服务端主机库
{ "host_set_watch_level", false, false, true, false },
// --- 远程交谈(McpChat)---
{ "chat_open", false, false, false, true },
{ "chat_send", false, false, false, true },
{ "chat_wait", false, false, false, true }, // 会取走 inbox 消息,不是纯读
{ "chat_close", false, false, true, true },
};
} // namespace
void ApplyToolAnnotations(Json::Value& tools) {
if (!tools.isArray()) return;
for (Json::Value& tool : tools) {
if (!tool.isObject() || !tool["name"].isString()) continue;
const std::string name = tool["name"].asString();
bool readOnly = false, destructive = true, idempotent = false, openWorld = true;
for (const auto& h : kToolHints) {
if (name == h.name) {
readOnly = h.readOnly;
destructive = h.destructive;
idempotent = h.idempotent;
openWorld = h.openWorld;
break;
}
}
Json::Value ann(Json::objectValue);
ann["readOnlyHint"] = readOnly;
// 只读工具的 destructiveHint 按规范无意义,统一置 false,免得客户端误报「破坏性」。
ann["destructiveHint"] = readOnly ? false : destructive;
ann["idempotentHint"] = idempotent;
ann["openWorldHint"] = openWorld;
tool["annotations"] = ann;
}
}
} // namespace McpInternal
+137
View File
@@ -0,0 +1,137 @@
#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);
// ===== 结果外露(content 文本块)=====
//
// MCP 规范(Tools > Structured Content)要求:返回 structuredContent 的工具,
// 应同时把序列化后的 JSON 放进一个 TextContent 块。有些客户端(如 WorkBuddy)
// 只把 content 交给模型、完全忽略 structuredContent——不补这一块,模型就拿不到
// id / session_id / pid 这类串联下一跳的关键字段,只能看到「共 N 台主机匹配」。
//
// 因此 BuildResult 默认给每个带非空 structuredContent 的结果追加一个文本块
// (紧凑 JSON)。工具的正文已经承载同一份载荷时,用 SetStructuredTextPayload
// 指定只外露哪部分,避免同一份内容在上下文里出现两三次:
//
// exec_command / terminal_exec → {"exit_code":N} (stdout 已在正文里)
// get_keylog → 行数/字节数等元数据(行已在正文里)
// get_activity_history → {"records":[…]}
// host_get_hosts_file → 去掉 content 的 sc (原文已在 lines 里)
void AppendStructuredText(Json::Value& result, const Json::Value& payload); // 内部用
void AppendStructuredText(Json::Value& result); // 内部用
// 本次结果只外露 payload(BuildResult 消费后移除,不出现在响应里)。
// payload 为空对象/空数组时本次不追加文本块。
void SetStructuredTextPayload(Json::Value& result, const Json::Value& payload);
// 仅 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);
// ===== 列表输出治理 =====
//
// 列表类工具统一走 limit/offset:默认 limit=100,硬上限 1000,offset 默认 0。
// structuredContent 里同时给出 total/totalAll/offset/limit/hasMore,与
// McpMachine.cpp 的 host_list_*/list_network_connections 保持同一套字段,
// 调用方据此翻页,而不是让一次返回把上下文撑爆。
struct PageWindow {
int offset = 0;
int limit = 100;
int total = 0; // ApplyPageWindow 填入:切片前的总条数(本工具无二次过滤,故等于 totalAll)
int totalAll = 0;
int returned = 0; // 本次实际返回条数
bool hasMore = false; // 窗口之后还有条目(供调用方判断是否继续翻页)
};
// 读 args 里的 limit/offset(缺省/非法/非正数按默认值,limit 超上限截断到上限)。
PageWindow ResolvePageWindow(const Json::Value& args, int defaultLimit = 100, int maxLimit = 1000);
// 按窗口切片:out = all[offset, offset+limit),并回填 w.total/totalAll/returned/hasMore。
void ApplyPageWindow(const Json::Value& all, PageWindow& w, Json::Value& out);
// 把 total/totalAll/offset/limit/hasMore 写进 structuredContent。
void WritePageFields(Json::Value& structuredContent, const PageWindow& w);
// 往 inputSchema 的 properties 追加 limit / offset 两个字段。
void AppendPagingProps(Json::Value& props, int defaultLimit = 100, int maxLimit = 1000);
// 往 inputSchema 的 properties 追加 ids(只读工具的批量入口,最多 50 个 id)。
void AppendBatchIdsProp(Json::Value& props);
// 把 inputSchema 的必填约束改成「id 或 ids 二选一」。
void MakeIdOrIdsRequired(Json::Value& schema);
// 统一的提示文字,例如「共 283 个进程,本次返回第 1-100 条(还有更多,可用 offset 继续取)。」
std::string PageSummary(const PageWindow& w, const char* unit);
// ===== 工具注解(A3)=====
//
// 给 tools/list 里的每个工具补 MCP annotations(readOnlyHint / destructiveHint /
// idempotentHint / openWorldHint),让 MCP 客户端能按语义分组审批、默认折叠只读工具。
// 名称未在注解表里的工具按 schema 规范的默认值处理(destructiveHint=true),
// 即「新增工具必须显式登记」,漏登记只会更保守,不会误标成只读。
void ApplyToolAnnotations(Json::Value& tools);
} // 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
File diff suppressed because it is too large. Load diff
+411 -9
View File
@@ -9,7 +9,10 @@
#include <condition_variable>
#include <map>
#include <set>
#include <unordered_map>
#include <vector>
#include <deque>
#include <memory>
#include <cstdint>
#include <ctime>
@@ -24,6 +27,8 @@
#define min(a,b) (((a) < (b)) ? (a) : (b))
#endif
#include "McpTlsProxy.h"
#pragma comment(lib, "ws2_32.lib")
class CMy2015RemoteDlg;
@@ -37,6 +42,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。
@@ -47,6 +60,18 @@ public:
void SetParentDlg(CMy2015RemoteDlg* pDlg) { m_parent = pDlg; }
void SetToken(const std::string& token) { m_token = token; }
// HTTPS(native TLS):开启后 httplib 退到 127.0.0.1:internalPort,对外由 McpTlsProxy
// 在 bind:port 上同端口嗅探(TLS 解密 / 明文直通)。internalPort <= 0 时取 port+1。
void SetHttps(bool enabled, const std::string& certPath, const std::string& keyPath,
int internalPort) {
m_httpsEnabled = enabled;
m_certPath = certPath;
m_keyPath = keyPath;
m_internalPort = internalPort;
}
bool IsHttps() const { return m_httpsEnabled; }
int GetInternalPort() const { return m_internalPort; }
bool Start(const std::string& bind, int port);
void Stop();
bool IsRunning() const { return m_running.load(); }
@@ -93,6 +118,31 @@ public:
// 等 TOKEN_FILE_LIST(调用方不关子链接)。
bool OnDriveList(uint64_t device_id, context* subCtx, const BYTE* buf, ULONG len);
// ===== B2:search_file(文件搜索,COMMAND_SEARCH_FILE → N×TOKEN_SEARCH_FILE_LIST
// + TOKEN_SEARCH_FILE_FINISH)=====
//
// 搜索结果是「流式多包」:客户端边搜边发,最后单独发一个 FINISH。子连接在 FINISH
// 之前绝不能关——客户端 CFileManager 的搜索线程持有 this 指针,连接在内搜索未停时
// 断开会让它访问已析构对象(客户端既有缺陷)。
//
// MessageHandle(TOKEN_SEARCH_FILE_LIST) 调用:挂起命中且为 search_file 则收下这一包。
// 超过收集上限时自行下发 COMMAND_FILES_SEARCH_STOP 并标记 truncated。
// 只接受来自登记过的那条子连接(pending.subCtx)的包:被放弃的旧搜索在设备重开后
// 仍可能吐尾包,按 context 身份区分,避免把旧搜索的结果/结束信号算到新搜索头上。
bool OnSearchFileRecords(uint64_t device_id, context* subCtx, const BYTE* buf, ULONG len);
// MessageHandle(TOKEN_SEARCH_FILE_FINISH) 调用:置 finished 并唤醒等待者。
// 同样只认 pending.subCtx 发来的 FINISH;其它子连接的 FINISH 只关它自己,不影响挂起。
void FinishSearchFile(uint64_t device_id, context* subCtx);
// 工具线程:等待搜索结束(或超时)。取走已收集的原始包;finished=false 表示还在搜。
bool WaitSearchFile(uint64_t device_id, std::vector<std::vector<BYTE>>& records,
bool& finished, bool& truncated, context*& subCtx, int timeoutMs);
// 工具线程:让客户端停止搜索(COMMAND_FILES_SEARCH_STOP,客户端会等搜索线程退出
// 后回 FINISH)。幂等。
void StopSearchFile(uint64_t device_id);
// ===== P3:list_registry(注册表查询,三阶段:COMMAND_REGEDIT → TOKEN_REGEDIT →
// COMMAND_REG_FIND → TOKEN_REG_PATH + TOKEN_REG_KEY)=====
@@ -103,6 +153,10 @@ public:
// MessageHandle(TOKEN_REG_PATH / TOKEN_REG_KEY) 调用:两包都到齐后置 done 并唤醒等待者。
void TakeRegPath(uint64_t device_id, const BYTE* data, ULONG len);
void TakeRegKey(uint64_t device_id, const BYTE* data, ULONG len);
// MessageHandle(TOKEN_REG_ERROR) 调用:键打不开(不存在/拒绝访问)。失败时客户端只发这一包,
// 故一次置满 pathDone/keyDone/done,让 WaitPendingRegistry 立即返回;错误包原样存进 regPath,
// 由 BuildListRegistry 读首字节转译成 -32009/-32010。
void TakeRegError(uint64_t device_id, const BYTE* data, ULONG len);
// 工具线程:等待注册表两包(子键 + 值);成功返回 true 并把两包分别写入 out,超时返回 false。
bool WaitPendingRegistry(uint64_t device_id, std::vector<BYTE>& subkeys,
@@ -150,10 +204,16 @@ public:
// 登记持久终端挂起(复用单设备单终端约束;sessionId 由调用方生成)。
bool BeginTermOpen(uint64_t device_id, const std::string& sessionId);
// 复位单条命令字段并置 busy;输出 subCtx/isPty。false = 不存在/不匹配/未就绪/忙碌/已关。
bool BeginTermCommand(uint64_t device_id, const std::string& sessionId,
const std::string& command, const std::string& nonce,
context*& subCtx, bool& isPty);
// 复位单条命令字段并置 busy;输出 subCtx/isPty。
// 返回:0=ok;1=会话不存在;2=sessionId 不匹配;3=未就绪;4=忙(另一条命令在飞);
// 5=shell 已退出。1/2 之外的原因由 DescribeTermDestroyed 提供可读文案。
int BeginTermCommand(uint64_t device_id, const std::string& sessionId,
const std::string& command, const std::string& nonce,
context*& subCtx, bool& isPty);
// 若该设备上的持久终端最近被销毁(超时/退出/关闭),返回可读原因(英文,含时间);
// 否则返回空串。sessionId 不匹配时也返回空串(那是「id 写错」而不是「已销毁」)。
std::string DescribeTermDestroyed(uint64_t device_id, const std::string& sessionId);
// 等待本条命令完成(done || closed || 超时)。done=保持会话;closed/超时=清理会话+路由。
bool WaitTermCommand(uint64_t device_id, std::vector<BYTE>& out, int& exitCode,
@@ -213,15 +273,58 @@ public:
// 该 host 是否有进行中的文件传输会话(MessageHandle 分派守卫)。
bool IsFileTransferPending(uint64_t device_id);
// 该 host 上是否有「MCP 发起的 C2C 传输」正发往 dst_id。用于 COMMAND_SEND_FILE_V2
// 转发分支:MCP 的 C2C 不给源端子连接挂进度对话框(挂上后子连接的后续包会被路由到
// 对话框而不是 MessageHandle,源端最后的 TOKEN_C2C_SEND_RESULT 就会丢)。
bool IsC2CTransferPending(uint64_t src_id, uint64_t dst_id);
// 登记文件传输会话(false = 该 host 已有文件会话或一次性挂起请求)。
bool BeginFileTransferPending(uint64_t device_id, const std::string& tool,
const std::string& localDir, const std::string& remotePath,
bool overwrite);
// 登记上传会话(false = 该 host 已有文件会话或一次性挂起请求)。upload 走主连接、
// 工具线程同步驱动 FileBatchTransferWorkerV2,会话仅为单设备单传输互斥标记
// 工具线程同步驱动 FileBatchTransferWorkerV2。会话同时用于单设备单传输互斥与
// POSIX 目标端回执匹配(登记 dstClientID/transferID,见 OnC2CRecvResult)。
// (无 fmSubCtx/streamSubCtx,ClearFileTransfer 对空指针安全)。
bool BeginFileUpload(uint64_t device_id);
bool BeginFileUpload(uint64_t device_id, uint64_t transfer_id);
// ===== C2C 文件传输(copy_files_c2c:源客户端 → 目标客户端,服务端只做中继)=====
// 会话键控在「源」设备上:工具线程只等源客户端回传的 TOKEN_C2C_SEND_RESULT,
// 目标端的收发由服务端现有的 COMMAND_SEND_FILE_V2 转发分支完成(不经过 MCP)。
struct C2CResult {
int error = 0; // 0=ok;1002=超时(工具侧);其余为客户端上报的 status
uint32_t status = 0; // C2CSendResultPacket.status(0=全部发出;FEV2_* / 1001)
DWORD win32err = 0; // 源端首个不可访问路径的 win32 码
int32_t workerRc = 0; // FileBatchTransferWorkerV2 返回值
uint32_t fileCount = 0;
uint64_t totalBytes = 0;
// 目标端回执(只有 POSIX 接收端会发;Windows 目标恒为 false)
bool recvAck = false; // 收到了目标端回执
uint32_t recvStatus = 0; // 回执 status(0=写入成功,FEV2_* = 失败原因)
DWORD recvErrno = 0; // 回执 win32err(POSIX 端放 errno)
uint32_t recvFileCount = 0; // 回执 fileCount(实收文件数)
uint64_t recvBytes = 0; // 回执 totalBytes(实收字节数)
};
// 登记 C2C 会话(false = 源设备已有文件会话/挂起请求,或源==目标)。
bool BeginC2CTransfer(uint64_t src_id, uint64_t dst_id, uint64_t transfer_id);
// TOKEN_C2C_SEND_RESULT:源客户端回传发送结果,填会话并唤醒工具线程。
// 无对应会话(迟到的结果、MFC 侧手写包)直接忽略。
void OnC2CResult(uint64_t src_id, const BYTE* buf, ULONG len);
// TOKEN_C2C_RECV_RESULT:目标客户端(目前只有 Linux)回传落盘回执。
// 会话匹配按 dstClientID + transferID:copy_files_c2c 的会话键在源端、只能反查;
// upload_file 的会话键就是目标端本身。回执可能早于源端结果到达,绝不置 done。
void OnC2CRecvResult(uint64_t dst_id, const BYTE* buf, ULONG len);
// 工具线程:等源客户端回传结果;true=全部发出(error=0)。调用方随后 ClearFileTransfer(src)。
bool WaitC2CDone(uint64_t src_id, int timeoutMs, C2CResult& out);
// 工具线程:源端报告发出后再等目标端回执(仅声明 CLIENT_CAP_C2C_RECV_ACK 的端会回);
// true=收到回执(out.recvStatus 判断成败),false=没有回执(老客户端/超时)。
bool WaitC2CReceiver(uint64_t src_id, int timeoutMs, C2CResult& out);
// TOKEN_DRIVE_LIST:识别 download_file,存文件管理器子链接并下发 CMD_DOWN_FILES_V2。
// 返回 true=已接管(保持子链接,收尾由 ClearFileTransfer);false=会话已清理(调用方 CancelIO)。
@@ -230,6 +333,11 @@ public:
// COMMAND_SEND_FILE_V2:解析 chunk,路径校验 + overwrite 判定 + 落盘(RecvFileChunkV2)。
void OnFileChunkV2(uint64_t device_id, context* streamSubCtx, const BYTE* buf, ULONG len);
// TOKEN_DOWNLOAD_ERROR:客户端在建立传输子链接之前就判定「无可传输文件」(远端路径不存在/
// 不可访问)。置会话 error=1005(不存在)/1006(拒绝访问)/1007(其他)并唤醒等待线程。
// 不在此 CancelIO:文件管理器子链接由 ClearFileTransfer 统一收尾。
void OnDownloadError(uint64_t device_id, context* fmSubCtx, const BYTE* buf, ULONG len);
// COMMAND_FILE_COMPLETE_V2:SHA-256 校验(HandleFileCompleteV2)+ 完成判定。
void OnFileCompleteV2(uint64_t device_id, const BYTE* buf, ULONG len);
@@ -237,11 +345,17 @@ public:
// 无论成败,files 都会返回已见文件的落盘路径(成功=完整文件,失败=供调用方删半成品)。
// 调用方随后必须调 ClearFileTransfer 收尾(擦会话 + CancelIO 子链接)。
bool WaitFileTransferDone(uint64_t device_id, int timeoutMs,
std::vector<FileTransferEntry>& files, int& skipped, int& error);
std::vector<FileTransferEntry>& files, int& skipped, int& error,
DWORD* errorDetail = nullptr);
// 收尾:擦会话 + 锁外 CancelIO 文件管理器/流式两条子链接(幂等)。
void ClearFileTransfer(uint64_t device_id);
// 文件传输子链接断开(OfflineProc 调用):清反查表 + 置空裸指针,避免工具线程超时路径
// 对已回收(连接池复用)的 context 误 CancelIO。流式子链接断开 = 传输失败(1003);
// 文件管理器子链接断开只是少了收尾对象,传输数据走流式子链接,不判失败。
void OnFileTransferContextClosed(context* subCtx);
// ===== P7:设备管理控制(kill_process / operate_window / control_service / power_action)=====
// 写工具复用 m_Pending 单飞行;followUp/followUpSent/subCtx 标记接管进度。
// 「就绪 token」与「确认 token」是同一 token(客户端子连接构造即回一包,写后再回一包),
@@ -265,17 +379,143 @@ public:
// 工具线程:等待写确认包(第二个同 token 包);超时/空数据清挂起并 CancelIO 子连接。
bool WaitPendingWrite(uint64_t device_id, std::vector<BYTE>& out, int timeoutMs);
// ===== 迟到首包吸收(工具放弃后不再弹出 MFC 对话框)=====
// 工具超时/失败清掉挂起后,客户端仍可能才把应答首包发上来(列盘、服务列表、注册表、
// 进程列表、终端都是「子连接建成即发」)。那时已无挂起会话,MessageHandle 会把它当成
// 人手点击而打开文件管理器/服务管理器/注册表/进程窗口/日志/终端窗口。
// 工具放弃时按设备登记该工具的应答首包 token;包到达时一次性吸收(调用方关子连接、
// 不弹窗)。命中即消费,过期即失效,绝不长期压制人工操作。
// MessageHandle 各对话框分支开头调用(早于挂起判断:成功路径同样消费,不留残留)。
bool TakeToolFirstPacket(uint64_t device_id, BYTE token);
// OfflineProc 调用:接管的子连接断开时清挂起(置 done 并清 subCtx,唤醒等待线程)。
// 不擦表(由 WaitPendingWrite 持有迭代器时自行擦除,防迭代器失效);清 subCtx 使
// 超时路径不会对已回收(连接池复用)的 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);
// ===== N3:键盘记录(get_keylog)=====
// 复用 P8 的会话表(PendingKind::Keylog,单设备单飞行),但不走「请求-响应」:
// 主连接下发 COMMAND_KEYBOARD(169) → 客户端新建子连接 → TOKEN_KEYBOARD_START(293)
// 作为就绪包绑定 → 之后客户端每约 1s 推一包 TOKEN_KEYBOARD_DATA(294) 击键文本,
// 服务端累积到 keylogBuf 由 WaitKeylogData 取走。独立开关 McpKeylog(默认关)。
// 见 docs/Mcp_Design.md。
void SetKeylogEnabled(bool enabled) { m_keylogEnabled = enabled; }
bool IsKeylogEnabled() const { return m_keylogEnabled; }
// ===== 工具默认等待超时([settings] McpToolTimeoutMs,ini-only 键)=====
// 慢主机上 20s 固定的工具超时太紧;调到 60s 更实用。范围 clamp 到 [1000, 600000]。
// 改动需重启服务端生效(与其它 Mcp* 开关一致)。
void SetToolTimeoutMs(int ms);
int ToolTimeoutMs() const { return m_toolTimeoutMs; }
bool BeginKeylogSession(uint64_t device_id, const std::string& tool, context* mainCtx);
enum class KeylogWaitResult { Ok, Timeout, Closed };
// 取走累积字节并清零;timeoutMs 内无数据则 Timeout。truncated 回传是否已到上限。
KeylogWaitResult WaitKeylogData(uint64_t device_id, std::string& out,
int timeoutMs, bool& truncated);
// 工具线程:发命令前清空上一次响应并登记期望 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; }
bool IsReadonly() const { return m_readonly; }
const std::string& GetCmdWhitelist() const { return m_cmdWhitelist; }
// 监听地址/端口(Start 时记录,供 get_server_status 报告)。
const std::string& GetBind() const { return m_bind; }
int GetPort() const { return m_port; }
// get_server_status:在飞会话与鉴权封禁计数。每类各取一次自己的锁,
// 返回前全部释放——调用方拿到的是「大致同一时刻」的估算值,不用来同步。
void GetRuntimeCounters(int& pending, int& terminal, int& screenCtrl,
int& fileXfer, int& chat, int& blockedIps);
private:
CMcpServer();
~CMcpServer();
@@ -285,10 +525,49 @@ private:
// POST /mcp 处理器:token 校验 + JSON-RPC 分发。
void HandleMcp(const httplib::Request& req, httplib::Response& res);
// 记一条「持久终端已销毁」墓碑(调用方须持有 m_TermMutex)。
void MarkTermDestroyedLocked(uint64_t device_id, const std::string& sessionId,
const std::string& reason);
// ===== 鉴权加固 =====
// 同一 IP 在窗口期内连续鉴权失败达到阈值即封禁一段时间;封禁期内直接 429,不再比对 token。
bool IsAuthBlocked(const std::string& ip);
bool RecordAuthFailure(const std::string& ip); // 返回 true 表示本次失败触发了封禁
void ClearAuthFailures(const std::string& ip);
// 审计日志(<exe>\logs\mcp_audit.log):只写时间/IP/工具名/结果等元数据,
// 绝不写 token、Authorization 头、请求参数或返回内容。
void AuditMcpEvent(const char* event, const std::string& ip, const std::string& detail);
static void AppendAuditFile(const std::string& line);
struct AuthFailRecord {
int count = 0;
std::chrono::steady_clock::time_point windowStart;
std::chrono::steady_clock::time_point blockedUntil;
};
std::mutex m_AuthMutex;
std::unordered_map<std::string, AuthFailRecord> m_AuthFails;
// 挂起请求类型:主机管理/连接管理会话与既有一次性请求共用 m_Pending 保证单设备单飞行,
// 但 MessageHandle 的 P2b/P3/P7 拦截分支(IsPending/TakeMainResponse)必须把这两类排除,
// 否则用户手动打开对话框时 UI 包会被 MCP 抢走。
enum class PendingKind { Generic, FollowUp, Machine, ConnMgr, Keylog };
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;
McpTlsProxy m_tlsProxy; // HTTPS 前端(仅在 m_httpsEnabled 时启动)
std::thread m_thread;
std::atomic<bool> m_running{false};
std::string m_token;
std::string m_bind; // Start 传入的监听地址
int m_port = 0; // Start 传入的监听端口
bool m_httpsEnabled = false; // SetHttps 设置(默认明文)
std::string m_certPath; // MCP TLS 证书(PEM)
std::string m_keyPath; // MCP TLS 私钥(PEM, PKCS#8)
int m_internalPort = 0; // httplib 实际监听的回环端口
CMy2015RemoteDlg* m_parent = nullptr;
// 挂起请求注册表(受 m_PendingMutex 保护,键 = device_id)。
@@ -306,11 +585,63 @@ 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; // 整个会话的截止时间
// ===== N3:键盘记录(kind = Keylog 时有效)=====
std::string keylogBuf; // 累积的原始击键字节(客户端编码,未含 token)
bool keylogTruncated = false; // 已到字节上限,后续数据被丢弃
// ===== B2:search_file(tool == "search_file" 时有效)=====
std::vector<std::vector<BYTE>> searchRecords; // 已收集的 TOKEN_SEARCH_FILE_LIST 原始包
size_t searchBytes = 0;
bool searchFinished = false; // 已收到 TOKEN_SEARCH_FILE_FINISH
bool searchStopSent = false; // 已下发 COMMAND_FILES_SEARCH_STOP
bool searchTruncated = false; // 命中收集上限,后续匹配被丢弃
};
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);
// ===== 迟到首包吸收(受 m_FirstPacketMutex 保护,独立锁避免与挂起/传输表形成锁序)=====
// 等待函数在「超时/失败」分支调用:登记该工具放弃后可能迟到的应答首包 token。
struct FirstPacketMark {
std::set<BYTE> tokens;
std::chrono::steady_clock::time_point expiry;
};
std::mutex m_FirstPacketMutex;
std::map<uint64_t, FirstPacketMark> m_FirstPacketMarks;
void MarkLateFirstPacket(uint64_t device_id, std::initializer_list<BYTE> tokens);
void MarkLateFirstPacketForTool(uint64_t device_id, const std::string& tool);
// 路由表大小(已绑定 + 已吸收的子连接数)。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};
@@ -336,6 +667,15 @@ private:
std::condition_variable m_TermCv;
std::map<uint64_t, TermSession> m_TermSessions; // device_id → 会话
std::map<context*, uint64_t> m_TermContextToDevice; // subCtx → device_id(顶部路由)
// 最近一次持久终端被销毁的原因(device → 信息)。终端因超时/退出/关闭被清理后,后续
// terminal_exec 无法区分「会话被超时销毁」与「session_id 写错」,只能报同一句
// "not found"(评审 P1)。留一条短墓碑,让错误文案能说清是哪种情况。
struct TermDestroyedInfo {
std::string sessionId;
std::string reason; // 英文短句,直接拼进 -32002 文案
std::chrono::steady_clock::time_point expiry;
};
std::map<uint64_t, TermDestroyedInfo> m_TermDestroyed; // device_id → 墓碑(10 分钟内有效)
// ===== P5:远程控制会话(受 m_ScreenCtrlMutex 保护;单设备单会话)=====
struct ScreenCtrlSession {
@@ -354,7 +694,20 @@ private:
// ===== P6:文件传输会话(受 m_FileXferMutex 保护;单设备单传输)=====
struct FileTransferSession {
std::string tool; // "download_file" / "upload_file"
std::string tool; // "download_file" / "upload_file" / "copy_files_c2c"
uint64_t dstClientID = 0; // copy_files_c2c:目标客户端(其余工具恒 0)
bool c2cResult = false; // copy_files_c2c:已收到源端结果包
uint32_t c2cStatus = 0; // 结果包 status(0=全部发出)
DWORD c2cWin32 = 0; // 结果包 win32err
int32_t c2cWorkerRc = 0; // 结果包 workerRc
uint32_t c2cFileCount = 0; // 结果包 fileCount
uint64_t c2cBytes = 0; // 结果包 totalBytes
// 目标端回执(POSIX 接收端写完最后一包后发的同一个 175 包,dstClientID = 自己)
bool recvAck = false; // 已收到目标端回执
uint32_t recvStatus = 0; // 回执 status(0=写入成功)
DWORD recvErrno = 0; // 回执 win32err(POSIX 端放 errno)
uint32_t recvFileCount = 0; // 回执 fileCount(实收文件数)
uint64_t recvBytes = 0; // 回执 totalBytes(实收字节数)
std::string localDir; // download:本机保存目录(ANSI,结尾 '\')
std::string remotePath; // 客户端远程路径(ANSI,发 CMD_DOWN_FILES_V2 用)
bool overwrite = false; // 是否覆盖已存在文件
@@ -365,15 +718,60 @@ private:
uint32_t directoryCount = 0; // 目录项计数(目录不发 COMPLETE 包)
uint32_t filesDone = 0; // 已完成的文件数(含跳过的)
bool done = false; // 全部完成或出错
int error = 0; // 0=ok;8=哈希不匹配;1001=路径逃逸;1002=超时
int error = 0; // 0=ok;8=哈希不匹配;1001=路径逃逸;1002=超时;1003=流式子连接断线;
// 1004=停滞(看门狗);1005=远端路径不存在;1006=拒绝访问;1007=其他下载失败
DWORD errorDetail = 0; // error=1005/1006/1007 时的 win32 码(原样带进文案,便于分支/排查)
std::map<uint32_t, FileTransferEntry> fileEntries; // fileIndex → {path,size,sha256}
std::set<uint32_t> skipIndexes; // overwrite=false 跳过的 fileIndex
std::vector<FileTransferEntry> skipped; // 跳过的文件(供输出)
time_t startAt = 0;
// 停滞看门狗:最后一次收到数据的时间。远程路径不存在时客户端一个包都不发,
// 旧实现只能干等满 timeout_ms(默认 600s,整台主机被单飞互斥锁住,评审 P2)。
std::chrono::steady_clock::time_point lastDataAt;
};
std::mutex m_FileXferMutex;
std::condition_variable m_FileXferCv;
std::map<uint64_t, FileTransferSession> m_FileXferSessions; // device_id → 会话
// 子连接反查(受 m_FileXferMutex 保护):OfflineProc 拿不到 device_id,只能按 context* 找会话。
std::map<context*, uint64_t> m_FileXferContextToDevice;
// ===== 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;
@@ -381,6 +779,10 @@ private:
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 高风险子集(冻结/解冻进程、停止/重启服务)
bool m_keylogEnabled = false; // N3 键盘记录开关(默认关;get_keylog)
int m_toolTimeoutMs = 20000; // 工具默认等待超时(McpToolTimeoutMs,见 SetToolTimeoutMs)
};
// 全局访问器(仿 WebService(),见 WebService.h 末尾)
+183 -5
View File
@@ -4,6 +4,7 @@
#include "McpServer.h" // GenerateRandomToken
#include "2015Remote.h" // THIS_CFG (GetThisCfg)
#include <atlconv.h>
#include <afxdlgs.h>
#ifdef _DEBUG
#define new DEBUG_NEW
@@ -95,6 +96,9 @@ std::string WhitelistForDisplay(const std::string& stored)
} // namespace
BEGIN_MESSAGE_MAP(CMcpSettingsDlg, CDialog)
ON_BN_CLICKED(IDC_MCP_HTTPS, &CMcpSettingsDlg::OnHttpsToggle)
ON_BN_CLICKED(IDC_MCP_CERT_BROWSE, &CMcpSettingsDlg::OnBrowseCert)
ON_BN_CLICKED(IDC_MCP_KEY_BROWSE, &CMcpSettingsDlg::OnBrowseKey)
END_MESSAGE_MAP()
CMcpSettingsDlg::CMcpSettingsDlg(CWnd* parent)
@@ -106,7 +110,7 @@ INT_PTR CMcpSettingsDlg::DoModal()
{
USES_CONVERSION;
CString title = _TR("MCP设置");
BuildDialogTemplate(m_Template, T2CW(title), 320, 420);
BuildDialogTemplate(m_Template, T2CW(title), 320, 640);
InitModalIndirect((LPCDLGTEMPLATE)m_Template.data());
return CDialog::DoModal();
}
@@ -133,6 +137,19 @@ BOOL CMcpSettingsDlg::OnInitDialog()
m_lblToken.Create(_TR("Token"), WS_CHILD | WS_VISIBLE, r0, this, (UINT)-1);
m_editToken.Create(WS_CHILD | WS_VISIBLE | WS_BORDER | WS_TABSTOP | ES_AUTOHSCROLL,
r0, this, IDC_MCP_TOKEN);
m_btnHttps.Create(_TR("启用 HTTPS(本端口同时接受 TLS 连接)"),
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
r0, this, IDC_MCP_HTTPS);
m_lblCert.Create(_TR("证书路径"), WS_CHILD | WS_VISIBLE, r0, this, (UINT)-1);
m_editCert.Create(WS_CHILD | WS_VISIBLE | WS_BORDER | WS_TABSTOP | ES_AUTOHSCROLL,
r0, this, IDC_MCP_CERT);
m_btnCertBrowse.Create(_TR("浏览"), WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON,
r0, this, IDC_MCP_CERT_BROWSE);
m_lblKey.Create(_TR("私钥路径"), WS_CHILD | WS_VISIBLE, r0, this, (UINT)-1);
m_editKey.Create(WS_CHILD | WS_VISIBLE | WS_BORDER | WS_TABSTOP | ES_AUTOHSCROLL,
r0, this, IDC_MCP_KEY);
m_btnKeyBrowse.Create(_TR("浏览"), WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON,
r0, this, IDC_MCP_KEY_BROWSE);
m_btnReadonly.Create(_TR("只读模式(禁命令执行)"),
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
r0, this, IDC_MCP_READONLY);
@@ -148,6 +165,18 @@ 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_btnKeylog.Create(_TR("启用键盘记录(AI 采集击键)"),
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
r0, this, IDC_MCP_KEYLOG);
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,
@@ -167,11 +196,22 @@ BOOL CMcpSettingsDlg::OnInitDialog()
m_editBind.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_lblToken.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_editToken.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_btnHttps.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_lblCert.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_editCert.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_btnCertBrowse.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_lblKey.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_editKey.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_btnKeyBrowse.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_btnReadonly.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_btnTerminal.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
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_btnKeylog.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,7 +229,18 @@ 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);
int keylog = THIS_CFG.GetInt("settings", "McpKeylog", 0);
std::string whitelist = THIS_CFG.GetStr("settings", "McpCmdWhitelist", "");
int https = THIS_CFG.GetInt("settings", "McpHttps", 0);
std::string certPath = THIS_CFG.GetStr("settings", "McpCertPath", "");
std::string keyPath = THIS_CFG.GetStr("settings", "McpKeyPath", "");
// 未单独配置 MCP 证书时,按启动逻辑的同一回落规则预填设备端口的 [tls] 路径,
// 用户改或直接用都可以(保存后即成为 MCP 自己的显式配置)。
if (certPath.empty()) certPath = THIS_CFG.GetStr("tls", "CertPath", "");
if (keyPath.empty()) keyPath = THIS_CFG.GetStr("tls", "KeyPath", "");
m_btnEnable.SetCheck(enabled ? BST_CHECKED : BST_UNCHECKED);
m_editPort.SetWindowText(CString(std::to_string(port).c_str()));
@@ -200,26 +251,92 @@ 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_btnKeylog.SetCheck(keylog ? BST_CHECKED : BST_UNCHECKED);
// 白名单存储为逗号分隔,展示为每行一条。
m_editWhitelist.SetWindowText(CString(WhitelistForDisplay(whitelist).c_str()));
m_btnHttps.SetCheck(https ? BST_CHECKED : BST_UNCHECKED);
m_editCert.SetWindowText(CString(certPath.c_str()));
m_editKey.SetWindowText(CString(keyPath.c_str()));
LayoutControls(cli.Width(), cli.Height());
UpdateHttpsState();
return TRUE;
}
void CMcpSettingsDlg::UpdateHttpsState()
{
const BOOL on = (m_btnHttps.GetCheck() == BST_CHECKED);
m_lblCert.EnableWindow(on);
m_editCert.EnableWindow(on);
m_btnCertBrowse.EnableWindow(on);
m_lblKey.EnableWindow(on);
m_editKey.EnableWindow(on);
m_btnKeyBrowse.EnableWindow(on);
}
void CMcpSettingsDlg::OnHttpsToggle()
{
UpdateHttpsState();
}
void CMcpSettingsDlg::OnBrowseCert()
{
CString cur;
m_editCert.GetWindowText(cur);
CFileDialog dlg(TRUE, _T("pem"), cur.IsEmpty() ? nullptr : (LPCTSTR)cur,
OFN_FILEMUSTEXIST | OFN_HIDEREADONLY,
_T("Certificate Files (*.pem;*.crt;*.cer)|*.pem;*.crt;*.cer|All Files (*.*)|*.*||"),
this);
dlg.m_ofn.lpstrTitle = _T("Select Certificate");
if (dlg.DoModal() == IDOK)
m_editCert.SetWindowText(dlg.GetPathName());
}
void CMcpSettingsDlg::OnBrowseKey()
{
CString cur;
m_editKey.GetWindowText(cur);
CFileDialog dlg(TRUE, _T("key"), cur.IsEmpty() ? nullptr : (LPCTSTR)cur,
OFN_FILEMUSTEXIST | OFN_HIDEREADONLY,
_T("Key Files (*.key;*.pem)|*.key;*.pem|All Files (*.*)|*.*||"),
this);
dlg.m_ofn.lpstrTitle = _T("Select Private Key");
if (dlg.DoModal() == IDOK)
m_editKey.SetWindowText(dlg.GetPathName());
}
void CMcpSettingsDlg::OnOK()
{
CString sPort, sBind, sToken, sWhitelist;
CString sPort, sBind, sToken, sWhitelist, sCert, sKey;
m_editPort.GetWindowText(sPort);
m_editBind.GetWindowText(sBind);
m_editToken.GetWindowText(sToken);
m_editWhitelist.GetWindowText(sWhitelist);
m_editCert.GetWindowText(sCert);
m_editKey.GetWindowText(sKey);
bool enabled = (m_btnEnable.GetCheck() == BST_CHECKED);
bool readonly = (m_btnReadonly.GetCheck() == BST_CHECKED);
bool terminal = (m_btnTerminal.GetCheck() == BST_CHECKED);
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);
bool keylog = (m_btnKeylog.GetCheck() == BST_CHECKED);
bool https = (m_btnHttps.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));
@@ -237,6 +354,27 @@ void CMcpSettingsDlg::OnOK()
return;
}
// HTTPS:证书与私钥必须都在且存在(启动时加载失败会直接拒绝监听,故此处先挡住)
std::string certPath = CT2A(sCert);
std::string keyPath = CT2A(sKey);
if (https) {
if (certPath.empty()) {
MessageBoxL(_TR("请填写证书路径"), _TR("提示"), MB_ICONWARNING);
return;
}
if (keyPath.empty()) {
MessageBoxL(_TR("请填写私钥路径"), _TR("提示"), MB_ICONWARNING);
return;
}
DWORD ca = GetFileAttributesA(certPath.c_str());
DWORD ka = GetFileAttributesA(keyPath.c_str());
if (ca == INVALID_FILE_ATTRIBUTES || (ca & FILE_ATTRIBUTE_DIRECTORY) ||
ka == INVALID_FILE_ATTRIBUTES || (ka & FILE_ATTRIBUTE_DIRECTORY)) {
MessageBoxL(_TR("证书或私钥文件不存在,请检查路径。"), _TR("提示"), MB_ICONWARNING);
return;
}
}
// 落盘
THIS_CFG.SetInt("settings", "McpEnabled", enabled ? 1 : 0);
THIS_CFG.SetInt("settings", "McpPort", port);
@@ -247,14 +385,26 @@ 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);
THIS_CFG.SetInt("settings", "McpKeylog", keylog ? 1 : 0);
std::string whitelist = CT2A(sWhitelist);
whitelist = NormalizeWhitelist(whitelist);
THIS_CFG.SetStr("settings", "McpCmdWhitelist", whitelist);
THIS_CFG.SetInt("settings", "McpHttps", https ? 1 : 0);
THIS_CFG.SetStr("settings", "McpCertPath", certPath);
THIS_CFG.SetStr("settings", "McpKeyPath", keyPath);
// 拆成两段可翻译的单行键,中间用 \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("远程交谈开关的改动需重启程序生效。") + _T("\r\n") +
_TR("键盘记录开关的改动需重启程序生效。") + _T("\r\n") +
_TR("HTTPS 开关与证书路径的改动需重启程序生效。") + _T("\r\n") +
_TR("证书须为 PEM 格式,私钥须为 PKCS#8 格式。"),
_TR("提示"), MB_ICONINFORMATION);
CDialog::OnOK();
@@ -285,6 +435,22 @@ void CMcpSettingsDlg::LayoutControls(int cx, int cy)
m_editToken.MoveWindow(margin + labelW, y - 2, cx - margin * 2 - labelW, rowH);
y += rowH + gap;
// HTTPS:勾选后证书/私钥两行才可编辑(未勾选时置灰,值仍保留)。
const int browseW = 64;
int editW = cx - margin * 2 - labelW - browseW - gap;
m_btnHttps.MoveWindow(margin, y, cx - margin * 2, 22);
y += 30;
m_lblCert.MoveWindow(margin, y, labelW, rowH);
m_editCert.MoveWindow(margin + labelW, y - 2, editW, rowH);
m_btnCertBrowse.MoveWindow(cx - margin - browseW, y - 2, browseW, rowH);
y += rowH + gap;
m_lblKey.MoveWindow(margin, y, labelW, rowH);
m_editKey.MoveWindow(margin + labelW, y - 2, editW, rowH);
m_btnKeyBrowse.MoveWindow(cx - margin - browseW, y - 2, browseW, rowH);
y += rowH + gap;
m_btnReadonly.MoveWindow(margin, y, cx - margin * 2, 22);
y += 30;
@@ -300,6 +466,18 @@ 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;
m_btnKeylog.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);
+23 -1
View File
@@ -4,7 +4,7 @@
#include <afxcmn.h>
#include <vector>
// 「MCP设置」配置对话框:启用 MCP / 端口 / 绑定地址 / Token。
// 「MCP设置」配置对话框:启用 MCP / 端口 / 绑定地址 / Token / HTTPS 与证书。
// 因 2015Remote.rc 为 UTF-16 编码、不宜手工编辑,参照 ZstaPickerDlg 用
// InitModalIndirect + 内存 DLGTEMPLATE 程序化创建(见 docs/Mcp_Design.md §3.8)。
class CMcpSettingsDlg : public CDialog
@@ -18,6 +18,10 @@ protected:
virtual BOOL OnInitDialog();
virtual void OnOK();
afx_msg void OnHttpsToggle();
afx_msg void OnBrowseCert();
afx_msg void OnBrowseKey();
DECLARE_MESSAGE_MAP()
private:
@@ -32,6 +36,15 @@ 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_* 工具族,不要求只读关)
IDC_MCP_KEYLOG = 1014, // 「启用键盘记录」复选框(get_keylog,不要求只读关)
IDC_MCP_HTTPS = 1015, // 「启用 HTTPS」复选框(MCP 端口同时接受 TLS)
IDC_MCP_CERT = 1016, // 证书路径编辑框(PEM)
IDC_MCP_KEY = 1017, // 私钥路径编辑框(PKCS#8)
IDC_MCP_CERT_BROWSE = 1018, // 证书路径「浏览」按钮
IDC_MCP_KEY_BROWSE = 1019, // 私钥路径「浏览」按钮
};
CButton m_btnEnable;
@@ -42,11 +55,20 @@ private:
CButton m_btnRemoteControl;
CButton m_btnFileTransfer;
CButton m_btnManage;
CButton m_btnMachine;
CButton m_btnMachineDangerous;
CButton m_btnChat;
CButton m_btnKeylog;
CStatic m_lblWhitelist;
CEdit m_editWhitelist;
CButton m_btnHttps;
CStatic m_lblCert, m_lblKey;
CEdit m_editCert, m_editKey;
CButton m_btnCertBrowse, m_btnKeyBrowse;
CButton m_btnOK, m_btnCancel;
std::vector<BYTE> m_Template; // 内存 DLGTEMPLATE 字节
void LayoutControls(int cx, int cy);
void UpdateHttpsState(); // 勾选 HTTPS 才允许编辑证书/私钥
};
+440
View File
@@ -0,0 +1,440 @@
// McpTlsProxy.cpp — MCP 端口的 TLS 前端实现(Schannel 入站,同端口嗅探)
#include "StdAfx.h"
#include "McpTlsProxy.h"
#include <ws2tcpip.h>
namespace
{
// MCP 身份在 CNG KSP 里的键名,与设备端口的 YamaServerTlsKey 区分,避免互相覆盖。
const wchar_t* kMcpKeyName = L"YamaMcpTlsKey";
const size_t kMaxConns = 64; // 并发连接上限(MCP 客户端数量很少,防资源耗尽)
const DWORD kSniffTimeoutMs = 10000; // 首字节嗅探超时:连上不说话的直接断开
}
bool McpTlsProxy::WaitReady(SOCKET sock, bool forRead, int timeoutMs)
{
fd_set fds;
FD_ZERO(&fds);
FD_SET(sock, &fds);
timeval tv;
tv.tv_sec = timeoutMs / 1000;
tv.tv_usec = (timeoutMs % 1000) * 1000;
return select(0, forRead ? &fds : NULL, forRead ? NULL : &fds, NULL, &tv) > 0;
}
bool McpTlsProxy::SendAll(SOCKET sock, const void* data, int len)
{
const char* p = (const char*)data;
int sent = 0;
while (sent < len)
{
int n = send(sock, p + sent, len - sent, 0);
if (n == SOCKET_ERROR)
{
if (WSAGetLastError() == WSAEWOULDBLOCK)
{
if (!WaitReady(sock, false, 30000))
return false;
continue;
}
return false;
}
if (n <= 0)
return false;
sent += n;
}
return true;
}
SOCKET McpTlsProxy::ConnectLoopback(int port)
{
SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s == INVALID_SOCKET)
return INVALID_SOCKET;
sockaddr_in addr = {};
addr.sin_family = AF_INET;
addr.sin_port = htons((u_short)port);
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
if (connect(s, (sockaddr*)&addr, sizeof(addr)) != 0)
{
closesocket(s);
return INVALID_SOCKET;
}
u_long nb = 1;
ioctlsocket(s, FIONBIO, &nb); // 连接建立后转非阻塞,交给 select 驱动
return s;
}
bool McpTlsProxy::Start(const std::string& bind, int listenPort, int backendPort,
const std::string& certPath, const std::string& keyPath)
{
if (m_running.load())
return true;
if (listenPort <= 0 || backendPort <= 0)
return false;
// 身份必须先加载成功:证书坏了就 fail-closed,绝不以明文对外监听。
if (!ServerTlsLoadIdentityFromPem(certPath, keyPath, kMcpKeyName, m_identity))
{
Mprintf("[McpTls] FATAL: cannot load MCP TLS identity (cert=%s key=%s); "
"refusing to start MCP listener\n", certPath.c_str(), keyPath.c_str());
return false;
}
m_identityLoaded = true;
m_backendPort = backendPort;
addrinfo hints = {};
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
addrinfo* res = nullptr;
char portStr[16] = {};
sprintf_s(portStr, "%d", listenPort);
const char* node = (bind.empty() || bind == "0.0.0.0") ? "0.0.0.0" : bind.c_str();
if (getaddrinfo(node, portStr, &hints, &res) != 0 || res == nullptr)
{
Mprintf("[McpTls] FATAL: cannot resolve bind address %s\n", node);
ServerTlsFreeIdentity(m_identity);
m_identityLoaded = false;
return false;
}
SOCKET ls = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (ls == INVALID_SOCKET)
{
freeaddrinfo(res);
ServerTlsFreeIdentity(m_identity);
m_identityLoaded = false;
return false;
}
BOOL reuse = TRUE;
setsockopt(ls, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(reuse));
u_long nb = 1;
ioctlsocket(ls, FIONBIO, &nb); // 非阻塞监听,accept 用 select 驱动
if (::bind(ls, res->ai_addr, (int)res->ai_addrlen) != 0 ||
listen(ls, SOMAXCONN) != 0)
{
Mprintf("[McpTls] FATAL: bind/listen %s:%d failed (%d)\n", node, listenPort, WSAGetLastError());
freeaddrinfo(res);
closesocket(ls);
ServerTlsFreeIdentity(m_identity);
m_identityLoaded = false;
return false;
}
freeaddrinfo(res);
m_listen = ls;
m_running.store(true);
m_acceptThread = std::thread(&McpTlsProxy::AcceptLoop, this);
Mprintf("[McpTls] listening on %s:%d (TLS + plaintext passthrough) -> 127.0.0.1:%d\n",
node, listenPort, backendPort);
return true;
}
void McpTlsProxy::Stop()
{
if (!m_running.exchange(false) && m_listen == INVALID_SOCKET && !m_acceptThread.joinable())
{
// 从未启动或已停止
if (m_identityLoaded)
{
ServerTlsFreeIdentity(m_identity);
m_identityLoaded = false;
}
return;
}
SOCKET ls = m_listen;
m_listen = INVALID_SOCKET;
if (ls != INVALID_SOCKET)
{
shutdown(ls, SD_BOTH); // 唤醒阻塞 accept
closesocket(ls);
}
if (m_acceptThread.joinable())
m_acceptThread.join();
std::vector<std::shared_ptr<Conn>> all;
{
std::lock_guard<std::mutex> lk(m_connMtx);
all.swap(m_conns);
}
for (auto& c : all)
{
if (c->done.load())
continue; // 已自行收尾,句柄可能已关闭,勿再触碰
SOCKET cl = c->client.load();
if (cl != INVALID_SOCKET)
shutdown(cl, SD_BOTH);
SOCKET b = c->backend.load();
if (b != INVALID_SOCKET)
shutdown(b, SD_BOTH);
}
for (auto& c : all)
{
if (c->th.joinable())
c->th.join();
}
if (m_identityLoaded)
{
ServerTlsFreeIdentity(m_identity);
m_identityLoaded = false;
}
Mprintf("[McpTls] stopped\n");
}
void McpTlsProxy::SweepFinished()
{
std::vector<std::shared_ptr<Conn>> finished;
{
std::lock_guard<std::mutex> lk(m_connMtx);
for (auto it = m_conns.begin(); it != m_conns.end();)
{
if ((*it)->done.load())
{
finished.push_back(*it);
it = m_conns.erase(it);
}
else
{
++it;
}
}
}
for (auto& c : finished)
{
if (c->th.joinable())
c->th.join();
}
}
void McpTlsProxy::AcceptLoop()
{
while (m_running.load())
{
if (!WaitReady(m_listen, true, 500))
continue; // 超时轮询 m_running,便于 Stop 及时退出
SOCKET cs = accept(m_listen, NULL, NULL);
if (cs == INVALID_SOCKET)
{
if (!m_running.load())
break;
int e = WSAGetLastError();
if (e == WSAEWOULDBLOCK)
continue;
Mprintf("[McpTls] accept failed (%d); listener stops\n", e);
break;
}
SweepFinished();
std::lock_guard<std::mutex> lk(m_connMtx);
if (m_conns.size() >= kMaxConns)
{
closesocket(cs);
continue;
}
u_long nb = 1;
ioctlsocket(cs, FIONBIO, &nb); // 嗅探/泵送全部走 select
auto c = std::make_shared<Conn>();
c->client.store(cs);
m_conns.push_back(c);
c->th = std::thread([this, c]() { ServeConn(c); });
}
}
void McpTlsProxy::CloseConn(Conn& c)
{
SOCKET cl = c.client.exchange(INVALID_SOCKET);
if (cl != INVALID_SOCKET)
{
shutdown(cl, SD_BOTH);
closesocket(cl);
}
SOCKET b = c.backend.exchange(INVALID_SOCKET);
if (b != INVALID_SOCKET)
{
shutdown(b, SD_BOTH);
closesocket(b);
}
c.done.store(true);
}
void McpTlsProxy::ServeConn(std::shared_ptr<Conn> sp)
{
Conn& c = *sp;
SOCKET client = c.client.load();
// ---- 1) 首字节嗅探(同设备端口 §5.2):0x16 0x03 = TLS ClientHello ----
BYTE peek[8] = {};
int pn = 0;
DWORD start = GetTickCount();
for (;;)
{
int r = recv(client, (char*)peek, sizeof(peek), MSG_PEEK);
if (r > 0)
{
pn = r;
break;
}
if (r == 0)
{
CloseConn(c); // 对端直接关闭
return;
}
if (WSAGetLastError() != WSAEWOULDBLOCK)
{
CloseConn(c);
return;
}
if (GetTickCount() - start > kSniffTimeoutMs || !m_running.load())
{
CloseConn(c); // 连上不说话的,直接断开
return;
}
WaitReady(client, true, 200);
}
const bool isTls = (peek[0] == 0x16) && (pn < 2 || peek[1] == 0x03);
// ---- 2) 后端:httplib 只监听 127.0.0.1 的内部端口 ----
SOCKET backend = ConnectLoopback(m_backendPort);
if (backend == INVALID_SOCKET)
{
Mprintf("[McpTls] backend 127.0.0.1:%d not reachable\n", m_backendPort);
CloseConn(c);
return;
}
c.backend.store(backend);
// ---- 3) 分流 ----
if (isTls)
{
// 嗅探用的是 MSG_PEEK(不消费),ClientHello 原样留在内核缓冲里;交多少字节
// HandshakeWithCred 都能自己补齐,这里直接让它从 socket 读完整首条记录。
ServerTlsSession sess;
if (!sess.HandshakeWithCred(client, NULL, 0, m_identity.cred))
{
Mprintf("[McpTls] TLS handshake failed; closing connection\n");
CloseConn(c);
return;
}
PumpTls(c, sess);
}
else
{
PumpRaw(c); // 本机 http://127.0.0.1:port 的既有用法原样透传
}
CloseConn(c);
}
void McpTlsProxy::PumpRaw(Conn& c)
{
char buf[16384];
const SOCKET client = c.client.load();
const SOCKET backend = c.backend.load();
for (;;)
{
fd_set rd;
FD_ZERO(&rd);
FD_SET(client, &rd);
FD_SET(backend, &rd);
int n = select(0, &rd, NULL, NULL, NULL);
if (n <= 0)
break;
if (FD_ISSET(client, &rd))
{
int r = recv(client, buf, sizeof(buf), 0);
if (r == 0) break;
if (r < 0)
{
if (WSAGetLastError() == WSAEWOULDBLOCK) continue;
break;
}
if (!SendAll(backend, buf, r)) break;
}
if (FD_ISSET(backend, &rd))
{
int r = recv(backend, buf, sizeof(buf), 0);
if (r == 0) break;
if (r < 0)
{
if (WSAGetLastError() == WSAEWOULDBLOCK) continue;
break;
}
if (!SendAll(client, buf, r)) break;
}
}
}
void McpTlsProxy::PumpTls(Conn& c, ServerTlsSession& sess)
{
char buf[16384];
const SOCKET client = c.client.load();
const SOCKET backend = c.backend.load();
std::vector<BYTE> plain;
std::vector<BYTE> wire;
// 握手阶段已经收到的明文要先送给后端:客户端复用 TLS 会话时会把 ChangeCipherSpec +
// Finished + 首条请求挤在同一批字节里,握手只会消费前两个,请求留在会话缓冲里。
// 不在这里取走,后端就一个字节也收不到,5s 后按 keep-alive 超时关连接,客户端看到的是
// “fetch failed (other side closed)”(实测 undici/Node 24 稳定复现)。
{
std::vector<BYTE> head;
if (sess.Decrypt(NULL, 0, head) < 0)
return;
if (!head.empty() && !SendAll(backend, head.data(), (int)head.size()))
return;
}
for (;;)
{
fd_set rd;
FD_ZERO(&rd);
FD_SET(client, &rd);
FD_SET(backend, &rd);
int n = select(0, &rd, NULL, NULL, NULL);
if (n <= 0)
break;
if (FD_ISSET(client, &rd))
{
int r = recv(client, buf, sizeof(buf), 0);
if (r == 0) break;
if (r < 0)
{
if (WSAGetLastError() == WSAEWOULDBLOCK) continue;
break;
}
plain.clear();
if (sess.Decrypt((const BYTE*)buf, r, plain) < 0)
break; // 对端 close_notify / 解密失败
if (!plain.empty() && !SendAll(backend, plain.data(), (int)plain.size()))
break;
}
if (FD_ISSET(backend, &rd))
{
int r = recv(backend, buf, sizeof(buf), 0);
if (r == 0) break;
if (r < 0)
{
if (WSAGetLastError() == WSAEWOULDBLOCK) continue;
break;
}
wire.clear();
if (sess.Encrypt((const BYTE*)buf, r, wire) < 0)
break;
if (!wire.empty() && !SendAll(client, wire.data(), (int)wire.size()))
break;
}
}
}
+77
View File
@@ -0,0 +1,77 @@
// McpTlsProxy.h — MCP 端口的 TLS 前端(同端口嗅探:TLS 解密 / 明文直通)
//
// 背景:CMcpServer 用的 httplib::Server 是明文 HTTP。要让 MCP 客户端经公网用 https
// 访问,又不引入 OpenSSL 依赖,这里在 MCP 前面加一层基于 Schannel 的 TLS 前端:
//
// 客户端 → :McpPort(本类)→ 127.0.0.1:<内部端口>(httplib)
//
// 首字节嗅探与设备端口(IOCPServer.cpp §5.2)同一套路:首字节 0x16 且次字节 0x03
// 视为 TLS ClientHello,走 ServerTlsSession 入站握手;否则按明文原样转发。因此本机
// 现有的 http://127.0.0.1:6544 用法不需要改动,远端可同时用 https。
//
// 身份:独立于设备端口的 [tls] 证书(MCP 面向公网客户端,需公共 CA 证书),
// 由 ServerTlsLoadIdentityFromPem 加载,CNG 键名 YamaMcpTlsKey,与设备端口互不覆盖。
#pragma once
#include <WinSock2.h>
#include <atomic>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
#include "ServerTlsSession.h"
class ServerTlsSession;
class McpTlsProxy
{
public:
McpTlsProxy() {}
~McpTlsProxy() { Stop(); }
McpTlsProxy(const McpTlsProxy&) = delete;
McpTlsProxy& operator=(const McpTlsProxy&) = delete;
// 监听 bind:listenPort,把解密后的字节转发到 127.0.0.1:backendPort。
// certPath/keyPath 为 PEM(证书 + PKCS#8 私钥)。任一环节失败返回 false(fail-closed)。
bool Start(const std::string& bind, int listenPort, int backendPort,
const std::string& certPath, const std::string& keyPath);
void Stop();
bool IsRunning() const { return m_running.load(); }
private:
// 单条前端连接:客户端套接字 + 连到 httplib 的后端套接字。
// Stop() 需要能打断正在 select/recv 的线程,故后端套接字放在原子量里随时可取。
struct Conn
{
std::atomic<SOCKET> client{ INVALID_SOCKET };
std::atomic<SOCKET> backend{ INVALID_SOCKET };
std::atomic<bool> done{ false };
std::thread th;
};
void AcceptLoop();
void ServeConn(std::shared_ptr<Conn> c);
void PumpRaw(Conn& c);
void PumpTls(Conn& c, ServerTlsSession& sess);
void SweepFinished();
void CloseConn(Conn& c);
static SOCKET ConnectLoopback(int port);
static bool WaitReady(SOCKET sock, bool forRead, int timeoutMs);
static bool SendAll(SOCKET sock, const void* data, int len);
SOCKET m_listen = INVALID_SOCKET;
std::thread m_acceptThread;
std::atomic<bool> m_running{ false };
int m_backendPort = 0;
ServerTlsExtraIdentity m_identity;
bool m_identityLoaded = false;
std::mutex m_connMtx;
std::vector<std::shared_ptr<Conn>> m_conns;
};
+227 -8
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)
@@ -1408,6 +1415,31 @@ VOID CScreenSpyDlg::DrawFirstScreen(void)
PostMessage(WM_PAINT);//触发WM_PAINT消息
}
// 把远程光标的位置/类型同步给 Web 客户端。抓屏画面本身不含光标(GDI/DXGI 都不合成),
// 非控制态的浏览器靠这条消息在画面上自己画一个光标。
// 类型变化 → 立即发(force=true);
// 位置变化 → 50ms 节流;
// 完全静止 → 每秒重发一次,让刚打开页面的观察者也能立刻看到光标位置
// (否则要等远程鼠标下一次移动)。
void CScreenSpyDlg::BroadcastCursorToWeb(bool force)
{
if (!m_bIsWebSession || !WebService().IsRunning()) return;
ULONGLONG now = GetTickCount64();
ULONGLONG since = now - m_nLastCursorBroadcast;
bool reshaped = force || m_bCursorIndex != m_bBroadcastCursorIndex;
bool moved = m_ClientCursorPos.x != m_ptBroadcastCursor.x ||
m_ClientCursorPos.y != m_ptBroadcastCursor.y;
if (!reshaped) {
if (since < 50) return; // 位置变化节流
if (!moved && since < 1000) return; // 静止时每秒兜底一次
}
m_nLastCursorBroadcast = now;
m_bBroadcastCursorIndex = m_bCursorIndex;
m_ptBroadcastCursor = m_ClientCursorPos;
WebService().BroadcastCursor(m_ClientID, m_bCursorIndex,
(int)m_ClientCursorPos.x, (int)m_ClientCursorPos.y);
}
VOID CScreenSpyDlg::DrawNextScreenDiff(bool keyFrame)
{
//该函数不是直接画到屏幕上,而是更新一下变化部分的屏幕数据然后调用
@@ -1445,10 +1477,6 @@ VOID CScreenSpyDlg::DrawNextScreenDiff(bool keyFrame)
m_bCursorIndex = m_ContextObject->InDeCompressedBuffer.GetBuffer(2+sizeof(POINT))[0];
if (bOldCursorIndex != m_bCursorIndex) {
bChange = TRUE;
// 通知 Web 客户端光标变化 (只有 Web 会话的对话框才广播)
if (m_bIsWebSession && WebService().IsRunning()) {
WebService().BroadcastCursor(m_ClientID, m_bCursorIndex);
}
if (m_bIsCtrl && !m_bIsTraceCursor) {//替换指定窗口所属类的WNDCLASSEX结构
HCURSOR cursor;
if (m_bCursorIndex == 254) { // -2: 使用自定义光标
@@ -1466,6 +1494,8 @@ VOID CScreenSpyDlg::DrawNextScreenDiff(bool keyFrame)
#endif
}
}
// 通知 Web 客户端光标位置/类型(内部按类型变化/位置节流/每秒兜底决定是否真发)
BroadcastCursorToWeb(false);
// 屏幕是否变化
if (NextScreenLength > 0) {
@@ -1631,11 +1661,9 @@ VOID CScreenSpyDlg::DrawScrollFrame()
m_bCursorIndex = m_ContextObject->InDeCompressedBuffer.GetBuffer(2 + sizeof(POINT))[0];
if (bOldCursorIndex != m_bCursorIndex) {
bChange = TRUE;
// 通知 Web 客户端光标变化 (只有 Web 会话的对话框才广播)
if (m_bIsWebSession && WebService().IsRunning()) {
WebService().BroadcastCursor(m_ClientID, m_bCursorIndex);
}
}
// 通知 Web 客户端光标位置/类型(内部按类型变化/位置节流/每秒兜底决定是否真发)
BroadcastCursorToWeb(false);
// 读取滚动参数
LPBYTE buffer = m_ContextObject->InDeCompressedBuffer.GetBuffer(ulHeadLength);
@@ -2121,6 +2149,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 +2754,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)
+15
View File
@@ -141,6 +141,7 @@ enum {
IDM_AUDIO_TOGGLE, // 音频开关
IDM_ENABLE_H264_HARD,
IDM_ENABLE_AV1_HARD,
IDM_MOUSE_CALIB, // 鼠标坐标校准(逐主机补偿客户端坐标换算偏差)
};
// 状态信息窗口 - 全屏时显示帧率/速度/质量
@@ -217,6 +218,10 @@ public:
bool IsWebSession() const { return m_bIsWebSession.load(); }
void SetWebSession(bool isWeb) { m_bIsWebSession.store(isWeb); }
// 把远程光标的位置/类型同步给 Web 客户端(非控制态由浏览器自己画光标)。
// force=true 用于类型变化,跳过节流立即发送。
void BroadcastCursorToWeb(bool force);
VOID SendNext(void);
VOID OnReceiveComplete();
HDC m_hFullDC;
@@ -243,6 +248,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);
@@ -256,6 +268,9 @@ public:
std::atomic<bool> m_bIsWebSession{false}; // True if this dialog was created by Web request (atomic for thread safety)
std::string m_strSaveNotice; // 截图保存路径提示
ULONGLONG m_nSaveNoticeTime = 0; // 截图提示开始时间
ULONGLONG m_nLastCursorBroadcast = 0; // 上次向 Web 广播光标的时间(50ms 节流)
BYTE m_bBroadcastCursorIndex = 0; // 上次广播的光标类型
POINT m_ptBroadcastCursor = {0, 0}; // 上次广播的光标位置
BOOL m_bUsingFRP = FALSE;
// 文件接收进度对话框(用于 Linux Ctrl+C -> 服务端 Ctrl+V)
+332 -88
View File
@@ -75,6 +75,31 @@ KeyFmt DetectKeyFormat(const std::string& keyPem)
return KF_PKCS1;
return KF_UNKNOWN;
}
// 证书文件里可能有多个 PEM 块(fullchain:叶证书 + 中间证书)。逐块切出来解码,
// 顺序即文件顺序。单证书文件也走这里(返回 1 块)。
std::vector<std::vector<BYTE>> PemToDerList(const std::string& pem)
{
static const std::string kBegin = "-----BEGIN CERTIFICATE-----";
static const std::string kEnd = "-----END CERTIFICATE-----";
std::vector<std::vector<BYTE>> out;
size_t pos = 0;
while (true)
{
size_t b = pem.find(kBegin, pos);
if (b == std::string::npos)
break;
size_t e = pem.find(kEnd, b);
if (e == std::string::npos)
break;
e += kEnd.size();
std::vector<BYTE> der;
if (PemToDer(pem.substr(b, e - b), der) && !der.empty())
out.push_back(std::move(der));
pos = e;
}
return out;
}
}
// =====================================================================================
@@ -143,7 +168,35 @@ bool ServerTlsIdentity::Load(config& cfg)
return true;
}
bool ServerTlsIdentity::LoadIdentity(const std::string& certPath, const std::string& keyPath)
namespace
{
// 用证书上下文换入站凭据:显式指定服务端证书,不请求客户端证书(单向 TLS)。
// 单独成函数,因为 EC 键的几种绑定方式都要靠「凭据能否建立」来验证。
SECURITY_STATUS AcquireInboundCredFor(PCCERT_CONTEXT cert, CredHandle& cred)
{
SCHANNEL_CRED sc = {};
sc.dwVersion = SCHANNEL_CRED_VERSION;
sc.cCreds = 1;
sc.paCred = &cert;
sc.grbitEnabledProtocols = SP_PROT_TLS1_2_SERVER;
// NO_DEFAULT_CREDS 避免回退到系统默认凭据,确保只用我们提供的证书/私钥。
//(单向 TLS 不请求客户端证书,故无需 SCH_CRED_MANUAL_CRED_VALIDATION。)
sc.dwFlags = SCH_CRED_NO_DEFAULT_CREDS;
cred = {};
TimeStamp tsExpiry = {};
return AcquireCredentialsHandleA(
NULL, (SEC_CHAR*)"Microsoft Unified Security Protocol Provider", SECPKG_CRED_INBOUND,
NULL, &sc, NULL, NULL, &cred, &tsExpiry);
}
// 按给定 PEM(证书链 + PKCS#8 私钥)与 CNG 持久化键名构造一份入站身份。
// 设备端口(ServerTlsIdentity,键名 YamaServerTlsKey)与 MCP 前端(独立键名)共用这段
// 逻辑;键名不同则两份身份可并存,互不覆盖。
// 成功时 outCred / outCert / outKey 均有效,生命周期由调用方释放。
bool BuildIdentity(const std::string& certPath, const std::string& keyPath,
const wchar_t* keyName,
CredHandle& outCred, PCCERT_CONTEXT& outCert, NCRYPT_KEY_HANDLE& outKey)
{
std::string certPem, keyPem;
if (!ReadFileText(certPath, certPem))
@@ -157,28 +210,100 @@ bool ServerTlsIdentity::LoadIdentity(const std::string& certPath, const std::str
return false;
}
// 1) 证书:PEM → DER → PCCERT_CONTEXT。
std::vector<BYTE> certDer;
if (!PemToDer(certPem, certDer))
// 1) 证书:PEM → DER → PCCERT_CONTEXT(第一块为叶证书)。
std::vector<std::vector<BYTE>> certDers = PemToDerList(certPem);
if (certDers.empty())
{
Mprintf("[TLS] FATAL: cert file %s is not a valid PEM\n", certPath.c_str());
return false;
}
PCCERT_CONTEXT cert = CertCreateCertificateContext(X509_ASN_ENCODING,
certDer.data(), (DWORD)certDer.size());
certDers[0].data(), (DWORD)certDers[0].size());
if (cert == NULL)
{
Mprintf("[TLS] FATAL: CertCreateCertificateContext failed (%u)\n", GetLastError());
return false;
}
// fullchain 里剩下的中间证书要补进「当前用户\中间证书颁发机构」库里:Schannel 的
// 握手在进程外完成,建链时只查系统证书库——塞进叶证书自带的内存库或 paCred 数组都
// 不会被下发(实测只发叶证书,缺中间证书的客户端建链失败)。补进库里之后 Schannel
// 会随握手把整条链下发,这与 .NET SslStreamCertificateContext 的做法一致。
// 已经是公开信息,留在库里无害;已在库中则跳过。
for (size_t i = 1; i < certDers.size(); ++i)
{
PCCERT_CONTEXT chainCert = CertCreateCertificateContext(
X509_ASN_ENCODING, certDers[i].data(), (DWORD)certDers[i].size());
if (chainCert == NULL)
{
Mprintf("[TLS] WARN: chain cert #%u in %s is unreadable (%u); "
"handshake will only send the certificates already in the store\n",
(unsigned)i, certPath.c_str(), GetLastError());
continue;
}
static HCERTSTORE s_caStore = NULL; // 进程级;关掉反而让 Schannel 后续取不到
if (s_caStore == NULL)
s_caStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_W, 0, 0,
CERT_SYSTEM_STORE_CURRENT_USER, L"CA");
bool inStore = s_caStore != NULL &&
CertFindCertificateInStore(s_caStore, X509_ASN_ENCODING, 0,
CERT_FIND_EXISTING, chainCert, NULL) != NULL;
if (!inStore &&
(s_caStore == NULL ||
!CertAddEncodedCertificateToStore(s_caStore, X509_ASN_ENCODING,
certDers[i].data(), (DWORD)certDers[i].size(),
CERT_STORE_ADD_USE_EXISTING, NULL)))
{
Mprintf("[TLS] WARN: cannot add chain cert #%u from %s to the user CA store (%u); "
"handshake may not send the full chain\n",
(unsigned)i, certPath.c_str(), GetLastError());
}
CertFreeCertificateContext(chainCert);
}
// 2) 私钥:PEM → DER → 持久化到 CNG KSP(仅支持 PKCS#8;PKCS#1 给出可操作的转换提示)。
//
// 关键:Schannel 入站凭据(AcquireCredentialsHandle)需要「能按名重开」的持久化私钥。
// NCryptImportKey 产出的是匿名临时键,绑定 CERT_NCRYPT_KEY_HANDLE_PROP_ID 后 Schannel 仍
// 拿不到(AcquireCredentialsHandle 返回 SEC_E_NO_CREDENTIALS 0x8009030e)。因此先把
// PKCS#8 导入为临时键、导出为裸 RSA 私钥 BLOB(NCryptSetProperty 只认裸 BLOB,不认
// PKCS#8),再写入持久化键并 finalize,最后用 CERT_KEY_PROV_INFO_PROP_ID 按名引用。
// 匿名临时键不行:绑定 CERT_NCRYPT_KEY_HANDLE_PROP_ID 或 CERT_KEY_CONTEXT_PROP_ID
// 后 Schannel 仍拿不到(AcquireCredentialsHandle 返回 SEC_E_NO_CREDENTIALS 0x8009030e)。
// 最后由 CERT_KEY_PROV_INFO_PROP_ID 按名引用持久化键。
//
// 私钥类型沿用证书公钥类型(早期版本写死 RSA,对 Let's Encrypt 现默认的 ECDSA 证书
// 导裸 BLOB 会拿 NTE_BAD_TYPE 0x8009000a,必须按 EC BLOB 导出)。判断用证书而不是
// NCryptGetProperty(BCRYPT_ALGORITHM_NAME):导入的临时键不支持该属性(实测
// NTE_NOT_SUPPORTED 0x80090029);且私钥本就该与证书匹配。
const char* certKeyOid = cert->pCertInfo->SubjectPublicKeyInfo.Algorithm.pszObjId;
const bool certKeyIsRsa = certKeyOid && strcmp(certKeyOid, szOID_RSA_RSA) == 0;
const bool certKeyIsEc = certKeyOid && strcmp(certKeyOid, szOID_ECC_PUBLIC_KEY) == 0;
if (!certKeyIsRsa && !certKeyIsEc)
{
Mprintf("[TLS] FATAL: cert %s uses unsupported public key type (%s); "
"RSA and ECDSA (P-256/P-384/P-521) are supported\n",
certPath.c_str(), certKeyOid ? certKeyOid : "unknown");
CertFreeCertificateContext(cert);
return false;
}
// ECDSA 只支持具名曲线:曲线在证书公钥参数里是 DER 编码的曲线 OID,先核对一遍,
// 好给出比 KSP 报错更清楚的提示(显式参数形式的曲线 KSP 也不吃)。
if (certKeyIsEc)
{
static const BYTE kP256[] = { 0x06,0x08,0x2A,0x86,0x48,0xCE,0x3D,0x03,0x01,0x07 };
static const BYTE kP384[] = { 0x06,0x05,0x2B,0x81,0x04,0x00,0x22 };
static const BYTE kP521[] = { 0x06,0x05,0x2B,0x81,0x04,0x00,0x23 };
const CRYPT_OBJID_BLOB& parm = cert->pCertInfo->SubjectPublicKeyInfo.Algorithm.Parameters;
auto isCurve = [&](const BYTE* der, DWORD len) {
return parm.cbData == len && parm.pbData && memcmp(parm.pbData, der, len) == 0;
};
if (!isCurve(kP256, sizeof(kP256)) && !isCurve(kP384, sizeof(kP384)) &&
!isCurve(kP521, sizeof(kP521)))
{
Mprintf("[TLS] FATAL: cert %s uses an ECDSA curve other than P-256/P-384/P-521 "
"(or explicit curve parameters); convert it to an RSA or named-curve key\n",
certPath.c_str());
CertFreeCertificateContext(cert);
return false;
}
}
std::vector<BYTE> keyDer;
NCRYPT_KEY_HANDLE persistedKey = 0;
if (DetectKeyFormat(keyPem) == KF_PKCS8)
@@ -201,37 +326,67 @@ bool ServerTlsIdentity::LoadIdentity(const std::string& certPath, const std::str
return false;
}
// 2a) PKCS#8 → 临时键。
NCRYPT_KEY_HANDLE tmp = 0;
st = NCryptImportKey(hProv, NULL, NCRYPT_PKCS8_PRIVATE_KEY_BLOB, NULL,
&tmp, keyDer.data(), (DWORD)keyDer.size(), 0);
if (st == ERROR_SUCCESS)
// EC 与 RSA 的落盘路径不同:
// - EC:MS Software KSP 唯一支持的「导入私钥并落盘」方式,是在导入参数表里给出
// 键名(NCRYPTBUFFER_PKCS_KEY_NAME)——不带键名一律按匿名临时键处理。同为导入
// 后的持久化,CreatePersistedKey 后写私钥 BLOB 虽然 SetProperty 返回 0,Finalize
// 却给 NTE_INVALID_PARAMETER(0x80090027);导入后再
// NCryptSetProperty(NCRYPT_NAME_PROPERTY) 给 NTE_NOT_SUPPORTED(0x80090029)。
// - RSA:导入为临时键 → 导出裸私钥 BLOB(NCryptSetProperty 只认裸 BLOB,不认
// PKCS#8)→ 写入持久化键 → finalize。
if (certKeyIsEc)
{
// 2b) 允许明文导出,导出为裸 RSA 私钥 BLOB。
DWORD policy = NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG | NCRYPT_ALLOW_EXPORT_FLAG;
NCryptSetProperty(tmp, NCRYPT_EXPORT_POLICY_PROPERTY, (PBYTE)&policy, sizeof(policy), 0);
std::wstring nameW(keyName);
NCryptBuffer nameBuf = {};
nameBuf.cbBuffer = (ULONG)((nameW.size() + 1) * sizeof(WCHAR));
nameBuf.BufferType = NCRYPTBUFFER_PKCS_KEY_NAME;
nameBuf.pvBuffer = (PVOID)nameW.c_str();
NCryptBufferDesc desc = {};
desc.ulVersion = NCRYPTBUFFER_VERSION;
desc.cBuffers = 1;
desc.pBuffers = &nameBuf;
std::vector<BYTE> raw;
DWORD rawLen = 0;
st = NCryptExportKey(tmp, NULL, BCRYPT_RSAFULLPRIVATE_BLOB, NULL, NULL, 0, &rawLen, 0);
st = NCryptImportKey(hProv, NULL, NCRYPT_PKCS8_PRIVATE_KEY_BLOB, &desc,
&persistedKey, keyDer.data(), (DWORD)keyDer.size(),
NCRYPT_OVERWRITE_KEY_FLAG);
}
else
{
NCRYPT_KEY_HANDLE tmp = 0;
st = NCryptImportKey(hProv, NULL, NCRYPT_PKCS8_PRIVATE_KEY_BLOB, NULL,
&tmp, keyDer.data(), (DWORD)keyDer.size(), 0);
if (st == ERROR_SUCCESS)
{
raw.resize(rawLen);
DWORD policy = NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG | NCRYPT_ALLOW_EXPORT_FLAG;
NCryptSetProperty(tmp, NCRYPT_EXPORT_POLICY_PROPERTY,
(PBYTE)&policy, sizeof(policy), 0);
std::vector<BYTE> raw;
DWORD rawLen = 0;
st = NCryptExportKey(tmp, NULL, BCRYPT_RSAFULLPRIVATE_BLOB, NULL,
raw.data(), rawLen, &rawLen, 0);
NULL, 0, &rawLen, 0);
if (st == ERROR_SUCCESS)
{
raw.resize(rawLen);
st = NCryptExportKey(tmp, NULL, BCRYPT_RSAFULLPRIVATE_BLOB, NULL,
raw.data(), rawLen, &rawLen, 0);
}
if (st == ERROR_SUCCESS)
{
st = NCryptCreatePersistedKey(hProv, &persistedKey, BCRYPT_RSA_ALGORITHM,
keyName, AT_KEYEXCHANGE,
NCRYPT_OVERWRITE_KEY_FLAG);
}
if (st == ERROR_SUCCESS)
{
st = NCryptSetProperty(persistedKey, BCRYPT_RSAFULLPRIVATE_BLOB,
raw.data(), (DWORD)raw.size(), 0);
}
if (st == ERROR_SUCCESS)
st = NCryptFinalizeKey(persistedKey, 0);
NCryptFreeObject(tmp);
}
// 2c) 写入持久化键并 finalize(落到 KSP,可被 Schannel 按名重开)。
if (st == ERROR_SUCCESS)
st = NCryptCreatePersistedKey(hProv, &persistedKey, BCRYPT_RSA_ALGORITHM,
g_keyName, AT_KEYEXCHANGE, NCRYPT_OVERWRITE_KEY_FLAG);
if (st == ERROR_SUCCESS)
st = NCryptSetProperty(persistedKey, BCRYPT_RSAFULLPRIVATE_BLOB,
raw.data(), (DWORD)raw.size(), 0);
if (st == ERROR_SUCCESS)
st = NCryptFinalizeKey(persistedKey, 0);
NCryptFreeObject(tmp);
}
NCryptFreeObject(hProv);
@@ -257,54 +412,55 @@ bool ServerTlsIdentity::LoadIdentity(const std::string& certPath, const std::str
// 3) 绑定私钥到证书上下文:按名引用持久化键。Schannel 经 CryptAcquireCertificatePrivateKey
// 在 MS_KEY_STORAGE_PROVIDER 里用 pwszContainerName 重开该键。
// 4) 换入站凭据(单向 TLS,不请求客户端证书)。
CRYPT_KEY_PROV_INFO provInfo = {};
provInfo.pwszContainerName = (LPWSTR)g_keyName;
provInfo.pwszContainerName = (LPWSTR)keyName;
provInfo.pwszProvName = (LPWSTR)MS_KEY_STORAGE_PROVIDER;
provInfo.dwProvType = 0; // 0 = CNG(无 CAPI provider type)
provInfo.dwKeySpec = AT_KEYEXCHANGE;
provInfo.dwKeySpec = certKeyIsEc ? 0 : AT_KEYEXCHANGE; // ECDSA 键无 legacy key spec
CredHandle cred = {};
SECURITY_STATUS st = SEC_E_NO_CREDENTIALS;
if (!CertSetCertificateContextProperty(cert, CERT_KEY_PROV_INFO_PROP_ID, 0, &provInfo))
{
st = (SECURITY_STATUS)HRESULT_FROM_WIN32(GetLastError());
Mprintf("[TLS] FATAL: CertSetCertificateContextProperty(CERT_KEY_PROV_INFO_PROP_ID) "
"failed (%u)\n", GetLastError());
NCryptDeleteKey(persistedKey, 0); // 删除并释放句柄
CertFreeCertificateContext(cert);
return false;
"failed 0x%08x\n", (unsigned)st);
}
else
{
st = AcquireInboundCredFor(cert, cred);
}
// 绑定后持久化键句柄交进程级 g_persistedKey,随 FreeIdentity 删除(覆盖旧键,避免残留)。
g_persistedKey = persistedKey;
// 4) 入站凭据:显式指定服务端证书,不请求客户端证书(单向 TLS)。
SCHANNEL_CRED sc = {};
sc.dwVersion = SCHANNEL_CRED_VERSION;
sc.cCreds = 1;
sc.paCred = &cert;
sc.grbitEnabledProtocols = SP_PROT_TLS1_2_SERVER;
// NO_DEFAULT_CREDS 避免回退到系统默认凭据,确保只用我们提供的证书/私钥。
//(单向 TLS 不请求客户端证书,故无需 SCH_CRED_MANUAL_CRED_VALIDATION。)
sc.dwFlags = SCH_CRED_NO_DEFAULT_CREDS;
TimeStamp tsExpiry = {};
SECURITY_STATUS st = AcquireCredentialsHandleA(
NULL, (SEC_CHAR*)"Microsoft Unified Security Protocol Provider", SECPKG_CRED_INBOUND,
NULL, &sc, NULL, NULL, &g_cred, &tsExpiry);
if (st != SEC_E_OK)
{
Mprintf("[TLS] FATAL: AcquireCredentialsHandle(SECPKG_CRED_INBOUND) failed 0x%08x\n",
(unsigned)st);
CertFreeCertificateContext(cert); // 无凭据引用,安全释放
g_cred = {};
if (g_persistedKey) // 回滚:删除已持久化的私钥,避免残留
{
NCryptDeleteKey(g_persistedKey, 0); // 删除并释放句柄
g_persistedKey = 0;
}
NCryptDeleteKey(persistedKey, 0); // 回滚:删除已持久化的私钥,避免残留
return false;
}
outCert = cert;
outKey = persistedKey;
outCred = cred;
return true;
}
} // namespace
bool ServerTlsIdentity::LoadIdentity(const std::string& certPath, const std::string& keyPath)
{
CredHandle cred = {};
PCCERT_CONTEXT cert = NULL;
NCRYPT_KEY_HANDLE key = 0;
if (!BuildIdentity(certPath, keyPath, g_keyName, cred, cert, key))
return false;
// 成功:把证书上下文生命周期交给进程级 g_cert,随 FreeIdentity 释放,
// 保证在 FreeCredentialsHandle 之前私钥一直可用。
g_cred = cred;
g_cert = cert;
g_persistedKey = key;
g_credValid = true;
return true;
}
@@ -385,25 +541,89 @@ bool ServerTlsSession::SendAll(SOCKET sock, const void* data, int len)
}
bool ServerTlsSession::Handshake(SOCKET sock, const BYTE* initial, int initialLen)
{
return HandshakeWithCred(sock, initial, initialLen, ServerTlsIdentity::Cred());
}
bool ServerTlsSession::HandshakeWithCred(SOCKET sock, const BYTE* initial, int initialLen,
CredHandle cred)
{
std::lock_guard<std::mutex> lk(m_mtx);
if (m_ctxValid)
CloseHandles(); // 防御:会话应只握手一次
CredHandle cred = ServerTlsIdentity::Cred();
// 单向 TLS:服务端不请求客户端证书,故无需 ASC_REQ_MANUAL_CRED_VALIDATION
//(该标志只在 mTLS 校验客户端证书时有意义;SDK 的 ASC 命名空间里亦无此常量)。
DWORD req = ASC_REQ_SEQUENCE_DETECT | ASC_REQ_REPLAY_DETECT | ASC_REQ_CONFIDENTIALITY |
ASC_REQ_ALLOCATE_MEMORY | ASC_REQ_STREAM;
std::vector<BYTE> hs(initial, initial + initialLen);
std::vector<BYTE> hs;
if (initial != NULL && initialLen > 0)
hs.assign(initial, initial + initialLen);
CtxtHandle ctx = {};
bool ctxValid = false;
TimeStamp tsExpiry = {};
ULONG attrs = 0;
SECURITY_STATUS sc = SEC_I_CONTINUE_NEEDED;
// 握手期间同步收字节:非阻塞套接字上等可读再收,避免误判为致命错误。
auto RecvMore = [&](std::vector<BYTE>& buf) -> bool
{
char raw[8192];
int r;
for (;;)
{
r = recv(sock, raw, sizeof(raw), 0);
if (r == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
{
if (!WaitSocketReady(sock, true, 15000))
{
r = SOCKET_ERROR;
break; // 等可读超时
}
continue;
}
break;
}
if (r <= 0)
{
Mprintf("[TLS] handshake recv failed/EOF (r=%d err=%d)\n", r, WSAGetLastError());
return false;
}
buf.insert(buf.end(), (BYTE*)raw, (BYTE*)raw + r);
return true;
};
// 首次 AcceptSecurityContext 之前必须凑齐一整条 TLS 记录(5 字节头 + 负载)。
// 实测(2026-10-26):用「半条 ClientHello」做首次调用,Schannel 会建出一个坏上下文,
// 之后补齐数据再送返回 SEC_E_UNKNOWN_CREDENTIALS(0x80090301),握手必失败。设备端口
// 一直整包到达所以没暴露;MCP TLS 前端按 8 字节嗅探后接手,稳定触发。故在此统一兜底:
// 调用方给多少都行,缺的字节由本函数从 socket 补齐。
for (;;)
{
if (hs.size() < 5)
{
if (!RecvMore(hs))
return false;
continue;
}
if (hs[0] != 0x16)
{
Mprintf("[TLS] handshake: first byte 0x%02x is not a handshake record; fail-closed\n", hs[0]);
return false;
}
const size_t recLen = 5 + (((size_t)hs[3] << 8) | (size_t)hs[4]);
if (recLen > 18432) // TLS 记录上限 16384 + 允许的额外开销
{
Mprintf("[TLS] handshake: absurd record length %u; fail-closed\n", (unsigned)recLen);
return false;
}
if (hs.size() >= recLen)
break;
if (!RecvMore(hs))
return false;
}
for (;;)
{
SecBuffer inBufs[2] = {
@@ -454,29 +674,11 @@ bool ServerTlsSession::Handshake(SOCKET sock, const BYTE* initial, int initialLe
break; // 真正的失败
}
char raw[8192];
int r;
for (;;)
if (!RecvMore(hs))
{
r = recv(sock, raw, sizeof(raw), 0);
if (r == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
{
if (!WaitSocketReady(sock, true, 15000))
{
r = SOCKET_ERROR;
break; // 等可读超时
}
continue; // 非阻塞套接字暂无数据:等可读后重试
}
break;
}
if (r <= 0)
{
Mprintf("[TLS] handshake recv failed/EOF (r=%d err=%d)\n", r, WSAGetLastError());
sc = SEC_E_INTERNAL_ERROR;
break;
}
hs.insert(hs.end(), (BYTE*)raw, (BYTE*)raw + r);
}
if (sc != SEC_E_OK)
@@ -512,11 +714,14 @@ int ServerTlsSession::Decrypt(const BYTE* cipher, int len, std::vector<BYTE>& pl
std::lock_guard<std::mutex> lk(m_mtx);
if (!m_ready)
return -1;
if (len <= 0)
// len == 0 表示「只取残留」:握手结束时会话里可能已经躺着紧随 Finished 的首条
// 应用数据(见 HandshakeWithCred 末尾),调用方必须在进入收发循环前取一次,
// 否则这份数据要等下一条密文到达才会被解出来。
if (len > 0)
m_raw.insert(m_raw.end(), cipher, cipher + len);
if (m_raw.empty())
return 0;
m_raw.insert(m_raw.end(), cipher, cipher + len);
for (;;)
{
SecBuffer bufs[4] = {
@@ -602,3 +807,42 @@ void CONTEXT_OBJECT::FreeTls()
delete tls;
tls = NULL;
}
// =====================================================================================
// 额外入站身份(MCP 等第二套证书)
// =====================================================================================
bool ServerTlsLoadIdentityFromPem(const std::string& certPath, const std::string& keyPath,
const wchar_t* keyName, ServerTlsExtraIdentity& out)
{
CredHandle cred = {};
PCCERT_CONTEXT cert = NULL;
NCRYPT_KEY_HANDLE key = 0;
if (!BuildIdentity(certPath, keyPath, keyName, cred, cert, key))
return false;
out.cred = cred;
out.cert = cert;
out.key = (ULONG_PTR)key;
return true;
}
void ServerTlsFreeIdentity(ServerTlsExtraIdentity& id)
{
// 顺序同 ServerTlsIdentity::FreeIdentity:凭据 → 证书 → 持久化私钥。
if (id.cred.dwLower || id.cred.dwUpper)
{
FreeCredentialsHandle(&id.cred);
id.cred = {};
}
if (id.cert)
{
CertFreeCertificateContext(id.cert);
id.cert = NULL;
}
if (id.key)
{
NCryptDeleteKey((NCRYPT_KEY_HANDLE)id.key, 0);
id.key = 0;
}
}
+27
View File
@@ -54,6 +54,27 @@ private:
static bool LoadIdentity(const std::string& certPath, const std::string& keyPath);
};
// ---- 额外入站身份(MCP 等第二套证书)----
//
// 进程级身份 ServerTlsIdentity 只服务设备端口,证书由 [tls] 指定(通常是自签
// CN=localhost)。MCP 要暴露给公网客户端,必须用公共 CA 签发的证书,故需要第二份
// 身份。两者可并存:证书/私钥各自加载,持久化私钥用不同的键名(keyName)分开存放,
// 不会互相覆盖。调用方负责在停止时调用 ServerTlsFreeIdentity。
struct ServerTlsExtraIdentity
{
CredHandle cred = {}; // AcquireCredentialsHandle 产出的入站凭据
PCCERT_CONTEXT cert = NULL; // 凭据按名引用的证书上下文
ULONG_PTR key = 0; // NCrypt 持久化私钥句柄(NCRYPT_KEY_HANDLE)
};
// 从 PEM(证书链 + PKCS#8 私钥)构造一份独立入站身份。keyName 为 CNG 持久化键名,
// 须与其它身份不同(例如 L"YamaServerTlsKey" / L"YamaMcpTlsKey")。
bool ServerTlsLoadIdentityFromPem(const std::string& certPath, const std::string& keyPath,
const wchar_t* keyName, ServerTlsExtraIdentity& out);
// 释放 ServerTlsLoadIdentityFromPem 构造的身份(先凭据、再证书、最后删除持久化私钥)。
void ServerTlsFreeIdentity(ServerTlsExtraIdentity& id);
// ---- 单连接服务端 TLS 会话(握手 + 加解密)----
class ServerTlsSession
{
@@ -69,7 +90,13 @@ public:
// 成功返回 true,失败 false(调用方关闭连接,fail-closed)。
bool Handshake(SOCKET sock, const BYTE* initial, int initialLen);
// 同上,但使用调用方提供的入站凭据(MCP TLS 前端用独立的第二份身份,
// 见 ServerTlsLoadIdentityFromPem)。
bool HandshakeWithCred(SOCKET sock, const BYTE* initial, int initialLen, CredHandle cred);
// 解密:把本次 WSARecv 收到的密文 cipher[0..len] 喂入,把能解出的明文追加到 plain。
// len == 0 表示只解出会话里已缓存的密文(握手结束后必须先取一次,否则紧随 Finished
// 到达的首条应用数据会一直躺着,直到客户端再发一包)。
// 返回 0 = 成功(可能无明文);-1 = 错误 / 对端 close_notify(调用方关闭连接)。
int Decrypt(const BYTE* cipher, int len, std::vector<BYTE>& plain);
+4 -1
View File
@@ -2344,7 +2344,7 @@ void CWebService::NotifyAudioState(uint64_t device_id, bool enabled) {
}
}
void CWebService::BroadcastCursor(uint64_t device_id, uint8_t cursor_index) {
void CWebService::BroadcastCursor(uint64_t device_id, uint8_t cursor_index, int x, int y) {
if (m_bStopping) return;
// Build JSON message
@@ -2352,6 +2352,9 @@ void CWebService::BroadcastCursor(uint64_t device_id, uint8_t cursor_index) {
res["cmd"] = "cursor";
res["id"] = std::to_string(device_id);
res["index"] = cursor_index;
// 位置是发送位图(即浏览器 canvas)坐标系;老页面忽略这两个字段。
res["x"] = x;
res["y"] = y;
Json::StreamWriterBuilder builder;
builder["indentation"] = "";
+5 -2
View File
@@ -167,8 +167,11 @@ public:
// clients watching this device and caches it for newcomers.
void NotifyAudioState(uint64_t device_id, bool enabled);
// Cursor change notification (called from ScreenSpyDlg)
void BroadcastCursor(uint64_t device_id, uint8_t cursor_index);
// Cursor notification (called from ScreenSpyDlg): the shape index plus the
// position in the transmitted frame's coordinate space. The browser draws
// the remote cursor itself while it is not in control mode — the captured
// frames never contain one.
void BroadcastCursor(uint64_t device_id, uint8_t cursor_index, int x, int y);
// 远程剪贴板文本回传通知(called from ScreenSpyDlg,payload 为 UTF-8)
void NotifyClipboardText(uint64_t device_id, const std::string& text);
+17
View File
@@ -81,6 +81,23 @@ public:
return (strtoul(caps.GetString(), nullptr, 16) & CLIENT_CAP_UTF8) != 0;
}
// 检查客户端是否支持按服务端给出的路径清单向另一客户端发送文件(COMMAND_C2C_SEND_FILES)。
// 只有 Windows 客户端实现该命令,老客户端无此能力位 → 服务端据此在 MCP 侧提前拒绝。
bool SupportsC2CPaths() const {
CString caps = GetClientData(ONLINELIST_CAPABILITIES);
if (caps.IsEmpty()) return false;
return (strtoul(caps.GetString(), nullptr, 16) & CLIENT_CAP_C2C_PATHS) != 0;
}
// 检查客户端作为 C2C 目标端时是否回落盘回执(TOKEN_C2C_RECV_RESULT)。
// 目前只有 Linux 客户端声明;没有此能力位的老客户端/Windows 端不回执,
// 服务端据此决定要不要等回执,避免给它们白等。
bool SupportsC2CRecvAck() const {
CString caps = GetClientData(ONLINELIST_CAPABILITIES);
if (caps.IsEmpty()) return false;
return (strtoul(caps.GetString(), nullptr, 16) & CLIENT_CAP_C2C_RECV_ACK) != 0;
}
// 检查客户端是否支持屏幕预览(双击主机时拉缩略图)。
bool SupportsScreenPreview() const {
CString caps = GetClientData(ONLINELIST_CAPABILITIES);
+21 -3
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,15 @@ 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.
启用键盘记录(AI 采集击键)=Keylogger aktivieren (KI-Tastenaufzeichnung)
键盘记录开关的改动需重启程序生效。=Aenderungen am Keylogger-Schalter werden erst 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
@@ -2083,8 +2092,8 @@ TLS
证书/私钥加载失败,加密功能未生效。请检查文件路径与格式(证书 PEM、私钥 PKCS#8)。=Zertifikat/privater Schluessel konnte nicht geladen werden; Verschluesselung ist inaktiv. Bitte Pfad und Format pruefen (PEM-Zertifikat, PKCS#8-Schluessel).
TLS传输=TLS-Transport
取消TLS=TLS deaktivieren
确定对选中主机启用 TLS 传输吗?(客户端下次启动生效)=TLS-Transport fuer die ausgewaehlten Hosts aktivieren? (wirkt nach Client-Neustart)
确定取消选中主机的 TLS 传输吗?(客户端下次启动生效)=TLS-Transport fuer die ausgewaehlten Hosts deaktivieren? (wirkt nach Client-Neustart)
确定对选中主机启用 TLS 传输吗?\n(Linux 客户端立即生效并断线重连;Windows 客户端下次启动生效)=TLS-Transport fuer die ausgewaehlten Hosts aktivieren?\n(Linux-Clients wechseln sofort und verbinden sich neu; Windows-Clients erst nach dem Neustart)
确定取消选中主机的 TLS 传输吗?\n(Linux 客户端立即生效并断线重连;Windows 客户端下次启动生效)=TLS-Transport fuer die ausgewaehlten Hosts deaktivieren?\n(Linux-Clients wechseln sofort und verbinden sich neu; Windows-Clients erst nach dem Neustart)
服务端未启用 TLS 证书,无法切换客户端 TLS 传输=Server-TLS-Zertifikat ist nicht aktiviert; TLS-Transport der Clients kann nicht umgeschaltet werden
读取服务端 TLS 证书失败,无法下发=Server-TLS-Zertifikat konnte nicht gelesen werden; Verteilung nicht moeglich
白名单=Whitelist
@@ -2100,3 +2109,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
+25 -3
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,19 @@ 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.
启用键盘记录(AI 采集击键)=Enable keylogger (AI keystroke capture)
键盘记录开关的改动需重启程序生效。=Changes to the keylogger switch take effect after restart.
启用 HTTPS(本端口同时接受 TLS 连接)=Enable HTTPS (this port also accepts TLS connections)
HTTPS 开关与证书路径的改动需重启程序生效。=Changes to the HTTPS switch and certificate paths take effect after restart.
证书或私钥文件不存在,请检查路径。=Certificate or private key file not found; check the path.
证书须为 PEM 格式,私钥须为 PKCS#8 格式。=Certificate must be PEM; private key must be PKCS#8.
主机管理的写操作需只读模式关闭;冻结/解冻进程、停止/重启服务还需启用危险主机操作。=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
@@ -2098,8 +2111,8 @@ TLS
证书/私钥加载失败,加密功能未生效。请检查文件路径与格式(证书 PEM、私钥 PKCS#8)。=Failed to load certificate/private key; encryption is not active. Check the file path and format (PEM certificate, PKCS#8 private key).
TLS传输=TLS Transport
取消TLS=Disable TLS
确定对选中主机启用 TLS 传输吗?(客户端下次启动生效)=Enable TLS transport for the selected host? (takes effect after the client restarts)
确定取消选中主机的 TLS 传输吗?(客户端下次启动生效)=Disable TLS transport for the selected host? (takes effect after the client restarts)
确定对选中主机启用 TLS 传输吗?\n(Linux 客户端立即生效并断线重连;Windows 客户端下次启动生效)=Enable TLS transport for the selected host?\n(Linux clients switch immediately and reconnect; Windows clients apply it on next start)
确定取消选中主机的 TLS 传输吗?\n(Linux 客户端立即生效并断线重连;Windows 客户端下次启动生效)=Disable TLS transport for the selected host?\n(Linux clients switch immediately and reconnect; Windows clients apply it on next start)
服务端未启用 TLS 证书,无法切换客户端 TLS 传输=Server TLS certificate is not enabled; cannot toggle client TLS transport
读取服务端 TLS 证书失败,无法下发=Failed to read the server TLS certificate; cannot distribute
白名单=Whitelist
@@ -2115,3 +2128,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
+25 -3
View File
@@ -1988,7 +1988,7 @@ MCP
端口需为 1-65535 的数字=連接埠需為 1-65535 的數字
Token 不能为空=Token 不能為空
MCP 设置已保存。=MCP 設定已儲存。
启用/端口/绑定地址/Token/只读/白名单/持久终端/远程控制/文件传输/管理操作的改动需重启程序生效。=啟用/連接埠/綁定位址/Token/唯讀/白名單/持久終端/遠端控制/檔案傳輸/管理操作的變更需重新啟動程式後生效。
启用/端口/绑定地址/Token/只读/白名单/持久终端/远程控制/文件传输/管理操作/主机管理/危险主机操作的改动需重启程序生效。=啟用/連接埠/綁定位址/Token/唯讀/白名單/持久終端/遠端控制/檔案傳輸/管理操作/主機管理/危險主機操作的變更需重新啟動程式後生效。
只读模式(禁命令执行)=唯讀模式(禁命令執行)
命令白名单=命令白名單
MCP命令执行=MCP命令執行
@@ -2002,6 +2002,19 @@ Token=Token
启用远程控制(AI 操控桌面)=啟用遠端控制(AI 操控桌面)
启用文件传输(download_file)=啟用檔案傳輸(download_file)
启用管理操作(进程/窗口/服务/电源)=啟用管理操作(程序/視窗/服務/電源)
启用主机管理(进程/窗口/服务/任务/网络状态)=啟用主機管理(處理程序/視窗/服務/排程工作/網路狀態)
启用危险主机操作(冻结/解冻进程、停止/重启服务)=啟用危險主機操作(凍結/解凍處理程序、停止/重新啟動服務)
危险主机操作依附于主机管理:请先启用主机管理。=危險主機操作依附於主機管理:請先啟用主機管理。
启用远程交谈(AI 与用户对话)=啟用遠端交談(AI 與使用者對話)
MCP远程交谈=MCP遠端交談
远程交谈开关的改动需重启程序生效。=遠端交談開關的變更需重新啟動程式後生效。
启用键盘记录(AI 采集击键)=啟用鍵盤記錄(AI 擷取按鍵)
键盘记录开关的改动需重启程序生效。=鍵盤記錄開關的改動需重新啟動程式方可生效。
启用 HTTPS(本端口同时接受 TLS 连接)=啟用 HTTPS(本連接埠同時接受 TLS 連線)
HTTPS 开关与证书路径的改动需重启程序生效。=HTTPS 開關與憑證路徑的改動需重啟程式生效。
证书或私钥文件不存在,请检查路径。=憑證或私鑰檔案不存在,請檢查路徑。
证书须为 PEM 格式,私钥须为 PKCS#8 格式。=憑證須為 PEM 格式,私鑰須為 PKCS#8 格式。
主机管理的写操作需只读模式关闭;冻结/解冻进程、停止/重启服务还需启用危险主机操作。=主機管理的寫入操作需關閉唯讀模式;凍結/解凍處理程序、停止/重新啟動服務還需啟用危險主機操作。
第 %d 个钱包地址不合法!=第 %d 個錢包位址不合法!
%d 新连接\r\n=%d 新連線\r\n
%d 本地连接断开\r\n=%d 本機連線斷開\r\n
@@ -2089,8 +2102,8 @@ TLS
证书/私钥加载失败,加密功能未生效。请检查文件路径与格式(证书 PEM、私钥 PKCS#8)。=憑證/私鑰載入失敗,加密功能未生效。請檢查檔案路徑與格式(憑證 PEM、私鑰 PKCS#8)。
TLS传输=TLS 傳輸
取消TLS=停用 TLS
确定对选中主机启用 TLS 传输吗?(客户端下次启动生效)=確定對選取主機啟用 TLS 傳輸嗎?(用戶端下次啟動生效)
确定取消选中主机的 TLS 传输吗?(客户端下次启动生效)=確定取消選取主機的 TLS 傳輸嗎?(用戶端下次啟動生效)
确定对选中主机启用 TLS 传输吗?\n(Linux 客户端立即生效并断线重连;Windows 客户端下次启动生效)=確定對選取主機啟用 TLS 傳輸嗎?\n(Linux 用戶端立即生效並斷線重連;Windows 用戶端下次啟動生效)
确定取消选中主机的 TLS 传输吗?\n(Linux 客户端立即生效并断线重连;Windows 客户端下次启动生效)=確定取消選取主機的 TLS 傳輸嗎?\n(Linux 用戶端立即生效並斷線重連;Windows 用戶端下次啟動生效)
服务端未启用 TLS 证书,无法切换客户端 TLS 传输=伺服器未啟用 TLS 憑證,無法切換用戶端 TLS 傳輸
读取服务端 TLS 证书失败,无法下发=讀取伺服器 TLS 憑證失敗,無法下發
白名单=白名單
@@ -2106,3 +2119,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);
+16 -5
View File
@@ -418,13 +418,24 @@ func (h *MyHandler) handleScreenFrame(ctx *connection.Context, data []byte, alwa
}
// data[0] is the token; the 11-byte header sits at data[1..12].
const skip = 1 + protocol.ScreenFrameHeaderLen
if len(data) <= skip {
if len(data) < skip {
return // truncated header
}
// Cursor position + index live in the per-frame header: [1]=algorithm,
// [2..9]=POINT (x,y int32 LE), [10]=cursor index. Publish before the heavy
// frame work so the browser sees cursor updates even if we drop the frame.
// The position is in the captured frame's coordinate space, which is also
// the browser canvas space — the overlay can draw it as-is.
//
// The client also sends header-only packets (no bitmap change) at the frame
// rate, so this keeps a static desktop's cursor fresh for non-controlling
// viewers; those packets carry no video and are dropped right after.
cursorX := int(int32(binary.LittleEndian.Uint32(data[2:6])))
cursorY := int(int32(binary.LittleEndian.Uint32(data[6:10])))
h.hub.PublishCursor(deviceID, data[10], cursorX, cursorY)
if len(data) == skip {
return
}
// Cursor index lives at the last byte of the small per-frame header
// (offset 1 + 1 + 8 = 10). Publish before the heavy frame work so the
// browser sees cursor updates even if we end up dropping frames later.
h.hub.PublishCursor(deviceID, data[10])
video := data[skip:]
// 按首字节嗅探 H.264 / AV1,分发到对应的 keyframe 探测器。浏览器侧用同样方式
+9 -9
View File
@@ -21,15 +21,15 @@ type recordedFrame struct {
func (r *frameRecorder) OnScreenFrame(deviceID string, packet []byte, isKeyframe bool) {
r.frames = append(r.frames, recordedFrame{deviceID, packet, isKeyframe})
}
func (r *frameRecorder) OnDeviceOnline(hub.DeviceInfo) {}
func (r *frameRecorder) OnDeviceOffline(string) {}
func (r *frameRecorder) OnDeviceUpdate(string, int, string) {}
func (r *frameRecorder) OnResolutionChange(string, int, int) {}
func (r *frameRecorder) OnCursorChange(string, byte) {}
func (r *frameRecorder) OnClipboardText(string, string) {}
func (r *frameRecorder) OnTerminalReady(string, bool) {}
func (r *frameRecorder) OnTerminalData(string, []byte) {}
func (r *frameRecorder) OnTerminalClosed(string, string) {}
func (r *frameRecorder) OnDeviceOnline(hub.DeviceInfo) {}
func (r *frameRecorder) OnDeviceOffline(string) {}
func (r *frameRecorder) OnDeviceUpdate(string, int, string) {}
func (r *frameRecorder) OnResolutionChange(string, int, int) {}
func (r *frameRecorder) OnCursorChange(string, byte, int, int) {}
func (r *frameRecorder) OnClipboardText(string, string) {}
func (r *frameRecorder) OnTerminalReady(string, bool) {}
func (r *frameRecorder) OnTerminalData(string, []byte) {}
func (r *frameRecorder) OnTerminalClosed(string, string) {}
// TestOnReceiveRelaysKeyframeToken guards the forced-IDR recovery path: when
// the browser asks for a keyframe, the client replies with TOKEN_KEYFRAME.
+8 -8
View File
@@ -193,14 +193,14 @@ func (s *Store) offlineAt(id string, at time.Time) {
}
// The remaining EventHandler methods are not relevant to device history.
func (s *Store) OnDeviceUpdate(string, int, string) {}
func (s *Store) OnScreenFrame(string, []byte, bool) {}
func (s *Store) OnResolutionChange(string, int, int) {}
func (s *Store) OnCursorChange(string, byte) {}
func (s *Store) OnClipboardText(string, string) {}
func (s *Store) OnTerminalReady(string, bool) {}
func (s *Store) OnTerminalData(string, []byte) {}
func (s *Store) OnTerminalClosed(string, string) {}
func (s *Store) OnDeviceUpdate(string, int, string) {}
func (s *Store) OnScreenFrame(string, []byte, bool) {}
func (s *Store) OnResolutionChange(string, int, int) {}
func (s *Store) OnCursorChange(string, byte, int, int) {}
func (s *Store) OnClipboardText(string, string) {}
func (s *Store) OnTerminalReady(string, bool) {}
func (s *Store) OnTerminalData(string, []byte) {}
func (s *Store) OnTerminalClosed(string, string) {}
// Offline returns the records whose IDs are not in online, newest last_seen
// first, converted to the hub's device payload shape with Online=false.
+37 -14
View File
@@ -73,11 +73,15 @@ type Device struct {
screenHeight int
lastKeyframe []byte // fully-packed WS binary packet of the most recent IDR
// Cursor index dedup: cursors arrive on every frame (~30 Hz) but only
// rarely change. Suppress duplicates so the WS doesn't carry redundant
// JSON messages.
// Cursor dedup/throttle: cursors arrive on every frame (~30 Hz) and the
// position changes most frames. An index change is published immediately
// (the shape matters visually); a position-only change is rate-limited so
// the WS doesn't carry 30 JSON messages per second per viewer.
cursorSeen bool
lastCursorIndex byte
lastCursorX int
lastCursorY int
cursorPubAt time.Time
// Terminal session state — at most one web terminal per device (MVP
// constraint shared with the C++ server). All three fields are
@@ -186,10 +190,11 @@ type EventHandler interface {
// OnResolutionChange fires when a screen session starts (TOKEN_BITMAPINFO)
// or whenever the device reports a new screen geometry mid-stream.
OnResolutionChange(deviceID string, width, height int)
// OnCursorChange fires when the device's foreground cursor index changes.
// Duplicates (same index as the previous frame) are filtered out by the
// hub before reaching subscribers.
OnCursorChange(deviceID string, index byte)
// OnCursorChange fires when the device's foreground cursor changes shape or
// moves. x/y are in the captured frame's coordinate space (== browser canvas
// space). The hub filters duplicates and rate-limits position-only changes
// before reaching subscribers.
OnCursorChange(deviceID string, index byte, x, y int)
// OnClipboardText delivers the device's clipboard text (already UTF-8),
// captured in response to a browser "clipboard_get" request.
OnClipboardText(deviceID string, text string)
@@ -536,25 +541,43 @@ func deviceToInfo(d *Device) DeviceInfo {
}
}
// cursorMinInterval rate-limits position-only cursor updates. Shape changes
// bypass it; pure movement is published at most this often.
const cursorMinInterval = 50 * time.Millisecond
// cursorRefreshInterval re-sends an unchanged cursor at least this often so a
// viewer that joins while the pointer is idle still learns where it is (it
// would otherwise wait for the next mouse movement).
const cursorRefreshInterval = time.Second
// PublishCursor notifies subscribers when the device reports a new cursor
// index. Repeated identical indices are suppressed so the WS isn't spammed
// with per-frame cursor JSON. No-op for unknown devices.
func (h *Hub) PublishCursor(deviceID string, index byte) {
// position/shape. x/y are in the captured frame's coordinate space. Identical
// reports are suppressed and position-only changes are throttled, so the WS
// isn't spammed with per-frame cursor JSON; an idle cursor is refreshed once a
// second for late joiners. No-op for unknown devices.
func (h *Hub) PublishCursor(deviceID string, index byte, x, y int) {
h.mu.Lock()
d, ok := h.devices[deviceID]
if !ok {
h.mu.Unlock()
return
}
if d.cursorSeen && d.lastCursorIndex == index {
h.mu.Unlock()
return
moved := d.lastCursorX != x || d.lastCursorY != y
reshaped := !d.cursorSeen || d.lastCursorIndex != index
if !reshaped {
since := time.Since(d.cursorPubAt)
if since < cursorMinInterval || (!moved && since < cursorRefreshInterval) {
h.mu.Unlock()
return
}
}
d.cursorSeen = true
d.lastCursorIndex = index
d.lastCursorX, d.lastCursorY = x, y
d.cursorPubAt = time.Now()
h.mu.Unlock()
for _, s := range h.snapshotSubscribers() {
s.OnCursorChange(deviceID, index)
s.OnCursorChange(deviceID, index, x, y)
}
}
+75 -1
View File
@@ -58,6 +58,7 @@ type captureHandler struct {
online []string
offline []string
updates []string // formatted "id:rtt"
cursors [][3]int // recorded {index, x, y}
}
func (c *captureHandler) OnDeviceOnline(d DeviceInfo) {
@@ -82,7 +83,11 @@ func (c *captureHandler) OnScreenFrame(_ string, _ []byte, _ bool) {}
func (c *captureHandler) OnResolutionChange(_ string, _, _ int) {}
func (c *captureHandler) OnCursorChange(_ string, _ byte) {}
func (c *captureHandler) OnCursorChange(_ string, index byte, x, y int) {
c.mu.Lock()
c.cursors = append(c.cursors, [3]int{int(index), x, y})
c.mu.Unlock()
}
func (c *captureHandler) OnClipboardText(_ string, _ string) {}
@@ -225,3 +230,72 @@ func TestHubConcurrent(t *testing.T) {
t.Fatalf("after all unregisters: want 0, got %d", got)
}
}
// The web console draws the remote cursor itself while the user is not in
// control mode, so the hub must deliver the position reliably but without
// relaying every ~30 Hz frame to every viewer.
func TestPublishCursorDedupAndThrottle(t *testing.T) {
h := New()
c := &captureHandler{}
h.Subscribe(c)
h.Register(&Device{ID: "d", Name: "d"}, stubCtx())
// First report always goes out, even for the zero value.
h.PublishCursor("d", 1, 10, 20)
if len(c.cursors) != 1 || c.cursors[0] != [3]int{1, 10, 20} {
t.Fatalf("first publish: %+v", c.cursors)
}
// Identical report: suppressed.
h.PublishCursor("d", 1, 10, 20)
if len(c.cursors) != 1 {
t.Fatalf("identical report should be dropped: %+v", c.cursors)
}
// Position-only change inside the throttle window: suppressed.
h.PublishCursor("d", 1, 11, 21)
if len(c.cursors) != 1 {
t.Fatalf("position-only change should be throttled: %+v", c.cursors)
}
// Shape change bypasses the throttle.
h.PublishCursor("d", 5, 12, 22)
if len(c.cursors) != 2 || c.cursors[1] != [3]int{5, 12, 22} {
t.Fatalf("shape change should be immediate: %+v", c.cursors)
}
// After the window a position-only change is delivered again.
time.Sleep(cursorMinInterval + 10*time.Millisecond)
h.PublishCursor("d", 5, 13, 23)
if len(c.cursors) != 3 || c.cursors[2] != [3]int{5, 13, 23} {
t.Fatalf("post-window move: %+v", c.cursors)
}
// Unknown device: no event, no panic.
h.PublishCursor("ghost", 1, 0, 0)
if len(c.cursors) != 3 {
t.Fatalf("unknown device should not publish: %+v", c.cursors)
}
}
// A viewer joining while the pointer is idle must still learn its position:
// the hub re-sends an unchanged cursor once the refresh interval passes.
func TestPublishCursorRefreshesIdleState(t *testing.T) {
h := New()
c := &captureHandler{}
h.Subscribe(c)
h.Register(&Device{ID: "d", Name: "d"}, stubCtx())
h.PublishCursor("d", 3, 100, 200)
time.Sleep(cursorRefreshInterval / 2)
h.PublishCursor("d", 3, 100, 200) // inside the refresh window: dropped
if len(c.cursors) != 1 {
t.Fatalf("duplicate inside refresh window should be dropped: %+v", c.cursors)
}
time.Sleep(cursorRefreshInterval/2 + 50*time.Millisecond)
h.PublishCursor("d", 3, 100, 200) // stale: re-published for late joiners
if len(c.cursors) != 2 || c.cursors[1] != [3]int{3, 100, 200} {
t.Fatalf("idle refresh missing: %+v", c.cursors)
}
}
+13 -5
View File
@@ -63,6 +63,11 @@ type wsClient struct {
user string // mirrors session username after login/resume
termWatching string // device ID for an open web terminal session, "" otherwise
// wheelResidue carries the sub-notch remainder between wheel events so one
// physical notch becomes exactly one WM_MOUSEWHEEL (see handleMouse). Only
// the read loop that owns this client touches it.
wheelResidue float64
// watchIDs is the set of devices this browser is streaming (the screen
// wall watches several at once). Empty while on the device list.
// Guarded by wsHub.mu.
@@ -346,15 +351,18 @@ func (h *wsHub) OnDeviceOffline(id string) {
}
}
// OnCursorChange relays the remote cursor index to every viewer of this
// device. The browser maps the index to a CSS cursor (desktop) or overlay
// SVG variant (touch). Hub already de-duplicates so we always have a real
// transition here.
func (h *wsHub) OnCursorChange(deviceID string, index byte) {
// OnCursorChange relays the remote cursor's shape and position to every viewer
// of this device. The browser draws the cursor itself while it is not in
// control mode (captured frames never contain one) and maps the index to a CSS
// cursor on desktop while in control mode. x/y are in frame/canvas space.
// Hub already de-duplicates and throttles, so we always have a real transition.
func (h *wsHub) OnCursorChange(deviceID string, index byte, x, y int) {
msg := mustJSON(map[string]any{
"cmd": "cursor",
"id": deviceID,
"index": index,
"x": x,
"y": y,
})
h.mu.RLock()
defer h.mu.RUnlock()
+58
View File
@@ -0,0 +1,58 @@
package web
import (
"encoding/json"
"testing"
)
// The non-controlling browser draws the remote cursor itself, so the relayed
// "cursor" message must carry the position, not just the shape index. Without
// x/y an older page still works (it ignores unknown fields), but the new
// overlay has nothing to place.
func TestOnCursorChangeCarriesPosition(t *testing.T) {
c := &wsClient{
send: make(chan wsMsg, 4),
closed: make(chan struct{}),
token: "tok",
watchIDs: map[string]struct{}{"42": {}},
}
h := &wsHub{clients: map[*wsClient]struct{}{c: {}}}
h.OnCursorChange("42", 5, 1280, 720)
var msg struct {
Cmd string `json:"cmd"`
ID string `json:"id"`
Index int `json:"index"`
X *int `json:"x"`
Y *int `json:"y"`
}
m := <-c.send
if m.binary {
t.Fatal("cursor message must be a text frame")
}
if err := json.Unmarshal(m.data, &msg); err != nil {
t.Fatalf("unmarshal %s: %v", m.data, err)
}
if msg.Cmd != "cursor" || msg.ID != "42" || msg.Index != 5 {
t.Fatalf("message = %+v", msg)
}
if msg.X == nil || msg.Y == nil || *msg.X != 1280 || *msg.Y != 720 {
t.Fatalf("position missing: x=%v y=%v (raw %s)", msg.X, msg.Y, m.data)
}
// A viewer not watching the device must not receive anything.
other := &wsClient{
send: make(chan wsMsg, 1),
closed: make(chan struct{}),
token: "tok",
watchIDs: map[string]struct{}{"7": {}},
}
h.clients[other] = struct{}{}
h.OnCursorChange("42", 5, 1, 1)
select {
case <-other.send:
t.Fatal("non-watching client received a cursor message")
default:
}
}
+54 -15
View File
@@ -3,6 +3,7 @@ package web
import (
"encoding/json"
"errors"
"math"
"sort"
"strings"
"time"
@@ -803,11 +804,12 @@ func (h *wsHub) handleMouse(c *wsClient, raw []byte) {
return
}
var in struct {
Type string `json:"type"`
X int32 `json:"x"`
Y int32 `json:"y"`
Button int `json:"button"`
Delta int `json:"delta"`
Type string `json:"type"`
X int32 `json:"x"`
Y int32 `json:"y"`
Button int `json:"button"`
Delta float64 `json:"delta"`
DeltaMode int `json:"deltaMode"`
}
if err := json.Unmarshal(raw, &in); err != nil {
return
@@ -845,17 +847,13 @@ func (h *wsHub) handleMouse(c *wsClient, raw []byte) {
message = protocol.WMMouseMove
case "wheel":
message = protocol.WMMouseWheel
// Windows expects ±120 per notch in HIWORD(wParam). Browsers report
// `deltaY` in pixels with sign flipped relative to Win32 conventions
// (positive deltaY = scroll down). Normalize to one notch per call,
// signed so up scrolls "up" on the remote.
var wheel int16
switch {
case in.Delta > 0:
wheel = -120
case in.Delta < 0:
wheel = 120
// Windows expects ±120 per notch in HIWORD(wParam); wheelNotches turns the
// browser's distance into whole notches (see its doc comment).
notches := wheelNotches(&c.wheelResidue, in.Delta, in.DeltaMode)
if notches == 0 {
return // less than a notch so far: keep it for the next event
}
wheel := int16(-notches * 120) // positive deltaY = scroll down
wParam = uint64(uint16(wheel)) << 16
case "dblclick":
// Windows synthesizes double-click from rapid down/up sequences, so
@@ -872,6 +870,47 @@ func (h *wsHub) handleMouse(c *wsClient, raw []byte) {
_ = h.devices.SendToScreen(deviceID, pkt)
}
// maxWheelNotches caps how many wheel notches one browser event may inject.
// A touchpad fling or a scrollbar drag can report a huge delta; without the cap
// the remote jumps pages at a time.
const maxWheelNotches = 20
// wheelNotches converts one browser wheel event into whole Windows wheel
// notches, carrying the sub-notch remainder in *residue.
//
// The browser reports a *distance*, not a notch count: deltaMode 0 = pixels
// (Chrome's notch is about 100px), 1 = lines (about 3 per notch), 2 = pages.
// Chrome's smooth scrolling splits one physical notch into several events with
// fractional deltas (33.33 + 33.33 + 33.34) and touchpads go well below one
// pixel per event, so events have to be accumulated: reading the delta as an
// int dropped every fractional event (the wheel did nothing at all), and
// treating every event as one notch scrolled three to four times too far.
//
// Rounding, not truncation: the split events do not sum to exactly 1.0 in
// float (33.33*3 = 99.99), so an integer cast would sit at 0.999 forever. With
// rounding the first notch fires halfway through a physical one, which is how
// native scrolling feels, and *residue always stays within ±0.5 — it is a
// positional carry, not a bank of credit — so a change of direction needs no
// special case.
func wheelNotches(residue *float64, delta float64, deltaMode int) int {
unit := 100.0
switch deltaMode {
case 1:
unit = 3
case 2:
unit = 1
}
*residue += delta / unit
notches := int(math.Round(*residue))
*residue -= float64(notches)
if notches > maxWheelNotches {
notches = maxWheelNotches
} else if notches < -maxWheelNotches {
notches = -maxWheelNotches
}
return notches
}
// handleKey forwards one keyboard event to the device. lParam is built to
// match the Windows convention so applications relying on TranslateMessage
// (e.g. text input fields) behave correctly. Mirrors
+93
View File
@@ -0,0 +1,93 @@
package web
import "testing"
// Chrome's smooth scrolling splits one physical notch (100px) into a few
// fractional wheel events. Each event must not become a notch on its own, and
// the whole physical notch must inject exactly one.
func TestWheelNotchesSmoothScrollSequence(t *testing.T) {
var residue float64
seq := []float64{33.33, 33.33, 33.34}
total := 0
for _, d := range seq {
total += abs(wheelNotches(&residue, d, 0))
}
if total != 1 {
t.Fatalf("one 100px notch in %d events gave %d notches, want 1", len(seq), total)
}
if residue > 0.5 || residue < -0.5 {
t.Fatalf("residue must stay within half a notch, got %v", residue)
}
}
// Touchpads report sub-pixel deltas: they used to truncate to 0 and the wheel
// did nothing at all. They must accumulate into one notch.
func TestWheelNotchesSubPixelDeltas(t *testing.T) {
var residue float64
got := 0
for i := 0; i < 167; i++ { // 167 events x 0.6px = 100.2px
got += wheelNotches(&residue, 0.6, 0)
}
if got != 1 {
t.Fatalf("167 x 0.6px gave %d notches, want 1", got)
}
}
// The same split in three equal parts must also land on exactly one notch:
// 33.33*3 is 99.99 in float, and truncating would never reach a whole notch.
func TestWheelNotchesEqualThirds(t *testing.T) {
var residue float64
got := 0
for i := 0; i < 3; i++ {
got += wheelNotches(&residue, 33.33, 0)
}
if got != 1 {
t.Fatalf("3 x 33.33px gave %d notches, want 1", got)
}
}
func TestWheelNotchesDirection(t *testing.T) {
var residue float64
if n := wheelNotches(&residue, 100, 0); n != 1 {
t.Fatalf("down: got %d notches, want 1", n)
}
if n := wheelNotches(&residue, -100, 0); n != -1 {
t.Fatalf("up: got %d notches, want -1", n)
}
// A half-scrolled notch does not block a reversal: the carry is a position,
// so 40px down then a full notch up is one notch up.
residue = 0.4
if n := wheelNotches(&residue, -100, 0); n != -1 {
t.Fatalf("flip: got %d notches, want -1", n)
}
}
func TestWheelNotchesDeltaModes(t *testing.T) {
var pixel, line, page float64
if n := wheelNotches(&pixel, 100, 0); n != 1 {
t.Fatalf("pixel mode: got %d, want 1", n)
}
if n := wheelNotches(&line, 3, 1); n != 1 {
t.Fatalf("line mode: got %d, want 1", n)
}
if n := wheelNotches(&page, 1, 2); n != 1 {
t.Fatalf("page mode: got %d, want 1", n)
}
}
func TestWheelNotchesClamp(t *testing.T) {
var residue float64
if n := wheelNotches(&residue, 100000, 0); n != maxWheelNotches {
t.Fatalf("huge delta gave %d notches, want %d", n, maxWheelNotches)
}
if n := wheelNotches(&residue, -100000, 0); n != -maxWheelNotches {
t.Fatalf("huge negative delta gave %d notches, want %d", n, -maxWheelNotches)
}
}
func abs(n int) int {
if n < 0 {
return -n
}
return n
}
+70 -14
View File
@@ -2648,8 +2648,12 @@
isAndroidRemote = msg.client_type === 'APK';
updateAndroidNavbar();
// Refresh cursor overlay and immersive layout
document.getElementById('cursor-overlay').classList.toggle(
'active', controlEnabled && isTouchDevice && !isAndroidRemote);
if (controlEnabled) {
document.getElementById('cursor-overlay').classList.toggle(
'active', isTouchDevice && !isAndroidRemote);
} else {
renderRemoteCursor();
}
if (isTouchDevice) updateUIForOrientation();
}
initDecoder(msg.width, msg.height);
@@ -2662,8 +2666,18 @@
// Update remote cursor visual: native CSS cursor on desktop,
// overlay variant on touch. 254=custom (unsupported), 255=unsupported.
currentCursorIndex = msg.index;
remoteCursor.index = msg.index;
// 服务端每帧带上光标位置(帧坐标 == canvas 坐标)。老版本服务端
// 只发 index,此时 known 保持 false,退回原来的表现。
if (typeof msg.x === 'number' && typeof msg.y === 'number') {
remoteCursor.x = msg.x;
remoteCursor.y = msg.y;
remoteCursor.known = true;
}
if (controlEnabled) {
applyRemoteCursor(msg.index);
} else {
renderRemoteCursor();
}
break;
}
@@ -2778,6 +2792,8 @@
// Update input shortcuts position after canvas resize
requestAnimationFrame(updateInputShortcutsPosition);
// 分辨率变了:非控制态的远程光标按新画布重新定位
requestAnimationFrame(renderRemoteCursor);
// Windows/Linux/macOS clients send bottom-up H.264 (BMP convention) → flip.
// Android MediaCodec sends top-down H.264 → no flip needed.
@@ -5193,6 +5209,11 @@
];
let currentCursorIndex = 1; // Default: arrow
// 远程真实光标位置(服务端随每帧回报)。抓屏画面本身不含光标,所以非控制态
// 由浏览器自己画一个。known=false 表示服务端还没上报过位置(老版本服务端),
// 这时退回浏览器自己的指针,保持原有观感。
let remoteCursor = { x: 0, y: 0, index: 1, known: false };
// IDC_* index -> CSS class on .cursor-overlay (touch-mode visual cursor).
// Indices not listed (0,2,4,6,8,14, custom) fall back to default arrow.
const cursorOverlayClassMap = {
@@ -5226,6 +5247,28 @@
}
}
// 非控制态的光标渲染:把远程光标画在它真正所在的位置上,同时藏起浏览器
// 自己的箭头,否则屏幕上会同时出现两个指针。控制态不走这里——桌面端本地
// 指针本身就是远程光标,触摸端由 updateCursorOverlay 画触控光标。
function renderRemoteCursor() {
if (controlEnabled) return;
const canvas = document.getElementById('screen-canvas');
const overlay = document.getElementById('cursor-overlay');
if (!canvas || !overlay) return;
// 屏幕墙(以及没打开远程桌面时)不画:多路光标会落在同一个固定层上。
const screenPage = document.getElementById('screen-page');
const onScreen = !!screenPage && screenPage.classList.contains('active');
// Android 直连模式没有指针概念(手指即指针),不画。
const show = onScreen && remoteCursor.known && !isAndroidRemote;
canvas.style.cursor = show ? 'none' : 'default';
overlay.className = 'cursor-overlay' + (show ? ' active' : '');
const cls = cursorOverlayClassMap[remoteCursor.index];
if (show) {
if (cls) overlay.classList.add(cls);
positionCursorOverlay(remoteCursor.x, remoteCursor.y);
}
}
// Floating toolbar state
let toolbarVisible = false;
let toolbarHideTimer = null;
@@ -5481,17 +5524,18 @@
// Cursor handling
const canvas = document.getElementById('screen-canvas');
const cursorOverlay = document.getElementById('cursor-overlay');
// Touch: hide native cursor and show our overlay (touchpad mode).
// Desktop: native CSS cursor is set by applyRemoteCursor below.
if (controlEnabled && isTouchDevice) {
canvas.style.cursor = 'none';
} else if (!controlEnabled) {
canvas.style.cursor = 'default';
}
// Android direct mode: no cursor overlay (finger IS the pointer)
cursorOverlay.classList.toggle('active', controlEnabled && isTouchDevice && !isAndroidRemote);
if (controlEnabled) {
// Touch: hide native cursor and show our overlay (touchpad mode).
// Desktop: native CSS cursor is set by applyRemoteCursor below.
if (isTouchDevice) {
canvas.style.cursor = 'none';
}
// Android direct mode: no cursor overlay (finger IS the pointer)
cursorOverlay.classList.toggle('active', isTouchDevice && !isAndroidRemote);
applyRemoteCursor(currentCursorIndex);
} else {
// 非控制态:藏起本地指针,只留远程真实光标
renderRemoteCursor();
}
// Sync the keyboard lock: in fullscreen + control mode, ESC and F11
// must be passed through to the remote OS instead of triggering the
@@ -5505,9 +5549,16 @@
// Only used on touch devices (touchpad mode)
function updateCursorOverlay(canvasX, canvasY) {
if (!controlEnabled || !isTouchDevice) return;
positionCursorOverlay(canvasX, canvasY);
}
// Place the overlay at a canvas coordinate, applying the zoom/pan
// transform. Shared by the touch control cursor and the non-control
// remote cursor.
function positionCursorOverlay(canvasX, canvasY) {
const canvas = document.getElementById('screen-canvas');
const cursorOverlay = document.getElementById('cursor-overlay');
if (!canvas || !cursorOverlay) return;
// Get canvas base position (without transform, use container + offset)
// offsetLeft/offsetTop are layout positions, unaffected by CSS transform
const container = document.querySelector('.canvas-container');
@@ -5679,6 +5730,8 @@
canvas.style.transformOrigin = zoomState.originX + '% ' + zoomState.originY + '%';
canvas.style.transform = 'scale(' + zoomState.scale + ') translate(' + zoomState.translateX + 'px, ' + zoomState.translateY + 'px)';
}
// 非控制态:缩放/平移后远程光标要跟着画面走
if (!controlEnabled) renderRemoteCursor();
}
function getPinchDistance(touches) {
@@ -5854,13 +5907,15 @@
};
}
function sendMouse(type, x, y, button, delta) {
function sendMouse(type, x, y, button, delta, deltaMode) {
if (!controlEnabled) return; // Control mode required
// Update cursor overlay position
updateCursorOverlay(x, y);
if (ws && ws.readyState === WebSocket.OPEN && token) {
const msg = { cmd: 'mouse', token, id: currentDeviceId(), type, x, y, button: button || 0 };
if (delta !== undefined) msg.delta = delta;
// deltaMode: 0=像素 1=行 2=页。服务端按它把 delta 换算成滚轮刻度。
if (deltaMode !== undefined) msg.deltaMode = deltaMode;
ws.send(JSON.stringify(msg));
}
}
@@ -6495,7 +6550,7 @@
canvas.addEventListener('wheel', function(e) {
e.preventDefault();
const pos = getMousePos(e);
sendMouse('wheel', pos.x, pos.y, 0, e.deltaY);
sendMouse('wheel', pos.x, pos.y, 0, e.deltaY, e.deltaMode);
}, { passive: false });
canvas.addEventListener('contextmenu', e => e.preventDefault());
@@ -6632,6 +6687,7 @@
// Strip any cursor-* variant on the overlay, leaving the bare default arrow.
document.getElementById('cursor-overlay').className = 'cursor-overlay';
currentCursorIndex = 1; // Reset to default arrow
remoteCursor = { x: 0, y: 0, index: 1, known: false }; // 切设备后位置作废
// Reset zoom state
zoomState.scale = 1;
+352
View File
@@ -0,0 +1,352 @@
<#
服务端 MCP 只读冒烟测试。
只调用「不会改变任何状态」的工具(列表/详情类),断言结构化字段齐全、
分页字段正确、鉴权与请求体上限生效。可在发布前对着任一台在线主机跑一遍,
确认 MCP 链路与改动前相比没有回归。
用法:
$env:YAMA_MCP_TOKEN = '<token>' # 与 service 的 McpToken 一致
powershell -ExecutionPolicy Bypass -File tools\mcp_smoke.ps1
powershell -ExecutionPolicy Bypass -File tools\mcp_smoke.ps1 -Base http://127.0.0.1:6545/mcp
参数:
-Base MCP 端点,默认 http://127.0.0.1:6544/mcp(Release 实例)
-Token 覆盖 env YAMA_MCP_TOKEN
-HostId 指定在线主机 id;缺省取 list_online_hosts 的第一台
-SkipHost 只测服务端本机工具,不触达远程主机(无在线主机时用)
-SearchPath 可选,跑 search_file 测试的搜索根目录(如 C:\Windows\Fonts)。
不指定就跳过:客户端递归用无界 wsprintf 拼 MAX_PATH 缓冲,
深目录会栈溢出(Debug 客户端弹 Run-Time Check Failure #2)。
-AuditLog 可选,服务端审计日志路径(如 Bin\logs\mcp_audit.log)。给了才断言
-32006 拒绝会写一条 CALL_DENIED。
退出码:0 全部通过;1 有失败项。token 不会被打印。
#>
param(
[string]$Base = 'http://127.0.0.1:6544/mcp',
[string]$Token = $env:YAMA_MCP_TOKEN,
[string]$HostId = '',
[switch]$SkipHost,
[string]$SearchPath = '',
[string]$AuditLog = ''
)
$ErrorActionPreference = 'Stop'
$script:pass = 0
$script:fail = 0
$script:failures = @()
function Check([string]$name, [bool]$ok, [string]$detail = '') {
if ($ok) {
$script:pass++
Write-Host (" [PASS] " + $name) -ForegroundColor Green
} else {
$script:fail++
$script:failures += $name + $(if ($detail) { " -- $detail" } else { "" })
Write-Host (" [FAIL] " + $name + $(if ($detail) { " -- " + $detail } else { "" })) -ForegroundColor Red
}
}
function Send-Raw([string]$json, [string]$auth) {
# 返回 @{ Status = <int>; Body = <string> };非 2xx 不抛异常。
$bytes = [System.Text.Encoding]::UTF8.GetBytes($json)
$headers = @{}
if ($auth) { $headers['Authorization'] = 'Bearer ' + $auth }
try {
$resp = Invoke-WebRequest -Uri $Base -Method Post -Body $bytes `
-ContentType 'application/json' -Headers $headers -TimeoutSec 180 -UseBasicParsing
return @{ Status = [int]$resp.StatusCode; Body = $resp.Content }
} catch {
$r = $_.Exception.Response
if ($r) { return @{ Status = [int]$r.StatusCode; Body = '' } }
return @{ Status = 0; Body = $_.Exception.Message }
}
}
function Rpc([string]$method, $params, [string]$toolName, $toolArgs) {
# tools/call 用 toolName+args,其余方法用 method+params。
if ($toolName) {
$payload = @{ jsonrpc = '2.0'; id = 1; method = 'tools/call';
params = @{ name = $toolName; arguments = $toolArgs } }
} else {
$payload = @{ jsonrpc = '2.0'; id = 1; method = $method; params = $params }
}
$json = $payload | ConvertTo-Json -Depth 12 -Compress
$raw = Send-Raw $json $Token
if ($raw.Status -ne 200) { throw "HTTP $($raw.Status) calling $method$toolName" }
return ($raw.Body | ConvertFrom-Json)
}
function HasPaging($obj) {
if ($null -eq $obj) { return $false }
foreach ($k in @('total', 'totalAll', 'offset', 'limit', 'hasMore')) {
if (-not ($obj.PSObject.Properties.Name -contains $k)) { return $false }
}
return $true
}
# 结果外露(docs/Mcp_Design.md §14):content 末尾必须有一个可解析的 JSON 文本块,
# 内容与 structuredContent 对应。只读 content 的客户端(WorkBuddy)靠它拿到 id。
function HasJsonText($rpc) {
if ($null -eq $rpc -or $null -eq $rpc.result) { return $false }
$c = @($rpc.result.content)
if ($c.Count -lt 2) { return $false }
$last = $c[$c.Count - 1]
if ($last.type -ne 'text' -or [string]::IsNullOrEmpty($last.text)) { return $false }
try { $null = $last.text | ConvertFrom-Json } catch { return $false }
return $true
}
Write-Host "MCP smoke test -> $Base"
if (-not $Token) {
Write-Host "缺少 token:请设置环境变量 YAMA_MCP_TOKEN 或传 -Token。" -ForegroundColor Red
exit 1
}
# ===== 1. 传输层 =====
Write-Host "`n[1] 传输层"
$bad = Send-Raw '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}' 'wrong-token-for-smoke-test'
Check '未授权 token 返回 401' ($bad.Status -eq 401) ("status=" + $bad.Status)
$big = '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"list_online_hosts","arguments":{"pad":"' +
('x' * (2 * 1024 * 1024 + 1024)) + '"}}}'
$o = Send-Raw $big $Token
Check '请求体超过 2 MB 返回 413' ($o.Status -eq 413) ("status=" + $o.Status)
# ===== 2. 协议层 =====
Write-Host "`n[2] 协议层"
$init = Rpc 'initialize' @{ protocolVersion = '2025-06-18'; capabilities = @{}; clientInfo = @{ name = 'smoke'; version = '1' } } $null $null
Check 'initialize 返回 serverInfo' ($null -ne $init.result.serverInfo)
$tl = Rpc 'tools/list' @{} $null $null
$tools = @($tl.result.tools)
Check 'tools/list 至少 40 个工具' ($tools.Count -ge 40) ("count=" + $tools.Count)
$annotated = @($tools | Where-Object {
$a = $_.annotations
$a -and ($a.PSObject.Properties.Name -contains 'readOnlyHint') -and
($a.PSObject.Properties.Name -contains 'destructiveHint') -and
($a.PSObject.Properties.Name -contains 'idempotentHint') -and
($a.PSObject.Properties.Name -contains 'openWorldHint')
})
Check '每个工具都带 annotations 四元组' ($annotated.Count -eq $tools.Count) ("annotated=" + $annotated.Count + "/" + $tools.Count)
$ro = @($tools | Where-Object { $_.annotations.readOnlyHint -eq $true })
Check '存在只读工具且无只读工具被标为破坏性' ($ro.Count -gt 0 -and
(@($ro | Where-Object { $_.annotations.destructiveHint -eq $true }).Count -eq 0)) ("readOnly=" + $ro.Count)
# ===== 2b. 协议层错误码 =====
Write-Host "`n[2b] 协议层错误码"
$um = Rpc 'bogus/method' @{} $null $null
Check '未知 method 返回 -32601' ([int]$um.error.code -eq -32601) ([string]$um.error.code)
$ut = Rpc '' $null 'no_such_tool' @{}
Check '未知工具返回 -32602' ([int]$ut.error.code -eq -32602) ([string]$ut.error.code)
$mi = Rpc '' $null 'get_host_detail' @{}
Check '缺少必填参数返回 -32602' ([int]$mi.error.code -eq -32602) ([string]$mi.error.message)
# ===== 2c. 批量入口上限 =====
$ids51 = (1..51 | ForEach-Object { '"99999999999999' + $_ + '"' }) -join ','
# Rpc 会把 ids 数组重新序列化,这里直接发原始请求体,避免 51 个 id 走两层转换
$raw51 = '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"list_processes","arguments":{"ids":[' +
$ids51 + ']}}}'
$r51 = Send-Raw $raw51 $Token
$j51 = $r51.Body | ConvertFrom-Json
Check '批量 51 个 id 返回 -32602' ([int]$j51.error.code -eq -32602) ([string]$j51.error.message)
# ===== 3. 服务端本机只读工具 =====
Write-Host "`n[3] 服务端本机工具"
$online = Rpc '' $null 'list_online_hosts' @{ limit = 100 }
$sc = $online.result.structuredContent
Check 'list_online_hosts 带分页字段' (HasPaging $sc)
Check 'list_online_hosts 每条都有 id/online' (@($sc.hosts | Where-Object { -not $_.id -or $_.online -ne $true }).Count -eq 0)
$noMatch = Rpc '' $null 'list_online_hosts' @{ group = 'zzz-no-such-group' }
Check 'list_online_hosts 过滤未命中返回 0 条' ($noMatch.error -eq $null -and [int]$noMatch.result.structuredContent.total -eq 0)
Check 'list_online_hosts 过滤后 totalAll 仍是全部在线数' ([int]$noMatch.result.structuredContent.totalAll -eq [int]$sc.totalAll)
$all = Rpc '' $null 'list_all_hosts' @{ limit = 5 }
Check 'list_all_hosts 带分页字段' (HasPaging $all.result.structuredContent)
Check 'list_all_hosts 的 content 附带结构化 JSON' (HasJsonText $all)
$allJson = $null
if (HasJsonText $all) { $allJson = $all.result.content[-1].text | ConvertFrom-Json }
Check 'content 的 JSON 里能取到主机 id(串联下一跳)' ($null -eq $allJson -or
@($allJson.hosts).Count -eq 0 -or [string]$allJson.hosts[0].id -ne '')
$found = Rpc '' $null 'search_hosts' @{ query = ''; limit = 5 }
Check 'search_hosts 正常返回' ($found.error -eq $null -and (HasPaging $found.result.structuredContent))
Check 'search_hosts 的 content 附带结构化 JSON' (HasJsonText $found)
$audit = Rpc '' $null 'get_audit_log' @{ limit = 5 }
Check 'get_audit_log 正常返回' ($audit.error -eq $null)
Check 'get_audit_log 带分页字段' (HasPaging $audit.result.structuredContent)
Check 'get_audit_log 条数不超过 limit' (@($audit.result.structuredContent.entries).Count -le 5)
$auditFiltered = Rpc '' $null 'get_audit_log' @{ type = 'zzz-no-such-type'; limit = 5 }
Check 'get_audit_log 过滤未命中返回 0 条' ($auditFiltered.error -eq $null -and @($auditFiltered.result.structuredContent.entries).Count -eq 0)
$status = Rpc '' $null 'get_server_status' @{}
$st = $status.result.structuredContent.status
Check 'get_server_status 正常返回' ($status.error -eq $null -and $null -ne $st)
$basePort = 6544
if ($Base -match ':(\d+)(/|$)') { $basePort = [int]$Matches[1] }
Check 'get_server_status 版本/端口/开关齐全' `
([string]$st.version -ne '' -and [int]$st.port -eq $basePort -and $null -ne $st.switches -and $null -ne $st.sessions)
Check 'get_server_status 不含 token' (($st | ConvertTo-Json -Depth 6) -notmatch '(?i)token')
Check 'get_server_status 的 content 附带结构化 JSON' (HasJsonText $status)
if (-not $HostId) {
$first = @($sc.hosts)[0]
if ($first) { $HostId = [string]$first.id }
}
if (-not $HostId) {
Write-Host "`n 没有在线主机,跳过主机类工具。" -ForegroundColor Yellow
$SkipHost = $true
}
# ===== 4. 主机只读工具 =====
if (-not $SkipHost) {
Write-Host "`n[4] 主机工具 (id=$HostId)"
$det = Rpc '' $null 'get_host_detail' @{ id = $HostId }
$h = $det.result.structuredContent.host
Check 'get_host_detail id 回显正确' (([string]$h.id) -eq $HostId)
Check 'get_host_detail 含 os/version/online' ($h.os -and $h.version -and ($null -ne $h.online))
$procs = Rpc '' $null 'list_processes' @{ id = $HostId; limit = 3 }
$ps = $procs.result.structuredContent
Check 'list_processes 分页字段' (HasPaging $ps)
Check 'list_processes 条数不超过 limit' (@($ps.processes).Count -le 3)
Check 'list_processes 总数为正' ([int]$ps.total -gt 0)
$wins = Rpc '' $null 'list_windows' @{ id = $HostId; limit = 3 }
Check 'list_windows 正常返回' ($wins.error -eq $null -and (HasPaging $wins.result.structuredContent))
$drv = Rpc '' $null 'list_files' @{ id = $HostId }
$ds = $drv.result.structuredContent
Check 'list_files 无 path 时返回驱动器列表' (@($ds.drives).Count -gt 0 -and (HasPaging $ds))
$drive = ''
if (@($ds.drives).Count -gt 0) { $drive = [string](@($ds.drives)[0].drive) }
if ($drive) {
$dir = Rpc '' $null 'list_files' @{ id = $HostId; path = $drive; limit = 5 }
Check ("list_files 目录列举 (" + $drive + ")") ($dir.error -eq $null -and (HasPaging $dir.result.structuredContent))
# search_file:客户端递归用无界 wsprintf 拼 MAX_PATH 缓冲,深目录会栈溢出
# (Debug 客户端弹 Run-Time Check Failure #2 并挂住搜索线程)。所以默认不跑,
# 需要时用 -SearchPath 指定一个中浅层目录(如 C:\Windows\Fonts)。
if ($SearchPath) {
$search = Rpc '' $null 'search_file' @{ id = $HostId; path = $SearchPath; pattern = '*.exe'; limit = 3; timeout_ms = 5000 }
$ss = $search.result.structuredContent
if ($search.error) {
Check 'search_file 正常返回' $false $search.error.message
} else {
Check 'search_file 带 finished/truncated 字段' (($null -ne $ss.finished) -and ($null -ne $ss.truncated))
Check 'search_file 命中项字段完整' (@($ss.files | Where-Object { -not $_.path -or $null -eq $_.size }).Count -eq 0)
# C4:结果侧过滤(大小 / 修改时间 / 精简字段),全部在服务端做
$base0 = [int]$ss.totalAll
$big = Rpc '' $null 'search_file' @{ id = $HostId; path = $SearchPath; pattern = '*.exe';
limit = 3; timeout_ms = 5000; min_size = 1073741824 }
$bs = $big.result.structuredContent
Check 'search_file min_size 过滤后 totalAll 不变' `
($big.error -eq $null -and [int]$bs.totalAll -eq $base0 -and [int]$bs.total -le $base0)
$slim = Rpc '' $null 'search_file' @{ id = $HostId; path = $SearchPath; pattern = '*.exe';
limit = 3; timeout_ms = 5000; name_only = $true }
$sl = @($slim.result.structuredContent.files)
Check 'search_file name_only 只返回 path/name' `
($slim.error -eq $null -and @($sl | Where-Object { $_.size -or $_.modified -or $_.dir }).Count -eq 0)
$bad = Rpc '' $null 'search_file' @{ id = $HostId; path = $SearchPath; pattern = '*.exe';
modified_after = '2026/01/01' }
Check 'search_file 非法 modified_after 返回 -32602' `
($bad.error -and [int]$bad.error.code -eq -32602)
}
} else {
Write-Host " 未指定 -SearchPath,跳过 search_file 测试(深目录会触发客户端已知的 MAX_PATH 栈溢出)。" -ForegroundColor Yellow
}
}
# 批量入口:一台真实主机 + 一台不存在的主机,验证 results 汇总
$batch = Rpc '' $null 'list_processes' @{ ids = @($HostId, '999999999999999'); limit = 1 }
$bs = $batch.result.structuredContent
Check '批量 results 覆盖全部 id' (@($bs.results).Count -eq 2 -and [int]$bs.succeeded -eq 1 -and [int]$bs.failed -eq 1)
}
# ===== 4b. 结构化失败(新客户端:TOKEN_*_ERROR → -32009/-32010) =====
# 老客户端没有这些回报包,对应工具会退化成「成功 + 空列表」或超时——
# 所以这三条只对「新客户端」成立;失败时先确认目标机客户端是否已升级。
if (-not $SkipHost -and $drive) {
Write-Host "`n[4b] 结构化失败"
$ghostDir = $drive.TrimEnd('\') + '\mcp_smoke_no_such_dir_xyz'
$lf = Rpc '' $null 'list_files' @{ id = $HostId; path = $ghostDir }
Check 'list_files 不存在路径返回 -32009' `
($lf.error -and [int]$lf.error.code -eq -32009) ([string]$lf.error.message)
$lr = Rpc '' $null 'list_registry' @{ id = $HostId; path = 'HKEY_LOCAL_MACHINE\SOFTWARE\MCPSmokeNoSuchKey_xyz' }
Check 'list_registry 不存在键返回 -32009' `
($lr.error -and [int]$lr.error.code -eq -32009) ([string]$lr.error.message)
if (@($tools | Where-Object { $_.name -eq 'download_file' }).Count -gt 0) {
$dlDir = Join-Path $env:TEMP 'mcp_smoke_dl'
$dl = Rpc '' $null 'download_file' @{ id = $HostId; remote_path = ($ghostDir + '\a.txt'); local_dir = $dlDir }
Check 'download_file 不存在路径返回 -32009' `
($dl.error -and [int]$dl.error.code -eq -32009) ([string]$dl.error.message)
Remove-Item -LiteralPath $dlDir -Recurse -Force -ErrorAction SilentlyContinue
} else {
Write-Host " download_file 未开启(McpFileTransfer),跳过下载负例。" -ForegroundColor Yellow
}
# copy_files_c2c:只测「不需要两台在线主机」的拒绝分支,避免冒烟改变远端文件。
# 同主机 → -32602(参数被拒);目标不在线 → -32002(主机找不到)。
if (@($tools | Where-Object { $_.name -eq 'copy_files_c2c' }).Count -gt 0) {
$c2cSame = Rpc '' $null 'copy_files_c2c' @{
src_id = $HostId; dst_id = $HostId
paths = @($ghostDir + '\a.txt'); dst_dir = (Join-Path $env:TEMP 'mcp_smoke_c2c')
}
Check 'copy_files_c2c 同主机返回 -32602' `
($c2cSame.error -and [int]$c2cSame.error.code -eq -32602) ([string]$c2cSame.error.message)
$c2cOff = Rpc '' $null 'copy_files_c2c' @{
src_id = $HostId; dst_id = '1'
paths = @($ghostDir + '\a.txt'); dst_dir = (Join-Path $env:TEMP 'mcp_smoke_c2c')
}
Check 'copy_files_c2c 目标离线返回 -32002' `
($c2cOff.error -and [int]$c2cOff.error.code -eq -32002) ([string]$c2cOff.error.message)
} else {
Write-Host " copy_files_c2c 未开启(McpFileTransfer/McpReadonly),跳过 C2C 负例。" -ForegroundColor Yellow
}
}
# ===== 5. 策略拒绝(-32006) =====
# 只在某个开关确实关闭时才有意义,所以先读 get_server_status 的 switches 再挑一个关着的功能。
# 全部开启时跳过(不算失败)——这条不是每次都能测,但测到时能证明拒绝路径与审计都还在。
Write-Host "`n[5] 策略拒绝"
$gateMap = @(
@{ swName = 'keylog'; tool = 'get_keylog'; args = @{} }
@{ swName = 'chat'; tool = 'chat_open'; args = @{} }
@{ swName = 'terminal'; tool = 'terminal_open'; args = @{} }
@{ swName = 'remote_control'; tool = 'get_screenshot'; args = @{} }
)
$offGate = $null
foreach ($g in $gateMap) {
if ($null -ne $st.switches -and $st.switches.PSObject.Properties.Name -contains $g.swName -and
$st.switches.($g.swName) -eq $false) { $offGate = $g; break }
}
if ($offGate) {
$args5 = @{}
if ($HostId) { $args5['id'] = $HostId }
foreach ($k in $offGate.args.Keys) { $args5[$k] = $offGate.args[$k] }
$refused = Rpc '' $null $offGate.tool $args5
Check ("关闭 " + $offGate.swName + " 后 " + $offGate.tool + " 返回 -32006") ([int]$refused.error.code -eq -32006) ([string]$refused.error.message)
if ($AuditLog) {
$tail = Get-Content -LiteralPath $AuditLog -Tail 20 -ErrorAction SilentlyContinue
Check '拒绝记录进审计日志(CALL_DENIED)' (@($tail | Where-Object { $_ -match 'CALL_DENIED' }).Count -gt 0)
}
} else {
Write-Host " 所有功能开关都开着,跳过 -32006 检查(关掉任一开关再跑一次可覆盖)。" -ForegroundColor Yellow
}
# ===== 汇总 =====
Write-Host ("`n通过 " + $script:pass + " 项,失败 " + $script:fail + " 项。") -ForegroundColor $(if ($script:fail -eq 0) { 'Green' } else { 'Red' })
if ($script:fail -gt 0) {
$script:failures | ForEach-Object { Write-Host (" - " + $_) -ForegroundColor Red }
exit 1
}
exit 0